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