Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / library_remap.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/library_remap.c
22  *  \ingroup bke
23  *
24  * Contains management of ID's and libraries remap, unlink and free logic.
25  */
26
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stddef.h>
32 #include <assert.h>
33
34 #include "MEM_guardedalloc.h"
35
36 /* all types are needed here, in order to do memory operations */
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_brush_types.h"
40 #include "DNA_camera_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_gpencil_types.h"
43 #include "DNA_ipo_types.h"
44 #include "DNA_key_types.h"
45 #include "DNA_lamp_types.h"
46 #include "DNA_lattice_types.h"
47 #include "DNA_linestyle_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meta_types.h"
51 #include "DNA_movieclip_types.h"
52 #include "DNA_mask_types.h"
53 #include "DNA_node_types.h"
54 #include "DNA_object_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_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_curve.h"
73 #include "BKE_depsgraph.h"
74 #include "BKE_fcurve.h"
75 #include "BKE_font.h"
76 #include "BKE_group.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_library.h"
85 #include "BKE_library_query.h"
86 #include "BKE_library_remap.h"
87 #include "BKE_linestyle.h"
88 #include "BKE_mesh.h"
89 #include "BKE_material.h"
90 #include "BKE_main.h"
91 #include "BKE_mask.h"
92 #include "BKE_mball.h"
93 #include "BKE_modifier.h"
94 #include "BKE_movieclip.h"
95 #include "BKE_multires.h"
96 #include "BKE_node.h"
97 #include "BKE_object.h"
98 #include "BKE_paint.h"
99 #include "BKE_speaker.h"
100 #include "BKE_sound.h"
101 #include "BKE_screen.h"
102 #include "BKE_scene.h"
103 #include "BKE_text.h"
104 #include "BKE_texture.h"
105 #include "BKE_world.h"
106
107 #ifdef WITH_PYTHON
108 #include "BPY_extern.h"
109 #endif
110
111 static BKE_library_free_window_manager_cb free_windowmanager_cb = NULL;
112
113 void BKE_library_callback_free_window_manager_set(BKE_library_free_window_manager_cb func)
114 {
115         free_windowmanager_cb = func;
116 }
117
118 static BKE_library_free_notifier_reference_cb free_notifier_reference_cb = NULL;
119
120 void BKE_library_callback_free_notifier_reference_set(BKE_library_free_notifier_reference_cb func)
121 {
122         free_notifier_reference_cb = func;
123 }
124
125 static BKE_library_remap_editor_id_reference_cb remap_editor_id_reference_cb = NULL;
126
127 void BKE_library_callback_remap_editor_id_reference_set(BKE_library_remap_editor_id_reference_cb func)
128 {
129         remap_editor_id_reference_cb = func;
130 }
131
132 typedef struct IDRemap {
133         ID *old_id;
134         ID *new_id;
135         ID *id;  /* The ID in which we are replacing old_id by new_id usages. */
136         short flag;
137
138         /* 'Output' data. */
139         short status;
140         int skipped_direct;  /* Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */
141         int skipped_indirect;  /* Number of indirect usecases that could not be remapped. */
142         int skipped_refcounted;  /* Number of skipped usecases that refcount the datablock. */
143 } IDRemap;
144
145 /* IDRemap->flag enums defined in BKE_library.h */
146
147 /* IDRemap->status */
148 enum {
149         /* *** Set by callback. *** */
150         ID_REMAP_IS_LINKED_DIRECT       = 1 << 0,  /* new_id is directly linked in current .blend. */
151         ID_REMAP_IS_USER_ONE_SKIPPED    = 1 << 1,  /* There was some skipped 'user_one' usages of old_id. */
152 };
153
154 static int foreach_libblock_remap_callback(void *user_data, ID *UNUSED(id_self), ID **id_p, int cb_flag)
155 {
156         IDRemap *id_remap_data = user_data;
157         ID *old_id = id_remap_data->old_id;
158         ID *new_id = id_remap_data->new_id;
159         ID *id = id_remap_data->id;
160
161         if (!old_id) {  /* Used to cleanup all IDs used by a specific one. */
162                 BLI_assert(!new_id);
163                 old_id = *id_p;
164         }
165
166         if (*id_p && (*id_p == old_id)) {
167                 const bool is_indirect = (cb_flag & IDWALK_INDIRECT_USAGE) != 0;
168                 const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
169                 /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct,
170                  *       on the other hand since they get reset to lib data on file open/reload it is indirect too...
171                  *       Edit Mode is also a 'skip direct' case. */
172                 const bool is_obj = (GS(id->name) == ID_OB);
173                 const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
174                 const bool is_never_null = ((cb_flag & IDWALK_NEVER_NULL) && (new_id == NULL) &&
175                                             (id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
176                 const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
177
178 #ifdef DEBUG_PRINT
179                 printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n",
180                        id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect);
181 #endif
182
183                 if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_NEVER_NULL)) {
184                         id->tag |= LIB_TAG_DOIT;
185                 }
186
187                 /* Special hack in case it's Object->data and we are in edit mode (skipped_direct too). */
188                 if ((is_never_null && skip_never_null) ||
189                     (is_obj_editmode && (((Object *)id)->data == *id_p)) ||
190                     (skip_indirect && is_indirect))
191                 {
192                         if (is_indirect) {
193                                 id_remap_data->skipped_indirect++;
194                         }
195                         else if (is_never_null || is_obj_editmode) {
196                                 id_remap_data->skipped_direct++;
197                         }
198                         else {
199                                 BLI_assert(0);
200                         }
201                         if (cb_flag & IDWALK_USER) {
202                                 id_remap_data->skipped_refcounted++;
203                         }
204                         else if (cb_flag & IDWALK_USER_ONE) {
205                                 /* No need to count number of times this happens, just a flag is enough. */
206                                 id_remap_data->status |= ID_REMAP_IS_USER_ONE_SKIPPED;
207                         }
208                 }
209                 else {
210                         if (!is_never_null) {
211                                 *id_p = new_id;
212                         }
213                         if (cb_flag & IDWALK_USER) {
214                                 id_us_min(old_id);
215                                 /* We do not want to handle LIB_TAG_INDIRECT/LIB_TAG_EXTERN here. */
216                                 if (new_id)
217                                         new_id->us++;
218                         }
219                         else if (cb_flag & IDWALK_USER_ONE) {
220                                 id_us_ensure_real(new_id);
221                                 /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
222                                  * that extra user is processed in final handling... */
223                         }
224                         if (!is_indirect) {
225                                 id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
226                         }
227                 }
228         }
229
230         return IDWALK_RET_NOP;
231 }
232
233 /* Some reamapping unfortunately require extra and/or specific handling, tackle those here. */
234 static void libblock_remap_data_preprocess_scene_base_unlink(
235         IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect)
236 {
237         if (skip_indirect && is_indirect) {
238                 r_id_remap_data->skipped_indirect++;
239                 r_id_remap_data->skipped_refcounted++;
240         }
241         else {
242                 id_us_min((ID *)base->object);
243                 BKE_scene_base_unlink(sce, base);
244                 MEM_freeN(base);
245                 if (!is_indirect) {
246                         r_id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
247                 }
248         }
249 }
250
251 static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
252 {
253         switch (GS(r_id_remap_data->id->name)) {
254                 case ID_SCE:
255                 {
256                         Scene *sce = (Scene *)r_id_remap_data->id;
257
258                         if (!r_id_remap_data->new_id) {
259                                 const bool is_indirect = (sce->id.lib != NULL);
260                                 const bool skip_indirect = (r_id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0;
261
262                                 /* In case we are unlinking... */
263                                 if (!r_id_remap_data->old_id) {
264                                         /* ... everything from scene. */
265                                         Base *base, *base_next;
266                                         for (base = sce->base.first; base; base = base_next) {
267                                                 base_next = base->next;
268                                                 libblock_remap_data_preprocess_scene_base_unlink(
269                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
270                                         }
271                                 }
272                                 else if (GS(r_id_remap_data->old_id->name) == ID_OB) {
273                                         /* ... a specific object from scene. */
274                                         Object *old_ob = (Object *)r_id_remap_data->old_id;
275                                         Base *base = BKE_scene_base_find(sce, old_ob);
276
277                                         if (base) {
278                                                 libblock_remap_data_preprocess_scene_base_unlink(
279                                                             r_id_remap_data, sce, base, skip_indirect, is_indirect);
280                                         }
281                                 }
282                         }
283                         break;
284                 }
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                                 }
299                         }
300                         break;
301                 }
302                 default:
303                         break;
304         }
305 }
306
307 static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, Object *old_ob, Object *new_ob)
308 {
309         if (old_ob->flag & OB_FROMGROUP) {
310                 /* Note that for Scene's BaseObject->flag, either we:
311                  *     - unlinked old_ob (i.e. new_ob is NULL), in which case scenes' bases have been removed already.
312                  *     - remapped old_ob by new_ob, in which case scenes' bases are still valid as is.
313                  * So in any case, no need to update them here. */
314                 if (BKE_group_object_find(NULL, old_ob) == NULL) {
315                         old_ob->flag &= ~OB_FROMGROUP;
316                 }
317                 if (new_ob == NULL) {  /* We need to remove NULL-ified groupobjects... */
318                         for (Group *group = bmain->group.first; group; group = group->id.next) {
319                                 BKE_group_object_unlink(group, NULL, NULL, NULL);
320                         }
321                 }
322                 else {
323                         new_ob->flag |= OB_FROMGROUP;
324                 }
325         }
326 }
327
328 static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
329 {
330         /* Note that here we assume no object has no base (i.e. all objects are assumed instanced
331          * in one scene...). */
332         for (Base *base = sce->base.first; base; base = base->next) {
333                 if (base->flag & OB_FROMGROUP) {
334                         Object *ob = base->object;
335
336                         if (ob->flag & OB_FROMGROUP) {
337                                 Group *grp = BKE_group_object_find(NULL, ob);
338
339                                 /* Unlinked group (old_id) is still in bmain... */
340                                 if (grp && (&grp->id == old_id || grp->id.us == 0)) {
341                                         grp = BKE_group_object_find(grp, ob);
342                                 }
343                                 if (!grp) {
344                                         ob->flag &= ~OB_FROMGROUP;
345                                 }
346                         }
347                         if (!(ob->flag & OB_FROMGROUP)) {
348                                 base->flag &= ~OB_FROMGROUP;
349                         }
350                 }
351         }
352 }
353
354 static void libblock_remap_data_postprocess_obdata_relink(Main *UNUSED(bmain), Object *ob, ID *new_id)
355 {
356         if (ob->data == new_id) {
357                 switch (GS(new_id->name)) {
358                         case ID_ME:
359                                 multires_force_update(ob);
360                                 break;
361                         case ID_CU:
362                                 BKE_curve_type_test(ob);
363                                 break;
364                         default:
365                                 break;
366                 }
367                 test_object_modifiers(ob);
368                 test_object_materials(ob, new_id);
369         }
370 }
371
372 /**
373  * Execute the 'data' part of the remapping (that is, all ID pointers from other ID datablocks).
374  *
375  * Behavior differs depending on whether given \a id is NULL or not:
376  * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not
377  *   (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id
378  *   are remapped to \a new_id.
379  * - \a id is non-NULL:
380  *   + 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
381  *     does not references any other datablock anymore).
382  *   + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only for given \a id.
383  *
384  * \param bmain: the Main data storage to operate on (can be NULL if \a id is non-NULL).
385  * \param id: the datablock to operate on (can be NULL if \a bmain is non-NULL).
386  * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL).
387  * \param new_id: the new datablock to replace \a old_id references with (may be NULL).
388  * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process).
389  */
390 static void libblock_remap_data(
391         Main *bmain, ID *id, ID *old_id, ID *new_id, const short remap_flags, IDRemap *r_id_remap_data)
392 {
393         IDRemap id_remap_data;
394         ListBase *lb_array[MAX_LIBARRAY];
395         int i;
396
397         if (r_id_remap_data == NULL) {
398                 r_id_remap_data = &id_remap_data;
399         }
400         r_id_remap_data->old_id = old_id;
401         r_id_remap_data->new_id = new_id;
402         r_id_remap_data->id = NULL;
403         r_id_remap_data->flag = remap_flags;
404         r_id_remap_data->status = 0;
405         r_id_remap_data->skipped_direct = 0;
406         r_id_remap_data->skipped_indirect = 0;
407         r_id_remap_data->skipped_refcounted = 0;
408
409         if (id) {
410 #ifdef DEBUG_PRINT
411                 printf("\tchecking id %s (%p, %p)\n", id->name, id, id->lib);
412 #endif
413                 r_id_remap_data->id = id;
414                 libblock_remap_data_preprocess(r_id_remap_data);
415                 BKE_library_foreach_ID_link(id, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
416         }
417         else {
418                 i = set_listbasepointers(bmain, lb_array);
419
420                 /* Note that this is a very 'bruteforce' approach, maybe we could use some depsgraph to only process
421                  * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
422
423                 while (i--) {
424                         ID *id_curr = lb_array[i]->first;
425
426                         if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(old_id->name))) {
427                                 continue;
428                         }
429
430                         for (; id_curr; id_curr = id_curr->next) {
431                                 /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
432                                  * the user count handling...
433                                  * XXX No more true (except for debug usage of those skipping counters). */
434                                 r_id_remap_data->id = id_curr;
435                                 libblock_remap_data_preprocess(r_id_remap_data);
436                                 BKE_library_foreach_ID_link(
437                                             id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
438                         }
439                 }
440         }
441
442         /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior
443          *     though, we can always add an option (flag) to control this later if needed. */
444         if (old_id && (old_id->flag & LIB_FAKEUSER)) {
445                 id_fake_user_clear(old_id);
446                 id_fake_user_set(new_id);
447         }
448
449         id_us_clear_real(old_id);
450
451         if (new_id && (new_id->tag & LIB_TAG_INDIRECT) && (r_id_remap_data->status & ID_REMAP_IS_LINKED_DIRECT)) {
452                 new_id->tag &= ~LIB_TAG_INDIRECT;
453                 new_id->tag |= LIB_TAG_EXTERN;
454         }
455
456 #ifdef DEBUG_PRINT
457         printf("%s: %d occurences skipped (%d direct and %d indirect ones)\n", __func__,
458                r_id_remap_data->skipped_direct + r_id_remap_data->skipped_indirect,
459                r_id_remap_data->skipped_direct, r_id_remap_data->skipped_indirect);
460 #endif
461 }
462
463 /**
464  * Replace all references in given Main to \a old_id by \a new_id
465  * (if \a new_id is NULL, it unlinks \a old_id).
466  */
467 void BKE_libblock_remap_locked(
468         Main *bmain, void *old_idv, void *new_idv,
469         const short remap_flags)
470 {
471         IDRemap id_remap_data;
472         ID *old_id = old_idv;
473         ID *new_id = new_idv;
474         int skipped_direct, skipped_refcounted;
475
476         BLI_assert(old_id != NULL);
477         BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
478         BLI_assert(old_id != new_id);
479
480         libblock_remap_data(bmain, NULL, old_id, new_id, remap_flags, &id_remap_data);
481
482         if (free_notifier_reference_cb) {
483                 free_notifier_reference_cb(old_id);
484         }
485
486         /* We assume editors do not hold references to their IDs... This is false in some cases
487          * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */
488         if (remap_editor_id_reference_cb) {
489                 remap_editor_id_reference_cb(old_id, new_id);
490         }
491
492         skipped_direct = id_remap_data.skipped_direct;
493         skipped_refcounted = id_remap_data.skipped_refcounted;
494
495         /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually
496          * been incremented for that, we have to decrease once more its user count... unless we had to skip
497          * some 'user_one' cases. */
498         if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) {
499                 id_us_min(old_id);
500                 old_id->tag &= ~LIB_TAG_EXTRAUSER_SET;
501         }
502
503         BLI_assert(old_id->us - skipped_refcounted >= 0);
504         UNUSED_VARS_NDEBUG(skipped_refcounted);
505
506         if (skipped_direct == 0) {
507                 /* old_id is assumed to not be used directly anymore... */
508                 if (old_id->lib && (old_id->tag & LIB_TAG_EXTERN)) {
509                         old_id->tag &= ~LIB_TAG_EXTERN;
510                         old_id->tag |= LIB_TAG_INDIRECT;
511                 }
512         }
513
514         /* Some after-process updates.
515          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
516          */
517         switch (GS(old_id->name)) {
518                 case ID_OB:
519                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id);
520                         break;
521                 case ID_GR:
522                         if (!new_id) {  /* Only affects us in case group was unlinked. */
523                                 for (Scene *sce = bmain->scene.first; sce; sce = sce->id.next) {
524                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
525                                 }
526                         }
527                         break;
528                 case ID_ME:
529                 case ID_CU:
530                 case ID_MB:
531                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
532                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
533                                         libblock_remap_data_postprocess_obdata_relink(bmain, ob, new_id);
534                                 }
535                         }
536                         break;
537                 default:
538                         break;
539         }
540
541         /* Full rebuild of DAG! */
542         DAG_relations_tag_update(bmain);
543 }
544
545 void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short remap_flags)
546 {
547         BKE_main_lock(bmain);
548
549         BKE_libblock_remap_locked(bmain, old_idv, new_idv, remap_flags);
550
551         BKE_main_unlock(bmain);
552 }
553
554 /**
555  * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID).
556  *
557  * \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
558  * (quite obviously, 'non-NULL' usages can never be unlinked by this function...).
559  */
560 void BKE_libblock_unlink(Main *bmain, void *idv, const bool do_flag_never_null, const bool do_skip_indirect)
561 {
562         const short remap_flags = (do_skip_indirect ? ID_REMAP_SKIP_INDIRECT_USAGE : 0) |
563                                   (do_flag_never_null ? ID_REMAP_FLAG_NEVER_NULL_USAGE : 0);
564
565         BKE_main_lock(bmain);
566
567         BKE_libblock_remap_locked(bmain, idv, NULL, remap_flags);
568
569         BKE_main_unlock(bmain);
570 }
571
572 /** Similar to libblock_remap, but only affects IDs used by given \a idv ID.
573  *
574  * \param old_idv: Unlike BKE_libblock_remap, can be NULL,
575  * in which case all ID usages by given \a idv will be cleared.
576  * \param us_min_never_null: If \a true and new_id is NULL,
577  * 'NEVER_NULL' ID usages keep their old id, but this one still gets its user count decremented
578  * (needed when given \a idv is going to be deleted right after being unlinked).
579  */
580 /* Should be able to replace all _relink() funcs (constraints, rigidbody, etc.) ? */
581 /* XXX Arg! Naming... :(
582  *     _relink? avoids confusion with _remap, but is confusing with _unlink
583  *     _remap_used_ids?
584  *     _remap_datablocks?
585  *     BKE_id_remap maybe?
586  *     ... sigh
587  */
588 void BKE_libblock_relink_ex(
589         Main *bmain, void *idv, void *old_idv, void *new_idv, const bool us_min_never_null)
590 {
591         ID *id = idv;
592         ID *old_id = old_idv;
593         ID *new_id = new_idv;
594         int remap_flags = us_min_never_null ? 0 : ID_REMAP_SKIP_NEVER_NULL_USAGE;
595
596         /* No need to lock here, we are only affecting given ID, not bmain database. */
597
598         BLI_assert(id);
599         if (old_id) {
600                 BLI_assert((new_id == NULL) || GS(old_id->name) == GS(new_id->name));
601                 BLI_assert(old_id != new_id);
602         }
603         else {
604                 BLI_assert(new_id == NULL);
605         }
606
607         libblock_remap_data(NULL, id, old_id, new_id, remap_flags, NULL);
608
609         /* Some after-process updates.
610          * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead?
611          */
612         switch (GS(id->name)) {
613                 case ID_SCE:
614                 {
615                         Scene *sce = (Scene *)id;
616
617                         if (old_id) {
618                                 switch (GS(old_id->name)) {
619                                         case ID_OB:
620                                         {
621                                                 libblock_remap_data_postprocess_object_fromgroup_update(
622                                                             bmain, (Object *)old_id, (Object *)new_id);
623                                                 break;
624                                         }
625                                         case ID_GR:
626                                                 if (!new_id) {  /* Only affects us in case group was unlinked. */
627                                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, old_id);
628                                                 }
629                                                 break;
630                                         default:
631                                                 break;
632                                 }
633                         }
634                         else {
635                                 /* No choice but to check whole objects/groups. */
636                                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
637                                         libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL);
638                                 }
639                                 for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
640                                         libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
641                                 }
642                         }
643                 }
644                 case ID_OB:
645                         if (new_id) {  /* Only affects us in case obdata was relinked (changed). */
646                                 libblock_remap_data_postprocess_obdata_relink(bmain, (Object *)id, new_id);
647                         }
648                         break;
649                 default:
650                         break;
651         }
652 }
653
654 static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata)
655 {
656         ChannelDriver *driver;
657         FCurve *fcu;
658
659         /* find the driver this belongs to and update it */
660         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
661                 driver = fcu->driver;
662                 
663                 if (driver) {
664                         DriverVar *dvar;
665                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
666                                 DRIVER_TARGETS_USED_LOOPER(dvar) 
667                                 {
668                                         if (dtar->id == userdata)
669                                                 dtar->id = NULL;
670                                 }
671                                 DRIVER_TARGETS_LOOPER_END
672                         }
673                 }
674         }
675 }
676
677 void BKE_libblock_free_data(Main *bmain, ID *id)
678 {
679         if (id->properties) {
680                 IDP_FreeProperty(id->properties);
681                 MEM_freeN(id->properties);
682         }
683         
684         /* this ID may be a driver target! */
685         BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id);
686 }
687
688 /**
689  * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
690  *
691  * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
692  */
693 void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user)
694 {
695         ID *id = idv;
696         short type = GS(id->name);
697         ListBase *lb = which_libbase(bmain, type);
698
699         DAG_id_type_tag(bmain, type);
700
701 #ifdef WITH_PYTHON
702         BPY_id_release(id);
703 #endif
704
705         if (do_id_user) {
706                 BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
707         }
708
709         switch (type) {
710                 case ID_SCE:
711                         BKE_scene_free((Scene *)id);
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_lamp_free((Lamp *)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_SO:
768                         BKE_sound_free((bSound *)id);
769                         break;
770                 case ID_GR:
771                         BKE_group_free((Group *)id);
772                         break;
773                 case ID_AR:
774                         BKE_armature_free((bArmature *)id);
775                         break;
776                 case ID_AC:
777                         BKE_action_free((bAction *)id);
778                         break;
779                 case ID_NT:
780                         ntreeFreeTree((bNodeTree *)id);
781                         break;
782                 case ID_BR:
783                         BKE_brush_free((Brush *)id);
784                         break;
785                 case ID_WM:
786                         if (free_windowmanager_cb)
787                                 free_windowmanager_cb(NULL, (wmWindowManager *)id);
788                         break;
789                 case ID_GD:
790                         BKE_gpencil_free((bGPdata *)id);
791                         break;
792                 case ID_MC:
793                         BKE_movieclip_free((MovieClip *)id);
794                         break;
795                 case ID_MSK:
796                         BKE_mask_free((Mask *)id);
797                         break;
798                 case ID_LS:
799                         BKE_linestyle_free((FreestyleLineStyle *)id);
800                         break;
801                 case ID_PAL:
802                         BKE_palette_free((Palette *)id);
803                         break;
804                 case ID_PC:
805                         BKE_paint_curve_free((PaintCurve *)id);
806                         break;
807         }
808
809         /* avoid notifying on removed data */
810         BKE_main_lock(bmain);
811
812         if (free_notifier_reference_cb) {
813                 free_notifier_reference_cb(id);
814         }
815
816         if (remap_editor_id_reference_cb) {
817                 remap_editor_id_reference_cb(id, NULL);
818         }
819
820         BLI_remlink(lb, id);
821
822         BKE_libblock_free_data(bmain, id);
823         BKE_main_unlock(bmain);
824
825         MEM_freeN(id);
826 }
827
828 void BKE_libblock_free(Main *bmain, void *idv)
829 {
830         BKE_libblock_free_ex(bmain, idv, true);
831 }
832
833 void BKE_libblock_free_us(Main *bmain, void *idv)      /* test users */
834 {
835         ID *id = idv;
836         
837         id_us_min(id);
838
839         /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding groups when deleting an object.
840          *     Since only 'user_one' usage of objects is groups, and only 'real user' usage of objects is scenes,
841          *     removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets
842          *     fully unlinked.
843          *     Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO.
844          */
845         if ((GS(id->name) == ID_OB) && (id->us == 1)) {
846                 id_us_clear_real(id);
847         }
848
849         if (id->us == 0) {
850                 BKE_libblock_unlink(bmain, id, false, false);
851                 
852                 BKE_libblock_free(bmain, id);
853         }
854 }
855
856 void BKE_libblock_delete(Main *bmain, void *idv)
857 {
858         ListBase *lbarray[MAX_LIBARRAY];
859         int base_count, i;
860
861         base_count = set_listbasepointers(bmain, lbarray);
862         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
863
864         /* First tag all datablocks directly from target lib.
865      * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects).
866      * Avoids to have to loop twice. */
867         for (i = 0; i < base_count; i++) {
868                 ListBase *lb = lbarray[i];
869                 ID *id;
870
871                 for (id = lb->first; id; id = id->next) {
872                         /* Note: in case we delete a library, we also delete all its datablocks! */
873                         if ((id == (ID *)idv) || (id->lib == (Library *)idv) || (id->tag & LIB_TAG_DOIT)) {
874                                 id->tag |= LIB_TAG_DOIT;
875                                 /* Will tag 'never NULL' users of this ID too.
876                                  * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!)
877                                  * links, this can lead to nasty crashing here in second, actual deleting loop.
878                                  * Also, this will also flag users of deleted data that cannot be unlinked
879                                  * (object using deleted obdata, etc.), so that they also get deleted. */
880                                 BKE_libblock_remap(bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE);
881                         }
882                 }
883         }
884
885         /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared
886          * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference'
887          * over meshes when we come to freeing obdata). */
888         for (i = base_count; i--; ) {
889                 ListBase *lb = lbarray[i];
890                 ID *id, *id_next;
891
892                 for (id = lb->first; id; id = id_next) {
893                         id_next = id->next;
894                         if (id->tag & LIB_TAG_DOIT) {
895                                 if (id->us != 0) {
896 #ifdef DEBUG_PRINT
897                                         printf("%s: deleting %s (%d)\n", __func__, id->name, id->us);
898 #endif
899                                         BLI_assert(id->us == 0);
900                                 }
901                                 BKE_libblock_free(bmain, id);
902                         }
903                 }
904         }
905 }