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