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