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_group_unlink(
283         IDRemap *r_id_remap_data, Object *ob, const bool skip_indirect, const bool is_indirect)
284 {
285         Main *bmain = r_id_remap_data->bmain;
286         for (Group *group = bmain->group.first; group; group = group->id.next) {
287                 if (BKE_group_object_exists(group, ob)) {
288                         if (skip_indirect && is_indirect) {
289                                 r_id_remap_data->skipped_indirect++;
290                                 r_id_remap_data->skipped_refcounted++;
291                         }
292                         else {
293                                 BKE_collections_object_remove(bmain, &group->id, ob, false);
294                                 if (!is_indirect) {
295                                         r_id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
296                                 }
297                         }
298                 }
299         }
300 }
301
302 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
303 {
304         switch (GS(r_id_remap_data->id->name)) {
305                 case ID_SCE:
306                 {
307                         Scene *sce = (Scene *)r_id_remap_data->id;
308
309                         if (!r_id_remap_data->new_id) {
310                                 const bool is_indirect = (sce->id.lib != NULL);
311                                 const bool skip_indirect = (r_id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
312
313                                 /* In case we are unlinking... */
314                                 if (!r_id_remap_data->old_id) {
315                                         /* ... everything from scene. */
316                                         FOREACH_SCENE_OBJECT_BEGIN(sce, ob_iter)
317                                         {
318                                                 libblock_remap_data_preprocess_scene_object_unlink(
319                                                             r_id_remap_data, sce, ob_iter, skip_indirect, is_indirect);
320                                                 libblock_remap_data_preprocess_group_unlink(
321                                                             r_id_remap_data, ob_iter, skip_indirect, is_indirect);
322                                         }
323                                         FOREACH_SCENE_OBJECT_END;
324                                 }
325                                 else if (GS(r_id_remap_data->old_id->name) == ID_OB) {
326                                         /* ... a specific object from scene. */
327                                         Object *old_ob = (Object *)r_id_remap_data->old_id;
328                                         libblock_remap_data_preprocess_scene_object_unlink(
329                                                     r_id_remap_data, sce, old_ob, skip_indirect, is_indirect);
330                                         libblock_remap_data_preprocess_group_unlink(
331                                                     r_id_remap_data, old_ob, skip_indirect, is_indirect);
332                                 }
333
334                         }
335                         break;
336                 }
337                 case ID_OB:
338                 {
339                         ID *old_id = r_id_remap_data->old_id;
340                         if (!old_id || GS(old_id->name) == ID_AR) {
341                                 Object *ob = (Object *)r_id_remap_data->id;
342                                 /* Object's pose holds reference to armature bones... sic */
343                                 /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states.
344                                  * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid
345                                  * another complex and risky condition nightmare like the one we have in
346                                  * foreach_libblock_remap_callback()... */
347                                 if (ob->pose && (!old_id || ob->data == old_id)) {
348                                         BLI_assert(ob->type == OB_ARMATURE);
349                                         ob->pose->flag |= POSE_RECALC;
350                                         /* We need to clear pose bone pointers immediately, things like undo writefile may be called
351                                          * before pose is actually recomputed, can lead to segfault... */
352                                         BKE_pose_clear_pointers(ob->pose);
353                                 }
354                         }
355                         break;
356                 }
357                 default:
358                         break;
359         }
360 }
361
362 static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob)
363 {
364         if (old_ob->flag & OB_FROMGROUP) {
365                 /* Note that for Scene's BaseObject->flag, either we:
366                  *     - unlinked old_ob (i.e. new_ob is NULL), in which case scenes' bases have been removed already.
367                  *     - remapped old_ob by new_ob, in which case scenes' bases are still valid as is.
368                  * So in any case, no need to update them here. */
369                 if (BKE_group_object_find(NULL, old_ob) == NULL) {
370                         old_ob->flag &= ~OB_FROMGROUP;
371                 }
372                 if (new_ob == NULL) {  /* We need to remove NULL-ified groupobjects... */
373                         for (Group *group = bmain->group.first; group; group = group->id.next) {
374                                 BKE_group_object_unlink(group, NULL);
375                         }
376                 }
377                 else {
378                         new_ob->flag |= OB_FROMGROUP;
379                 }
380         }
381         if (old_ob->type == OB_MBALL) {
382                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
383                         if (ob->type == OB_MBALL && BKE_mball_is_basis_for(ob, old_ob)) {
384                                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
385                         }
386                 }
387         }
388 }
389
390 static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
391 {
392         /* Note that here we assume no object has no base (i.e. all objects are assumed instanced
393          * in one scene...). */
394         FOREACH_SCENE_OBJECT_BEGIN(sce, ob)
395         {
396                 if (ob->flag & OB_FROMGROUP) {
397                         Group *grp = BKE_group_object_find(NULL, ob);
398
399                         /* Unlinked group (old_id) is still in bmain... */
400                         if (grp && (&grp->id == old_id || grp->id.us == 0)) {
401                                 grp = BKE_group_object_find(grp, ob);
402                         }
403                         if (!grp) {
404                                 ob->flag &= ~OB_FROMGROUP;
405                         }
406                 }
407         }
408         FOREACH_SCENE_OBJECT_END;
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         if (id->override_static) {
777                 BKE_override_static_free(&id->override_static);
778         }
779
780         /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */
781 }
782
783 void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag))
784 {
785         const short type = GS(id->name);
786         switch (type) {
787                 case ID_SCE:
788                         BKE_scene_free((Scene *)id);
789                         break;
790                 case ID_LI:
791                         BKE_library_free((Library *)id);
792                         break;
793                 case ID_OB:
794                         BKE_object_free((Object *)id);
795                         break;
796                 case ID_ME:
797                         BKE_mesh_free((Mesh *)id);
798                         break;
799                 case ID_CU:
800                         BKE_curve_free((Curve *)id);
801                         break;
802                 case ID_MB:
803                         BKE_mball_free((MetaBall *)id);
804                         break;
805                 case ID_MA:
806                         BKE_material_free((Material *)id);
807                         break;
808                 case ID_TE:
809                         BKE_texture_free((Tex *)id);
810                         break;
811                 case ID_IM:
812                         BKE_image_free((Image *)id);
813                         break;
814                 case ID_LT:
815                         BKE_lattice_free((Lattice *)id);
816                         break;
817                 case ID_LA:
818                         BKE_lamp_free((Lamp *)id);
819                         break;
820                 case ID_CA:
821                         BKE_camera_free((Camera *) id);
822                         break;
823                 case ID_IP:  /* Deprecated. */
824                         BKE_ipo_free((Ipo *)id);
825                         break;
826                 case ID_KE:
827                         BKE_key_free((Key *)id);
828                         break;
829                 case ID_WO:
830                         BKE_world_free((World *)id);
831                         break;
832                 case ID_SCR:
833                         BKE_screen_free((bScreen *)id);
834                         break;
835                 case ID_VF:
836                         BKE_vfont_free((VFont *)id);
837                         break;
838                 case ID_TXT:
839                         BKE_text_free((Text *)id);
840                         break;
841                 case ID_SPK:
842                         BKE_speaker_free((Speaker *)id);
843                         break;
844                 case ID_LP:
845                         BKE_lightprobe_free((LightProbe *)id);
846                         break;
847                 case ID_SO:
848                         BKE_sound_free((bSound *)id);
849                         break;
850                 case ID_GR:
851                         BKE_group_free((Group *)id);
852                         break;
853                 case ID_AR:
854                         BKE_armature_free((bArmature *)id);
855                         break;
856                 case ID_AC:
857                         BKE_action_free((bAction *)id);
858                         break;
859                 case ID_NT:
860                         ntreeFreeTree((bNodeTree *)id);
861                         break;
862                 case ID_BR:
863                         BKE_brush_free((Brush *)id);
864                         break;
865                 case ID_PA:
866                         BKE_particlesettings_free((ParticleSettings *)id);
867                         break;
868                 case ID_WM:
869                         if (free_windowmanager_cb)
870                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
871                         break;
872                 case ID_GD:
873                         BKE_gpencil_free((bGPdata *)id, true);
874                         break;
875                 case ID_MC:
876                         BKE_movieclip_free((MovieClip *)id);
877                         break;
878                 case ID_MSK:
879                         BKE_mask_free((Mask *)id);
880                         break;
881                 case ID_LS:
882                         BKE_linestyle_free((FreestyleLineStyle *)id);
883                         break;
884                 case ID_PAL:
885                         BKE_palette_free((Palette *)id);
886                         break;
887                 case ID_PC:
888                         BKE_paint_curve_free((PaintCurve *)id);
889                         break;
890                 case ID_CF:
891                         BKE_cachefile_free((CacheFile *)id);
892                         break;
893                 case ID_WS:
894                         BKE_workspace_free((WorkSpace *)id);
895                         break;
896         }
897 }
898
899
900 void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag)
901 {
902         ID *id = idv;
903
904         if (use_flag_from_idtag) {
905                 if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
906                         flag |= LIB_ID_FREE_NO_MAIN;
907                 }
908                 else {
909                         flag &= ~LIB_ID_FREE_NO_MAIN;
910                 }
911
912                 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
913                         flag |= LIB_ID_FREE_NO_USER_REFCOUNT;
914                 }
915                 else {
916                         flag &= ~LIB_ID_FREE_NO_USER_REFCOUNT;
917                 }
918
919                 if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
920                         flag |= LIB_ID_FREE_NOT_ALLOCATED;
921                 }
922                 else {
923                         flag &= ~LIB_ID_FREE_NOT_ALLOCATED;
924                 }
925         }
926
927         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || bmain != NULL);
928         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NOT_ALLOCATED) == 0);
929         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
930
931         const short type = GS(id->name);
932
933         if (bmain && (flag & LIB_ID_FREE_NO_DEG_TAG) == 0) {
934                 DEG_id_type_tag(bmain, type);
935         }
936
937 #ifdef WITH_PYTHON
938         BPY_id_release(id);
939 #endif
940
941         if ((flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0) {
942                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
943         }
944
945         BKE_libblock_free_datablock(id, flag);
946
947         /* avoid notifying on removed data */
948         if (bmain) {
949                 BKE_main_lock(bmain);
950         }
951
952         if ((flag & LIB_ID_FREE_NO_UI_USER) == 0) {
953                 if (free_notifier_reference_cb) {
954                         free_notifier_reference_cb(id);
955                 }
956
957                 if (remap_editor_id_reference_cb) {
958                         remap_editor_id_reference_cb(id, NULL);
959                 }
960         }
961
962         if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
963                 ListBase *lb = which_libbase(bmain, type);
964                 BLI_remlink(lb, id);
965         }
966
967         BKE_libblock_free_data(id, (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
968
969         if (bmain) {
970                 BKE_main_unlock(bmain);
971         }
972
973         if ((flag & LIB_ID_FREE_NOT_ALLOCATED) == 0) {
974                 MEM_freeN(id);
975         }
976 }
977
978 void BKE_id_free(Main *bmain, void *idv)
979 {
980         BKE_id_free_ex(bmain, idv, 0, true);
981 }
982
983 /**
984  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
985  *
986  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
987  *                    (only applies to main database)
988  * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
989  *                    \a id.
990  */
991 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
992 {
993         ID *id = idv;
994         short type = GS(id->name);
995         ListBase *lb = which_libbase(bmain, type);
996
997         DEG_id_type_tag(bmain, type);
998
999 #ifdef WITH_PYTHON
1000 #ifdef WITH_PYTHON_SAFETY
1001         BPY_id_release(id);
1002 #endif
1003         if (id->py_instance) {
1004                 BPY_DECREF_RNA_INVALIDATE(id->py_instance);
1005         }
1006 #endif
1007
1008         if (do_id_user) {
1009                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
1010         }
1011
1012         BKE_libblock_free_datablock(id, 0);
1013
1014         /* avoid notifying on removed data */
1015         BKE_main_lock(bmain);
1016
1017         if (do_ui_user) {
1018                 if (free_notifier_reference_cb) {
1019                         free_notifier_reference_cb(id);
1020                 }
1021
1022                 if (remap_editor_id_reference_cb) {
1023                         remap_editor_id_reference_cb(id, NULL);
1024                 }
1025         }
1026
1027         BLI_remlink(lb, id);
1028
1029         BKE_libblock_free_data(id, do_id_user);
1030         BKE_main_unlock(bmain);
1031
1032         MEM_freeN(id);
1033 }
1034
1035 void BKE_libblock_free(Main *bmain, void *idv)
1036 {
1037         BKE_libblock_free_ex(bmain, idv, true, true);
1038 }
1039
1040 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
1041 {
1042         ID *id = idv;
1043         
1044         id_us_min(id);
1045
1046         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
1047          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
1048          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
1049          *     fully unlinked.
1050          *     But only for local objects, not linked ones!
1051          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
1052          */
1053         if ((GS(id->name) == ID_OB) && (id->us == 1) && (id->lib == NULL)) {
1054                 id_us_clear_real(id);
1055         }
1056
1057         if (id->us == 0) {
1058                 BKE_libblock_unlink(bmain, id, false, false);
1059                 
1060                 BKE_libblock_free(bmain, id);
1061         }
1062 }
1063
1064 void BKE_libblock_delete(Main *bmain, void *idv)
1065 {
1066         ListBase *lbarray[MAX_LIBARRAY];
1067         int base_count, i;
1068
1069         base_count = set_listbasepointers(bmain, lbarray);
1070         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1071
1072         /* First tag all datablocks directly from target lib.
1073          * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
1074          * Avoids to have to loop twice. */
1075         for (i = 0; i < base_count; i++) {
1076                 ListBase *lb = lbarray[i];
1077                 ID *id;
1078
1079                 for (id = lb->first; id; id = id->next) {
1080                         /* Note: in case we delete a library, we also delete all its datablocks! */
1081                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
1082                                 id->tag |= LIB_TAG_DOIT;
1083                                 /* Will tag 'never NULL' users of this ID too.
1084                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
1085                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
1086                                  * Also, this will also flag users of deleted data that cannot be unlinked
1087                                  * (object using deleted obdata, etc.), so that they also get deleted. */
1088                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
1089                         }
1090                 }
1091         }
1092
1093         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
1094          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
1095          * over meshes when we come to freeing obdata). */
1096         for (i = base_count; i--; ) {
1097                 ListBase *lb = lbarray[i];
1098                 ID *id, *id_next;
1099
1100                 for (id = lb->first; id; id = id_next) {
1101                         id_next = id->next;
1102                         if (id->tag & LIB_TAG_DOIT) {
1103                                 if (id->us != 0) {
1104 #ifdef DEBUG_PRINT
1105                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
1106 #endif
1107                                         BLI_assert(id->us == 0);
1108                                 }
1109                                 BKE_libblock_free(bmain, id);
1110                         }
1111                 }
1112         }
1113 }