Cleanup: remove redundant doxygen \file argument
[blender.git] / source / blender / blenkernel / intern / library_query.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2014 by Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file \ingroup bke
21  */
22
23 #include <stdlib.h>
24
25 #include "MEM_guardedalloc.h"
26
27 #include "DNA_anim_types.h"
28 #include "DNA_armature_types.h"
29 #include "DNA_brush_types.h"
30 #include "DNA_camera_types.h"
31 #include "DNA_collection_types.h"
32 #include "DNA_constraint_types.h"
33 #include "DNA_gpencil_types.h"
34 #include "DNA_key_types.h"
35 #include "DNA_lamp_types.h"
36 #include "DNA_lattice_types.h"
37 #include "DNA_linestyle_types.h"
38 #include "DNA_material_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_meta_types.h"
42 #include "DNA_movieclip_types.h"
43 #include "DNA_mask_types.h"
44 #include "DNA_node_types.h"
45 #include "DNA_object_force_types.h"
46 #include "DNA_lightprobe_types.h"
47 #include "DNA_rigidbody_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_sequence_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_speaker_types.h"
52 #include "DNA_sound_types.h"
53 #include "DNA_text_types.h"
54 #include "DNA_vfont_types.h"
55 #include "DNA_windowmanager_types.h"
56 #include "DNA_workspace_types.h"
57 #include "DNA_world_types.h"
58
59 #include "BLI_utildefines.h"
60 #include "BLI_ghash.h"
61 #include "BLI_linklist_stack.h"
62
63 #include "BKE_animsys.h"
64 #include "BKE_collection.h"
65 #include "BKE_constraint.h"
66 #include "BKE_fcurve.h"
67 #include "BKE_gpencil_modifier.h"
68 #include "BKE_idprop.h"
69 #include "BKE_library.h"
70 #include "BKE_library_query.h"
71 #include "BKE_main.h"
72 #include "BKE_modifier.h"
73 #include "BKE_node.h"
74 #include "BKE_particle.h"
75 #include "BKE_rigidbody.h"
76 #include "BKE_sequencer.h"
77 #include "BKE_shader_fx.h"
78 #include "BKE_tracking.h"
79 #include "BKE_workspace.h"
80
81
82 #define FOREACH_FINALIZE _finalize
83 #define FOREACH_FINALIZE_VOID \
84         if (0) { goto FOREACH_FINALIZE; } \
85         FOREACH_FINALIZE: ((void)0)
86
87 #define FOREACH_CALLBACK_INVOKE_ID_PP(_data, id_pp, _cb_flag) \
88         CHECK_TYPE(id_pp, ID **); \
89         if (!((_data)->status & IDWALK_STOP)) { \
90                 const int _flag = (_data)->flag; \
91                 ID *old_id = *(id_pp); \
92                 const int callback_return = (_data)->callback((_data)->user_data, (_data)->self_id, id_pp, _cb_flag | (_data)->cb_flag); \
93                 if (_flag & IDWALK_READONLY) { \
94                         BLI_assert(*(id_pp) == old_id); \
95                 } \
96                 if (old_id && (_flag & IDWALK_RECURSE)) { \
97                         if (BLI_gset_add((_data)->ids_handled, old_id)) { \
98                                 if (!(callback_return & IDWALK_RET_STOP_RECURSION)) { \
99                                         BLI_LINKSTACK_PUSH((_data)->ids_todo, old_id); \
100                                 } \
101                         } \
102                 } \
103                 if (callback_return & IDWALK_RET_STOP_ITER) { \
104                         (_data)->status |= IDWALK_STOP; \
105                         goto FOREACH_FINALIZE; \
106                 } \
107         } \
108         else { \
109                 goto FOREACH_FINALIZE; \
110         } ((void)0)
111
112 #define FOREACH_CALLBACK_INVOKE_ID(_data, id, cb_flag) \
113         { \
114                 CHECK_TYPE_ANY(id, ID *, void *); \
115                 FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id), cb_flag); \
116         } ((void)0)
117
118 #define FOREACH_CALLBACK_INVOKE(_data, id_super, cb_flag) \
119         { \
120                 CHECK_TYPE(&((id_super)->id), ID *); \
121                 FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id_super), cb_flag); \
122         } ((void)0)
123
124 /* status */
125 enum {
126         IDWALK_STOP     = 1 << 0,
127 };
128
129 typedef struct LibraryForeachIDData {
130         ID *self_id;
131         int flag;
132         int cb_flag;
133         LibraryIDLinkCallback callback;
134         void *user_data;
135         int status;
136
137         /* To handle recursion. */
138         GSet *ids_handled;  /* All IDs that are either already done, or still in ids_todo stack. */
139         BLI_LINKSTACK_DECLARE(ids_todo, ID *);
140 } LibraryForeachIDData;
141
142 static void library_foreach_idproperty_ID_link(LibraryForeachIDData *data, IDProperty *prop, int flag)
143 {
144         if (!prop)
145                 return;
146
147         switch (prop->type) {
148                 case IDP_GROUP:
149                 {
150                         for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
151                                 library_foreach_idproperty_ID_link(data, loop, flag);
152                         }
153                         break;
154                 }
155                 case IDP_IDPARRAY:
156                 {
157                         IDProperty *loop = IDP_Array(prop);
158                         for (int i = 0; i < prop->len; i++) {
159                                 library_foreach_idproperty_ID_link(data, &loop[i], flag);
160                         }
161                         break;
162                 }
163                 case IDP_ID:
164                         FOREACH_CALLBACK_INVOKE_ID(data, prop->data.pointer, flag);
165                         break;
166                 default:
167                         break;  /* Nothing to do here with other types of IDProperties... */
168         }
169
170         FOREACH_FINALIZE_VOID;
171 }
172
173 static void library_foreach_rigidbodyworldSceneLooper(
174         struct RigidBodyWorld *UNUSED(rbw), ID **id_pointer, void *user_data, int cb_flag)
175 {
176         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
177         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
178
179         FOREACH_FINALIZE_VOID;
180 }
181
182 static void library_foreach_modifiersForeachIDLink(
183         void *user_data, Object *UNUSED(object), ID **id_pointer, int cb_flag)
184 {
185         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
186         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
187
188         FOREACH_FINALIZE_VOID;
189 }
190
191 static void library_foreach_gpencil_modifiersForeachIDLink(
192         void *user_data, Object *UNUSED(object), ID **id_pointer, int cb_flag)
193 {
194         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
195         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
196
197         FOREACH_FINALIZE_VOID;
198 }
199
200 static void library_foreach_shaderfxForeachIDLink(
201         void *user_data, Object *UNUSED(object), ID **id_pointer, int cb_flag)
202 {
203         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
204         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
205
206         FOREACH_FINALIZE_VOID;
207 }
208
209 static void library_foreach_constraintObjectLooper(bConstraint *UNUSED(con), ID **id_pointer,
210                                                    bool is_reference, void *user_data)
211 {
212         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
213         const int cb_flag = is_reference ? IDWALK_CB_USER : IDWALK_CB_NOP;
214         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
215
216         FOREACH_FINALIZE_VOID;
217 }
218
219 static void library_foreach_particlesystemsObjectLooper(
220         ParticleSystem *UNUSED(psys), ID **id_pointer, void *user_data, int cb_flag)
221 {
222         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
223         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag);
224
225         FOREACH_FINALIZE_VOID;
226 }
227
228 static void library_foreach_nla_strip(LibraryForeachIDData *data, NlaStrip *strip)
229 {
230         NlaStrip *substrip;
231
232         FOREACH_CALLBACK_INVOKE(data, strip->act, IDWALK_CB_USER);
233
234         for (substrip = strip->strips.first; substrip; substrip = substrip->next) {
235                 library_foreach_nla_strip(data, substrip);
236         }
237
238         FOREACH_FINALIZE_VOID;
239 }
240
241 static void library_foreach_animationData(LibraryForeachIDData *data, AnimData *adt)
242 {
243         FCurve *fcu;
244         NlaTrack *nla_track;
245         NlaStrip *nla_strip;
246
247         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
248                 ChannelDriver *driver = fcu->driver;
249                 DriverVar *dvar;
250
251                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
252                         /* only used targets */
253                         DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
254                         {
255                                 FOREACH_CALLBACK_INVOKE_ID(data, dtar->id, IDWALK_CB_NOP);
256                         }
257                         DRIVER_TARGETS_LOOPER_END;
258                 }
259         }
260
261         FOREACH_CALLBACK_INVOKE(data, adt->action, IDWALK_CB_USER);
262         FOREACH_CALLBACK_INVOKE(data, adt->tmpact, IDWALK_CB_USER);
263
264         for (nla_track = adt->nla_tracks.first; nla_track; nla_track = nla_track->next) {
265                 for (nla_strip = nla_track->strips.first; nla_strip; nla_strip = nla_strip->next) {
266                         library_foreach_nla_strip(data, nla_strip);
267                 }
268         }
269
270         FOREACH_FINALIZE_VOID;
271 }
272
273 static void library_foreach_mtex(LibraryForeachIDData *data, MTex *mtex)
274 {
275         FOREACH_CALLBACK_INVOKE(data, mtex->object, IDWALK_CB_NOP);
276         FOREACH_CALLBACK_INVOKE(data, mtex->tex, IDWALK_CB_USER);
277
278         FOREACH_FINALIZE_VOID;
279 }
280
281 static void library_foreach_paint(LibraryForeachIDData *data, Paint *paint)
282 {
283         FOREACH_CALLBACK_INVOKE(data, paint->brush, IDWALK_CB_USER);
284         for (int i = 0; i < paint->tool_slots_len; i++) {
285                 FOREACH_CALLBACK_INVOKE(data, paint->tool_slots[i].brush, IDWALK_CB_USER);
286         }
287         FOREACH_CALLBACK_INVOKE(data, paint->palette, IDWALK_CB_USER);
288
289         FOREACH_FINALIZE_VOID;
290 }
291
292 static void library_foreach_bone(LibraryForeachIDData *data, Bone *bone)
293 {
294         library_foreach_idproperty_ID_link(data, bone->prop, IDWALK_CB_USER);
295
296         for (Bone *curbone = bone->childbase.first; curbone; curbone = curbone->next) {
297                 library_foreach_bone(data, curbone);
298         }
299
300         FOREACH_FINALIZE_VOID;
301 }
302
303 static void library_foreach_layer_collection(LibraryForeachIDData *data, ListBase *lb)
304 {
305         for (LayerCollection *lc = lb->first; lc; lc = lc->next) {
306                 FOREACH_CALLBACK_INVOKE(data, lc->collection, IDWALK_CB_NOP);
307                 library_foreach_layer_collection(data, &lc->layer_collections);
308         }
309
310         FOREACH_FINALIZE_VOID;
311 }
312
313 static void library_foreach_ID_as_subdata_link(
314         ID **id_pp, LibraryIDLinkCallback callback, void *user_data, int flag, LibraryForeachIDData *data)
315 {
316         /* Needed e.g. for callbacks handling relationships... This call shall be absolutely readonly. */
317         ID *id = *id_pp;
318         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pp, IDWALK_CB_PRIVATE);
319         BLI_assert(id == *id_pp);
320
321         if (flag & IDWALK_RECURSE) {
322                 /* Defer handling into main loop, recursively calling BKE_library_foreach_ID_link in IDWALK_RECURSE case is
323                  * troublesome, see T49553. */
324                 if (BLI_gset_add(data->ids_handled, id)) {
325                         BLI_LINKSTACK_PUSH(data->ids_todo, id);
326                 }
327         }
328         else {
329                 BKE_library_foreach_ID_link(NULL, id, callback, user_data, flag);
330         }
331
332         FOREACH_FINALIZE_VOID;
333 }
334
335 /**
336  * Loop over all of the ID's this datablock links to.
337  *
338  * \note: May be extended to be recursive in the future.
339  */
340 void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback callback, void *user_data, int flag)
341 {
342         LibraryForeachIDData data;
343         int i;
344
345         if (flag & IDWALK_RECURSE) {
346                 /* For now, recusion implies read-only. */
347                 flag |= IDWALK_READONLY;
348
349                 data.ids_handled = BLI_gset_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
350                 BLI_LINKSTACK_INIT(data.ids_todo);
351
352                 BLI_gset_add(data.ids_handled, id);
353         }
354         else {
355                 data.ids_handled = NULL;
356         }
357         data.flag = flag;
358         data.status = 0;
359         data.callback = callback;
360         data.user_data = user_data;
361
362 #define CALLBACK_INVOKE_ID(check_id, cb_flag) \
363         FOREACH_CALLBACK_INVOKE_ID(&data, check_id, cb_flag)
364
365 #define CALLBACK_INVOKE(check_id_super, cb_flag) \
366         FOREACH_CALLBACK_INVOKE(&data, check_id_super, cb_flag)
367
368         for (; id != NULL; id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL) {
369                 data.self_id = id;
370                 data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0;
371
372                 if (bmain != NULL && bmain->relations != NULL && (flag & IDWALK_READONLY)) {
373                         /* Note that this is minor optimization, even in worst cases (like id being an object with lots of
374                          * drivers and constraints and modifiers, or material etc. with huge node tree),
375                          * but we might as well use it (Main->relations is always assumed valid, it's responsibility of code
376                          * creating it to free it, especially if/when it starts modifying Main database). */
377                         MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->id_user_to_used, id);
378                         for (; entry != NULL; entry = entry->next) {
379                                 FOREACH_CALLBACK_INVOKE_ID_PP(&data, entry->id_pointer, entry->usage_flag);
380                         }
381                         continue;
382                 }
383
384                 if (id->override_static != NULL) {
385                         CALLBACK_INVOKE_ID(id->override_static->reference, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
386                         CALLBACK_INVOKE_ID(id->override_static->storage, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE);
387                 }
388
389                 library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER);
390
391                 AnimData *adt = BKE_animdata_from_id(id);
392                 if (adt) {
393                         library_foreach_animationData(&data, adt);
394                 }
395
396                 switch ((ID_Type)GS(id->name)) {
397                         case ID_LI:
398                         {
399                                 Library *lib = (Library *) id;
400                                 CALLBACK_INVOKE(lib->parent, IDWALK_CB_NOP);
401                                 break;
402                         }
403                         case ID_SCE:
404                         {
405                                 Scene *scene = (Scene *) id;
406                                 ToolSettings *toolsett = scene->toolsettings;
407
408                                 CALLBACK_INVOKE(scene->camera, IDWALK_CB_NOP);
409                                 CALLBACK_INVOKE(scene->world, IDWALK_CB_USER);
410                                 CALLBACK_INVOKE(scene->set, IDWALK_CB_NOP);
411                                 CALLBACK_INVOKE(scene->clip, IDWALK_CB_USER);
412                                 CALLBACK_INVOKE(scene->r.bake.cage_object, IDWALK_CB_NOP);
413                                 if (scene->nodetree) {
414                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
415                                         library_foreach_ID_as_subdata_link((ID **)&scene->nodetree, callback, user_data, flag, &data);
416                                 }
417                                 if (scene->ed) {
418                                         Sequence *seq;
419                                         SEQP_BEGIN(scene->ed, seq)
420                                         {
421                                                 CALLBACK_INVOKE(seq->scene, IDWALK_CB_NOP);
422                                                 CALLBACK_INVOKE(seq->scene_camera, IDWALK_CB_NOP);
423                                                 CALLBACK_INVOKE(seq->clip, IDWALK_CB_USER);
424                                                 CALLBACK_INVOKE(seq->mask, IDWALK_CB_USER);
425                                                 CALLBACK_INVOKE(seq->sound, IDWALK_CB_USER);
426                                                 library_foreach_idproperty_ID_link(&data, seq->prop, IDWALK_CB_USER);
427                                                 for (SequenceModifierData *smd = seq->modifiers.first; smd; smd = smd->next) {
428                                                         CALLBACK_INVOKE(smd->mask_id, IDWALK_CB_USER);
429                                                 }
430
431                                                 if (seq->type == SEQ_TYPE_TEXT && seq->effectdata) {
432                                                         TextVars *text_data = seq->effectdata;
433                                                         CALLBACK_INVOKE(text_data->text_font, IDWALK_CB_USER);
434                                                 }
435                                         } SEQ_END;
436                                 }
437
438
439                                 for (CollectionObject *cob = scene->master_collection->gobject.first; cob; cob = cob->next) {
440                                         CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
441                                 }
442                                 for (CollectionChild *child = scene->master_collection->children.first; child; child = child->next) {
443                                         CALLBACK_INVOKE(child->collection, IDWALK_CB_USER);
444                                 }
445
446                                 ViewLayer *view_layer;
447                                 for (view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
448                                         CALLBACK_INVOKE(view_layer->mat_override, IDWALK_CB_USER);
449
450                                         for (Base *base = view_layer->object_bases.first; base; base = base->next) {
451                                                 CALLBACK_INVOKE(base->object, IDWALK_CB_NOP);
452                                         }
453
454                                         library_foreach_layer_collection(&data, &view_layer->layer_collections);
455
456                                         for (FreestyleModuleConfig  *fmc = view_layer->freestyle_config.modules.first; fmc; fmc = fmc->next) {
457                                                 if (fmc->script) {
458                                                         CALLBACK_INVOKE(fmc->script, IDWALK_CB_NOP);
459                                                 }
460                                         }
461
462                                         for (FreestyleLineSet *fls = view_layer->freestyle_config.linesets.first; fls; fls = fls->next) {
463                                                 if (fls->group) {
464                                                         CALLBACK_INVOKE(fls->group, IDWALK_CB_USER);
465                                                 }
466
467                                                 if (fls->linestyle) {
468                                                         CALLBACK_INVOKE(fls->linestyle, IDWALK_CB_USER);
469                                                 }
470                                         }
471                                 }
472
473                                 for (TimeMarker *marker = scene->markers.first; marker; marker = marker->next) {
474                                         CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
475                                 }
476
477                                 if (toolsett) {
478                                         CALLBACK_INVOKE(toolsett->particle.scene, IDWALK_CB_NOP);
479                                         CALLBACK_INVOKE(toolsett->particle.object, IDWALK_CB_NOP);
480                                         CALLBACK_INVOKE(toolsett->particle.shape_object, IDWALK_CB_NOP);
481
482                                         library_foreach_paint(&data, &toolsett->imapaint.paint);
483                                         CALLBACK_INVOKE(toolsett->imapaint.stencil, IDWALK_CB_USER);
484                                         CALLBACK_INVOKE(toolsett->imapaint.clone, IDWALK_CB_USER);
485                                         CALLBACK_INVOKE(toolsett->imapaint.canvas, IDWALK_CB_USER);
486
487                                         if (toolsett->vpaint) {
488                                                 library_foreach_paint(&data, &toolsett->vpaint->paint);
489                                         }
490                                         if (toolsett->wpaint) {
491                                                 library_foreach_paint(&data, &toolsett->wpaint->paint);
492                                         }
493                                         if (toolsett->sculpt) {
494                                                 library_foreach_paint(&data, &toolsett->sculpt->paint);
495                                                 CALLBACK_INVOKE(toolsett->sculpt->gravity_object, IDWALK_CB_NOP);
496                                         }
497                                         if (toolsett->uvsculpt) {
498                                                 library_foreach_paint(&data, &toolsett->uvsculpt->paint);
499                                         }
500                                         if (toolsett->gp_paint) {
501                                                 library_foreach_paint(&data, &toolsett->gp_paint->paint);
502                                         }
503
504                                         CALLBACK_INVOKE(toolsett->gp_sculpt.guide.reference_object, IDWALK_CB_NOP);
505
506                                 }
507
508                                 if (scene->rigidbody_world) {
509                                         BKE_rigidbody_world_id_loop(scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data);
510                                 }
511
512                                 break;
513                         }
514
515                         case ID_OB:
516                         {
517                                 Object *object = (Object *) id;
518                                 ParticleSystem *psys;
519
520                                 /* Object is special, proxies make things hard... */
521                                 const int data_cb_flag = data.cb_flag;
522                                 const int proxy_cb_flag = ((data.flag & IDWALK_NO_INDIRECT_PROXY_DATA_USAGE) == 0 && (object->proxy || object->proxy_group)) ?
523                                                               IDWALK_CB_INDIRECT_USAGE : 0;
524
525                                 /* object data special case */
526                                 data.cb_flag |= proxy_cb_flag;
527                                 if (object->type == OB_EMPTY) {
528                                         /* empty can have NULL or Image */
529                                         CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER);
530                                 }
531                                 else {
532                                         /* when set, this can't be NULL */
533                                         if (object->data) {
534                                                 CALLBACK_INVOKE_ID(object->data, IDWALK_CB_USER | IDWALK_CB_NEVER_NULL);
535                                         }
536                                 }
537                                 data.cb_flag = data_cb_flag;
538
539                                 CALLBACK_INVOKE(object->parent, IDWALK_CB_NOP);
540                                 CALLBACK_INVOKE(object->track, IDWALK_CB_NOP);
541                                 /* object->proxy is refcounted, but not object->proxy_group... *sigh* */
542                                 CALLBACK_INVOKE(object->proxy, IDWALK_CB_USER);
543                                 CALLBACK_INVOKE(object->proxy_group, IDWALK_CB_NOP);
544
545                                 /* Special case!
546                                  * Since this field is set/owned by 'user' of this ID (and not ID itself), it is only indirect usage
547                                  * if proxy object is linked... Twisted. */
548                                 if (object->proxy_from) {
549                                         data.cb_flag = ID_IS_LINKED(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0;
550                                 }
551                                 CALLBACK_INVOKE(object->proxy_from, IDWALK_CB_LOOPBACK);
552                                 data.cb_flag = data_cb_flag;
553
554                                 CALLBACK_INVOKE(object->poselib, IDWALK_CB_USER);
555
556                                 data.cb_flag |= proxy_cb_flag;
557                                 for (i = 0; i < object->totcol; i++) {
558                                         CALLBACK_INVOKE(object->mat[i], IDWALK_CB_USER);
559                                 }
560                                 data.cb_flag = data_cb_flag;
561
562                                 CALLBACK_INVOKE(object->gpd, IDWALK_CB_USER);
563                                 CALLBACK_INVOKE(object->dup_group, IDWALK_CB_USER);
564
565                                 if (object->pd) {
566                                         CALLBACK_INVOKE(object->pd->tex, IDWALK_CB_USER);
567                                         CALLBACK_INVOKE(object->pd->f_source, IDWALK_CB_NOP);
568                                 }
569                                 /* Note that ob->effect is deprecated, so no need to handle it here. */
570
571                                 if (object->pose) {
572                                         bPoseChannel *pchan;
573
574                                         data.cb_flag |= proxy_cb_flag;
575                                         for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
576                                                 library_foreach_idproperty_ID_link(&data, pchan->prop, IDWALK_CB_USER);
577                                                 CALLBACK_INVOKE(pchan->custom, IDWALK_CB_USER);
578                                                 BKE_constraints_id_loop(&pchan->constraints, library_foreach_constraintObjectLooper, &data);
579                                         }
580                                         data.cb_flag = data_cb_flag;
581                                 }
582
583                                 if (object->rigidbody_constraint) {
584                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob1, IDWALK_CB_NOP);
585                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob2, IDWALK_CB_NOP);
586                                 }
587
588                                 if (object->lodlevels.first) {
589                                         LodLevel *level;
590                                         for (level = object->lodlevels.first; level; level = level->next) {
591                                                 CALLBACK_INVOKE(level->source, IDWALK_CB_NOP);
592                                         }
593                                 }
594
595                                 modifiers_foreachIDLink(object, library_foreach_modifiersForeachIDLink, &data);
596                                 BKE_gpencil_modifiers_foreachIDLink(object, library_foreach_gpencil_modifiersForeachIDLink, &data);
597                                 BKE_constraints_id_loop(&object->constraints, library_foreach_constraintObjectLooper, &data);
598                                 BKE_shaderfx_foreachIDLink(object, library_foreach_shaderfxForeachIDLink, &data);
599
600                                 for (psys = object->particlesystem.first; psys; psys = psys->next) {
601                                         BKE_particlesystem_id_loop(psys, library_foreach_particlesystemsObjectLooper, &data);
602                                 }
603
604                                 if (object->soft) {
605                                         CALLBACK_INVOKE(object->soft->collision_group, IDWALK_CB_NOP);
606
607                                         if (object->soft->effector_weights) {
608                                                 CALLBACK_INVOKE(object->soft->effector_weights->group, IDWALK_CB_NOP);
609                                         }
610                                 }
611                                 break;
612                         }
613
614                         case ID_AR:
615                         {
616                                 bArmature *arm = (bArmature *)id;
617
618                                 for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
619                                         library_foreach_bone(&data, bone);
620                                 }
621                                 break;
622                         }
623
624                         case ID_ME:
625                         {
626                                 Mesh *mesh = (Mesh *) id;
627                                 CALLBACK_INVOKE(mesh->texcomesh, IDWALK_CB_USER);
628                                 CALLBACK_INVOKE(mesh->key, IDWALK_CB_USER);
629                                 for (i = 0; i < mesh->totcol; i++) {
630                                         CALLBACK_INVOKE(mesh->mat[i], IDWALK_CB_USER);
631                                 }
632                                 break;
633                         }
634
635                         case ID_CU:
636                         {
637                                 Curve *curve = (Curve *) id;
638                                 CALLBACK_INVOKE(curve->bevobj, IDWALK_CB_NOP);
639                                 CALLBACK_INVOKE(curve->taperobj, IDWALK_CB_NOP);
640                                 CALLBACK_INVOKE(curve->textoncurve, IDWALK_CB_NOP);
641                                 CALLBACK_INVOKE(curve->key, IDWALK_CB_USER);
642                                 for (i = 0; i < curve->totcol; i++) {
643                                         CALLBACK_INVOKE(curve->mat[i], IDWALK_CB_USER);
644                                 }
645                                 CALLBACK_INVOKE(curve->vfont, IDWALK_CB_USER);
646                                 CALLBACK_INVOKE(curve->vfontb, IDWALK_CB_USER);
647                                 CALLBACK_INVOKE(curve->vfonti, IDWALK_CB_USER);
648                                 CALLBACK_INVOKE(curve->vfontbi, IDWALK_CB_USER);
649                                 break;
650                         }
651
652                         case ID_MB:
653                         {
654                                 MetaBall *metaball = (MetaBall *) id;
655                                 for (i = 0; i < metaball->totcol; i++) {
656                                         CALLBACK_INVOKE(metaball->mat[i], IDWALK_CB_USER);
657                                 }
658                                 break;
659                         }
660
661                         case ID_MA:
662                         {
663                                 Material *material = (Material *) id;
664                                 if (material->nodetree) {
665                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
666                                         library_foreach_ID_as_subdata_link((ID **)&material->nodetree, callback, user_data, flag, &data);
667                                 }
668                                 if (material->texpaintslot != NULL) {
669                                         CALLBACK_INVOKE(material->texpaintslot->ima, IDWALK_CB_NOP);
670                                 }
671                                 if (material->gp_style != NULL) {
672                                         CALLBACK_INVOKE(material->gp_style->sima, IDWALK_CB_USER);
673                                         CALLBACK_INVOKE(material->gp_style->ima, IDWALK_CB_USER);
674                                 }
675                                 break;
676                         }
677
678                         case ID_TE:
679                         {
680                                 Tex *texture = (Tex *) id;
681                                 if (texture->nodetree) {
682                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
683                                         library_foreach_ID_as_subdata_link((ID **)&texture->nodetree, callback, user_data, flag, &data);
684                                 }
685                                 CALLBACK_INVOKE(texture->ima, IDWALK_CB_USER);
686                                 break;
687                         }
688
689                         case ID_LT:
690                         {
691                                 Lattice *lattice = (Lattice *) id;
692                                 CALLBACK_INVOKE(lattice->key, IDWALK_CB_USER);
693                                 break;
694                         }
695
696                         case ID_LA:
697                         {
698                                 Lamp *lamp = (Lamp *) id;
699                                 if (lamp->nodetree) {
700                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
701                                         library_foreach_ID_as_subdata_link((ID **)&lamp->nodetree, callback, user_data, flag, &data);
702                                 }
703                                 break;
704                         }
705
706                         case ID_CA:
707                         {
708                                 Camera *camera = (Camera *) id;
709                                 CALLBACK_INVOKE(camera->dof_ob, IDWALK_CB_NOP);
710                                 for (CameraBGImage *bgpic = camera->bg_images.first; bgpic; bgpic = bgpic->next) {
711                                         if (bgpic->source == CAM_BGIMG_SOURCE_IMAGE) {
712                                                 CALLBACK_INVOKE(bgpic->ima, IDWALK_CB_USER);
713                                         }
714                                         else if (bgpic->source == CAM_BGIMG_SOURCE_MOVIE) {
715                                                 CALLBACK_INVOKE(bgpic->clip, IDWALK_CB_USER);
716                                         }
717                                 }
718
719                                 break;
720                         }
721
722                         case ID_KE:
723                         {
724                                 Key *key = (Key *) id;
725                                 CALLBACK_INVOKE_ID(key->from, IDWALK_CB_LOOPBACK);
726                                 break;
727                         }
728
729                         case ID_WO:
730                         {
731                                 World *world = (World *) id;
732                                 if (world->nodetree) {
733                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
734                                         library_foreach_ID_as_subdata_link((ID **)&world->nodetree, callback, user_data, flag, &data);
735                                 }
736                                 break;
737                         }
738
739                         case ID_SPK:
740                         {
741                                 Speaker *speaker = (Speaker *) id;
742                                 CALLBACK_INVOKE(speaker->sound, IDWALK_CB_USER);
743                                 break;
744                         }
745
746                         case ID_LP:
747                         {
748                                 LightProbe *probe = (LightProbe *) id;
749                                 CALLBACK_INVOKE(probe->image, IDWALK_CB_USER);
750                                 CALLBACK_INVOKE(probe->visibility_grp, IDWALK_CB_NOP);
751                                 break;
752                         }
753
754                         case ID_GR:
755                         {
756                                 Collection *collection = (Collection *) id;
757                                 for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
758                                         CALLBACK_INVOKE(cob->ob, IDWALK_CB_USER);
759                                 }
760                                 for (CollectionChild *child = collection->children.first; child; child = child->next) {
761                                         CALLBACK_INVOKE(child->collection, IDWALK_CB_USER);
762                                 }
763                                 for (CollectionParent *parent = collection->parents.first; parent; parent = parent->next) {
764                                         CALLBACK_INVOKE(parent->collection, IDWALK_CB_NOP);
765                                 }
766                                 break;
767                         }
768
769                         case ID_NT:
770                         {
771                                 bNodeTree *ntree = (bNodeTree *) id;
772                                 bNode *node;
773                                 bNodeSocket *sock;
774
775                                 CALLBACK_INVOKE(ntree->gpd, IDWALK_CB_USER);
776
777                                 for (node = ntree->nodes.first; node; node = node->next) {
778                                         CALLBACK_INVOKE_ID(node->id, IDWALK_CB_USER);
779
780                                         library_foreach_idproperty_ID_link(&data, node->prop, IDWALK_CB_USER);
781                                         for (sock = node->inputs.first; sock; sock = sock->next) {
782                                                 library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
783                                         }
784                                         for (sock = node->outputs.first; sock; sock = sock->next) {
785                                                 library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
786                                         }
787                                 }
788
789                                 for (sock = ntree->inputs.first; sock; sock = sock->next) {
790                                         library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
791                                 }
792                                 for (sock = ntree->outputs.first; sock; sock = sock->next) {
793                                         library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
794                                 }
795                                 break;
796                         }
797
798                         case ID_BR:
799                         {
800                                 Brush *brush = (Brush *) id;
801                                 CALLBACK_INVOKE(brush->toggle_brush, IDWALK_CB_NOP);
802                                 CALLBACK_INVOKE(brush->clone.image, IDWALK_CB_NOP);
803                                 CALLBACK_INVOKE(brush->paint_curve, IDWALK_CB_USER);
804                                 if (brush->gpencil_settings) {
805                                         CALLBACK_INVOKE(brush->gpencil_settings->material, IDWALK_CB_USER);
806                                 }
807                                 library_foreach_mtex(&data, &brush->mtex);
808                                 library_foreach_mtex(&data, &brush->mask_mtex);
809                                 break;
810                         }
811
812                         case ID_PA:
813                         {
814                                 ParticleSettings *psett = (ParticleSettings *) id;
815                                 CALLBACK_INVOKE(psett->dup_group, IDWALK_CB_NOP);
816                                 CALLBACK_INVOKE(psett->dup_ob, IDWALK_CB_NOP);
817                                 CALLBACK_INVOKE(psett->bb_ob, IDWALK_CB_NOP);
818                                 CALLBACK_INVOKE(psett->collision_group, IDWALK_CB_NOP);
819
820                                 for (i = 0; i < MAX_MTEX; i++) {
821                                         if (psett->mtex[i]) {
822                                                 library_foreach_mtex(&data, psett->mtex[i]);
823                                         }
824                                 }
825
826                                 if (psett->effector_weights) {
827                                         CALLBACK_INVOKE(psett->effector_weights->group, IDWALK_CB_NOP);
828                                 }
829
830                                 if (psett->pd) {
831                                         CALLBACK_INVOKE(psett->pd->tex, IDWALK_CB_USER);
832                                         CALLBACK_INVOKE(psett->pd->f_source, IDWALK_CB_NOP);
833                                 }
834                                 if (psett->pd2) {
835                                         CALLBACK_INVOKE(psett->pd2->tex, IDWALK_CB_USER);
836                                         CALLBACK_INVOKE(psett->pd2->f_source, IDWALK_CB_NOP);
837                                 }
838
839                                 if (psett->boids) {
840                                         BoidState *state;
841                                         BoidRule *rule;
842
843                                         for (state = psett->boids->states.first; state; state = state->next) {
844                                                 for (rule = state->rules.first; rule; rule = rule->next) {
845                                                         if (rule->type == eBoidRuleType_Avoid) {
846                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
847                                                                 CALLBACK_INVOKE(gabr->ob, IDWALK_CB_NOP);
848                                                         }
849                                                         else if (rule->type == eBoidRuleType_FollowLeader) {
850                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
851                                                                 CALLBACK_INVOKE(flbr->ob, IDWALK_CB_NOP);
852                                                         }
853                                                 }
854                                         }
855                                 }
856
857                                 for (ParticleDupliWeight *dw = psett->dupliweights.first; dw; dw = dw->next) {
858                                         CALLBACK_INVOKE(dw->ob, IDWALK_CB_NOP);
859                                 }
860                                 break;
861                         }
862
863                         case ID_MC:
864                         {
865                                 MovieClip *clip = (MovieClip *) id;
866                                 MovieTracking *tracking = &clip->tracking;
867                                 MovieTrackingObject *object;
868                                 MovieTrackingTrack *track;
869                                 MovieTrackingPlaneTrack *plane_track;
870
871                                 CALLBACK_INVOKE(clip->gpd, IDWALK_CB_USER);
872
873                                 for (track = tracking->tracks.first; track; track = track->next) {
874                                         CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
875                                 }
876                                 for (object = tracking->objects.first; object; object = object->next) {
877                                         for (track = object->tracks.first; track; track = track->next) {
878                                                 CALLBACK_INVOKE(track->gpd, IDWALK_CB_USER);
879                                         }
880                                 }
881
882                                 for (plane_track = tracking->plane_tracks.first; plane_track; plane_track = plane_track->next) {
883                                         CALLBACK_INVOKE(plane_track->image, IDWALK_CB_USER);
884                                 }
885                                 break;
886                         }
887
888                         case ID_MSK:
889                         {
890                                 Mask *mask = (Mask *) id;
891                                 MaskLayer *mask_layer;
892                                 for (mask_layer = mask->masklayers.first; mask_layer; mask_layer = mask_layer->next) {
893                                         MaskSpline *mask_spline;
894
895                                         for (mask_spline = mask_layer->splines.first; mask_spline; mask_spline = mask_spline->next) {
896                                                 for (i = 0; i < mask_spline->tot_point; i++) {
897                                                         MaskSplinePoint *point = &mask_spline->points[i];
898                                                         CALLBACK_INVOKE_ID(point->parent.id, IDWALK_CB_USER);
899                                                 }
900                                         }
901                                 }
902                                 break;
903                         }
904
905                         case ID_LS:
906                         {
907                                 FreestyleLineStyle *linestyle = (FreestyleLineStyle *) id;
908                                 LineStyleModifier *lsm;
909                                 for (i = 0; i < MAX_MTEX; i++) {
910                                         if (linestyle->mtex[i]) {
911                                                 library_foreach_mtex(&data, linestyle->mtex[i]);
912                                         }
913                                 }
914                                 if (linestyle->nodetree) {
915                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
916                                         library_foreach_ID_as_subdata_link((ID **)&linestyle->nodetree, callback, user_data, flag, &data);
917                                 }
918
919                                 for (lsm = linestyle->color_modifiers.first; lsm; lsm = lsm->next) {
920                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
921                                                 LineStyleColorModifier_DistanceFromObject *p = (LineStyleColorModifier_DistanceFromObject *)lsm;
922                                                 if (p->target) {
923                                                         CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
924                                                 }
925                                         }
926                                 }
927                                 for (lsm = linestyle->alpha_modifiers.first; lsm; lsm = lsm->next) {
928                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
929                                                 LineStyleAlphaModifier_DistanceFromObject *p = (LineStyleAlphaModifier_DistanceFromObject *)lsm;
930                                                 if (p->target) {
931                                                         CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
932                                                 }
933                                         }
934                                 }
935                                 for (lsm = linestyle->thickness_modifiers.first; lsm; lsm = lsm->next) {
936                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
937                                                 LineStyleThicknessModifier_DistanceFromObject *p = (LineStyleThicknessModifier_DistanceFromObject *)lsm;
938                                                 if (p->target) {
939                                                         CALLBACK_INVOKE(p->target, IDWALK_CB_NOP);
940                                                 }
941                                         }
942                                 }
943                                 break;
944                         }
945                         case ID_AC:
946                         {
947                                 bAction *act = (bAction *) id;
948
949                                 for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
950                                         CALLBACK_INVOKE(marker->camera, IDWALK_CB_NOP);
951                                 }
952                                 break;
953                         }
954
955                         case ID_WM:
956                         {
957                                 wmWindowManager *wm = (wmWindowManager *)id;
958
959                                 for (wmWindow *win = wm->windows.first; win; win = win->next) {
960                                         ID *workspace = (ID *)BKE_workspace_active_get(win->workspace_hook);
961
962                                         CALLBACK_INVOKE(win->scene, IDWALK_CB_USER_ONE);
963
964                                         CALLBACK_INVOKE_ID(workspace, IDWALK_CB_NOP);
965                                         /* allow callback to set a different workspace */
966                                         BKE_workspace_active_set(win->workspace_hook, (WorkSpace *)workspace);
967                                 }
968                                 break;
969                         }
970
971                         case ID_WS:
972                         {
973                                 WorkSpace *workspace = (WorkSpace *)id;
974                                 ListBase *layouts = BKE_workspace_layouts_get(workspace);
975
976                                 for (WorkSpaceLayout *layout = layouts->first; layout; layout = layout->next) {
977                                         bScreen *screen = BKE_workspace_layout_screen_get(layout);
978
979                                         /* CALLBACK_INVOKE expects an actual pointer, not a variable holding the pointer.
980                                          * However we can't access layout->screen here since we are outside the workspace project. */
981                                         CALLBACK_INVOKE(screen, IDWALK_CB_USER);
982                                         /* allow callback to set a different screen */
983                                         BKE_workspace_layout_screen_set(layout, screen);
984                                 }
985                                 break;
986                         }
987                         case ID_GD:
988                         {
989                                 bGPdata *gpencil = (bGPdata *) id;
990                                 /* materials */
991                                 for (i = 0; i < gpencil->totcol; i++) {
992                                         CALLBACK_INVOKE(gpencil->mat[i], IDWALK_CB_USER);
993                                 }
994
995                                 for (bGPDlayer *gplayer = gpencil->layers.first; gplayer != NULL; gplayer = gplayer->next) {
996                                         CALLBACK_INVOKE(gplayer->parent, IDWALK_CB_NOP);
997                                 }
998
999                                 break;
1000                         }
1001
1002                         /* Nothing needed for those... */
1003                         case ID_SCR:
1004                         case ID_IM:
1005                         case ID_VF:
1006                         case ID_TXT:
1007                         case ID_SO:
1008                         case ID_PAL:
1009                         case ID_PC:
1010                         case ID_CF:
1011                                 break;
1012
1013                         /* Deprecated. */
1014                         case ID_IP:
1015                                 break;
1016
1017                 }
1018         }
1019
1020 FOREACH_FINALIZE:
1021         if (data.ids_handled) {
1022                 BLI_gset_free(data.ids_handled, NULL);
1023                 BLI_LINKSTACK_FREE(data.ids_todo);
1024         }
1025
1026 #undef CALLBACK_INVOKE_ID
1027 #undef CALLBACK_INVOKE
1028 }
1029
1030 #undef FOREACH_CALLBACK_INVOKE_ID
1031 #undef FOREACH_CALLBACK_INVOKE
1032
1033 /**
1034  * re-usable function, use when replacing ID's
1035  */
1036 void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cb_flag)
1037 {
1038         if (cb_flag & IDWALK_CB_USER) {
1039                 id_us_min(id_src);
1040                 id_us_plus(id_dst);
1041         }
1042         else if (cb_flag & IDWALK_CB_USER_ONE) {
1043                 id_us_ensure_real(id_dst);
1044         }
1045 }
1046
1047 /**
1048  * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used.
1049  *
1050  * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above, quite useful to reduce
1051  * useless iterations in some cases.
1052  */
1053 /* XXX This has to be fully rethink, basing check on ID type is not really working anymore (and even worth once
1054  *     IDProps will support ID pointers), we'll have to do some quick checks on IDs themselves... */
1055 bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used)
1056 {
1057         /* any type of ID can be used in custom props. */
1058         if (id_owner->properties) {
1059                 return true;
1060         }
1061
1062         const short id_type_owner = GS(id_owner->name);
1063
1064         /* IDProps of armature bones and nodes, and bNode->id can use virtually any type of ID. */
1065         if (ELEM(id_type_owner, ID_NT, ID_AR)) {
1066                 return true;
1067         }
1068
1069         if (ntreeFromID(id_owner)) {
1070                 return true;
1071         }
1072
1073         if (BKE_animdata_from_id(id_owner)) {
1074                 return true;  /* AnimationData can use virtually any kind of datablocks, through drivers especially. */
1075         }
1076
1077         switch ((ID_Type)id_type_owner) {
1078                 case ID_LI:
1079                         return ELEM(id_type_used, ID_LI);
1080                 case ID_SCE:
1081                         return (ELEM(id_type_used, ID_OB, ID_WO, ID_SCE, ID_MC, ID_MA, ID_GR, ID_TXT,
1082                                                    ID_LS, ID_MSK, ID_SO, ID_GD, ID_BR, ID_PAL, ID_IM, ID_NT));
1083                 case ID_OB:
1084                         /* Could be more specific, but simpler to just always say 'yes' here. */
1085                         return true;
1086                 case ID_ME:
1087                         return ELEM(id_type_used, ID_ME, ID_KE, ID_MA, ID_IM);
1088                 case ID_CU:
1089                         return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
1090                 case ID_MB:
1091                         return ELEM(id_type_used, ID_MA);
1092                 case ID_MA:
1093                         return (ELEM(id_type_used, ID_TE, ID_GR));
1094                 case ID_TE:
1095                         return (ELEM(id_type_used, ID_IM, ID_OB));
1096                 case ID_LT:
1097                         return ELEM(id_type_used, ID_KE);
1098                 case ID_LA:
1099                         return (ELEM(id_type_used, ID_TE));
1100                 case ID_CA:
1101                         return ELEM(id_type_used, ID_OB);
1102                 case ID_KE:
1103                         return ELEM(id_type_used, ID_ME, ID_CU, ID_LT);  /* Warning! key->from, could be more types in future? */
1104                 case ID_SCR:
1105                         return ELEM(id_type_used, ID_SCE);
1106                 case ID_WO:
1107                         return (ELEM(id_type_used, ID_TE));
1108                 case ID_SPK:
1109                         return ELEM(id_type_used, ID_SO);
1110                 case ID_GR:
1111                         return ELEM(id_type_used, ID_OB, ID_GR);
1112                 case ID_NT:
1113                         /* Could be more specific, but node.id has no type restriction... */
1114                         return true;
1115                 case ID_BR:
1116                         return ELEM(id_type_used, ID_BR, ID_IM, ID_PC, ID_TE, ID_MA);
1117                 case ID_PA:
1118                         return ELEM(id_type_used, ID_OB, ID_GR, ID_TE);
1119                 case ID_MC:
1120                         return ELEM(id_type_used, ID_GD, ID_IM);
1121                 case ID_MSK:
1122                         return ELEM(id_type_used, ID_MC);  /* WARNING! mask->parent.id, not typed. */
1123                 case ID_LS:
1124                         return (ELEM(id_type_used, ID_TE, ID_OB));
1125                 case ID_LP:
1126                         return ELEM(id_type_used, ID_IM);
1127                 case ID_GD:
1128                         return ELEM(id_type_used, ID_MA);
1129                 case ID_WS:
1130                         return ELEM(id_type_used, ID_SCR, ID_SCE);
1131                 case ID_IM:
1132                 case ID_VF:
1133                 case ID_TXT:
1134                 case ID_SO:
1135                 case ID_AR:
1136                 case ID_AC:
1137                 case ID_WM:
1138                 case ID_PAL:
1139                 case ID_PC:
1140                 case ID_CF:
1141                         /* Those types never use/reference other IDs... */
1142                         return false;
1143                 case ID_IP:
1144                         /* Deprecated... */
1145                         return false;
1146         }
1147         return false;
1148 }
1149
1150
1151 /* ***** ID users iterator. ***** */
1152 typedef struct IDUsersIter {
1153         ID *id;
1154
1155         ListBase *lb_array[MAX_LIBARRAY];
1156         int lb_idx;
1157
1158         ID *curr_id;
1159         int count_direct, count_indirect;  /* Set by callback. */
1160 } IDUsersIter;
1161
1162 static int foreach_libblock_id_users_callback(void *user_data, ID *UNUSED(self_id), ID **id_p, int cb_flag)
1163 {
1164         IDUsersIter *iter = user_data;
1165
1166         if (*id_p) {
1167                 /* 'Loopback' ID pointers (the ugly 'from' ones, Object->proxy_from and Key->from).
1168                  * Those are not actually ID usage, we can ignore them here.
1169                  */
1170                 if (cb_flag & IDWALK_CB_LOOPBACK) {
1171                         return IDWALK_RET_NOP;
1172                 }
1173
1174                 if (*id_p == iter->id) {
1175 #if 0
1176                         printf("%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, indirect_usage: %d)\n",
1177                                    iter->curr_id->name, iter->id->name, (cb_flag & IDWALK_USER) ? 1 : 0, (cb_flag & IDWALK_USER_ONE) ? 1 : 0,
1178                                    (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0, (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0,
1179                                    (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0);
1180 #endif
1181                         if (cb_flag & IDWALK_CB_INDIRECT_USAGE) {
1182                                 iter->count_indirect++;
1183                         }
1184                         else {
1185                                 iter->count_direct++;
1186                         }
1187                 }
1188         }
1189
1190         return IDWALK_RET_NOP;
1191 }
1192
1193 /**
1194  * Return the number of times given \a id_user uses/references \a id_used.
1195  *
1196  * \note This only checks for pointer references of an ID, shallow usages (like e.g. by RNA paths, as done
1197  *       for FCurves) are not detected at all.
1198  *
1199  * \param id_user: the ID which is supposed to use (reference) \a id_used.
1200  * \param id_used: the ID which is supposed to be used (referenced) by \a id_user.
1201  * \return the number of direct usages/references of \a id_used by \a id_user.
1202  */
1203 int BKE_library_ID_use_ID(ID *id_user, ID *id_used)
1204 {
1205         IDUsersIter iter;
1206
1207         /* We do not care about iter.lb_array/lb_idx here... */
1208         iter.id = id_used;
1209         iter.curr_id = id_user;
1210         iter.count_direct = iter.count_indirect = 0;
1211
1212         BKE_library_foreach_ID_link(NULL, iter.curr_id, foreach_libblock_id_users_callback, (void *)&iter, IDWALK_READONLY);
1213
1214         return iter.count_direct + iter.count_indirect;
1215 }
1216
1217 static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
1218 {
1219         IDUsersIter iter;
1220         ListBase *lb_array[MAX_LIBARRAY];
1221         ID *id = idv;
1222         int i = set_listbasepointers(bmain, lb_array);
1223         bool is_defined = false;
1224
1225         iter.id = id;
1226         iter.count_direct = iter.count_indirect = 0;
1227         while (i-- && !is_defined) {
1228                 ID *id_curr = lb_array[i]->first;
1229
1230                 if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1231                         continue;
1232                 }
1233
1234                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
1235                         if (id_curr == id) {
1236                                 /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1237                                 continue;
1238                         }
1239                         iter.curr_id = id_curr;
1240                         BKE_library_foreach_ID_link(
1241                                     bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1242
1243                         is_defined = ((check_linked ? iter.count_indirect : iter.count_direct) != 0);
1244                 }
1245         }
1246
1247         return is_defined;
1248 }
1249
1250 /**
1251  * Check whether given ID is used locally (i.e. by another non-linked ID).
1252  */
1253 bool BKE_library_ID_is_locally_used(Main *bmain, void *idv)
1254 {
1255         return library_ID_is_used(bmain, idv, false);
1256 }
1257
1258 /**
1259  * Check whether given ID is used indirectly (i.e. by another linked ID).
1260  */
1261 bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv)
1262 {
1263         return library_ID_is_used(bmain, idv, true);
1264 }
1265
1266 /**
1267  * Combine \a BKE_library_ID_is_locally_used() and \a BKE_library_ID_is_indirectly_used() in a single call.
1268  */
1269 void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked)
1270 {
1271         IDUsersIter iter;
1272         ListBase *lb_array[MAX_LIBARRAY];
1273         ID *id = idv;
1274         int i = set_listbasepointers(bmain, lb_array);
1275         bool is_defined = false;
1276
1277         iter.id = id;
1278         iter.count_direct = iter.count_indirect = 0;
1279         while (i-- && !is_defined) {
1280                 ID *id_curr = lb_array[i]->first;
1281
1282                 if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
1283                         continue;
1284                 }
1285
1286                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
1287                         if (id_curr == id) {
1288                                 /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1289                                 continue;
1290                         }
1291                         iter.curr_id = id_curr;
1292                         BKE_library_foreach_ID_link(bmain, id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_READONLY);
1293
1294                         is_defined = (iter.count_direct != 0 && iter.count_indirect != 0);
1295                 }
1296         }
1297
1298         *is_used_local = (iter.count_direct != 0);
1299         *is_used_linked = (iter.count_indirect != 0);
1300 }
1301
1302 /* ***** IDs usages.checking/tagging. ***** */
1303 static int foreach_libblock_used_linked_data_tag_clear_cb(
1304         void *user_data, ID *self_id, ID **id_p, int UNUSED(cb_flag))
1305 {
1306         bool *is_changed = user_data;
1307
1308         if (*id_p) {
1309                 /* XXX This is actually some kind of hack...
1310                  * Issue is, shapekeys' 'from' ID pointer is not actually ID usage.
1311                  * Maybe we should even nuke it from BKE_library_foreach_ID_link, not 100% sure yet...
1312                  */
1313                 if ((GS(self_id->name) == ID_KE) && (((Key *)self_id)->from == *id_p)) {
1314                         return IDWALK_RET_NOP;
1315                 }
1316                 /* XXX another hack, for similar reasons as above one. */
1317                 if ((GS(self_id->name) == ID_OB) && (((Object *)self_id)->proxy_from == (Object *)*id_p)) {
1318                         return IDWALK_RET_NOP;
1319                 }
1320
1321                 /* If checked id is used by an assumed used ID, then it is also used and not part of any linked archipelago. */
1322                 if (!(self_id->tag & LIB_TAG_DOIT) && ((*id_p)->tag & LIB_TAG_DOIT)) {
1323                         (*id_p)->tag &= ~LIB_TAG_DOIT;
1324                         *is_changed = true;
1325                 }
1326         }
1327
1328         return IDWALK_RET_NOP;
1329 }
1330
1331 /**
1332  * Detect orphaned linked data blocks (i.e. linked data not used (directly or indirectly) in any way by any local data),
1333  * including complex cases like 'linked archipelagoes', i.e. linked datablocks that use each other in loops,
1334  * which prevents their deletion by 'basic' usage checks...
1335  *
1336  * \param do_init_tag: if \a true, all linked data are checked, if \a false, only linked datablocks already tagged with
1337  *                    LIB_TAG_DOIT are checked.
1338  */
1339 void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag)
1340 {
1341         ListBase *lb_array[MAX_LIBARRAY];
1342
1343         if (do_init_tag) {
1344                 int i = set_listbasepointers(bmain, lb_array);
1345
1346                 while (i--) {
1347                         for (ID *id = lb_array[i]->first; id; id = id->next) {
1348                                 if (id->lib && (id->tag & LIB_TAG_INDIRECT) != 0) {
1349                                         id->tag |= LIB_TAG_DOIT;
1350                                 }
1351                                 else {
1352                                         id->tag &= ~LIB_TAG_DOIT;
1353                                 }
1354                         }
1355                 }
1356         }
1357
1358         bool do_loop = true;
1359         while (do_loop) {
1360                 int i = set_listbasepointers(bmain, lb_array);
1361                 do_loop = false;
1362
1363                 while (i--) {
1364                         for (ID *id = lb_array[i]->first; id; id = id->next) {
1365                                 if (id->tag & LIB_TAG_DOIT) {
1366                                         /* Unused ID (so far), no need to check it further. */
1367                                         continue;
1368                                 }
1369                                 BKE_library_foreach_ID_link(
1370                                             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1371                         }
1372                 }
1373         }
1374 }
1375
1376 /**
1377  * Untag linked data blocks used by other untagged linked datablocks.
1378  * Used to detect datablocks that we can forcefully make local (instead of copying them to later get rid of original):
1379  * All datablocks we want to make local are tagged by caller, after this function has ran caller knows datablocks still
1380  * tagged can directly be made local, since they are only used by other datablocks that will also be made fully local.
1381  */
1382 void BKE_library_indirectly_used_data_tag_clear(Main *bmain)
1383 {
1384         ListBase *lb_array[MAX_LIBARRAY];
1385
1386         bool do_loop = true;
1387         while (do_loop) {
1388                 int i = set_listbasepointers(bmain, lb_array);
1389                 do_loop = false;
1390
1391                 while (i--) {
1392                         for (ID *id = lb_array[i]->first; id; id = id->next) {
1393                                 if (id->lib == NULL || id->tag & LIB_TAG_DOIT) {
1394                                         /* Local or non-indirectly-used ID (so far), no need to check it further. */
1395                                         continue;
1396                                 }
1397                                 BKE_library_foreach_ID_link(
1398                                             bmain, id, foreach_libblock_used_linked_data_tag_clear_cb, &do_loop, IDWALK_READONLY);
1399                         }
1400                 }
1401         }
1402 }