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         const int foreach_id_flags = (remap_flags & ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE) != 0 ? IDWALK_NO_INDIRECT_PROXY_DATA_USAGE : IDWALK_NOP;
451
452         if (r_id_remap_data == NULL) {
453                 r_id_remap_data = &id_remap_data;
454         }
455         r_id_remap_data->bmain = bmain;
456         r_id_remap_data->old_id = old_id;
457         r_id_remap_data->new_id = new_id;
458         r_id_remap_data->id = NULL;
459         r_id_remap_data->flag = remap_flags;
460         r_id_remap_data->status = 0;
461         r_id_remap_data->skipped_direct = 0;
462         r_id_remap_data->skipped_indirect = 0;
463         r_id_remap_data->skipped_refcounted = 0;
464
465         if (id) {
466 #ifdef DEBUG_PRINT
467                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
468 #endif
469                 r_id_remap_data->id = id;
470                 libblock_remap_data_preprocess(r_id_remap_data);
471                 BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
472         }
473         else {
474                 i = set_listbasepointers(bmain, lb_array);
475
476                 /* Note that this is a very 'bruteforce' approach, maybe we could use some depsgraph to only process
477                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
478
479                 while (i--) {
480                         for (ID *id_curr = lb_array[i]->first; id_curr; id_curr = id_curr->next) {
481                                 if (BKE_library_id_can_use_idtype(id_curr, GS(old_id->name))) {
482                                         /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
483                                          * the user count handling...
484                                          * XXX No more true (except for debug usage of those skipping counters). */
485                                         r_id_remap_data->id = id_curr;
486                                         libblock_remap_data_preprocess(r_id_remap_data);
487                                         BKE_library_foreach_ID_link(
488                                                     NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
489                                 }
490                         }
491                 }
492         }
493
494         if (old_id && GS(old_id->name) == ID_OB) {
495                 BKE_sca_logic_links_remap(bmain, (Object *)old_id, (Object *)new_id);
496         }
497
498         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
499          *     though, we can always add an option (flag) to control this later if needed. */
500         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
501                 id_fake_user_clear(old_id);
502                 id_fake_user_set(new_id);
503         }
504
505         id_us_clear_real(old_id);
506
507         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
508                 new_id->tag &= ~LIB_TAG_INDIRECT;
509                 new_id->tag |= LIB_TAG_EXTERN;
510         }
511
512 #ifdef DEBUG_PRINT
513         printf("%s: %d occurences skipped (%d direct and %d indirect ones)\n", __func__,
514                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
515                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
516 #endif
517 }
518
519 /**
520  * Replace all references in given Main to \a old_id by \a new_id
521  * (if \a new_id is NULL, it unlinks \a old_id).
522  */
523 void BKE_libblock_remap_locked(
524         Main *bmain, void *old_idv, void *new_idv,
525         const short remap_flags)
526 {
527         IDRemap id_remap_data;
528         ID *old_id = old_idv;
529         ID *new_id = new_idv;
530         int skipped_direct, skipped_refcounted;
531
532         BLI_assert(old_id != NULL);
533         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
534         BLI_assert(old_id != new_id);
535
536         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
537
538         if (free_notifier_reference_cb) {
539                 free_notifier_reference_cb(old_id);
540         }
541
542         /* We assume editors do not hold references to their IDs... This is false in some cases
543          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
544         if (remap_editor_id_reference_cb) {
545                 remap_editor_id_reference_cb(old_id, new_id);
546         }
547
548         skipped_direct = id_remap_data.skipped_direct;
549         skipped_refcounted = id_remap_data.skipped_refcounted;
550
551         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
552          * been incremented for that, we have to decrease once more its user count... unless we had to skip
553          * some 'user_one' cases. */
554         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
555                 id_us_clear_real(old_id);
556         }
557
558         if (old_id->us - skipped_refcounted < 0) {
559                 printf("Error in remapping process from '%s' (%p) to '%s' (%p): "
560                        "wrong user count in old ID after process (summing up to %d)\n",
561                        old_id->name, old_id, new_id ? new_id->name : "<NULL>", new_id, old_id->us - skipped_refcounted);
562                 BLI_assert(0);
563         }
564
565         if (skipped_direct == 0) {
566                 /* old_id is assumed to not be used directly anymore... */
567                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
568                         old_id->tag &= ~LIB_TAG_EXTERN;
569                         old_id->tag |= LIB_TAG_INDIRECT;
570                 }
571         }
572
573         /* Some after-process updates.
574          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
575          */
576         switch (GS(old_id->name)) {
577                 case ID_OB:
578                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id);
579                         break;
580                 case ID_GR:
581                         if (!new_id) {  /* Only affects us in case group was unlinked. */
582                                 for (Scene *sce = bmain->scene.first; sce; sce = sce->id.next) {
583                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
584                                 }
585                         }
586                         break;
587                 case ID_ME:
588                 case ID_CU:
589                 case ID_MB:
590                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
591                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
592                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
593                                 }
594                         }
595                         break;
596                 default:
597                         break;
598         }
599
600         /* Node trees may virtually use any kind of data-block... */
601         /* XXX Yuck!!!! nodetree update can do pretty much any thing when talking about py nodes,
602          *     including creating new data-blocks (see T50385), so we need to unlock main here. :(
603          *     Why can't we have re-entrent locks? */
604         BKE_main_unlock(bmain);
605         libblock_remap_data_postprocess_nodetree_update(bmain, new_id);
606         BKE_main_lock(bmain);
607
608         /* Full rebuild of DAG! */
609         DEG_relations_tag_update(bmain);
610 }
611
612 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
613 {
614         BKE_main_lock(bmain);
615
616         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
617
618         BKE_main_unlock(bmain);
619 }
620
621 /**
622  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
623  *
624  * \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
625  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
626  */
627 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
628 {
629         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
630                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
631
632         BKE_main_lock(bmain);
633
634         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
635
636         BKE_main_unlock(bmain);
637 }
638
639 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
640  *
641  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
642  * in which case all ID usages by given \a idv will be cleared.
643  * \param us_min_never_null: If \a true and new_id is NULL,
644  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
645  * (needed when given \a idv is going to be deleted right after being unlinked).
646  */
647 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
648 /* XXX Arg! Naming... :(
649  *     _relink? avoids confusion with _remap, but is confusing with _unlink
650  *     _remap_used_ids?
651  *     _remap_datablocks?
652  *     BKE_id_remap maybe?
653  *     ... sigh
654  */
655 void BKE_libblock_relink_ex(
656         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
657 {
658         ID *id = idv;
659         ID *old_id = old_idv;
660         ID *new_id = new_idv;
661         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
662
663         /* No need to lock here, we are only affecting given ID, not bmain database. */
664
665         BLI_assert(id);
666         if (old_id) {
667                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
668                 BLI_assert(old_id != new_id);
669         }
670         else {
671                 BLI_assert(new_id == NULL);
672         }
673
674         libblock_remap_data(bmain, id, old_id, new_id, remap_flags, NULL);
675
676         /* Some after-process updates.
677          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
678          */
679         switch (GS(id->name)) {
680                 case ID_SCE:
681                 {
682                         Scene *sce = (Scene *)id;
683
684                         if (old_id) {
685                                 switch (GS(old_id->name)) {
686                                         case ID_OB:
687                                         {
688                                                 libblock_remap_data_postprocess_object_fromgroup_update(
689                                                             bmain, (Object *)old_id, (Object *)new_id);
690                                                 break;
691                                         }
692                                         case ID_GR:
693                                                 if (!new_id) {  /* Only affects us in case group was unlinked. */
694                                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
695                                                 }
696                                                 break;
697                                         default:
698                                                 break;
699                                 }
700                         }
701                         else {
702                                 /* No choice but to check whole objects/groups. */
703                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
704                                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL);
705                                 }
706                                 for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
707                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
708                                 }
709                         }
710                         break;
711                 }
712                 case ID_OB:
713                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
714                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
715                         }
716                         break;
717                 default:
718                         break;
719         }
720 }
721
722 static int id_relink_to_newid_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cb_flag)
723 {
724         if (cb_flag & IDWALK_CB_PRIVATE) {
725                 return IDWALK_RET_NOP;
726         }
727
728         ID *id = *id_pointer;
729         if (id) {
730                 /* See: NEW_ID macro */
731                 if (id->newid) {
732                         BKE_library_update_ID_link_user(id->newid, id, cb_flag);
733                         *id_pointer = id->newid;
734                 }
735                 else if (id->tag & LIB_TAG_NEW) {
736                         id->tag &= ~LIB_TAG_NEW;
737                         BKE_libblock_relink_to_newid(id);
738                 }
739         }
740         return IDWALK_RET_NOP;
741 }
742
743 /** Similar to libblock_relink_ex, but is remapping IDs to their newid value if non-NULL, in given \a id.
744  *
745  * Very specific usage, not sure we'll keep it on the long run, currently only used in Object duplication code...
746  */
747 void BKE_libblock_relink_to_newid(ID *id)
748 {
749         if (ID_IS_LINKED_DATABLOCK(id))
750                 return;
751
752         BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0);
753 }
754
755 void BKE_libblock_free_data(ID *id, const bool do_id_user)
756 {
757         if (id->properties) {
758                 IDP_FreeProperty_ex(id->properties, do_id_user);
759                 MEM_freeN(id->properties);
760         }
761 }
762
763 void BKE_libblock_free_datablock(ID *id)
764 {
765         const short type = GS(id->name);
766         switch (type) {
767                 case ID_SCE:
768                         BKE_scene_free((Scene *)id);
769                         break;
770                 case ID_LI:
771                         BKE_library_free((Library *)id);
772                         break;
773                 case ID_OB:
774                         BKE_object_free((Object *)id);
775                         break;
776                 case ID_ME:
777                         BKE_mesh_free((Mesh *)id);
778                         break;
779                 case ID_CU:
780                         BKE_curve_free((Curve *)id);
781                         break;
782                 case ID_MB:
783                         BKE_mball_free((MetaBall *)id);
784                         break;
785                 case ID_MA:
786                         BKE_material_free((Material *)id);
787                         break;
788                 case ID_TE:
789                         BKE_texture_free((Tex *)id);
790                         break;
791                 case ID_IM:
792                         BKE_image_free((Image *)id);
793                         break;
794                 case ID_LT:
795                         BKE_lattice_free((Lattice *)id);
796                         break;
797                 case ID_LA:
798                         BKE_lamp_free((Lamp *)id);
799                         break;
800                 case ID_CA:
801                         BKE_camera_free((Camera *) id);
802                         break;
803                 case ID_IP:  /* Deprecated. */
804                         BKE_ipo_free((Ipo *)id);
805                         break;
806                 case ID_KE:
807                         BKE_key_free((Key *)id);
808                         break;
809                 case ID_WO:
810                         BKE_world_free((World *)id);
811                         break;
812                 case ID_SCR:
813                         BKE_screen_free((bScreen *)id);
814                         break;
815                 case ID_VF:
816                         BKE_vfont_free((VFont *)id);
817                         break;
818                 case ID_TXT:
819                         BKE_text_free((Text *)id);
820                         break;
821                 case ID_SPK:
822                         BKE_speaker_free((Speaker *)id);
823                         break;
824                 case ID_LP:
825                         BKE_lightprobe_free((LightProbe *)id);
826                         break;
827                 case ID_SO:
828                         BKE_sound_free((bSound *)id);
829                         break;
830                 case ID_GR:
831                         BKE_group_free((Group *)id);
832                         break;
833                 case ID_AR:
834                         BKE_armature_free((bArmature *)id);
835                         break;
836                 case ID_AC:
837                         BKE_action_free((bAction *)id);
838                         break;
839                 case ID_NT:
840                         ntreeFreeTree((bNodeTree *)id);
841                         break;
842                 case ID_BR:
843                         BKE_brush_free((Brush *)id);
844                         break;
845                 case ID_PA:
846                         BKE_particlesettings_free((ParticleSettings *)id);
847                         break;
848                 case ID_WM:
849                         if (free_windowmanager_cb)
850                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
851                         break;
852                 case ID_GD:
853                         BKE_gpencil_free((bGPdata *)id, true);
854                         break;
855                 case ID_MC:
856                         BKE_movieclip_free((MovieClip *)id);
857                         break;
858                 case ID_MSK:
859                         BKE_mask_free((Mask *)id);
860                         break;
861                 case ID_LS:
862                         BKE_linestyle_free((FreestyleLineStyle *)id);
863                         break;
864                 case ID_PAL:
865                         BKE_palette_free((Palette *)id);
866                         break;
867                 case ID_PC:
868                         BKE_paint_curve_free((PaintCurve *)id);
869                         break;
870                 case ID_CF:
871                         BKE_cachefile_free((CacheFile *)id);
872                         break;
873                 case ID_WS:
874                         BKE_workspace_free((WorkSpace *)id);
875                         break;
876         }
877 }
878
879 /**
880  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
881  *
882  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
883  *                    (only applies to main database)
884  * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
885  *                    \a id.
886  */
887 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
888 {
889         ID *id = idv;
890         short type = GS(id->name);
891         ListBase *lb = which_libbase(bmain, type);
892
893         DEG_id_type_tag(bmain, type);
894
895 #ifdef WITH_PYTHON
896         BPY_id_release(id);
897 #endif
898
899         if (do_id_user) {
900                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
901         }
902
903         BKE_libblock_free_datablock(id);
904
905         /* avoid notifying on removed data */
906         BKE_main_lock(bmain);
907
908         if (do_ui_user) {
909                 if (free_notifier_reference_cb) {
910                         free_notifier_reference_cb(id);
911                 }
912
913                 if (remap_editor_id_reference_cb) {
914                         remap_editor_id_reference_cb(id, NULL);
915                 }
916         }
917
918         BLI_remlink(lb, id);
919
920         BKE_libblock_free_data(id, do_id_user);
921         BKE_main_unlock(bmain);
922
923         MEM_freeN(id);
924 }
925
926 void BKE_libblock_free(Main *bmain, void *idv)
927 {
928         BKE_libblock_free_ex(bmain, idv, true, true);
929 }
930
931 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
932 {
933         ID *id = idv;
934         
935         id_us_min(id);
936
937         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
938          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
939          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
940          *     fully unlinked.
941          *     But only for local objects, not linked ones!
942          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
943          */
944         if ((GS(id->name) == ID_OB) && (id->us == 1) && (id->lib == NULL)) {
945                 id_us_clear_real(id);
946         }
947
948         if (id->us == 0) {
949                 BKE_libblock_unlink(bmain, id, false, false);
950                 
951                 BKE_libblock_free(bmain, id);
952         }
953 }
954
955 void BKE_libblock_delete(Main *bmain, void *idv)
956 {
957         ListBase *lbarray[MAX_LIBARRAY];
958         int base_count, i;
959
960         base_count = set_listbasepointers(bmain, lbarray);
961         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
962
963         /* First tag all datablocks directly from target lib.
964          * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
965          * Avoids to have to loop twice. */
966         for (i = 0; i < base_count; i++) {
967                 ListBase *lb = lbarray[i];
968                 ID *id;
969
970                 for (id = lb->first; id; id = id->next) {
971                         /* Note: in case we delete a library, we also delete all its datablocks! */
972                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
973                                 id->tag |= LIB_TAG_DOIT;
974                                 /* Will tag 'never NULL' users of this ID too.
975                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
976                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
977                                  * Also, this will also flag users of deleted data that cannot be unlinked
978                                  * (object using deleted obdata, etc.), so that they also get deleted. */
979                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
980                         }
981                 }
982         }
983
984         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
985          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
986          * over meshes when we come to freeing obdata). */
987         for (i = base_count; i--; ) {
988                 ListBase *lb = lbarray[i];
989                 ID *id, *id_next;
990
991                 for (id = lb->first; id; id = id_next) {
992                         id_next = id->next;
993                         if (id->tag & LIB_TAG_DOIT) {
994                                 if (id->us != 0) {
995 #ifdef DEBUG_PRINT
996                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
997 #endif
998                                         BLI_assert(id->us == 0);
999                                 }
1000                                 BKE_libblock_free(bmain, id);
1001                         }
1002                 }
1003         }
1004 }