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