Cleanup: Indentation
[blender.git] / source / blender / blenkernel / intern / library_remap.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/library_remap.c
22  *  \ingroup bke
23  *
24  * Contains management of ID's and libraries remap, unlink and free logic.
25  */
26
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stddef.h>
32 #include <assert.h>
33
34 #include "MEM_guardedalloc.h"
35
36 /* all types are needed here, in order to do memory operations */
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_brush_types.h"
40 #include "DNA_camera_types.h"
41 #include "DNA_cachefile_types.h"
42 #include "DNA_group_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_ipo_types.h"
45 #include "DNA_key_types.h"
46 #include "DNA_lamp_types.h"
47 #include "DNA_lattice_types.h"
48 #include "DNA_linestyle_types.h"
49 #include "DNA_material_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meta_types.h"
52 #include "DNA_movieclip_types.h"
53 #include "DNA_mask_types.h"
54 #include "DNA_node_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_screen_types.h"
58 #include "DNA_speaker_types.h"
59 #include "DNA_sound_types.h"
60 #include "DNA_text_types.h"
61 #include "DNA_vfont_types.h"
62 #include "DNA_windowmanager_types.h"
63 #include "DNA_world_types.h"
64
65 #include "BLI_blenlib.h"
66 #include "BLI_utildefines.h"
67
68 #include "BKE_action.h"
69 #include "BKE_animsys.h"
70 #include "BKE_armature.h"
71 #include "BKE_brush.h"
72 #include "BKE_camera.h"
73 #include "BKE_cachefile.h"
74 #include "BKE_curve.h"
75 #include "BKE_depsgraph.h"
76 #include "BKE_fcurve.h"
77 #include "BKE_font.h"
78 #include "BKE_group.h"
79 #include "BKE_gpencil.h"
80 #include "BKE_idprop.h"
81 #include "BKE_image.h"
82 #include "BKE_ipo.h"
83 #include "BKE_key.h"
84 #include "BKE_lamp.h"
85 #include "BKE_lattice.h"
86 #include "BKE_library.h"
87 #include "BKE_library_query.h"
88 #include "BKE_library_remap.h"
89 #include "BKE_linestyle.h"
90 #include "BKE_mesh.h"
91 #include "BKE_material.h"
92 #include "BKE_main.h"
93 #include "BKE_mask.h"
94 #include "BKE_mball.h"
95 #include "BKE_modifier.h"
96 #include "BKE_movieclip.h"
97 #include "BKE_multires.h"
98 #include "BKE_node.h"
99 #include "BKE_object.h"
100 #include "BKE_paint.h"
101 #include "BKE_particle.h"
102 #include "BKE_speaker.h"
103 #include "BKE_sound.h"
104 #include "BKE_screen.h"
105 #include "BKE_scene.h"
106 #include "BKE_text.h"
107 #include "BKE_texture.h"
108 #include "BKE_world.h"
109
110 #ifdef WITH_PYTHON
111 #include "BPY_extern.h"
112 #endif
113
114 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
115
116 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
117 {
118         free_windowmanager_cb = func;
119 }
120
121 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
122
123 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
124 {
125         free_notifier_reference_cb = func;
126 }
127
128 static BKE_library_remap_editor_id_reference_cb remap_editor_id_reference_cb = NULL;
129
130 void BKE_library_callback_remap_editor_id_reference_set(BKE_library_remap_editor_id_reference_cb func)
131 {
132         remap_editor_id_reference_cb = func;
133 }
134
135 typedef struct IDRemap {
136         ID *old_id;
137         ID *new_id;
138         ID *id;  /* The ID in which we are replacing old_id by new_id usages. */
139         short flag;
140
141         /* 'Output' data. */
142         short status;
143         int skipped_direct;  /* Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */
144         int skipped_indirect;  /* Number of indirect usecases that could not be remapped. */
145         int skipped_refcounted;  /* Number of skipped usecases that refcount the datablock. */
146 } IDRemap;
147
148 /* IDRemap->flag enums defined in BKE_library.h */
149
150 /* IDRemap->status */
151 enum {
152         /* *** Set by callback. *** */
153         ID_REMAP_IS_LINKED_DIRECT       = 1 << 0,  /* new_id is directly linked in current .blend. */
154         ID_REMAP_IS_USER_ONE_SKIPPED    = 1 << 1,  /* There was some skipped 'user_one' usages of old_id. */
155 };
156
157 static int foreach_libblock_remap_callback(void *user_data, ID *UNUSED(id_self), ID **id_p, int cb_flag)
158 {
159         IDRemap *id_remap_data = user_data;
160         ID *old_id = id_remap_data->old_id;
161         ID *new_id = id_remap_data->new_id;
162         ID *id = id_remap_data->id;
163
164         if (!old_id) {  /* Used to cleanup all IDs used by a specific one. */
165                 BLI_assert(!new_id);
166                 old_id = *id_p;
167         }
168
169         if (*id_p && (*id_p == old_id)) {
170                 const bool is_indirect = (cb_flag & IDWALK_INDIRECT_USAGE) != 0;
171                 const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
172                 /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct,
173                  *       on the other hand since they get reset to lib data on file open/reload it is indirect too...
174                  *       Edit Mode is also a 'skip direct' case. */
175                 const bool is_obj = (GS(id->name) == ID_OB);
176                 const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
177                 const bool is_never_null = ((cb_flag & IDWALK_NEVER_NULL) && (new_id == NULL) &&
178                                             (id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
179                 const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
180
181 #ifdef DEBUG_PRINT
182                 printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n",
183                        id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect);
184 #endif
185
186                 if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_NEVER_NULL)) {
187                         id->tag |= LIB_TAG_DOIT;
188                 }
189
190                 /* Special hack in case it's Object->data and we are in edit mode (skipped_direct too). */
191                 if ((is_never_null && skip_never_null) ||
192                     (is_obj_editmode && (((Object *)id)->data == *id_p)) ||
193                     (skip_indirect && is_indirect))
194                 {
195                         if (is_indirect) {
196                                 id_remap_data->skipped_indirect++;
197                         }
198                         else if (is_never_null || is_obj_editmode) {
199                                 id_remap_data->skipped_direct++;
200                         }
201                         else {
202                                 BLI_assert(0);
203                         }
204                         if (cb_flag & IDWALK_USER) {
205                                 id_remap_data->skipped_refcounted++;
206                         }
207                         else if (cb_flag & IDWALK_USER_ONE) {
208                                 /* No need to count number of times this happens, just a flag is enough. */
209                                 id_remap_data->status |= ID_REMAP_IS_USER_ONE_SKIPPED;
210                         }
211                 }
212                 else {
213                         if (!is_never_null) {
214                                 *id_p = new_id;
215                         }
216                         if (cb_flag & IDWALK_USER) {
217                                 id_us_min(old_id);
218                                 /* We do not want to handle LIB_TAG_INDIRECT/LIB_TAG_EXTERN here. */
219                                 if (new_id)
220                                         new_id->us++;
221                         }
222                         else if (cb_flag & IDWALK_USER_ONE) {
223                                 id_us_ensure_real(new_id);
224                                 /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
225                                  * that extra user is processed in final handling... */
226                         }
227                         if (!is_indirect) {
228                                 id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
229                         }
230                 }
231         }
232
233         return IDWALK_RET_NOP;
234 }
235
236 /* Some reamapping unfortunately require extra and/or specific handling, tackle those here. */
237 static void libblock_remap_data_preprocess_scene_base_unlink(
238         IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect)
239 {
240         if (skip_indirect && is_indirect) {
241                 r_id_remap_data->skipped_indirect++;
242                 r_id_remap_data->skipped_refcounted++;
243         }
244         else {
245                 id_us_min((ID *)base->object);
246                 BKE_scene_base_unlink(sce, base);
247                 MEM_freeN(base);
248                 if (!is_indirect) {
249                         r_id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
250                 }
251         }
252 }
253
254 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
255 {
256         switch (GS(r_id_remap_data->id->name)) {
257                 case ID_SCE:
258                 {
259                         Scene *sce = (Scene *)r_id_remap_data->id;
260
261                         if (!r_id_remap_data->new_id) {
262                                 const bool is_indirect = (sce->id.lib != NULL);
263                                 const bool skip_indirect = (r_id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
264
265                                 /* In case we are unlinking... */
266                                 if (!r_id_remap_data->old_id) {
267                                         /* ... everything from scene. */
268                                         Base *base, *base_next;
269                                         for (base = sce->base.first; base; base = base_next) {
270                                                 base_next = base->next;
271                                                 libblock_remap_data_preprocess_scene_base_unlink(
272                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
273                                         }
274                                 }
275                                 else if (GS(r_id_remap_data->old_id->name) == ID_OB) {
276                                         /* ... a specific object from scene. */
277                                         Object *old_ob = (Object *)r_id_remap_data->old_id;
278                                         Base *base = BKE_scene_base_find(sce, old_ob);
279
280                                         if (base) {
281                                                 libblock_remap_data_preprocess_scene_base_unlink(
282                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
283                                         }
284                                 }
285                         }
286                         break;
287                 }
288                 case ID_OB:
289                 {
290                         ID *old_id = r_id_remap_data->old_id;
291                         if (!old_id || GS(old_id->name) == ID_AR) {
292                                 Object *ob = (Object *)r_id_remap_data->id;
293                                 /* Object's pose holds reference to armature bones... sic */
294                                 /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states.
295                                  * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid
296                                  * another complex and risky condition nightmare like the one we have in
297                                  * foreach_libblock_remap_callback()... */
298                                 if (ob->pose && (!old_id || ob->data == old_id)) {
299                                         BLI_assert(ob->type == OB_ARMATURE);
300                                         ob->pose->flag |= POSE_RECALC;
301                                         /* We need to clear pose bone pointers immediately, things like undo writefile may be called
302                                          * before pose is actually recomputed, can lead to segfault... */
303                                         BKE_pose_clear_pointers(ob->pose);
304                                 }
305                         }
306                         break;
307                 }
308                 default:
309                         break;
310         }
311 }
312
313 static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, Object *old_ob, Object *new_ob)
314 {
315         if (old_ob->flag & OB_FROMGROUP) {
316                 /* Note that for Scene's BaseObject->flag, either we:
317                  *     - unlinked old_ob (i.e. new_ob is NULL), in which case scenes' bases have been removed already.
318                  *     - remapped old_ob by new_ob, in which case scenes' bases are still valid as is.
319                  * So in any case, no need to update them here. */
320                 if (BKE_group_object_find(NULL, old_ob) == NULL) {
321                         old_ob->flag &= ~OB_FROMGROUP;
322                 }
323                 if (new_ob == NULL) {  /* We need to remove NULL-ified groupobjects... */
324                         for (Group *group = bmain->group.first; group; group = group->id.next) {
325                                 BKE_group_object_unlink(group, NULL, NULL, NULL);
326                         }
327                 }
328                 else {
329                         new_ob->flag |= OB_FROMGROUP;
330                 }
331         }
332 }
333
334 static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
335 {
336         /* Note that here we assume no object has no base (i.e. all objects are assumed instanced
337          * in one scene...). */
338         for (Base *base = sce->base.first; base; base = base->next) {
339                 if (base->flag & OB_FROMGROUP) {
340                         Object *ob = base->object;
341
342                         if (ob->flag & OB_FROMGROUP) {
343                                 Group *grp = BKE_group_object_find(NULL, ob);
344
345                                 /* Unlinked group (old_id) is still in bmain... */
346                                 if (grp && (&grp->id == old_id || grp->id.us == 0)) {
347                                         grp = BKE_group_object_find(grp, ob);
348                                 }
349                                 if (!grp) {
350                                         ob->flag &= ~OB_FROMGROUP;
351                                 }
352                         }
353                         if (!(ob->flag & OB_FROMGROUP)) {
354                                 base->flag &= ~OB_FROMGROUP;
355                         }
356                 }
357         }
358 }
359
360 static void libblock_remap_data_postprocess_obdata_relink(Main *UNUSED(bmain), Object *ob, ID *new_id)
361 {
362         if (ob->data == new_id) {
363                 switch (GS(new_id->name)) {
364                         case ID_ME:
365                                 multires_force_update(ob);
366                                 break;
367                         case ID_CU:
368                                 BKE_curve_type_test(ob);
369                                 break;
370                         default:
371                                 break;
372                 }
373                 test_object_modifiers(ob);
374                 test_object_materials(ob, new_id);
375         }
376 }
377
378 /**
379  * Execute the 'data' part of the remapping (that is, all ID pointers from other ID datablocks).
380  *
381  * Behavior differs depending on whether given \a id is NULL or not:
382  * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not
383  *   (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id
384  *   are remapped to \a new_id.
385  * - \a id is non-NULL:
386  *   + If \a old_id is NULL, \a new_id must also be NULL, and all ID pointers from \a id are cleared (i.e. \a id
387  *     does not references any other datablock anymore).
388  *   + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only for given \a id.
389  *
390  * \param bmain: the Main data storage to operate on (can be NULL if \a id is non-NULL).
391  * \param id: the datablock to operate on (can be NULL if \a bmain is non-NULL).
392  * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL).
393  * \param new_id: the new datablock to replace \a old_id references with (may be NULL).
394  * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process).
395  */
396 static void libblock_remap_data(
397         Main *bmain, ID *id, ID *old_id, ID *new_id, const short remap_flags, IDRemap *r_id_remap_data)
398 {
399         IDRemap id_remap_data;
400         ListBase *lb_array[MAX_LIBARRAY];
401         int i;
402
403         if (r_id_remap_data == NULL) {
404                 r_id_remap_data = &id_remap_data;
405         }
406         r_id_remap_data->old_id = old_id;
407         r_id_remap_data->new_id = new_id;
408         r_id_remap_data->id = NULL;
409         r_id_remap_data->flag = remap_flags;
410         r_id_remap_data->status = 0;
411         r_id_remap_data->skipped_direct = 0;
412         r_id_remap_data->skipped_indirect = 0;
413         r_id_remap_data->skipped_refcounted = 0;
414
415         if (id) {
416 #ifdef DEBUG_PRINT
417                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
418 #endif
419                 r_id_remap_data->id = id;
420                 libblock_remap_data_preprocess(r_id_remap_data);
421                 BKE_library_foreach_ID_link(id, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
422         }
423         else {
424                 i = set_listbasepointers(bmain, lb_array);
425
426                 /* Note that this is a very 'bruteforce' approach, maybe we could use some depsgraph to only process
427                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
428
429                 while (i--) {
430                         ID *id_curr = lb_array[i]->first;
431
432                         if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(old_id->name))) {
433                                 continue;
434                         }
435
436                         for (; id_curr; id_curr = id_curr->next) {
437                                 /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
438                                  * the user count handling...
439                                  * XXX No more true (except for debug usage of those skipping counters). */
440                                 r_id_remap_data->id = id_curr;
441                                 libblock_remap_data_preprocess(r_id_remap_data);
442                                 BKE_library_foreach_ID_link(
443                                             id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
444                         }
445                 }
446         }
447
448         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
449          *     though, we can always add an option (flag) to control this later if needed. */
450         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
451                 id_fake_user_clear(old_id);
452                 id_fake_user_set(new_id);
453         }
454
455         id_us_clear_real(old_id);
456
457         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
458                 new_id->tag &= ~LIB_TAG_INDIRECT;
459                 new_id->tag |= LIB_TAG_EXTERN;
460         }
461
462 #ifdef DEBUG_PRINT
463         printf("%s: %d occurences skipped (%d direct and %d indirect ones)\n", __func__,
464                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
465                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
466 #endif
467 }
468
469 /**
470  * Replace all references in given Main to \a old_id by \a new_id
471  * (if \a new_id is NULL, it unlinks \a old_id).
472  */
473 void BKE_libblock_remap_locked(
474         Main *bmain, void *old_idv, void *new_idv,
475         const short remap_flags)
476 {
477         IDRemap id_remap_data;
478         ID *old_id = old_idv;
479         ID *new_id = new_idv;
480         int skipped_direct, skipped_refcounted;
481
482         BLI_assert(old_id != NULL);
483         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
484         BLI_assert(old_id != new_id);
485
486         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
487
488         if (free_notifier_reference_cb) {
489                 free_notifier_reference_cb(old_id);
490         }
491
492         /* We assume editors do not hold references to their IDs... This is false in some cases
493          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
494         if (remap_editor_id_reference_cb) {
495                 remap_editor_id_reference_cb(old_id, new_id);
496         }
497
498         skipped_direct = id_remap_data.skipped_direct;
499         skipped_refcounted = id_remap_data.skipped_refcounted;
500
501         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
502          * been incremented for that, we have to decrease once more its user count... unless we had to skip
503          * some 'user_one' cases. */
504         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
505                 id_us_min(old_id);
506                 old_id->tag &= ~LIB_TAG_EXTRAUSER_SET;
507         }
508
509         BLI_assert(old_id->us - skipped_refcounted >= 0);
510         UNUSED_VARS_NDEBUG(skipped_refcounted);
511
512         if (skipped_direct == 0) {
513                 /* old_id is assumed to not be used directly anymore... */
514                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
515                         old_id->tag &= ~LIB_TAG_EXTERN;
516                         old_id->tag |= LIB_TAG_INDIRECT;
517                 }
518         }
519
520         /* Some after-process updates.
521          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
522          */
523         switch (GS(old_id->name)) {
524                 case ID_OB:
525                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id);
526                         break;
527                 case ID_GR:
528                         if (!new_id) {  /* Only affects us in case group was unlinked. */
529                                 for (Scene *sce = bmain->scene.first; sce; sce = sce->id.next) {
530                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
531                                 }
532                         }
533                         break;
534                 case ID_ME:
535                 case ID_CU:
536                 case ID_MB:
537                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
538                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
539                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
540                                 }
541                         }
542                         break;
543                 default:
544                         break;
545         }
546
547         /* Full rebuild of DAG! */
548         DAG_relations_tag_update(bmain);
549 }
550
551 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
552 {
553         BKE_main_lock(bmain);
554
555         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
556
557         BKE_main_unlock(bmain);
558 }
559
560 /**
561  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
562  *
563  * \param do_flag_never_null: If true, all IDs using \a idv in a 'non-NULL' way are flagged by \a LIB_TAG_DOIT flag
564  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
565  */
566 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
567 {
568         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
569                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
570
571         BKE_main_lock(bmain);
572
573         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
574
575         BKE_main_unlock(bmain);
576 }
577
578 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
579  *
580  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
581  * in which case all ID usages by given \a idv will be cleared.
582  * \param us_min_never_null: If \a true and new_id is NULL,
583  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
584  * (needed when given \a idv is going to be deleted right after being unlinked).
585  */
586 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
587 /* XXX Arg! Naming... :(
588  *     _relink? avoids confusion with _remap, but is confusing with _unlink
589  *     _remap_used_ids?
590  *     _remap_datablocks?
591  *     BKE_id_remap maybe?
592  *     ... sigh
593  */
594 void BKE_libblock_relink_ex(
595         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
596 {
597         ID *id = idv;
598         ID *old_id = old_idv;
599         ID *new_id = new_idv;
600         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
601
602         /* No need to lock here, we are only affecting given ID, not bmain database. */
603
604         BLI_assert(id);
605         if (old_id) {
606                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
607                 BLI_assert(old_id != new_id);
608         }
609         else {
610                 BLI_assert(new_id == NULL);
611         }
612
613         libblock_remap_data(NULL, id, old_id, new_id, remap_flags, NULL);
614
615         /* Some after-process updates.
616          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
617          */
618         switch (GS(id->name)) {
619                 case ID_SCE:
620                 {
621                         Scene *sce = (Scene *)id;
622
623                         if (old_id) {
624                                 switch (GS(old_id->name)) {
625                                         case ID_OB:
626                                         {
627                                                 libblock_remap_data_postprocess_object_fromgroup_update(
628                                                             bmain, (Object *)old_id, (Object *)new_id);
629                                                 break;
630                                         }
631                                         case ID_GR:
632                                                 if (!new_id) {  /* Only affects us in case group was unlinked. */
633                                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
634                                                 }
635                                                 break;
636                                         default:
637                                                 break;
638                                 }
639                         }
640                         else {
641                                 /* No choice but to check whole objects/groups. */
642                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
643                                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL);
644                                 }
645                                 for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
646                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
647                                 }
648                         }
649                         break;
650                 }
651                 case ID_OB:
652                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
653                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
654                         }
655                         break;
656                 default:
657                         break;
658         }
659 }
660
661 static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
662 {
663         ChannelDriver *driver;
664         FCurve *fcu;
665
666         /* find the driver this belongs to and update it */
667         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
668                 driver = fcu->driver;
669                 
670                 if (driver) {
671                         DriverVar *dvar;
672                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
673                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
674                                 {
675                                         if (dtar->id == userdata)
676                                                 dtar->id = NULL;
677                                 }
678                                 DRIVER_TARGETS_LOOPER_END
679                         }
680                 }
681         }
682 }
683
684 void BKE_libblock_free_data(Main *bmain, ID *id)
685 {
686         if (id->properties) {
687                 IDP_FreeProperty(id->properties);
688                 MEM_freeN(id->properties);
689         }
690         
691         /* this ID may be a driver target! */
692         BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
693 }
694
695 /**
696  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
697  *
698  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
699  */
700 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user)
701 {
702         ID *id = idv;
703         short type = GS(id->name);
704         ListBase *lb = which_libbase(bmain, type);
705
706         DAG_id_type_tag(bmain, type);
707
708 #ifdef WITH_PYTHON
709         BPY_id_release(id);
710 #endif
711
712         if (do_id_user) {
713                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
714         }
715
716         switch (type) {
717                 case ID_SCE:
718                         BKE_scene_free((Scene *)id);
719                         break;
720                 case ID_LI:
721                         BKE_library_free((Library *)id);
722                         break;
723                 case ID_OB:
724                         BKE_object_free((Object *)id);
725                         break;
726                 case ID_ME:
727                         BKE_mesh_free((Mesh *)id);
728                         break;
729                 case ID_CU:
730                         BKE_curve_free((Curve *)id);
731                         break;
732                 case ID_MB:
733                         BKE_mball_free((MetaBall *)id);
734                         break;
735                 case ID_MA:
736                         BKE_material_free((Material *)id);
737                         break;
738                 case ID_TE:
739                         BKE_texture_free((Tex *)id);
740                         break;
741                 case ID_IM:
742                         BKE_image_free((Image *)id);
743                         break;
744                 case ID_LT:
745                         BKE_lattice_free((Lattice *)id);
746                         break;
747                 case ID_LA:
748                         BKE_lamp_free((Lamp *)id);
749                         break;
750                 case ID_CA:
751                         BKE_camera_free((Camera *) id);
752                         break;
753                 case ID_IP:  /* Deprecated. */
754                         BKE_ipo_free((Ipo *)id);
755                         break;
756                 case ID_KE:
757                         BKE_key_free((Key *)id);
758                         break;
759                 case ID_WO:
760                         BKE_world_free((World *)id);
761                         break;
762                 case ID_SCR:
763                         BKE_screen_free((bScreen *)id);
764                         break;
765                 case ID_VF:
766                         BKE_vfont_free((VFont *)id);
767                         break;
768                 case ID_TXT:
769                         BKE_text_free((Text *)id);
770                         break;
771                 case ID_SPK:
772                         BKE_speaker_free((Speaker *)id);
773                         break;
774                 case ID_SO:
775                         BKE_sound_free((bSound *)id);
776                         break;
777                 case ID_GR:
778                         BKE_group_free((Group *)id);
779                         break;
780                 case ID_AR:
781                         BKE_armature_free((bArmature *)id);
782                         break;
783                 case ID_AC:
784                         BKE_action_free((bAction *)id);
785                         break;
786                 case ID_NT:
787                         ntreeFreeTree((bNodeTree *)id);
788                         break;
789                 case ID_BR:
790                         BKE_brush_free((Brush *)id);
791                         break;
792                 case ID_PA:
793                         BKE_particlesettings_free((ParticleSettings *)id);
794                         break;
795                 case ID_WM:
796                         if (free_windowmanager_cb)
797                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
798                         break;
799                 case ID_GD:
800                         BKE_gpencil_free((bGPdata *)id, true);
801                         break;
802                 case ID_MC:
803                         BKE_movieclip_free((MovieClip *)id);
804                         break;
805                 case ID_MSK:
806                         BKE_mask_free((Mask *)id);
807                         break;
808                 case ID_LS:
809                         BKE_linestyle_free((FreestyleLineStyle *)id);
810                         break;
811                 case ID_PAL:
812                         BKE_palette_free((Palette *)id);
813                         break;
814                 case ID_PC:
815                         BKE_paint_curve_free((PaintCurve *)id);
816                         break;
817                 case ID_CF:
818                         BKE_cachefile_free((CacheFile *)id);
819                         break;
820         }
821
822         /* avoid notifying on removed data */
823         BKE_main_lock(bmain);
824
825         if (free_notifier_reference_cb) {
826                 free_notifier_reference_cb(id);
827         }
828
829         if (remap_editor_id_reference_cb) {
830                 remap_editor_id_reference_cb(id, NULL);
831         }
832
833         BLI_remlink(lb, id);
834
835         BKE_libblock_free_data(bmain, id);
836         BKE_main_unlock(bmain);
837
838         MEM_freeN(id);
839 }
840
841 void BKE_libblock_free(Main *bmain, void *idv)
842 {
843         BKE_libblock_free_ex(bmain, idv, true);
844 }
845
846 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
847 {
848         ID *id = idv;
849         
850         id_us_min(id);
851
852         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
853          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
854          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
855          *     fully unlinked.
856          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
857          */
858         if ((GS(id->name) == ID_OB) && (id->us == 1)) {
859                 id_us_clear_real(id);
860         }
861
862         if (id->us == 0) {
863                 BKE_libblock_unlink(bmain, id, false, false);
864                 
865                 BKE_libblock_free(bmain, id);
866         }
867 }
868
869 void BKE_libblock_delete(Main *bmain, void *idv)
870 {
871         ListBase *lbarray[MAX_LIBARRAY];
872         int base_count, i;
873
874         base_count = set_listbasepointers(bmain, lbarray);
875         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
876
877         /* First tag all datablocks directly from target lib.
878          * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
879          * Avoids to have to loop twice. */
880         for (i = 0; i < base_count; i++) {
881                 ListBase *lb = lbarray[i];
882                 ID *id;
883
884                 for (id = lb->first; id; id = id->next) {
885                         /* Note: in case we delete a library, we also delete all its datablocks! */
886                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
887                                 id->tag |= LIB_TAG_DOIT;
888                                 /* Will tag 'never NULL' users of this ID too.
889                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
890                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
891                                  * Also, this will also flag users of deleted data that cannot be unlinked
892                                  * (object using deleted obdata, etc.), so that they also get deleted. */
893                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
894                         }
895                 }
896         }
897
898         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
899          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
900          * over meshes when we come to freeing obdata). */
901         for (i = base_count; i--; ) {
902                 ListBase *lb = lbarray[i];
903                 ID *id, *id_next;
904
905                 for (id = lb->first; id; id = id_next) {
906                         id_next = id->next;
907                         if (id->tag & LIB_TAG_DOIT) {
908                                 if (id->us != 0) {
909 #ifdef DEBUG_PRINT
910                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
911 #endif
912                                         BLI_assert(id->us == 0);
913                                 }
914                                 BKE_libblock_free(bmain, id);
915                         }
916                 }
917         }
918 }