Fix T62613: In duplicated collections objects loses patrenting.
[blender.git] / source / blender / blenkernel / intern / library_remap.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file
18  * \ingroup bke
19  *
20  * Contains management of ID's and libraries remap, unlink and free logic.
21  */
22
23 #include <stdio.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <assert.h>
29
30 #include "CLG_log.h"
31
32 #include "MEM_guardedalloc.h"
33
34 /* all types are needed here, in order to do memory operations */
35 #include "DNA_anim_types.h"
36 #include "DNA_armature_types.h"
37 #include "DNA_brush_types.h"
38 #include "DNA_camera_types.h"
39 #include "DNA_cachefile_types.h"
40 #include "DNA_collection_types.h"
41 #include "DNA_gpencil_types.h"
42 #include "DNA_ipo_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_light_types.h"
45 #include "DNA_lattice_types.h"
46 #include "DNA_linestyle_types.h"
47 #include "DNA_material_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meta_types.h"
50 #include "DNA_movieclip_types.h"
51 #include "DNA_mask_types.h"
52 #include "DNA_node_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_lightprobe_types.h"
55 #include "DNA_scene_types.h"
56 #include "DNA_screen_types.h"
57 #include "DNA_speaker_types.h"
58 #include "DNA_sound_types.h"
59 #include "DNA_text_types.h"
60 #include "DNA_vfont_types.h"
61 #include "DNA_windowmanager_types.h"
62 #include "DNA_workspace_types.h"
63 #include "DNA_world_types.h"
64
65 #include "BLI_blenlib.h"
66 #include "BLI_utildefines.h"
67
68 #include "BKE_action.h"
69 #include "BKE_animsys.h"
70 #include "BKE_armature.h"
71 #include "BKE_brush.h"
72 #include "BKE_camera.h"
73 #include "BKE_cachefile.h"
74 #include "BKE_collection.h"
75 #include "BKE_curve.h"
76 #include "BKE_fcurve.h"
77 #include "BKE_font.h"
78 #include "BKE_gpencil.h"
79 #include "BKE_idprop.h"
80 #include "BKE_image.h"
81 #include "BKE_ipo.h"
82 #include "BKE_key.h"
83 #include "BKE_light.h"
84 #include "BKE_lattice.h"
85 #include "BKE_layer.h"
86 #include "BKE_library.h"
87 #include "BKE_library_override.h"
88 #include "BKE_library_query.h"
89 #include "BKE_library_remap.h"
90 #include "BKE_linestyle.h"
91 #include "BKE_mesh.h"
92 #include "BKE_material.h"
93 #include "BKE_main.h"
94 #include "BKE_mask.h"
95 #include "BKE_mball.h"
96 #include "BKE_modifier.h"
97 #include "BKE_movieclip.h"
98 #include "BKE_multires.h"
99 #include "BKE_node.h"
100 #include "BKE_object.h"
101 #include "BKE_paint.h"
102 #include "BKE_particle.h"
103 #include "BKE_lightprobe.h"
104 #include "BKE_speaker.h"
105 #include "BKE_sound.h"
106 #include "BKE_screen.h"
107 #include "BKE_scene.h"
108 #include "BKE_text.h"
109 #include "BKE_texture.h"
110 #include "BKE_workspace.h"
111 #include "BKE_world.h"
112
113 #include "DEG_depsgraph.h"
114 #include "DEG_depsgraph_build.h"
115
116 #ifdef WITH_PYTHON
117 #include "BPY_extern.h"
118 #endif
119
120 static CLG_LogRef LOG = {"bke.library_remap"};
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                 /* Better remap to NULL than not remapping at all, then we can handle it as a regular remap-to-NULL case... */
184                 if ((cb_flag & IDWALK_CB_NEVER_SELF) && (new_id == id_self)) {
185                         new_id = NULL;
186                 }
187
188                 const bool is_reference = (cb_flag & IDWALK_CB_STATIC_OVERRIDE_REFERENCE) != 0;
189                 const bool is_indirect = (cb_flag & IDWALK_CB_INDIRECT_USAGE) != 0;
190                 const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
191                 /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct,
192                  *       on the other hand since they get reset to lib data on file open/reload it is indirect too...
193                  *       Edit Mode is also a 'skip direct' case. */
194                 const bool is_obj = (GS(id->name) == ID_OB);
195                 const bool is_obj_proxy = (is_obj && (((Object *)id)->proxy || ((Object *)id)->proxy_group));
196                 const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
197                 const bool is_never_null = ((cb_flag & IDWALK_CB_NEVER_NULL) &&
198                                             (new_id == NULL) &&
199                                             (id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
200                 const bool skip_reference = (id_remap_data->flag & ID_REMAP_SKIP_STATIC_OVERRIDE) != 0;
201                 const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
202
203 #ifdef DEBUG_PRINT
204                 printf("In %s (lib %p): Remapping %s (%p) to %s (%p) "
205                        "(is_indirect: %d, skip_indirect: %d, is_reference: %d, skip_reference: %d)\n",
206                        id->name, id->lib, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id,
207                        is_indirect, skip_indirect, is_reference, skip_reference);
208 #endif
209
210                 if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) {
211                         id->tag |= LIB_TAG_DOIT;
212                 }
213
214                 /* Special hack in case it's Object->data and we are in edit mode, and new_id is not NULL
215                  * (otherwise, we follow common NEVER_NULL flags).
216                  * (skipped_indirect too). */
217                 if ((is_never_null && skip_never_null) ||
218                     (is_obj_editmode && (((Object *)id)->data == *id_p) && new_id != NULL) ||
219                     (skip_indirect && is_indirect) ||
220                     (is_reference && skip_reference))
221                 {
222                         if (is_indirect) {
223                                 id_remap_data->skipped_indirect++;
224                                 if (is_obj) {
225                                         Object *ob = (Object *)id;
226                                         if (ob->data == *id_p && ob->proxy != NULL) {
227                                                 /* And another 'Proudly brought to you by Proxy Hell' hack!
228                                                  * This will allow us to avoid clearing 'LIB_EXTERN' flag of obdata of proxies... */
229                                                 id_remap_data->skipped_direct++;
230                                         }
231                                 }
232                         }
233                         else if (is_never_null || is_obj_editmode || is_reference) {
234                                 id_remap_data->skipped_direct++;
235                         }
236                         else {
237                                 BLI_assert(0);
238                         }
239                         if (cb_flag & IDWALK_CB_USER) {
240                                 id_remap_data->skipped_refcounted++;
241                         }
242                         else if (cb_flag & IDWALK_CB_USER_ONE) {
243                                 /* No need to count number of times this happens, just a flag is enough. */
244                                 id_remap_data->status |= ID_REMAP_IS_USER_ONE_SKIPPED;
245                         }
246                 }
247                 else {
248                         if (!is_never_null) {
249                                 *id_p = new_id;
250                                 DEG_id_tag_update_ex(id_remap_data->bmain, id_self,
251                                                      ID_RECALC_COPY_ON_WRITE | ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
252                         }
253                         if (cb_flag & IDWALK_CB_USER) {
254                                 /* NOTE: We don't user-count IDs which are not in the main database.
255                                  * This is because in certain conditions we can have datablocks in
256                                  * the main which are referencing datablocks outside of it.
257                                  * For example, BKE_mesh_new_from_object() called on an evaluated
258                                  * object will cause such situation.
259                                  */
260                                 if ((old_id->tag & LIB_TAG_NO_MAIN) == 0) {
261                                         id_us_min(old_id);
262                                 }
263                                 if (new_id != NULL && (new_id->tag & LIB_TAG_NO_MAIN) == 0) {
264                                         /* We do not want to handle LIB_TAG_INDIRECT/LIB_TAG_EXTERN here. */
265                                         new_id->us++;
266                                 }
267                         }
268                         else if (cb_flag & IDWALK_CB_USER_ONE) {
269                                 id_us_ensure_real(new_id);
270                                 /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
271                                  * that extra user is processed in final handling... */
272                         }
273                         if (!is_indirect || is_obj_proxy) {
274                                 id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
275                         }
276                 }
277         }
278
279         return IDWALK_RET_NOP;
280 }
281
282 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
283 {
284         switch (GS(r_id_remap_data->id->name)) {
285                 case ID_OB:
286                 {
287                         ID *old_id = r_id_remap_data->old_id;
288                         if (!old_id || GS(old_id->name) == ID_AR) {
289                                 Object *ob = (Object *)r_id_remap_data->id;
290                                 /* Object's pose holds reference to armature bones... sic */
291                                 /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states.
292                                  * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid
293                                  * another complex and risky condition nightmare like the one we have in
294                                  * foreach_libblock_remap_callback()... */
295                                 if (ob->pose && (!old_id || ob->data == old_id)) {
296                                         BLI_assert(ob->type == OB_ARMATURE);
297                                         ob->pose->flag |= POSE_RECALC;
298                                         /* We need to clear pose bone pointers immediately, things like undo writefile may be called
299                                          * before pose is actually recomputed, can lead to segfault... */
300                                         BKE_pose_clear_pointers(ob->pose);
301                                 }
302                         }
303                         break;
304                 }
305                 default:
306                         break;
307         }
308 }
309
310 /* Can be called with both old_ob and new_ob being NULL, this means we have to check whole Main database then. */
311 static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob)
312 {
313         if (new_ob == NULL) {
314                 /* In case we unlinked old_ob (new_ob is NULL), the object has already
315                  * been removed from the scenes and their collections. We still have
316                  * to remove the NULL children from collections not used in any scene. */
317                 BKE_collections_object_remove_nulls(bmain);
318         }
319
320         BKE_main_collection_sync_remap(bmain);
321
322         if (old_ob == NULL) {
323                 for (Object *ob = bmain->object.first; ob != NULL; ob = ob->id.next) {
324                         if (ob->type == OB_MBALL && BKE_mball_is_basis(ob)) {
325                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
326                         }
327                 }
328         }
329         else {
330                 for (Object *ob = bmain->object.first; ob != NULL; ob = ob->id.next) {
331                         if (ob->type == OB_MBALL && BKE_mball_is_basis_for(ob, old_ob)) {
332                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
333                                 break;  /* There is only one basis... */
334                         }
335                 }
336         }
337 }
338
339 /* Can be called with both old_collection and new_collection being NULL,
340  * this means we have to check whole Main database then. */
341 static void libblock_remap_data_postprocess_collection_update(
342         Main *bmain, Collection *UNUSED(old_collection), Collection *new_collection)
343 {
344         if (new_collection == NULL) {
345                 /* XXX Complex cases can lead to NULL pointers in other collections than old_collection,
346                  * and BKE_main_collection_sync_remap() does not tolerate any of those, so for now always check whole
347                  * existing collections for NULL pointers.
348                  * I'd consider optimizing that whole collection remapping process a TODO for later. */
349                 BKE_collections_child_remove_nulls(bmain, NULL /*old_collection*/);
350         }
351
352         BKE_main_collection_sync_remap(bmain);
353 }
354
355 static void libblock_remap_data_postprocess_obdata_relink(Main *bmain, Object *ob, ID *new_id)
356 {
357         if (ob->data == new_id) {
358                 switch (GS(new_id->name)) {
359                         case ID_ME:
360                                 multires_force_update(ob);
361                                 break;
362                         case ID_CU:
363                                 BKE_curve_type_test(ob);
364                                 break;
365                         default:
366                                 break;
367                 }
368                 test_object_modifiers(ob);
369                 test_object_materials(bmain, ob, new_id);
370         }
371 }
372
373 static void libblock_remap_data_postprocess_nodetree_update(Main *bmain, ID *new_id)
374 {
375         /* Verify all nodetree user nodes. */
376         ntreeVerifyNodes(bmain, new_id);
377
378         /* Update node trees as necessary. */
379         FOREACH_NODETREE_BEGIN(bmain, ntree, id) {
380                 /* make an update call for the tree */
381                 ntreeUpdateTree(bmain, ntree);
382         } FOREACH_NODETREE_END;
383 }
384
385 /**
386  * Execute the 'data' part of the remapping (that is, all ID pointers from other ID datablocks).
387  *
388  * Behavior differs depending on whether given \a id is NULL or not:
389  * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not
390  *   (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id
391  *   are remapped to \a new_id.
392  * - \a id is non-NULL:
393  *   + 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
394  *     does not references any other datablock anymore).
395  *   + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only within given \a id.
396  *
397  * \param bmain: the Main data storage to operate on (must never be NULL).
398  * \param id: the datablock to operate on (can be NULL, in which case we operate over all IDs from given bmain).
399  * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL).
400  * \param new_id: the new datablock to replace \a old_id references with (may be NULL).
401  * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process).
402  */
403 ATTR_NONNULL(1) static void libblock_remap_data(
404         Main *bmain, ID *id, ID *old_id, ID *new_id, const short remap_flags, IDRemap *r_id_remap_data)
405 {
406         IDRemap id_remap_data;
407         const int foreach_id_flags = (remap_flags & ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE) != 0 ? IDWALK_NO_INDIRECT_PROXY_DATA_USAGE : IDWALK_NOP;
408
409         if (r_id_remap_data == NULL) {
410                 r_id_remap_data = &id_remap_data;
411         }
412         r_id_remap_data->bmain = bmain;
413         r_id_remap_data->old_id = old_id;
414         r_id_remap_data->new_id = new_id;
415         r_id_remap_data->id = NULL;
416         r_id_remap_data->flag = remap_flags;
417         r_id_remap_data->status = 0;
418         r_id_remap_data->skipped_direct = 0;
419         r_id_remap_data->skipped_indirect = 0;
420         r_id_remap_data->skipped_refcounted = 0;
421
422         if (id) {
423 #ifdef DEBUG_PRINT
424                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
425 #endif
426                 r_id_remap_data->id = id;
427                 libblock_remap_data_preprocess(r_id_remap_data);
428                 BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
429         }
430         else {
431                 /* Note that this is a very 'brute force' approach, maybe we could use some depsgraph to only process
432                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
433                 ID *id_curr;
434
435                 FOREACH_MAIN_ID_BEGIN(bmain, id_curr)
436                 {
437                         if (BKE_library_id_can_use_idtype(id_curr, GS(old_id->name))) {
438                                 /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
439                                  * the user count handling...
440                                  * XXX No more true (except for debug usage of those skipping counters). */
441                                 r_id_remap_data->id = id_curr;
442                                 libblock_remap_data_preprocess(r_id_remap_data);
443                                 BKE_library_foreach_ID_link(
444                                             NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
445                         }
446                 }
447                 FOREACH_MAIN_ID_END;
448         }
449
450         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
451          *     though, we can always add an option (flag) to control this later if needed. */
452         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
453                 id_fake_user_clear(old_id);
454                 id_fake_user_set(new_id);
455         }
456
457         id_us_clear_real(old_id);
458
459         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
460                 new_id->tag &= ~LIB_TAG_INDIRECT;
461                 new_id->tag |= LIB_TAG_EXTERN;
462         }
463
464 #ifdef DEBUG_PRINT
465         printf("%s: %d occurrences skipped (%d direct and %d indirect ones)\n", __func__,
466                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
467                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
468 #endif
469 }
470
471 /**
472  * Replace all references in given Main to \a old_id by \a new_id
473  * (if \a new_id is NULL, it unlinks \a old_id).
474  */
475 void BKE_libblock_remap_locked(
476         Main *bmain, void *old_idv, void *new_idv,
477         const short remap_flags)
478 {
479         IDRemap id_remap_data;
480         ID *old_id = old_idv;
481         ID *new_id = new_idv;
482         int skipped_direct, skipped_refcounted;
483
484         BLI_assert(old_id != NULL);
485         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
486         BLI_assert(old_id != new_id);
487
488         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
489
490         if (free_notifier_reference_cb) {
491                 free_notifier_reference_cb(old_id);
492         }
493
494         /* We assume editors do not hold references to their IDs... This is false in some cases
495          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
496         if (remap_editor_id_reference_cb) {
497                 remap_editor_id_reference_cb(old_id, new_id);
498         }
499
500         skipped_direct = id_remap_data.skipped_direct;
501         skipped_refcounted = id_remap_data.skipped_refcounted;
502
503         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
504          * been incremented for that, we have to decrease once more its user count... unless we had to skip
505          * some 'user_one' cases. */
506         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
507                 id_us_clear_real(old_id);
508         }
509
510         if (old_id->us - skipped_refcounted < 0) {
511                 CLOG_ERROR(&LOG, "Error in remapping process from '%s' (%p) to '%s' (%p): "
512                            "wrong user count in old ID after process (summing up to %d)",
513                            old_id->name, old_id, new_id ? new_id->name : "<NULL>", new_id, old_id->us - skipped_refcounted);
514                 BLI_assert(0);
515         }
516
517         if (skipped_direct == 0) {
518                 /* old_id is assumed to not be used directly anymore... */
519                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
520                         old_id->tag &= ~LIB_TAG_EXTERN;
521                         old_id->tag |= LIB_TAG_INDIRECT;
522                 }
523         }
524
525         /* Some after-process updates.
526          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
527          */
528         switch (GS(old_id->name)) {
529                 case ID_OB:
530                         libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
531                         break;
532                 case ID_GR:
533                         libblock_remap_data_postprocess_collection_update(bmain, (Collection *)old_id, (Collection *)new_id);
534                         break;
535                 case ID_ME:
536                 case ID_CU:
537                 case ID_MB:
538                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
539                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
540                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
541                                 }
542                         }
543                         break;
544                 default:
545                         break;
546         }
547
548         /* Node trees may virtually use any kind of data-block... */
549         /* XXX Yuck!!!! nodetree update can do pretty much any thing when talking about py nodes,
550          *     including creating new data-blocks (see T50385), so we need to unlock main here. :(
551          *     Why can't we have re-entrent locks? */
552         BKE_main_unlock(bmain);
553         libblock_remap_data_postprocess_nodetree_update(bmain, new_id);
554         BKE_main_lock(bmain);
555
556         /* Full rebuild of DEG! */
557         DEG_relations_tag_update(bmain);
558 }
559
560 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
561 {
562         BKE_main_lock(bmain);
563
564         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
565
566         BKE_main_unlock(bmain);
567 }
568
569 /**
570  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
571  *
572  * \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
573  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
574  */
575 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
576 {
577         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
578                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
579
580         BKE_main_lock(bmain);
581
582         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
583
584         BKE_main_unlock(bmain);
585 }
586
587 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
588  *
589  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
590  * in which case all ID usages by given \a idv will be cleared.
591  * \param us_min_never_null: If \a true and new_id is NULL,
592  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
593  * (needed when given \a idv is going to be deleted right after being unlinked).
594  */
595 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
596 /* XXX Arg! Naming... :(
597  *     _relink? avoids confusion with _remap, but is confusing with _unlink
598  *     _remap_used_ids?
599  *     _remap_datablocks?
600  *     BKE_id_remap maybe?
601  *     ... sigh
602  */
603 void BKE_libblock_relink_ex(
604         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
605 {
606         ID *id = idv;
607         ID *old_id = old_idv;
608         ID *new_id = new_idv;
609         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
610
611         /* No need to lock here, we are only affecting given ID, not bmain database. */
612
613         BLI_assert(id);
614         if (old_id) {
615                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
616                 BLI_assert(old_id != new_id);
617         }
618         else {
619                 BLI_assert(new_id == NULL);
620         }
621
622         libblock_remap_data(bmain, id, old_id, new_id, remap_flags, NULL);
623
624         /* Some after-process updates.
625          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
626          */
627         switch (GS(id->name)) {
628                 case ID_SCE:
629                 {
630                         if (old_id) {
631                                 switch (GS(old_id->name)) {
632                                         case ID_OB:
633                                                 libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
634                                                 break;
635                                         case ID_GR:
636                                                 libblock_remap_data_postprocess_collection_update(bmain, (Collection *)old_id, (Collection *)new_id);
637                                                 break;
638                                         default:
639                                                 break;
640                                 }
641                         }
642                         else {
643                                 /* No choice but to check whole objects/collections. */
644                                 libblock_remap_data_postprocess_collection_update(bmain, NULL, NULL);
645                                 libblock_remap_data_postprocess_object_update(bmain, NULL, NULL);
646                         }
647                         break;
648                 }
649                 case ID_OB:
650                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
651                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
652                         }
653                         break;
654                 default:
655                         break;
656         }
657 }
658
659 static int id_relink_to_newid_looper(void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int cb_flag)
660 {
661         if (cb_flag & IDWALK_CB_PRIVATE) {
662                 return IDWALK_RET_NOP;
663         }
664
665         ID *id = *id_pointer;
666         if (id) {
667                 /* See: NEW_ID macro */
668                 if (id->newid) {
669                         BKE_library_update_ID_link_user(id->newid, id, cb_flag);
670                         *id_pointer = id->newid;
671                 }
672                 else if (id->tag & LIB_TAG_NEW) {
673                         id->tag &= ~LIB_TAG_NEW;
674                         BKE_libblock_relink_to_newid(id);
675                 }
676         }
677         return IDWALK_RET_NOP;
678 }
679
680 /** Similar to libblock_relink_ex, but is remapping IDs to their newid value if non-NULL, in given \a id.
681  *
682  * Very specific usage, not sure we'll keep it on the long run, currently only used in Object/Collection duplication code...
683  */
684 void BKE_libblock_relink_to_newid(ID *id)
685 {
686         if (ID_IS_LINKED(id))
687                 return;
688
689         BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0);
690 }
691
692 void BKE_libblock_free_data(ID *id, const bool do_id_user)
693 {
694         if (id->properties) {
695                 IDP_FreeProperty_ex(id->properties, do_id_user);
696                 MEM_freeN(id->properties);
697         }
698
699         if (id->override_static) {
700                 BKE_override_static_free(&id->override_static);
701         }
702
703         /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */
704 }
705
706 void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag))
707 {
708         const short type = GS(id->name);
709         switch (type) {
710                 case ID_SCE:
711                         BKE_scene_free_ex((Scene *)id, false);
712                         break;
713                 case ID_LI:
714                         BKE_library_free((Library *)id);
715                         break;
716                 case ID_OB:
717                         BKE_object_free((Object *)id);
718                         break;
719                 case ID_ME:
720                         BKE_mesh_free((Mesh *)id);
721                         break;
722                 case ID_CU:
723                         BKE_curve_free((Curve *)id);
724                         break;
725                 case ID_MB:
726                         BKE_mball_free((MetaBall *)id);
727                         break;
728                 case ID_MA:
729                         BKE_material_free((Material *)id);
730                         break;
731                 case ID_TE:
732                         BKE_texture_free((Tex *)id);
733                         break;
734                 case ID_IM:
735                         BKE_image_free((Image *)id);
736                         break;
737                 case ID_LT:
738                         BKE_lattice_free((Lattice *)id);
739                         break;
740                 case ID_LA:
741                         BKE_light_free((Light *)id);
742                         break;
743                 case ID_CA:
744                         BKE_camera_free((Camera *) id);
745                         break;
746                 case ID_IP:  /* Deprecated. */
747                         BKE_ipo_free((Ipo *)id);
748                         break;
749                 case ID_KE:
750                         BKE_key_free((Key *)id);
751                         break;
752                 case ID_WO:
753                         BKE_world_free((World *)id);
754                         break;
755                 case ID_SCR:
756                         BKE_screen_free((bScreen *)id);
757                         break;
758                 case ID_VF:
759                         BKE_vfont_free((VFont *)id);
760                         break;
761                 case ID_TXT:
762                         BKE_text_free((Text *)id);
763                         break;
764                 case ID_SPK:
765                         BKE_speaker_free((Speaker *)id);
766                         break;
767                 case ID_LP:
768                         BKE_lightprobe_free((LightProbe *)id);
769                         break;
770                 case ID_SO:
771                         BKE_sound_free((bSound *)id);
772                         break;
773                 case ID_GR:
774                         BKE_collection_free((Collection *)id);
775                         break;
776                 case ID_AR:
777                         BKE_armature_free((bArmature *)id);
778                         break;
779                 case ID_AC:
780                         BKE_action_free((bAction *)id);
781                         break;
782                 case ID_NT:
783                         ntreeFreeTree((bNodeTree *)id);
784                         break;
785                 case ID_BR:
786                         BKE_brush_free((Brush *)id);
787                         break;
788                 case ID_PA:
789                         BKE_particlesettings_free((ParticleSettings *)id);
790                         break;
791                 case ID_WM:
792                         if (free_windowmanager_cb)
793                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
794                         break;
795                 case ID_GD:
796                         BKE_gpencil_free((bGPdata *)id, true);
797                         break;
798                 case ID_MC:
799                         BKE_movieclip_free((MovieClip *)id);
800                         break;
801                 case ID_MSK:
802                         BKE_mask_free((Mask *)id);
803                         break;
804                 case ID_LS:
805                         BKE_linestyle_free((FreestyleLineStyle *)id);
806                         break;
807                 case ID_PAL:
808                         BKE_palette_free((Palette *)id);
809                         break;
810                 case ID_PC:
811                         BKE_paint_curve_free((PaintCurve *)id);
812                         break;
813                 case ID_CF:
814                         BKE_cachefile_free((CacheFile *)id);
815                         break;
816                 case ID_WS:
817                         BKE_workspace_free((WorkSpace *)id);
818                         break;
819         }
820 }
821
822 /**
823  * Complete ID freeing, extended version for corner cases.
824  * Can override default (and safe!) freeing process, to gain some speed up.
825  *
826  * At that point, given id is assumed to not be used by any other data-block already
827  * (might not be actually true, in case e.g. several inter-related IDs get freed together...).
828  * However, they might still be using (referencing) other IDs, this code takes care of it if
829  * \a LIB_TAG_NO_USER_REFCOUNT is not defined.
830  *
831  * \param bmain: Main database containing the freed ID, can be NULL in case it's a temp ID outside of any Main.
832  * \param idv: Pointer to ID to be freed.
833  * \param flag: Set of \a LIB_ID_FREE_... flags controlling/overriding usual freeing process,
834  * 0 to get default safe behavior.
835  * \param use_flag_from_idtag: Still use freeing info flags from given ID datablock,
836  * even if some overriding ones are passed in \a falg parameter.
837  */
838 void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag)
839 {
840         ID *id = idv;
841
842         if (use_flag_from_idtag) {
843                 if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
844                         flag |= LIB_ID_FREE_NO_MAIN | LIB_ID_FREE_NO_UI_USER | LIB_ID_FREE_NO_DEG_TAG;
845                 }
846                 else {
847                         flag &= ~LIB_ID_FREE_NO_MAIN;
848                 }
849
850                 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
851                         flag |= LIB_ID_FREE_NO_USER_REFCOUNT;
852                 }
853                 else {
854                         flag &= ~LIB_ID_FREE_NO_USER_REFCOUNT;
855                 }
856
857                 if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
858                         flag |= LIB_ID_FREE_NOT_ALLOCATED;
859                 }
860                 else {
861                         flag &= ~LIB_ID_FREE_NOT_ALLOCATED;
862                 }
863         }
864
865         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || bmain != NULL);
866         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NOT_ALLOCATED) == 0);
867         BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
868
869         const short type = GS(id->name);
870
871         if (bmain && (flag & LIB_ID_FREE_NO_DEG_TAG) == 0) {
872                 DEG_id_type_tag(bmain, type);
873         }
874
875 #ifdef WITH_PYTHON
876 #  ifdef WITH_PYTHON_SAFETY
877         BPY_id_release(id);
878 #  endif
879         if (id->py_instance) {
880                 BPY_DECREF_RNA_INVALIDATE(id->py_instance);
881         }
882 #endif
883
884         if ((flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0) {
885                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
886         }
887
888         BKE_libblock_free_datablock(id, flag);
889
890         /* avoid notifying on removed data */
891         if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
892                 BKE_main_lock(bmain);
893         }
894
895         if ((flag & LIB_ID_FREE_NO_UI_USER) == 0) {
896                 if (free_notifier_reference_cb) {
897                         free_notifier_reference_cb(id);
898                 }
899
900                 if (remap_editor_id_reference_cb) {
901                         remap_editor_id_reference_cb(id, NULL);
902                 }
903         }
904
905         if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
906                 ListBase *lb = which_libbase(bmain, type);
907                 BLI_remlink(lb, id);
908         }
909
910         BKE_libblock_free_data(id, (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
911
912         if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
913                 BKE_main_unlock(bmain);
914         }
915
916         if ((flag & LIB_ID_FREE_NOT_ALLOCATED) == 0) {
917                 MEM_freeN(id);
918         }
919 }
920
921 /**
922  * Complete ID freeing, should be usable in most cases (even for out-of-Main IDs).
923  *
924  * See #BKE_id_free_ex description for full details.
925  *
926  * \param bmain: Main database containing the freed ID, can be NULL in case it's a temp ID outside of any Main.
927  * \param idv: Pointer to ID to be freed.
928  */
929 void BKE_id_free(Main *bmain, void *idv)
930 {
931         BKE_id_free_ex(bmain, idv, 0, true);
932 }
933
934 /**
935  * Not really a freeing function by itself, it decrements usercount of given id, and only frees it if it reaches 0.
936  */
937 void BKE_id_free_us(Main *bmain, void *idv)      /* test users */
938 {
939         ID *id = idv;
940
941         id_us_min(id);
942
943         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding collections when deleting an object.
944          *     Since only 'user_one' usage of objects is collections, and only 'real user' usage of objects is scenes,
945          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
946          *     fully unlinked.
947          *     But only for local objects, not linked ones!
948          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
949          */
950         if ((GS(id->name) == ID_OB) && (id->us == 1) && (id->lib == NULL)) {
951                 id_us_clear_real(id);
952         }
953
954         if (id->us == 0) {
955                 BKE_libblock_unlink(bmain, id, false, false);
956
957                 BKE_id_free(bmain, id);
958         }
959 }
960
961 static void id_delete(Main *bmain, const bool do_tagged_deletion)
962 {
963         const int tag = LIB_TAG_DOIT;
964         ListBase *lbarray[MAX_LIBARRAY];
965         Link dummy_link = {0};
966         int base_count, i;
967
968         /* Used by batch tagged deletion, when we call BKE_id_free then, id is no more in Main database,
969          * and has already properly unlinked its other IDs usages.
970          * UI users are always cleared in BKE_libblock_remap_locked() call, so we can always skip it. */
971         const int free_flag = LIB_ID_FREE_NO_UI_USER |
972                               (do_tagged_deletion ? LIB_ID_FREE_NO_MAIN | LIB_ID_FREE_NO_USER_REFCOUNT : 0);
973         ListBase tagged_deleted_ids = {NULL};
974
975         base_count = set_listbasepointers(bmain, lbarray);
976
977         BKE_main_lock(bmain);
978         if (do_tagged_deletion) {
979                 /* Main idea of batch deletion is to remove all IDs to be deleted from Main database.
980                  * This means that we won't have to loop over all deleted IDs to remove usages
981                  * of other deleted IDs.
982                  * This gives tremendous speed-up when deleting a large amount of IDs from a Main
983                  * containing thousands of those.
984                  * This also means that we have to be very careful here, as we by-pass many 'common'
985                  * processing, hence risking to 'corrupt' at least user counts, if not IDs themselves. */
986                 bool keep_looping = true;
987                 while (keep_looping) {
988                         ID *id, *id_next;
989                         ID *last_remapped_id = tagged_deleted_ids.last;
990                         keep_looping = false;
991
992                         /* First tag and remove from Main all datablocks directly from target lib.
993                          * Note that we go forward here, since we want to check dependencies before users
994                          * (e.g. meshes before objects). Avoids to have to loop twice. */
995                         for (i = 0; i < base_count; i++) {
996                                 ListBase *lb = lbarray[i];
997
998                                 for (id = lb->first; id; id = id_next) {
999                                         id_next = id->next;
1000                                         /* Note: in case we delete a library, we also delete all its datablocks! */
1001                                         if ((id->tag & tag) || (id->lib != NULL && (id->lib->id.tag & tag))) {
1002                                                 BLI_remlink(lb, id);
1003                                                 BLI_addtail(&tagged_deleted_ids, id);
1004                                                 id->tag |= tag | LIB_TAG_NO_MAIN;
1005                                                 keep_looping = true;
1006                                         }
1007                                 }
1008                         }
1009                         if (last_remapped_id == NULL) {
1010                                 dummy_link.next = tagged_deleted_ids.first;
1011                                 last_remapped_id = (ID *)(&dummy_link);
1012                         }
1013                         for (id = last_remapped_id->next; id; id = id->next) {
1014                                 /* Will tag 'never NULL' users of this ID too.
1015                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
1016                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
1017                                  * Also, this will also flag users of deleted data that cannot be unlinked
1018                                  * (object using deleted obdata, etc.), so that they also get deleted. */
1019                                 BKE_libblock_remap_locked(
1020                                             bmain, id, NULL,
1021                                             ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
1022                                 /* Since we removed ID from Main, we also need to unlink its own other IDs usages ourself. */
1023                                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
1024                                 /* This is needed because we may not have remapped usages of that ID by other deleted ones. */
1025 //                              id->us = 0;  /* Is it actually? */
1026                         }
1027                 }
1028         }
1029         else {
1030                 /* First tag all datablocks directly from target lib.
1031                  * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
1032                  * Avoids to have to loop twice. */
1033                 for (i = 0; i < base_count; i++) {
1034                         ListBase *lb = lbarray[i];
1035                         ID *id, *id_next;
1036
1037                         for (id = lb->first; id; id = id_next) {
1038                                 id_next = id->next;
1039                                 /* Note: in case we delete a library, we also delete all its datablocks! */
1040                                 if ((id->tag & tag) || (id->lib != NULL && (id->lib->id.tag & tag))) {
1041                                         id->tag |= tag;
1042
1043                                         /* Will tag 'never NULL' users of this ID too.
1044                                          * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
1045                                          * links, this can lead to nasty crashing here in second, actual deleting loop.
1046                                          * Also, this will also flag users of deleted data that cannot be unlinked
1047                                          * (object using deleted obdata, etc.), so that they also get deleted. */
1048                                         BKE_libblock_remap_locked(
1049                                                     bmain, id, NULL,
1050                                                     ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
1051                                 }
1052                         }
1053                 }
1054         }
1055         BKE_main_unlock(bmain);
1056
1057         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
1058          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
1059          * over meshes when we come to freeing obdata). */
1060         for (i = do_tagged_deletion ? 1 : base_count; i--; ) {
1061                 ListBase *lb = lbarray[i];
1062                 ID *id, *id_next;
1063
1064                 for (id = do_tagged_deletion ? tagged_deleted_ids.first : lb->first; id; id = id_next) {
1065                         id_next = id->next;
1066                         if (id->tag & tag) {
1067                                 if (id->us != 0) {
1068 #ifdef DEBUG_PRINT
1069                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
1070 #endif
1071                                         BLI_assert(id->us == 0);
1072                                 }
1073                                 BKE_id_free_ex(bmain, id, free_flag, !do_tagged_deletion);
1074                         }
1075                 }
1076         }
1077
1078         bmain->is_memfile_undo_written = false;
1079 }
1080
1081 /**
1082  * Properly delete a single ID from given \a bmain database.
1083  */
1084 void BKE_id_delete(Main *bmain, void *idv)
1085 {
1086         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1087         ((ID *)idv)->tag |= LIB_TAG_DOIT;
1088
1089         id_delete(bmain, false);
1090 }
1091
1092 /**
1093  * Properly delete all IDs tagged with \a LIB_TAG_DOIT, in given \a bmain database.
1094  *
1095  * This is more efficient than calling #BKE_id_delete repetitively on a large set of IDs
1096  * (several times faster when deleting most of the IDs at once)...
1097  *
1098  * \warning Considered experimental for now, seems to be working OK but this is
1099  *          risky code in a complicated area.
1100  */
1101 void BKE_id_multi_tagged_delete(Main *bmain)
1102 {
1103         id_delete(bmain, true);
1104 }