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_brush_types.h"
37 #include "DNA_camera_types.h"
38 #include "DNA_constraint_types.h"
39 #include "DNA_controller_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_gpencil_types.h"
42 #include "DNA_key_types.h"
43 #include "DNA_lamp_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_linestyle_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_mesh_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_meta_types.h"
50 #include "DNA_movieclip_types.h"
51 #include "DNA_mask_types.h"
52 #include "DNA_node_types.h"
53 #include "DNA_object_force.h"
54 #include "DNA_object_types.h"
55 #include "DNA_rigidbody_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_sensor_types.h"
58 #include "DNA_sequence_types.h"
59 #include "DNA_screen_types.h"
60 #include "DNA_speaker_types.h"
61 #include "DNA_sound_types.h"
62 #include "DNA_text_types.h"
63 #include "DNA_vfont_types.h"
64 #include "DNA_world_types.h"
65
66 #include "BLI_utildefines.h"
67 #include "BLI_ghash.h"
68 #include "BLI_linklist_stack.h"
69
70 #include "BKE_animsys.h"
71 #include "BKE_constraint.h"
72 #include "BKE_fcurve.h"
73 #include "BKE_library.h"
74 #include "BKE_library_query.h"
75 #include "BKE_main.h"
76 #include "BKE_modifier.h"
77 #include "BKE_rigidbody.h"
78 #include "BKE_sca.h"
79 #include "BKE_sequencer.h"
80 #include "BKE_tracking.h"
81
82
83 #define FOREACH_FINALIZE _finalize
84 #define FOREACH_FINALIZE_VOID FOREACH_FINALIZE: (void)0
85
86 #define FOREACH_CALLBACK_INVOKE_ID_PP(_data, id_pp, cb_flag) \
87         if (!((_data)->status & IDWALK_STOP)) { \
88                 const int _flag = (_data)->flag; \
89                 ID *old_id = *(id_pp); \
90                 const int callback_return = (_data)->callback((_data)->user_data, (_data)->self_id, id_pp, cb_flag | (_data)->cd_flag); \
91                 if (_flag & IDWALK_READONLY) { \
92                         BLI_assert(*(id_pp) == old_id); \
93                 } \
94                 if (old_id && (_flag & IDWALK_RECURSE)) { \
95                         if (!BLI_gset_haskey((_data)->ids_handled, old_id)) { \
96                                 BLI_gset_add((_data)->ids_handled, old_id); \
97                                 if (!(callback_return & IDWALK_RET_STOP_RECURSION)) { \
98                                         BLI_LINKSTACK_PUSH((_data)->ids_todo, old_id); \
99                                 } \
100                         } \
101                 } \
102                 if (callback_return & IDWALK_RET_STOP_ITER) { \
103                         (_data)->status |= IDWALK_STOP; \
104                         goto FOREACH_FINALIZE; \
105                 } \
106         } \
107         else { \
108                 goto FOREACH_FINALIZE; \
109         } ((void)0)
110
111 #define FOREACH_CALLBACK_INVOKE_ID(_data, id, cb_flag) \
112         { \
113                 CHECK_TYPE_ANY(id, ID *, void *); \
114                 FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id), cb_flag); \
115         } ((void)0)
116
117 #define FOREACH_CALLBACK_INVOKE(_data, id_super, cb_flag) \
118         { \
119                 CHECK_TYPE(&((id_super)->id), ID *); \
120                 FOREACH_CALLBACK_INVOKE_ID_PP(_data, (ID **)&(id_super), cb_flag); \
121         } ((void)0)
122
123 /* status */
124 enum {
125         IDWALK_STOP     = 1 << 0,
126 };
127
128 typedef struct LibraryForeachIDData {
129         ID *self_id;
130         int flag;
131         int cd_flag;
132         LibraryIDLinkCallback callback;
133         void *user_data;
134         int status;
135
136         /* To handle recursion. */
137         GSet *ids_handled;  /* All IDs that are either already done, or still in ids_todo stack. */
138         BLI_LINKSTACK_DECLARE(ids_todo, ID *);
139 } LibraryForeachIDData;
140
141 static void library_foreach_rigidbodyworldSceneLooper(
142         struct RigidBodyWorld *UNUSED(rbw), ID **id_pointer, void *user_data, int cd_flag)
143 {
144         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
145         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
146
147         FOREACH_FINALIZE_VOID;
148 }
149
150 static void library_foreach_modifiersForeachIDLink(
151         void *user_data, Object *UNUSED(object), ID **id_pointer, int cd_flag)
152 {
153         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
154         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
155
156         FOREACH_FINALIZE_VOID;
157 }
158
159 static void library_foreach_constraintObjectLooper(bConstraint *UNUSED(con), ID **id_pointer,
160                                                    bool is_reference, void *user_data)
161 {
162         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
163         const int cd_flag = is_reference ? IDWALK_USER : IDWALK_NOP;
164         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
165
166         FOREACH_FINALIZE_VOID;
167 }
168
169 static void library_foreach_sensorsObjectLooper(
170         bSensor *UNUSED(sensor), ID **id_pointer, void *user_data, int cd_flag)
171 {
172         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
173         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
174
175         FOREACH_FINALIZE_VOID;
176 }
177
178 static void library_foreach_controllersObjectLooper(
179         bController *UNUSED(controller), ID **id_pointer, void *user_data, int cd_flag)
180 {
181         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
182         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
183
184         FOREACH_FINALIZE_VOID;
185 }
186
187 static void library_foreach_actuatorsObjectLooper(
188         bActuator *UNUSED(actuator), ID **id_pointer, void *user_data, int cd_flag)
189 {
190         LibraryForeachIDData *data = (LibraryForeachIDData *) user_data;
191         FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cd_flag);
192
193         FOREACH_FINALIZE_VOID;
194 }
195
196 static void library_foreach_nla_strip(LibraryForeachIDData *data, NlaStrip *strip)
197 {
198         NlaStrip *substrip;
199
200         FOREACH_CALLBACK_INVOKE(data, strip->act, IDWALK_USER);
201
202         for (substrip = strip->strips.first; substrip; substrip = substrip->next) {
203                 library_foreach_nla_strip(data, substrip);
204         }
205
206         FOREACH_FINALIZE_VOID;
207 }
208
209 static void library_foreach_animationData(LibraryForeachIDData *data, AnimData *adt)
210 {
211         FCurve *fcu;
212         NlaTrack *nla_track;
213         NlaStrip *nla_strip;
214
215         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
216                 ChannelDriver *driver = fcu->driver;
217                 DriverVar *dvar;
218
219                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
220                         /* only used targets */
221                         DRIVER_TARGETS_USED_LOOPER(dvar)
222                         {
223                                 FOREACH_CALLBACK_INVOKE_ID(data, dtar->id, IDWALK_NOP);
224                         }
225                         DRIVER_TARGETS_LOOPER_END
226                 }
227         }
228
229         FOREACH_CALLBACK_INVOKE(data, adt->action, IDWALK_USER);
230         FOREACH_CALLBACK_INVOKE(data, adt->tmpact, IDWALK_USER);
231
232         for (nla_track = adt->nla_tracks.first; nla_track; nla_track = nla_track->next) {
233                 for (nla_strip = nla_track->strips.first; nla_strip; nla_strip = nla_strip->next) {
234                         library_foreach_nla_strip(data, nla_strip);
235                 }
236         }
237
238         FOREACH_FINALIZE_VOID;
239 }
240
241 static void library_foreach_mtex(LibraryForeachIDData *data, MTex *mtex)
242 {
243         FOREACH_CALLBACK_INVOKE(data, mtex->object, IDWALK_NOP);
244         FOREACH_CALLBACK_INVOKE(data, mtex->tex, IDWALK_USER);
245
246         FOREACH_FINALIZE_VOID;
247 }
248
249 static void library_foreach_paint(LibraryForeachIDData *data, Paint *paint)
250 {
251         FOREACH_CALLBACK_INVOKE(data, paint->brush, IDWALK_USER);
252         FOREACH_CALLBACK_INVOKE(data, paint->palette, IDWALK_USER);
253
254         FOREACH_FINALIZE_VOID;
255 }
256
257
258 /**
259  * Loop over all of the ID's this datablock links to.
260  *
261  * \note: May be extended to be recursive in the future.
262  */
263 void BKE_library_foreach_ID_link(ID *id, LibraryIDLinkCallback callback, void *user_data, int flag)
264 {
265         LibraryForeachIDData data;
266         int i;
267
268         if (flag & IDWALK_RECURSE) {
269                 /* For now, recusion implies read-only. */
270                 flag |= IDWALK_READONLY;
271
272                 data.ids_handled = BLI_gset_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
273                 BLI_LINKSTACK_INIT(data.ids_todo);
274         }
275         else {
276                 data.ids_handled = NULL;
277         }
278         data.flag = flag;
279         data.status = 0;
280         data.callback = callback;
281         data.user_data = user_data;
282
283 #define CALLBACK_INVOKE_ID(check_id, cb_flag) \
284         FOREACH_CALLBACK_INVOKE_ID(&data, check_id, cb_flag)
285
286 #define CALLBACK_INVOKE(check_id_super, cb_flag) \
287         FOREACH_CALLBACK_INVOKE(&data, check_id_super, cb_flag)
288
289         do {
290                 data.self_id = id;
291                 data.cd_flag = ID_IS_LINKED_DATABLOCK(id) ? IDWALK_INDIRECT_USAGE : 0;
292
293                 AnimData *adt = BKE_animdata_from_id(id);
294                 if (adt) {
295                         library_foreach_animationData(&data, adt);
296                 }
297
298                 switch (GS(id->name)) {
299                         case ID_LI:
300                         {
301                                 Library *lib = (Library *) id;
302                                 CALLBACK_INVOKE(lib->parent, IDWALK_NOP);
303                                 break;
304                         }
305                         case ID_SCE:
306                         {
307                                 Scene *scene = (Scene *) id;
308                                 ToolSettings *toolsett = scene->toolsettings;
309                                 SceneRenderLayer *srl;
310                                 Base *base;
311
312                                 CALLBACK_INVOKE(scene->camera, IDWALK_NOP);
313                                 CALLBACK_INVOKE(scene->world, IDWALK_USER);
314                                 CALLBACK_INVOKE(scene->set, IDWALK_NOP);
315                                 CALLBACK_INVOKE(scene->clip, IDWALK_USER);
316                                 if (scene->nodetree) {
317                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
318                                         BKE_library_foreach_ID_link((ID *)scene->nodetree, callback, user_data, flag);
319                                 }
320                                 /* DO NOT handle scene->basact here, it's doubling with the loop over whole scene->base later,
321                                  * since basact is just a pointer to one of those items. */
322                                 CALLBACK_INVOKE(scene->obedit, IDWALK_NOP);
323
324                                 for (srl = scene->r.layers.first; srl; srl = srl->next) {
325                                         FreestyleModuleConfig *fmc;
326                                         FreestyleLineSet *fls;
327
328                                         if (srl->mat_override) {
329                                                 CALLBACK_INVOKE(srl->mat_override, IDWALK_USER);
330                                         }
331                                         if (srl->light_override) {
332                                                 CALLBACK_INVOKE(srl->light_override, IDWALK_USER);
333                                         }
334                                         for (fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
335                                                 if (fmc->script) {
336                                                         CALLBACK_INVOKE(fmc->script, IDWALK_NOP);
337                                                 }
338                                         }
339                                         for (fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
340                                                 if (fls->group) {
341                                                         CALLBACK_INVOKE(fls->group, IDWALK_USER);
342                                                 }
343                                                 if (fls->linestyle) {
344                                                         CALLBACK_INVOKE(fls->linestyle, IDWALK_USER);
345                                                 }
346                                         }
347                                 }
348
349                                 if (scene->ed) {
350                                         Sequence *seq;
351                                         SEQP_BEGIN(scene->ed, seq)
352                                         {
353                                                 CALLBACK_INVOKE(seq->scene, IDWALK_NOP);
354                                                 CALLBACK_INVOKE(seq->scene_camera, IDWALK_NOP);
355                                                 CALLBACK_INVOKE(seq->clip, IDWALK_USER);
356                                                 CALLBACK_INVOKE(seq->mask, IDWALK_USER);
357                                                 CALLBACK_INVOKE(seq->sound, IDWALK_USER);
358                                                 for (SequenceModifierData *smd = seq->modifiers.first; smd; smd = smd->next) {
359                                                         CALLBACK_INVOKE(smd->mask_id, IDWALK_USER);
360                                                 }
361                                         }
362                                         SEQ_END
363                                 }
364
365                                 CALLBACK_INVOKE(scene->gpd, IDWALK_USER);
366
367                                 for (base = scene->base.first; base; base = base->next) {
368                                         CALLBACK_INVOKE(base->object, IDWALK_USER);
369                                 }
370
371                                 if (toolsett) {
372                                         CALLBACK_INVOKE(toolsett->skgen_template, IDWALK_NOP);
373
374                                         library_foreach_paint(&data, &toolsett->imapaint.paint);
375                                         CALLBACK_INVOKE(toolsett->imapaint.stencil, IDWALK_USER);
376                                         CALLBACK_INVOKE(toolsett->imapaint.clone, IDWALK_USER);
377                                         CALLBACK_INVOKE(toolsett->imapaint.canvas, IDWALK_USER);
378
379                                         if (toolsett->vpaint) {
380                                                 library_foreach_paint(&data, &toolsett->vpaint->paint);
381                                         }
382                                         if (toolsett->wpaint) {
383                                                 library_foreach_paint(&data, &toolsett->wpaint->paint);
384                                         }
385                                         if (toolsett->sculpt) {
386                                                 library_foreach_paint(&data, &toolsett->sculpt->paint);
387                                                 CALLBACK_INVOKE(toolsett->sculpt->gravity_object, IDWALK_NOP);
388                                         }
389                                         if (toolsett->uvsculpt) {
390                                                 library_foreach_paint(&data, &toolsett->uvsculpt->paint);
391                                         }
392                                 }
393
394                                 if (scene->rigidbody_world) {
395                                         BKE_rigidbody_world_id_loop(scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data);
396                                 }
397
398                                 CALLBACK_INVOKE(scene->gm.dome.warptext, IDWALK_NOP);
399
400                                 break;
401                         }
402
403                         case ID_OB:
404                         {
405                                 Object *object = (Object *) id;
406
407                                 /* Object is special, proxies make things hard... */
408                                 const int data_cd_flag = data.cd_flag;
409                                 const int proxy_cd_flag = (object->proxy || object->proxy_group) ? IDWALK_INDIRECT_USAGE : 0;
410
411                                 /* object data special case */
412                                 data.cd_flag |= proxy_cd_flag;
413                                 if (object->type == OB_EMPTY) {
414                                         /* empty can have NULL or Image */
415                                         CALLBACK_INVOKE_ID(object->data, IDWALK_USER);
416                                 }
417                                 else {
418                                         /* when set, this can't be NULL */
419                                         if (object->data) {
420                                                 CALLBACK_INVOKE_ID(object->data, IDWALK_USER | IDWALK_NEVER_NULL);
421                                         }
422                                 }
423                                 data.cd_flag = data_cd_flag;
424
425                                 CALLBACK_INVOKE(object->parent, IDWALK_NOP);
426                                 CALLBACK_INVOKE(object->track, IDWALK_NOP);
427                                 /* object->proxy is refcounted, but not object->proxy_group... *sigh* */
428                                 CALLBACK_INVOKE(object->proxy, IDWALK_USER);
429                                 CALLBACK_INVOKE(object->proxy_group, IDWALK_NOP);
430                                 CALLBACK_INVOKE(object->proxy_from, IDWALK_NOP);
431                                 CALLBACK_INVOKE(object->poselib, IDWALK_USER);
432
433                                 data.cd_flag |= proxy_cd_flag;
434                                 for (i = 0; i < object->totcol; i++) {
435                                         CALLBACK_INVOKE(object->mat[i], IDWALK_USER);
436                                 }
437                                 data.cd_flag = data_cd_flag;
438
439                                 CALLBACK_INVOKE(object->gpd, IDWALK_USER);
440                                 CALLBACK_INVOKE(object->dup_group, IDWALK_USER);
441
442                                 if (object->pd) {
443                                         CALLBACK_INVOKE(object->pd->tex, IDWALK_USER);
444                                         CALLBACK_INVOKE(object->pd->f_source, IDWALK_NOP);
445                                 }
446                                 /* Note that ob->effect is deprecated, so no need to handle it here. */
447
448                                 if (object->pose) {
449                                         bPoseChannel *pchan;
450
451                                         data.cd_flag |= proxy_cd_flag;
452                                         for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
453                                                 CALLBACK_INVOKE(pchan->custom, IDWALK_USER);
454                                                 BKE_constraints_id_loop(&pchan->constraints, library_foreach_constraintObjectLooper, &data);
455                                         }
456                                         data.cd_flag = data_cd_flag;
457                                 }
458
459                                 if (object->rigidbody_constraint) {
460                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob1, IDWALK_NOP);
461                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob2, IDWALK_NOP);
462                                 }
463
464                                 if (object->lodlevels.first) {
465                                         LodLevel *level;
466                                         for (level = object->lodlevels.first; level; level = level->next) {
467                                                 CALLBACK_INVOKE(level->source, IDWALK_NOP);
468                                         }
469                                 }
470
471                                 modifiers_foreachIDLink(object, library_foreach_modifiersForeachIDLink, &data);
472                                 BKE_constraints_id_loop(&object->constraints, library_foreach_constraintObjectLooper, &data);
473
474                                 BKE_sca_sensors_id_loop(&object->sensors, library_foreach_sensorsObjectLooper, &data);
475                                 BKE_sca_controllers_id_loop(&object->controllers, library_foreach_controllersObjectLooper, &data);
476                                 BKE_sca_actuators_id_loop(&object->actuators, library_foreach_actuatorsObjectLooper, &data);
477                                 break;
478                         }
479
480                         case ID_ME:
481                         {
482                                 Mesh *mesh = (Mesh *) id;
483                                 CALLBACK_INVOKE(mesh->texcomesh, IDWALK_USER);
484                                 CALLBACK_INVOKE(mesh->key, IDWALK_USER);
485                                 for (i = 0; i < mesh->totcol; i++) {
486                                         CALLBACK_INVOKE(mesh->mat[i], IDWALK_USER);
487                                 }
488
489                                 /* XXX Really not happy with this - probably texface should rather use some kind of
490                                  * 'texture slots' and just set indices in each poly/face item - would also save some memory.
491                                  * Maybe a nice TODO for blender2.8? */
492                                 if (mesh->mtface || mesh->mtpoly) {
493                                         for (i = 0; i < mesh->pdata.totlayer; i++) {
494                                                 if (mesh->pdata.layers[i].type == CD_MTEXPOLY) {
495                                                         MTexPoly *txface = (MTexPoly *)mesh->pdata.layers[i].data;
496
497                                                         for (int j = 0; j < mesh->totpoly; j++, txface++) {
498                                                                 CALLBACK_INVOKE(txface->tpage, IDWALK_USER_ONE);
499                                                         }
500                                                 }
501                                         }
502
503                                         for (i = 0; i < mesh->fdata.totlayer; i++) {
504                                                 if (mesh->fdata.layers[i].type == CD_MTFACE) {
505                                                         MTFace *tface = (MTFace *)mesh->fdata.layers[i].data;
506
507                                                         for (int j = 0; j < mesh->totface; j++, tface++) {
508                                                                 CALLBACK_INVOKE(tface->tpage, IDWALK_USER_ONE);
509                                                         }
510                                                 }
511                                         }
512                                 }
513                                 break;
514                         }
515
516                         case ID_CU:
517                         {
518                                 Curve *curve = (Curve *) id;
519                                 CALLBACK_INVOKE(curve->bevobj, IDWALK_NOP);
520                                 CALLBACK_INVOKE(curve->taperobj, IDWALK_NOP);
521                                 CALLBACK_INVOKE(curve->textoncurve, IDWALK_NOP);
522                                 CALLBACK_INVOKE(curve->key, IDWALK_USER);
523                                 for (i = 0; i < curve->totcol; i++) {
524                                         CALLBACK_INVOKE(curve->mat[i], IDWALK_USER);
525                                 }
526                                 CALLBACK_INVOKE(curve->vfont, IDWALK_USER);
527                                 CALLBACK_INVOKE(curve->vfontb, IDWALK_USER);
528                                 CALLBACK_INVOKE(curve->vfonti, IDWALK_USER);
529                                 CALLBACK_INVOKE(curve->vfontbi, IDWALK_USER);
530                                 break;
531                         }
532
533                         case ID_MB:
534                         {
535                                 MetaBall *metaball = (MetaBall *) id;
536                                 for (i = 0; i < metaball->totcol; i++) {
537                                         CALLBACK_INVOKE(metaball->mat[i], IDWALK_USER);
538                                 }
539                                 break;
540                         }
541
542                         case ID_MA:
543                         {
544                                 Material *material = (Material *) id;
545                                 for (i = 0; i < MAX_MTEX; i++) {
546                                         if (material->mtex[i]) {
547                                                 library_foreach_mtex(&data, material->mtex[i]);
548                                         }
549                                 }
550                                 if (material->nodetree) {
551                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
552                                         BKE_library_foreach_ID_link((ID *)material->nodetree, callback, user_data, flag);
553                                 }
554                                 CALLBACK_INVOKE(material->group, IDWALK_USER);
555                                 break;
556                         }
557
558                         case ID_TE:
559                         {
560                                 Tex *texture = (Tex *) id;
561                                 if (texture->nodetree) {
562                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
563                                         BKE_library_foreach_ID_link((ID *)texture->nodetree, callback, user_data, flag);
564                                 }
565                                 CALLBACK_INVOKE(texture->ima, IDWALK_USER);
566                                 if (texture->env) {
567                                         CALLBACK_INVOKE(texture->env->object, IDWALK_NOP);
568                                         CALLBACK_INVOKE(texture->env->ima, IDWALK_USER);
569                                 }
570                                 if (texture->pd)
571                                         CALLBACK_INVOKE(texture->pd->object, IDWALK_NOP);
572                                 if (texture->vd)
573                                         CALLBACK_INVOKE(texture->vd->object, IDWALK_NOP);
574                                 if (texture->ot)
575                                         CALLBACK_INVOKE(texture->ot->object, IDWALK_NOP);
576                                 break;
577                         }
578
579                         case ID_LT:
580                         {
581                                 Lattice *lattice = (Lattice *) id;
582                                 CALLBACK_INVOKE(lattice->key, IDWALK_USER);
583                                 break;
584                         }
585
586                         case ID_LA:
587                         {
588                                 Lamp *lamp = (Lamp *) id;
589                                 for (i = 0; i < MAX_MTEX; i++) {
590                                         if (lamp->mtex[i]) {
591                                                 library_foreach_mtex(&data, lamp->mtex[i]);
592                                         }
593                                 }
594                                 if (lamp->nodetree) {
595                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
596                                         BKE_library_foreach_ID_link((ID *)lamp->nodetree, callback, user_data, flag);
597                                 }
598                                 break;
599                         }
600
601                         case ID_CA:
602                         {
603                                 Camera *camera = (Camera *) id;
604                                 CALLBACK_INVOKE(camera->dof_ob, IDWALK_NOP);
605                                 break;
606                         }
607
608                         case ID_KE:
609                         {
610                                 Key *key = (Key *) id;
611                                 CALLBACK_INVOKE_ID(key->from, IDWALK_NOP);
612                                 break;
613                         }
614
615                         case ID_SCR:
616                         {
617                                 bScreen *screen = (bScreen *) id;
618                                 CALLBACK_INVOKE(screen->scene, IDWALK_USER_ONE);
619                                 break;
620                         }
621
622                         case ID_WO:
623                         {
624                                 World *world = (World *) id;
625                                 for (i = 0; i < MAX_MTEX; i++) {
626                                         if (world->mtex[i]) {
627                                                 library_foreach_mtex(&data, world->mtex[i]);
628                                         }
629                                 }
630                                 if (world->nodetree) {
631                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
632                                         BKE_library_foreach_ID_link((ID *)world->nodetree, callback, user_data, flag);
633                                 }
634                                 break;
635                         }
636
637                         case ID_SPK:
638                         {
639                                 Speaker *speaker = (Speaker *) id;
640                                 CALLBACK_INVOKE(speaker->sound, IDWALK_USER);
641                                 break;
642                         }
643
644                         case ID_GR:
645                         {
646                                 Group *group = (Group *) id;
647                                 GroupObject *gob;
648                                 for (gob = group->gobject.first; gob; gob = gob->next) {
649                                         CALLBACK_INVOKE(gob->ob, IDWALK_USER_ONE);
650                                 }
651                                 break;
652                         }
653
654                         case ID_NT:
655                         {
656                                 bNodeTree *ntree = (bNodeTree *) id;
657                                 bNode *node;
658                                 CALLBACK_INVOKE(ntree->gpd, IDWALK_USER);
659                                 for (node = ntree->nodes.first; node; node = node->next) {
660                                         CALLBACK_INVOKE_ID(node->id, IDWALK_USER);
661                                 }
662                                 break;
663                         }
664
665                         case ID_BR:
666                         {
667                                 Brush *brush = (Brush *) id;
668                                 CALLBACK_INVOKE(brush->toggle_brush, IDWALK_NOP);
669                                 CALLBACK_INVOKE(brush->clone.image, IDWALK_NOP);
670                                 CALLBACK_INVOKE(brush->paint_curve, IDWALK_USER);
671                                 library_foreach_mtex(&data, &brush->mtex);
672                                 library_foreach_mtex(&data, &brush->mask_mtex);
673                                 break;
674                         }
675
676                         case ID_MC:
677                         {
678                                 MovieClip *clip = (MovieClip *) id;
679                                 MovieTracking *tracking = &clip->tracking;
680                                 MovieTrackingObject *object;
681                                 MovieTrackingTrack *track;
682                                 MovieTrackingPlaneTrack *plane_track;
683
684                                 CALLBACK_INVOKE(clip->gpd, IDWALK_USER);
685
686                                 for (track = tracking->tracks.first; track; track = track->next) {
687                                         CALLBACK_INVOKE(track->gpd, IDWALK_USER);
688                                 }
689                                 for (object = tracking->objects.first; object; object = object->next) {
690                                         for (track = object->tracks.first; track; track = track->next) {
691                                                 CALLBACK_INVOKE(track->gpd, IDWALK_USER);
692                                         }
693                                 }
694
695                                 for (plane_track = tracking->plane_tracks.first; plane_track; plane_track = plane_track->next) {
696                                         CALLBACK_INVOKE(plane_track->image, IDWALK_USER);
697                                 }
698                                 break;
699                         }
700
701                         case ID_MSK:
702                         {
703                                 Mask *mask = (Mask *) id;
704                                 MaskLayer *mask_layer;
705                                 for (mask_layer = mask->masklayers.first; mask_layer; mask_layer = mask_layer->next) {
706                                         MaskSpline *mask_spline;
707
708                                         for (mask_spline = mask_layer->splines.first; mask_spline; mask_spline = mask_spline->next) {
709                                                 for (i = 0; i < mask_spline->tot_point; i++) {
710                                                         MaskSplinePoint *point = &mask_spline->points[i];
711                                                         CALLBACK_INVOKE_ID(point->parent.id, IDWALK_USER);
712                                                 }
713                                         }
714                                 }
715                                 break;
716                         }
717
718                         case ID_LS:
719                         {
720                                 FreestyleLineStyle *linestyle = (FreestyleLineStyle *) id;
721                                 LineStyleModifier *lsm;
722                                 for (i = 0; i < MAX_MTEX; i++) {
723                                         if (linestyle->mtex[i]) {
724                                                 library_foreach_mtex(&data, linestyle->mtex[i]);
725                                         }
726                                 }
727                                 if (linestyle->nodetree) {
728                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
729                                         BKE_library_foreach_ID_link((ID *)linestyle->nodetree, callback, user_data, flag);
730                                 }
731
732                                 for (lsm = linestyle->color_modifiers.first; lsm; lsm = lsm->next) {
733                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
734                                                 LineStyleColorModifier_DistanceFromObject *p = (LineStyleColorModifier_DistanceFromObject *)lsm;
735                                                 if (p->target) {
736                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
737                                                 }
738                                         }
739                                 }
740                                 for (lsm = linestyle->alpha_modifiers.first; lsm; lsm = lsm->next) {
741                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
742                                                 LineStyleAlphaModifier_DistanceFromObject *p = (LineStyleAlphaModifier_DistanceFromObject *)lsm;
743                                                 if (p->target) {
744                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
745                                                 }
746                                         }
747                                 }
748                                 for (lsm = linestyle->thickness_modifiers.first; lsm; lsm = lsm->next) {
749                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
750                                                 LineStyleThicknessModifier_DistanceFromObject *p = (LineStyleThicknessModifier_DistanceFromObject *)lsm;
751                                                 if (p->target) {
752                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
753                                                 }
754                                         }
755                                 }
756                                 break;
757                         }
758                 }
759         } while ((id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL));
760
761 FOREACH_FINALIZE:
762         if (data.ids_handled) {
763                 BLI_gset_free(data.ids_handled, NULL);
764                 BLI_LINKSTACK_FREE(data.ids_todo);
765         }
766
767 #undef CALLBACK_INVOKE_ID
768 #undef CALLBACK_INVOKE
769 }
770
771 #undef FOREACH_CALLBACK_INVOKE_ID
772 #undef FOREACH_CALLBACK_INVOKE
773
774 /**
775  * re-usable function, use when replacing ID's
776  */
777 void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cd_flag)
778 {
779         if (cd_flag & IDWALK_USER) {
780                 id_us_min(id_src);
781                 id_us_plus(id_dst);
782         }
783         else if (cd_flag & IDWALK_USER_ONE) {
784                 id_us_ensure_real(id_dst);
785         }
786 }
787
788 /**
789  * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used.
790  */
791 /* This is a 'simplified' abstract version of BKE_library_foreach_ID_link() above, quite useful to reduce
792  * useless ietrations in some cases. */
793 bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id_type_used)
794 {
795         if (id_type_used == ID_AC) {
796                 return id_type_can_have_animdata(id_type_owner);
797         }
798
799         switch (id_type_owner) {
800                 case ID_LI:
801                         return ELEM(id_type_used, ID_LI);
802                 case ID_SCE:
803                         return (ELEM(id_type_used, ID_OB, ID_WO, ID_SCE, ID_MC, ID_MA, ID_GR, ID_TXT,
804                                                    ID_LS, ID_MSK, ID_SO, ID_GD, ID_BR, ID_PAL, ID_IM, ID_NT) ||
805                                 BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
806                 case ID_OB:
807                         /* Could be the following, but simpler to just always say 'yes' here. */
808 #if 0
809                         return ELEM(id_type_used, ID_ME, ID_CU, ID_MB, ID_LT, ID_SPK, ID_AR, ID_LA, ID_CA,  /* obdata */
810                                                   ID_OB, ID_MA, ID_GD, ID_GR, ID_TE, ID_TXT, ID_SO, ID_MC, ID_IM, ID_AC
811                                                   /* + constraints, modifiers and game logic ID types... */);
812 #else
813                         return true;
814 #endif
815                 case ID_ME:
816                         return ELEM(id_type_used, ID_ME, ID_KE, ID_MA);
817                 case ID_CU:
818                         return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
819                 case ID_MB:
820                         return ELEM(id_type_used, ID_MA);
821                 case ID_MA:
822                         return (ELEM(id_type_used, ID_TE, ID_GR) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
823                 case ID_TE:
824                         return (ELEM(id_type_used, ID_IM, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
825                 case ID_LT:
826                         return ELEM(id_type_used, ID_KE);
827                 case ID_LA:
828                         return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
829                 case ID_CA:
830                         return ELEM(id_type_used, ID_OB);
831                 case ID_KE:
832                         return ELEM(id_type_used, ID_ME, ID_CU, ID_LT);  /* Warning! key->from, could be more types in future? */
833                 case ID_SCR:
834                         return ELEM(id_type_used, ID_SCE);
835                 case ID_WO:
836                         return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
837                 case ID_SPK:
838                         return ELEM(id_type_used, ID_SO);
839                 case ID_GR:
840                         return ELEM(id_type_used, ID_OB);
841                 case ID_NT:
842                         /* Could be the following, but node.id has no type restriction... */
843 #if 0
844                         return ELEM(id_type_used, ID_GD /* + node.id types... */);
845 #else
846                         return true;
847 #endif
848                 case ID_BR:
849                         return ELEM(id_type_used, ID_BR, ID_IM, ID_PC, ID_TE);
850                 case ID_MC:
851                         return ELEM(id_type_used, ID_GD, ID_IM);
852                 case ID_MSK:
853                         return ELEM(id_type_used, ID_MC);  /* WARNING! mask->parent.id, not typed. */
854                 case ID_LS:
855                         return (ELEM(id_type_used, ID_TE, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
856                 default:
857                         return false;
858         }
859 }
860
861
862 /* ***** ID users iterator. ***** */
863 typedef struct IDUsersIter {
864         ID *id;
865
866         ListBase *lb_array[MAX_LIBARRAY];
867         int lb_idx;
868
869         ID *curr_id;
870         int count_direct, count_indirect;  /* Set by callback. */
871 } IDUsersIter;
872
873 static int foreach_libblock_id_users_callback(void *user_data, ID *UNUSED(self_id), ID **id_p, int cb_flag)
874 {
875         IDUsersIter *iter = user_data;
876
877         if (*id_p && (*id_p == iter->id)) {
878 #if 0
879                 printf("%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, indirect_usage: %d)\n",
880                        iter->curr_id->name, iter->id->name, (cb_flag & IDWALK_USER) ? 1 : 0, (cb_flag & IDWALK_USER_ONE) ? 1 : 0,
881                        (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0, (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0,
882                        (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0);
883 #endif
884                 if (cb_flag & IDWALK_INDIRECT_USAGE) {
885                         iter->count_indirect++;
886                 }
887                 else {
888                         iter->count_direct++;
889                 }
890         }
891
892         return IDWALK_RET_NOP;
893 }
894
895 /**
896  * Return the number of times given \a id_user uses/references \a id_used.
897  *
898  * \note This only checks for pointer references of an ID, shallow usages (like e.g. by RNA paths, as done
899  *       for FCurves) are not detected at all.
900  *
901  * \param id_user the ID which is supposed to use (reference) \a id_used.
902  * \param id_used the ID which is supposed to be used (referenced) by \a id_user.
903  * \return the number of direct usages/references of \a id_used by \a id_user.
904  */
905 int BKE_library_ID_use_ID(ID *id_user, ID *id_used)
906 {
907         IDUsersIter iter;
908
909         /* We do not care about iter.lb_array/lb_idx here... */
910         iter.id = id_used;
911         iter.curr_id = id_user;
912         iter.count_direct = iter.count_indirect = 0;
913
914         BKE_library_foreach_ID_link(iter.curr_id, foreach_libblock_id_users_callback, (void *)&iter, IDWALK_NOP);
915
916         return iter.count_direct + iter.count_indirect;
917 }
918
919 static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
920 {
921         IDUsersIter iter;
922         ListBase *lb_array[MAX_LIBARRAY];
923         ID *id = idv;
924         int i = set_listbasepointers(bmain, lb_array);
925         bool is_defined = false;
926
927         iter.id = id;
928         iter.count_direct = iter.count_indirect = 0;
929         while (i-- && !is_defined) {
930                 ID *id_curr = lb_array[i]->first;
931
932                 if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
933                         continue;
934                 }
935
936                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
937                         iter.curr_id = id_curr;
938                         BKE_library_foreach_ID_link(
939                                     id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_NOP);
940
941                         is_defined = ((check_linked ? iter.count_indirect : iter.count_direct) != 0);
942                 }
943         }
944
945         return is_defined;
946 }
947
948 /**
949  * Check whether given ID is used locally (i.e. by another non-linked ID).
950  */
951 bool BKE_library_ID_is_locally_used(Main *bmain, void *idv)
952 {
953         return library_ID_is_used(bmain, idv, false);
954 }
955
956 /**
957  * Check whether given ID is used indirectly (i.e. by another linked ID).
958  */
959 bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv)
960 {
961         return library_ID_is_used(bmain, idv, true);
962 }
963
964 /**
965  * Combine \a BKE_library_ID_is_locally_used() and \a BKE_library_ID_is_indirectly_used() in a single call.
966  */
967 void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked)
968 {
969         IDUsersIter iter;
970         ListBase *lb_array[MAX_LIBARRAY];
971         ID *id = idv;
972         int i = set_listbasepointers(bmain, lb_array);
973         bool is_defined = false;
974
975         iter.id = id;
976         iter.count_direct = iter.count_indirect = 0;
977         while (i-- && !is_defined) {
978                 ID *id_curr = lb_array[i]->first;
979
980                 if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
981                         continue;
982                 }
983
984                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
985                         iter.curr_id = id_curr;
986                         BKE_library_foreach_ID_link(id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_NOP);
987
988                         is_defined = (iter.count_direct != 0 && iter.count_indirect != 0);
989                 }
990         }
991
992         *is_used_local = (iter.count_direct != 0);
993         *is_used_linked = (iter.count_indirect != 0);
994 }