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