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 ((ID_Type)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                                 for (TimeMarker *marker = scene->markers.first; marker; marker = marker->next) {
372                                         CALLBACK_INVOKE(marker->camera, IDWALK_NOP);
373                                 }
374
375                                 if (toolsett) {
376                                         CALLBACK_INVOKE(toolsett->skgen_template, IDWALK_NOP);
377
378                                         library_foreach_paint(&data, &toolsett->imapaint.paint);
379                                         CALLBACK_INVOKE(toolsett->imapaint.stencil, IDWALK_USER);
380                                         CALLBACK_INVOKE(toolsett->imapaint.clone, IDWALK_USER);
381                                         CALLBACK_INVOKE(toolsett->imapaint.canvas, IDWALK_USER);
382
383                                         if (toolsett->vpaint) {
384                                                 library_foreach_paint(&data, &toolsett->vpaint->paint);
385                                         }
386                                         if (toolsett->wpaint) {
387                                                 library_foreach_paint(&data, &toolsett->wpaint->paint);
388                                         }
389                                         if (toolsett->sculpt) {
390                                                 library_foreach_paint(&data, &toolsett->sculpt->paint);
391                                                 CALLBACK_INVOKE(toolsett->sculpt->gravity_object, IDWALK_NOP);
392                                         }
393                                         if (toolsett->uvsculpt) {
394                                                 library_foreach_paint(&data, &toolsett->uvsculpt->paint);
395                                         }
396                                 }
397
398                                 if (scene->rigidbody_world) {
399                                         BKE_rigidbody_world_id_loop(scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data);
400                                 }
401
402                                 CALLBACK_INVOKE(scene->gm.dome.warptext, IDWALK_NOP);
403
404                                 break;
405                         }
406
407                         case ID_OB:
408                         {
409                                 Object *object = (Object *) id;
410
411                                 /* Object is special, proxies make things hard... */
412                                 const int data_cd_flag = data.cd_flag;
413                                 const int proxy_cd_flag = (object->proxy || object->proxy_group) ? IDWALK_INDIRECT_USAGE : 0;
414
415                                 /* object data special case */
416                                 data.cd_flag |= proxy_cd_flag;
417                                 if (object->type == OB_EMPTY) {
418                                         /* empty can have NULL or Image */
419                                         CALLBACK_INVOKE_ID(object->data, IDWALK_USER);
420                                 }
421                                 else {
422                                         /* when set, this can't be NULL */
423                                         if (object->data) {
424                                                 CALLBACK_INVOKE_ID(object->data, IDWALK_USER | IDWALK_NEVER_NULL);
425                                         }
426                                 }
427                                 data.cd_flag = data_cd_flag;
428
429                                 CALLBACK_INVOKE(object->parent, IDWALK_NOP);
430                                 CALLBACK_INVOKE(object->track, IDWALK_NOP);
431                                 /* object->proxy is refcounted, but not object->proxy_group... *sigh* */
432                                 CALLBACK_INVOKE(object->proxy, IDWALK_USER);
433                                 CALLBACK_INVOKE(object->proxy_group, IDWALK_NOP);
434
435                                 /* Special case!
436                                  * Since this field is set/owned by 'user' of this ID (and not ID itself), it is only indirect usage
437                                  * if proxy object is linked... Twisted. */
438                                 if (object->proxy_from) {
439                                         data.cd_flag = ID_IS_LINKED_DATABLOCK(object->proxy_from) ? IDWALK_INDIRECT_USAGE : 0;
440                                 }
441                                 CALLBACK_INVOKE(object->proxy_from, IDWALK_NOP);
442                                 data.cd_flag = data_cd_flag;
443
444                                 CALLBACK_INVOKE(object->poselib, IDWALK_USER);
445
446                                 data.cd_flag |= proxy_cd_flag;
447                                 for (i = 0; i < object->totcol; i++) {
448                                         CALLBACK_INVOKE(object->mat[i], IDWALK_USER);
449                                 }
450                                 data.cd_flag = data_cd_flag;
451
452                                 CALLBACK_INVOKE(object->gpd, IDWALK_USER);
453                                 CALLBACK_INVOKE(object->dup_group, IDWALK_USER);
454
455                                 if (object->pd) {
456                                         CALLBACK_INVOKE(object->pd->tex, IDWALK_USER);
457                                         CALLBACK_INVOKE(object->pd->f_source, IDWALK_NOP);
458                                 }
459                                 /* Note that ob->effect is deprecated, so no need to handle it here. */
460
461                                 if (object->pose) {
462                                         bPoseChannel *pchan;
463
464                                         data.cd_flag |= proxy_cd_flag;
465                                         for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
466                                                 CALLBACK_INVOKE(pchan->custom, IDWALK_USER);
467                                                 BKE_constraints_id_loop(&pchan->constraints, library_foreach_constraintObjectLooper, &data);
468                                         }
469                                         data.cd_flag = data_cd_flag;
470                                 }
471
472                                 if (object->rigidbody_constraint) {
473                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob1, IDWALK_NOP);
474                                         CALLBACK_INVOKE(object->rigidbody_constraint->ob2, IDWALK_NOP);
475                                 }
476
477                                 if (object->lodlevels.first) {
478                                         LodLevel *level;
479                                         for (level = object->lodlevels.first; level; level = level->next) {
480                                                 CALLBACK_INVOKE(level->source, IDWALK_NOP);
481                                         }
482                                 }
483
484                                 modifiers_foreachIDLink(object, library_foreach_modifiersForeachIDLink, &data);
485                                 BKE_constraints_id_loop(&object->constraints, library_foreach_constraintObjectLooper, &data);
486
487                                 if (object->soft) {
488                                         CALLBACK_INVOKE(object->soft->collision_group, IDWALK_NOP);
489
490                                         if (object->soft->effector_weights) {
491                                                 CALLBACK_INVOKE(object->soft->effector_weights->group, IDWALK_NOP);
492                                         }
493                                 }
494
495                                 BKE_sca_sensors_id_loop(&object->sensors, library_foreach_sensorsObjectLooper, &data);
496                                 BKE_sca_controllers_id_loop(&object->controllers, library_foreach_controllersObjectLooper, &data);
497                                 BKE_sca_actuators_id_loop(&object->actuators, library_foreach_actuatorsObjectLooper, &data);
498                                 break;
499                         }
500
501                         case ID_ME:
502                         {
503                                 Mesh *mesh = (Mesh *) id;
504                                 CALLBACK_INVOKE(mesh->texcomesh, IDWALK_USER);
505                                 CALLBACK_INVOKE(mesh->key, IDWALK_USER);
506                                 for (i = 0; i < mesh->totcol; i++) {
507                                         CALLBACK_INVOKE(mesh->mat[i], IDWALK_USER);
508                                 }
509
510                                 /* XXX Really not happy with this - probably texface should rather use some kind of
511                                  * 'texture slots' and just set indices in each poly/face item - would also save some memory.
512                                  * Maybe a nice TODO for blender2.8? */
513                                 if (mesh->mtface || mesh->mtpoly) {
514                                         for (i = 0; i < mesh->pdata.totlayer; i++) {
515                                                 if (mesh->pdata.layers[i].type == CD_MTEXPOLY) {
516                                                         MTexPoly *txface = (MTexPoly *)mesh->pdata.layers[i].data;
517
518                                                         for (int j = 0; j < mesh->totpoly; j++, txface++) {
519                                                                 CALLBACK_INVOKE(txface->tpage, IDWALK_USER_ONE);
520                                                         }
521                                                 }
522                                         }
523
524                                         for (i = 0; i < mesh->fdata.totlayer; i++) {
525                                                 if (mesh->fdata.layers[i].type == CD_MTFACE) {
526                                                         MTFace *tface = (MTFace *)mesh->fdata.layers[i].data;
527
528                                                         for (int j = 0; j < mesh->totface; j++, tface++) {
529                                                                 CALLBACK_INVOKE(tface->tpage, IDWALK_USER_ONE);
530                                                         }
531                                                 }
532                                         }
533                                 }
534                                 break;
535                         }
536
537                         case ID_CU:
538                         {
539                                 Curve *curve = (Curve *) id;
540                                 CALLBACK_INVOKE(curve->bevobj, IDWALK_NOP);
541                                 CALLBACK_INVOKE(curve->taperobj, IDWALK_NOP);
542                                 CALLBACK_INVOKE(curve->textoncurve, IDWALK_NOP);
543                                 CALLBACK_INVOKE(curve->key, IDWALK_USER);
544                                 for (i = 0; i < curve->totcol; i++) {
545                                         CALLBACK_INVOKE(curve->mat[i], IDWALK_USER);
546                                 }
547                                 CALLBACK_INVOKE(curve->vfont, IDWALK_USER);
548                                 CALLBACK_INVOKE(curve->vfontb, IDWALK_USER);
549                                 CALLBACK_INVOKE(curve->vfonti, IDWALK_USER);
550                                 CALLBACK_INVOKE(curve->vfontbi, IDWALK_USER);
551                                 break;
552                         }
553
554                         case ID_MB:
555                         {
556                                 MetaBall *metaball = (MetaBall *) id;
557                                 for (i = 0; i < metaball->totcol; i++) {
558                                         CALLBACK_INVOKE(metaball->mat[i], IDWALK_USER);
559                                 }
560                                 break;
561                         }
562
563                         case ID_MA:
564                         {
565                                 Material *material = (Material *) id;
566                                 for (i = 0; i < MAX_MTEX; i++) {
567                                         if (material->mtex[i]) {
568                                                 library_foreach_mtex(&data, material->mtex[i]);
569                                         }
570                                 }
571                                 if (material->nodetree) {
572                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
573                                         BKE_library_foreach_ID_link((ID *)material->nodetree, callback, user_data, flag);
574                                 }
575                                 CALLBACK_INVOKE(material->group, IDWALK_USER);
576                                 break;
577                         }
578
579                         case ID_TE:
580                         {
581                                 Tex *texture = (Tex *) id;
582                                 if (texture->nodetree) {
583                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
584                                         BKE_library_foreach_ID_link((ID *)texture->nodetree, callback, user_data, flag);
585                                 }
586                                 CALLBACK_INVOKE(texture->ima, IDWALK_USER);
587                                 if (texture->env) {
588                                         CALLBACK_INVOKE(texture->env->object, IDWALK_NOP);
589                                         CALLBACK_INVOKE(texture->env->ima, IDWALK_USER);
590                                 }
591                                 if (texture->pd)
592                                         CALLBACK_INVOKE(texture->pd->object, IDWALK_NOP);
593                                 if (texture->vd)
594                                         CALLBACK_INVOKE(texture->vd->object, IDWALK_NOP);
595                                 if (texture->ot)
596                                         CALLBACK_INVOKE(texture->ot->object, IDWALK_NOP);
597                                 break;
598                         }
599
600                         case ID_LT:
601                         {
602                                 Lattice *lattice = (Lattice *) id;
603                                 CALLBACK_INVOKE(lattice->key, IDWALK_USER);
604                                 break;
605                         }
606
607                         case ID_LA:
608                         {
609                                 Lamp *lamp = (Lamp *) id;
610                                 for (i = 0; i < MAX_MTEX; i++) {
611                                         if (lamp->mtex[i]) {
612                                                 library_foreach_mtex(&data, lamp->mtex[i]);
613                                         }
614                                 }
615                                 if (lamp->nodetree) {
616                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
617                                         BKE_library_foreach_ID_link((ID *)lamp->nodetree, callback, user_data, flag);
618                                 }
619                                 break;
620                         }
621
622                         case ID_CA:
623                         {
624                                 Camera *camera = (Camera *) id;
625                                 CALLBACK_INVOKE(camera->dof_ob, IDWALK_NOP);
626                                 break;
627                         }
628
629                         case ID_KE:
630                         {
631                                 /* XXX Only ID pointer from shapekeys is the 'from' one, which is not actually ID usage.
632                                  * Maybe we should even nuke it from here, not 100% sure yet...
633                                  * (see also foreach_libblock_id_users_callback).
634                                  */
635                                 Key *key = (Key *) id;
636                                 CALLBACK_INVOKE_ID(key->from, IDWALK_NOP);
637                                 break;
638                         }
639
640                         case ID_SCR:
641                         {
642                                 bScreen *screen = (bScreen *) id;
643                                 CALLBACK_INVOKE(screen->scene, IDWALK_USER_ONE);
644                                 break;
645                         }
646
647                         case ID_WO:
648                         {
649                                 World *world = (World *) id;
650                                 for (i = 0; i < MAX_MTEX; i++) {
651                                         if (world->mtex[i]) {
652                                                 library_foreach_mtex(&data, world->mtex[i]);
653                                         }
654                                 }
655                                 if (world->nodetree) {
656                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
657                                         BKE_library_foreach_ID_link((ID *)world->nodetree, callback, user_data, flag);
658                                 }
659                                 break;
660                         }
661
662                         case ID_SPK:
663                         {
664                                 Speaker *speaker = (Speaker *) id;
665                                 CALLBACK_INVOKE(speaker->sound, IDWALK_USER);
666                                 break;
667                         }
668
669                         case ID_GR:
670                         {
671                                 Group *group = (Group *) id;
672                                 GroupObject *gob;
673                                 for (gob = group->gobject.first; gob; gob = gob->next) {
674                                         CALLBACK_INVOKE(gob->ob, IDWALK_USER_ONE);
675                                 }
676                                 break;
677                         }
678
679                         case ID_NT:
680                         {
681                                 bNodeTree *ntree = (bNodeTree *) id;
682                                 bNode *node;
683                                 CALLBACK_INVOKE(ntree->gpd, IDWALK_USER);
684                                 for (node = ntree->nodes.first; node; node = node->next) {
685                                         CALLBACK_INVOKE_ID(node->id, IDWALK_USER);
686                                 }
687                                 break;
688                         }
689
690                         case ID_BR:
691                         {
692                                 Brush *brush = (Brush *) id;
693                                 CALLBACK_INVOKE(brush->toggle_brush, IDWALK_NOP);
694                                 CALLBACK_INVOKE(brush->clone.image, IDWALK_NOP);
695                                 CALLBACK_INVOKE(brush->paint_curve, IDWALK_USER);
696                                 library_foreach_mtex(&data, &brush->mtex);
697                                 library_foreach_mtex(&data, &brush->mask_mtex);
698                                 break;
699                         }
700
701                         case ID_MC:
702                         {
703                                 MovieClip *clip = (MovieClip *) id;
704                                 MovieTracking *tracking = &clip->tracking;
705                                 MovieTrackingObject *object;
706                                 MovieTrackingTrack *track;
707                                 MovieTrackingPlaneTrack *plane_track;
708
709                                 CALLBACK_INVOKE(clip->gpd, IDWALK_USER);
710
711                                 for (track = tracking->tracks.first; track; track = track->next) {
712                                         CALLBACK_INVOKE(track->gpd, IDWALK_USER);
713                                 }
714                                 for (object = tracking->objects.first; object; object = object->next) {
715                                         for (track = object->tracks.first; track; track = track->next) {
716                                                 CALLBACK_INVOKE(track->gpd, IDWALK_USER);
717                                         }
718                                 }
719
720                                 for (plane_track = tracking->plane_tracks.first; plane_track; plane_track = plane_track->next) {
721                                         CALLBACK_INVOKE(plane_track->image, IDWALK_USER);
722                                 }
723                                 break;
724                         }
725
726                         case ID_MSK:
727                         {
728                                 Mask *mask = (Mask *) id;
729                                 MaskLayer *mask_layer;
730                                 for (mask_layer = mask->masklayers.first; mask_layer; mask_layer = mask_layer->next) {
731                                         MaskSpline *mask_spline;
732
733                                         for (mask_spline = mask_layer->splines.first; mask_spline; mask_spline = mask_spline->next) {
734                                                 for (i = 0; i < mask_spline->tot_point; i++) {
735                                                         MaskSplinePoint *point = &mask_spline->points[i];
736                                                         CALLBACK_INVOKE_ID(point->parent.id, IDWALK_USER);
737                                                 }
738                                         }
739                                 }
740                                 break;
741                         }
742
743                         case ID_LS:
744                         {
745                                 FreestyleLineStyle *linestyle = (FreestyleLineStyle *) id;
746                                 LineStyleModifier *lsm;
747                                 for (i = 0; i < MAX_MTEX; i++) {
748                                         if (linestyle->mtex[i]) {
749                                                 library_foreach_mtex(&data, linestyle->mtex[i]);
750                                         }
751                                 }
752                                 if (linestyle->nodetree) {
753                                         /* nodetree **are owned by IDs**, treat them as mere sub-data and not real ID! */
754                                         BKE_library_foreach_ID_link((ID *)linestyle->nodetree, callback, user_data, flag);
755                                 }
756
757                                 for (lsm = linestyle->color_modifiers.first; lsm; lsm = lsm->next) {
758                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
759                                                 LineStyleColorModifier_DistanceFromObject *p = (LineStyleColorModifier_DistanceFromObject *)lsm;
760                                                 if (p->target) {
761                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
762                                                 }
763                                         }
764                                 }
765                                 for (lsm = linestyle->alpha_modifiers.first; lsm; lsm = lsm->next) {
766                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
767                                                 LineStyleAlphaModifier_DistanceFromObject *p = (LineStyleAlphaModifier_DistanceFromObject *)lsm;
768                                                 if (p->target) {
769                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
770                                                 }
771                                         }
772                                 }
773                                 for (lsm = linestyle->thickness_modifiers.first; lsm; lsm = lsm->next) {
774                                         if (lsm->type == LS_MODIFIER_DISTANCE_FROM_OBJECT) {
775                                                 LineStyleThicknessModifier_DistanceFromObject *p = (LineStyleThicknessModifier_DistanceFromObject *)lsm;
776                                                 if (p->target) {
777                                                         CALLBACK_INVOKE(p->target, IDWALK_NOP);
778                                                 }
779                                         }
780                                 }
781                                 break;
782                         }
783                         case ID_AC:
784                         {
785                                 bAction *act = (bAction *) id;
786
787                                 for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
788                                         CALLBACK_INVOKE(marker->camera, IDWALK_NOP);
789                                 }
790                                 break;
791                         }
792
793                         /* Nothing needed for those... */
794                         case ID_IM:
795                         case ID_VF:
796                         case ID_TXT:
797                         case ID_SO:
798                         case ID_AR:
799                         case ID_GD:
800                         case ID_WM:
801                         case ID_PAL:
802                         case ID_PC:
803                         case ID_CF:
804                                 break;
805
806                         /* Deprecated. */
807                         case ID_IP:
808                                 break;
809
810                 }
811         } while ((id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL));
812
813 FOREACH_FINALIZE:
814         if (data.ids_handled) {
815                 BLI_gset_free(data.ids_handled, NULL);
816                 BLI_LINKSTACK_FREE(data.ids_todo);
817         }
818
819 #undef CALLBACK_INVOKE_ID
820 #undef CALLBACK_INVOKE
821 }
822
823 #undef FOREACH_CALLBACK_INVOKE_ID
824 #undef FOREACH_CALLBACK_INVOKE
825
826 /**
827  * re-usable function, use when replacing ID's
828  */
829 void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cd_flag)
830 {
831         if (cd_flag & IDWALK_USER) {
832                 id_us_min(id_src);
833                 id_us_plus(id_dst);
834         }
835         else if (cd_flag & IDWALK_USER_ONE) {
836                 id_us_ensure_real(id_dst);
837         }
838 }
839
840 /**
841  * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used.
842  *
843  * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above, quite useful to reduce
844  * useless iterations in some cases.
845  */
846 /* XXX This has to be fully rethink, basing check on ID type is not really working anymore (and even worth once
847  *     IDProps will support ID pointers), we'll have to do some quick checks on IDs themselves... */
848 bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id_type_used)
849 {
850         if (id_type_can_have_animdata(id_type_owner)) {
851                 return true;  /* AnimationData can use virtually any kind of datablocks, through drivers especially. */
852         }
853
854         switch ((ID_Type)id_type_owner) {
855                 case ID_LI:
856                         return ELEM(id_type_used, ID_LI);
857                 case ID_SCE:
858                         return (ELEM(id_type_used, ID_OB, ID_WO, ID_SCE, ID_MC, ID_MA, ID_GR, ID_TXT,
859                                                    ID_LS, ID_MSK, ID_SO, ID_GD, ID_BR, ID_PAL, ID_IM, ID_NT) ||
860                                 BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
861                 case ID_OB:
862                         /* Could be the following, but simpler to just always say 'yes' here. */
863 #if 0
864                         return ELEM(id_type_used, ID_ME, ID_CU, ID_MB, ID_LT, ID_SPK, ID_AR, ID_LA, ID_CA,  /* obdata */
865                                                   ID_OB, ID_MA, ID_GD, ID_GR, ID_TE, ID_TXT, ID_SO, ID_MC, ID_IM, ID_AC
866                                                   /* + constraints, modifiers and game logic ID types... */);
867 #else
868                         return true;
869 #endif
870                 case ID_ME:
871                         return ELEM(id_type_used, ID_ME, ID_KE, ID_MA);
872                 case ID_CU:
873                         return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
874                 case ID_MB:
875                         return ELEM(id_type_used, ID_MA);
876                 case ID_MA:
877                         return (ELEM(id_type_used, ID_TE, ID_GR) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
878                 case ID_TE:
879                         return (ELEM(id_type_used, ID_IM, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
880                 case ID_LT:
881                         return ELEM(id_type_used, ID_KE);
882                 case ID_LA:
883                         return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
884                 case ID_CA:
885                         return ELEM(id_type_used, ID_OB);
886                 case ID_KE:
887                         return ELEM(id_type_used, ID_ME, ID_CU, ID_LT);  /* Warning! key->from, could be more types in future? */
888                 case ID_SCR:
889                         return ELEM(id_type_used, ID_SCE);
890                 case ID_WO:
891                         return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
892                 case ID_SPK:
893                         return ELEM(id_type_used, ID_SO);
894                 case ID_GR:
895                         return ELEM(id_type_used, ID_OB);
896                 case ID_NT:
897                         /* Could be the following, but node.id has no type restriction... */
898 #if 0
899                         return ELEM(id_type_used, ID_GD /* + node.id types... */);
900 #else
901                         return true;
902 #endif
903                 case ID_BR:
904                         return ELEM(id_type_used, ID_BR, ID_IM, ID_PC, ID_TE);
905                 case ID_MC:
906                         return ELEM(id_type_used, ID_GD, ID_IM);
907                 case ID_MSK:
908                         return ELEM(id_type_used, ID_MC);  /* WARNING! mask->parent.id, not typed. */
909                 case ID_LS:
910                         return (ELEM(id_type_used, ID_TE, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
911                 case ID_IM:
912                 case ID_VF:
913                 case ID_TXT:
914                 case ID_SO:
915                 case ID_AR:
916                 case ID_AC:
917                 case ID_GD:
918                 case ID_WM:
919                 case ID_PAL:
920                 case ID_PC:
921                 case ID_CF:
922                         /* Those types never use/reference other IDs... */
923                         return false;
924                 case ID_IP:
925                         /* Deprecated... */
926                         return false;
927         }
928         return false;
929 }
930
931
932 /* ***** ID users iterator. ***** */
933 typedef struct IDUsersIter {
934         ID *id;
935
936         ListBase *lb_array[MAX_LIBARRAY];
937         int lb_idx;
938
939         ID *curr_id;
940         int count_direct, count_indirect;  /* Set by callback. */
941 } IDUsersIter;
942
943 static int foreach_libblock_id_users_callback(void *user_data, ID *self_id, ID **id_p, int cb_flag)
944 {
945         IDUsersIter *iter = user_data;
946
947         /* XXX This is actually some kind of hack...
948          * Issue is, shapekeys' 'from' ID pointer is not actually ID usage.
949          * Maybe we should even nuke it from BKE_library_foreach_ID_link, not 100% sure yet...
950          */
951         if ((GS(self_id->name) == ID_KE) && (((Key *)self_id)->from == *id_p)) {
952                 return IDWALK_RET_NOP;
953         }
954
955         if (*id_p && (*id_p == iter->id)) {
956 #if 0
957                 printf("%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, indirect_usage: %d)\n",
958                        iter->curr_id->name, iter->id->name, (cb_flag & IDWALK_USER) ? 1 : 0, (cb_flag & IDWALK_USER_ONE) ? 1 : 0,
959                        (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0, (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0,
960                        (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0);
961 #endif
962                 if (cb_flag & IDWALK_INDIRECT_USAGE) {
963                         iter->count_indirect++;
964                 }
965                 else {
966                         iter->count_direct++;
967                 }
968         }
969
970         return IDWALK_RET_NOP;
971 }
972
973 /**
974  * Return the number of times given \a id_user uses/references \a id_used.
975  *
976  * \note This only checks for pointer references of an ID, shallow usages (like e.g. by RNA paths, as done
977  *       for FCurves) are not detected at all.
978  *
979  * \param id_user the ID which is supposed to use (reference) \a id_used.
980  * \param id_used the ID which is supposed to be used (referenced) by \a id_user.
981  * \return the number of direct usages/references of \a id_used by \a id_user.
982  */
983 int BKE_library_ID_use_ID(ID *id_user, ID *id_used)
984 {
985         IDUsersIter iter;
986
987         /* We do not care about iter.lb_array/lb_idx here... */
988         iter.id = id_used;
989         iter.curr_id = id_user;
990         iter.count_direct = iter.count_indirect = 0;
991
992         BKE_library_foreach_ID_link(iter.curr_id, foreach_libblock_id_users_callback, (void *)&iter, IDWALK_NOP);
993
994         return iter.count_direct + iter.count_indirect;
995 }
996
997 static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
998 {
999         IDUsersIter iter;
1000         ListBase *lb_array[MAX_LIBARRAY];
1001         ID *id = idv;
1002         int i = set_listbasepointers(bmain, lb_array);
1003         bool is_defined = false;
1004
1005         iter.id = id;
1006         iter.count_direct = iter.count_indirect = 0;
1007         while (i-- && !is_defined) {
1008                 ID *id_curr = lb_array[i]->first;
1009
1010                 if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
1011                         continue;
1012                 }
1013
1014                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
1015                         if (id_curr == id) {
1016                                 /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1017                                 continue;
1018                         }
1019                         iter.curr_id = id_curr;
1020                         BKE_library_foreach_ID_link(
1021                                     id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_NOP);
1022
1023                         is_defined = ((check_linked ? iter.count_indirect : iter.count_direct) != 0);
1024                 }
1025         }
1026
1027         return is_defined;
1028 }
1029
1030 /**
1031  * Check whether given ID is used locally (i.e. by another non-linked ID).
1032  */
1033 bool BKE_library_ID_is_locally_used(Main *bmain, void *idv)
1034 {
1035         return library_ID_is_used(bmain, idv, false);
1036 }
1037
1038 /**
1039  * Check whether given ID is used indirectly (i.e. by another linked ID).
1040  */
1041 bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv)
1042 {
1043         return library_ID_is_used(bmain, idv, true);
1044 }
1045
1046 /**
1047  * Combine \a BKE_library_ID_is_locally_used() and \a BKE_library_ID_is_indirectly_used() in a single call.
1048  */
1049 void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked)
1050 {
1051         IDUsersIter iter;
1052         ListBase *lb_array[MAX_LIBARRAY];
1053         ID *id = idv;
1054         int i = set_listbasepointers(bmain, lb_array);
1055         bool is_defined = false;
1056
1057         iter.id = id;
1058         iter.count_direct = iter.count_indirect = 0;
1059         while (i-- && !is_defined) {
1060                 ID *id_curr = lb_array[i]->first;
1061
1062                 if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
1063                         continue;
1064                 }
1065
1066                 for (; id_curr && !is_defined; id_curr = id_curr->next) {
1067                         if (id_curr == id) {
1068                                 /* We are not interested in self-usages (mostly from drivers or bone constraints...). */
1069                                 continue;
1070                         }
1071                         iter.curr_id = id_curr;
1072                         BKE_library_foreach_ID_link(id_curr, foreach_libblock_id_users_callback, &iter, IDWALK_NOP);
1073
1074                         is_defined = (iter.count_direct != 0 && iter.count_indirect != 0);
1075                 }
1076         }
1077
1078         *is_used_local = (iter.count_direct != 0);
1079         *is_used_linked = (iter.count_indirect != 0);
1080 }