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