2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/library.c
31 * Contains management of ID's and libraries
32 * allocate and free of all library data
42 #include "MEM_guardedalloc.h"
44 /* all types are needed here, in order to do memory operations */
45 #include "DNA_anim_types.h"
46 #include "DNA_armature_types.h"
47 #include "DNA_brush_types.h"
48 #include "DNA_cachefile_types.h"
49 #include "DNA_camera_types.h"
50 #include "DNA_group_types.h"
51 #include "DNA_gpencil_types.h"
52 #include "DNA_ipo_types.h"
53 #include "DNA_key_types.h"
54 #include "DNA_lamp_types.h"
55 #include "DNA_lattice_types.h"
56 #include "DNA_linestyle_types.h"
57 #include "DNA_material_types.h"
58 #include "DNA_mesh_types.h"
59 #include "DNA_meta_types.h"
60 #include "DNA_modifier_types.h"
61 #include "DNA_movieclip_types.h"
62 #include "DNA_mask_types.h"
63 #include "DNA_node_types.h"
64 #include "DNA_object_types.h"
65 #include "DNA_scene_types.h"
66 #include "DNA_screen_types.h"
67 #include "DNA_speaker_types.h"
68 #include "DNA_sound_types.h"
69 #include "DNA_text_types.h"
70 #include "DNA_vfont_types.h"
71 #include "DNA_windowmanager_types.h"
72 #include "DNA_world_types.h"
74 #include "BLI_blenlib.h"
75 #include "BLI_utildefines.h"
76 #include "BLI_ghash.h"
77 #include "BLI_linklist.h"
78 #include "BLI_memarena.h"
79 #include "BLI_mempool.h"
80 #include "BLI_string_utils.h"
82 #include "BLI_threads.h"
83 #include "BLT_translation.h"
85 #include "BKE_action.h"
86 #include "BKE_animsys.h"
87 #include "BKE_armature.h"
88 #include "BKE_bpath.h"
89 #include "BKE_brush.h"
90 #include "BKE_camera.h"
91 #include "BKE_cachefile.h"
92 #include "BKE_context.h"
93 #include "BKE_curve.h"
94 #include "BKE_depsgraph.h"
96 #include "BKE_global.h"
97 #include "BKE_group.h"
98 #include "BKE_gpencil.h"
99 #include "BKE_idcode.h"
100 #include "BKE_idprop.h"
101 #include "BKE_image.h"
103 #include "BKE_lamp.h"
104 #include "BKE_lattice.h"
105 #include "BKE_library.h"
106 #include "BKE_library_query.h"
107 #include "BKE_library_remap.h"
108 #include "BKE_linestyle.h"
109 #include "BKE_mesh.h"
110 #include "BKE_material.h"
111 #include "BKE_main.h"
112 #include "BKE_mball.h"
113 #include "BKE_mask.h"
114 #include "BKE_movieclip.h"
115 #include "BKE_node.h"
116 #include "BKE_object.h"
117 #include "BKE_paint.h"
118 #include "BKE_particle.h"
119 #include "BKE_packedFile.h"
120 #include "BKE_sound.h"
121 #include "BKE_speaker.h"
122 #include "BKE_scene.h"
123 #include "BKE_text.h"
124 #include "BKE_texture.h"
125 #include "BKE_world.h"
127 #include "DEG_depsgraph.h"
129 #include "RNA_access.h"
131 #include "IMB_imbuf.h"
132 #include "IMB_imbuf_types.h"
134 #include "atomic_ops.h"
139 # include "PIL_time_utildefines.h"
142 /* GS reads the memory pointed at in a specific ordering.
143 * only use this definition, makes little and big endian systems
144 * work fine, in conjunction with MAKE_ID */
146 /* ************* general ************************ */
149 /* this has to be called from each make_local_* func, we could call
150 * from id_make_local() but then the make local functions would not be self
152 * also note that the id _must_ have a library - campbell */
153 void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
155 const char *bpath_user_data[2] = {bmain->name, lib->filepath};
157 BKE_bpath_traverse_id(bmain, id,
158 BKE_bpath_relocate_visitor,
159 BKE_BPATH_TRAVERSE_SKIP_MULTIFILE,
160 (void *)bpath_user_data);
163 void id_lib_extern(ID *id)
165 if (id && ID_IS_LINKED_DATABLOCK(id)) {
166 BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
167 if (id->tag & LIB_TAG_INDIRECT) {
168 id->tag -= LIB_TAG_INDIRECT;
169 id->tag |= LIB_TAG_EXTERN;
174 /* ensure we have a real user */
175 /* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure
176 * we always have a real user.
177 * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later
178 * to make this change... */
179 void id_us_ensure_real(ID *id)
182 const int limit = ID_FAKE_USERS(id);
183 id->tag |= LIB_TAG_EXTRAUSER;
184 if (id->us <= limit) {
185 if (id->us < limit || ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER_SET))) {
186 printf("ID user count error: %s (from '%s')\n", id->name, id->lib ? id->lib->filepath : "[Main]");
190 id->tag |= LIB_TAG_EXTRAUSER_SET;
195 void id_us_clear_real(ID *id)
197 if (id && (id->tag & LIB_TAG_EXTRAUSER)) {
198 if (id->tag & LIB_TAG_EXTRAUSER_SET) {
200 BLI_assert(id->us >= ID_FAKE_USERS(id));
202 id->tag &= ~(LIB_TAG_EXTRAUSER | LIB_TAG_EXTRAUSER_SET);
207 * Same as \a id_us_plus, but does not handle lib indirect -> extern.
208 * Only used by readfile.c so far, but simpler/safer to keep it here nonetheless.
210 void id_us_plus_no_lib(ID *id)
213 if ((id->tag & LIB_TAG_EXTRAUSER) && (id->tag & LIB_TAG_EXTRAUSER_SET)) {
214 BLI_assert(id->us >= 1);
215 /* No need to increase count, just tag extra user as no more set.
216 * Avoids annoying & inconsistent +1 in user count. */
217 id->tag &= ~LIB_TAG_EXTRAUSER_SET;
220 BLI_assert(id->us >= 0);
227 void id_us_plus(ID *id)
230 id_us_plus_no_lib(id);
235 /* decrements the user count for *id. */
236 void id_us_min(ID *id)
239 const int limit = ID_FAKE_USERS(id);
241 if (id->us <= limit) {
242 printf("ID user decrement error: %s (from '%s'): %d <= %d\n",
243 id->name, id->lib ? id->lib->filepath : "[Main]", id->us, limit);
251 if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) {
252 /* We need an extra user here, but never actually incremented user count for it so far, do it now. */
253 id_us_ensure_real(id);
258 void id_fake_user_set(ID *id)
260 if (id && !(id->flag & LIB_FAKEUSER)) {
261 id->flag |= LIB_FAKEUSER;
266 void id_fake_user_clear(ID *id)
268 if (id && (id->flag & LIB_FAKEUSER)) {
269 id->flag &= ~LIB_FAKEUSER;
274 void BKE_id_clear_newpoin(ID *id)
277 id->newid->tag &= ~LIB_TAG_NEW;
282 static int id_expand_local_callback(
283 void *UNUSED(user_data), struct ID *id_self, struct ID **id_pointer, int cb_flag)
285 if (cb_flag & IDWALK_CB_PRIVATE) {
286 return IDWALK_RET_NOP;
289 /* Can hapen that we get unlinkable ID here, e.g. with shapekey referring to itself (through drivers)...
290 * Just skip it, shape key can only be either indirectly linked, or fully local, period.
291 * And let's curse one more time that stupid useless shapekey ID type! */
292 if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) {
293 id_lib_extern(*id_pointer);
296 return IDWALK_RET_NOP;
300 * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions.
302 void BKE_id_expand_local(Main *bmain, ID *id)
304 BKE_library_foreach_ID_link(bmain, id, id_expand_local_callback, NULL, IDWALK_READONLY);
308 * Ensure new (copied) ID is fully made local.
310 void BKE_id_copy_ensure_local(Main *bmain, const ID *old_id, ID *new_id)
312 if (ID_IS_LINKED_DATABLOCK(old_id)) {
313 BKE_id_expand_local(bmain, new_id);
314 BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
319 * Generic 'make local' function, works for most of datablock types...
321 void BKE_id_make_local_generic(Main *bmain, ID *id, const bool id_in_mainlist, const bool lib_local)
323 bool is_local = false, is_lib = false;
325 /* - only lib users: do nothing (unless force_local is set)
326 * - only local users: set flag
328 * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
331 if (!ID_IS_LINKED_DATABLOCK(id)) {
335 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
337 if (lib_local || is_local) {
339 id_clear_lib_data_ex(bmain, id, id_in_mainlist);
340 BKE_id_expand_local(bmain, id);
345 /* Should not fail in expected usecases, but id_copy does not copy Scene e.g. */
346 if (id_copy(bmain, id, &id_new, false)) {
349 /* setting newid is mandatory for complex make_lib_local logic... */
350 ID_NEW_SET(id, id_new);
351 Key *key = BKE_key_from_id(id), *key_new = BKE_key_from_id(id);
352 if (key && key_new) {
353 ID_NEW_SET(key, key_new);
355 bNodeTree *ntree = ntreeFromID(id), *ntree_new = ntreeFromID(id_new);
356 if (ntree && ntree_new) {
357 ID_NEW_SET(ntree, ntree_new);
361 BKE_libblock_remap(bmain, id, id_new, ID_REMAP_SKIP_INDIRECT_USAGE);
369 * Calls the appropriate make_local method for the block, unless test is set.
371 * \note Always set ID->newid pointer in case it gets duplicated...
373 * \param lib_local Special flag used when making a whole library's content local, it needs specific handling.
375 * \return true if the block can be made local.
377 bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
379 /* We don't care whether ID is directly or indirectly linked in case we are making a whole lib local... */
380 if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) {
384 switch ((ID_Type)GS(id->name)) {
386 if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local);
389 if (!test) BKE_object_make_local(bmain, (Object *)id, lib_local);
392 if (!test) BKE_mesh_make_local(bmain, (Mesh *)id, lib_local);
395 if (!test) BKE_curve_make_local(bmain, (Curve *)id, lib_local);
398 if (!test) BKE_mball_make_local(bmain, (MetaBall *)id, lib_local);
401 if (!test) BKE_material_make_local(bmain, (Material *)id, lib_local);
404 if (!test) BKE_texture_make_local(bmain, (Tex *)id, lib_local);
407 if (!test) BKE_image_make_local(bmain, (Image *)id, lib_local);
410 if (!test) BKE_lattice_make_local(bmain, (Lattice *)id, lib_local);
413 if (!test) BKE_lamp_make_local(bmain, (Lamp *)id, lib_local);
416 if (!test) BKE_camera_make_local(bmain, (Camera *)id, lib_local);
419 if (!test) BKE_speaker_make_local(bmain, (Speaker *)id, lib_local);
422 if (!test) BKE_world_make_local(bmain, (World *)id, lib_local);
425 if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
428 if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local);
431 if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local);
434 if (!test) BKE_group_make_local(bmain, (Group *)id, lib_local);
437 if (!test) BKE_armature_make_local(bmain, (bArmature *)id, lib_local);
440 if (!test) BKE_action_make_local(bmain, (bAction *)id, lib_local);
443 if (!test) ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local);
446 if (!test) BKE_brush_make_local(bmain, (Brush *)id, lib_local);
449 if (!test) BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local);
452 if (!test) BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local);
455 if (!test) BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local);
458 if (!test) BKE_mask_make_local(bmain, (Mask *)id, lib_local);
461 if (!test) BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local);
464 if (!test) BKE_palette_make_local(bmain, (Palette *)id, lib_local);
467 if (!test) BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local);
470 if (!test) BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local);
476 return false; /* can't be linked */
478 return false; /* deprecated */
484 struct IDCopyLibManagementData {
489 /* Increases usercount as required, and remap self ID pointers. */
490 static int id_copy_libmanagement_cb(void *user_data, ID *id_self, ID **id_pointer, int cb_flag)
492 struct IDCopyLibManagementData *data = user_data;
493 ID *id = *id_pointer;
495 /* Remap self-references to new copied ID. */
496 if (id == data->id_src) {
497 id = *id_pointer = id_self;
500 /* Increase used IDs refcount if needed and required. */
501 if ((data->flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0 && (cb_flag & IDWALK_CB_USER)) {
505 return IDWALK_RET_NOP;
509 * Generic entry point for copying a datablock (new API).
511 * \note Copy is only affecting given data-block (no ID used by copied one will be affected, besides usercount).
512 * There is only one exception, if LIB_ID_COPY_ACTIONS is defined, actions used by animdata will be duplicated.
514 * \note Usercount of new copy is always set to 1.
516 * \param bmain Main database, may be NULL only if LIB_ID_COPY_NO_MAIN is specified.
517 * \param id Source datablock.
518 * \param r_newid Pointer to new (copied) ID pointer.
519 * \param flag Set of copy options, see DNA_ID.h enum for details (leave to zero for default, full copy).
520 * \param test If set, do not do any copy, just test whether copy is supported.
521 * \return False when copying that ID type is not supported, true otherwise.
523 /* XXX TODO remove test thing, *all* IDs should be copyable that way! */
524 bool BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag, const bool test)
526 #define LIB_ID_TYPES_NOCOPY ID_LI, ID_SCR, ID_WM, /* Not supported */ \
527 ID_IP /* Deprecated */
529 BLI_assert(test || (r_newid != NULL));
530 if (r_newid != NULL) {
537 if (ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY)) {
544 BKE_libblock_copy_ex(bmain, id, r_newid, flag);
546 switch ((ID_Type)GS(id->name)) {
548 BKE_scene_copy_data(bmain, (Scene *)*r_newid, (Scene *)id, flag);
551 BKE_object_copy_data(bmain, (Object *)*r_newid, (Object *)id, flag);
554 BKE_mesh_copy_data(bmain, (Mesh *)*r_newid, (Mesh *)id, flag);
557 BKE_curve_copy_data(bmain, (Curve *)*r_newid, (Curve *)id, flag);
560 BKE_mball_copy_data(bmain, (MetaBall *)*r_newid, (MetaBall *)id, flag);
563 BKE_material_copy_data(bmain, (Material *)*r_newid, (Material *)id, flag);
566 BKE_texture_copy_data(bmain, (Tex *)*r_newid, (Tex *)id, flag);
569 BKE_image_copy_data(bmain, (Image *)*r_newid, (Image *)id, flag);
572 BKE_lattice_copy_data(bmain, (Lattice *)*r_newid, (Lattice *)id, flag);
575 BKE_lamp_copy_data(bmain, (Lamp *)*r_newid, (Lamp *)id, flag);
578 BKE_speaker_copy_data(bmain, (Speaker *)*r_newid, (Speaker *)id, flag);
581 BKE_camera_copy_data(bmain, (Camera *)*r_newid, (Camera *)id, flag);
584 BKE_key_copy_data(bmain, (Key *)*r_newid, (Key *)id, flag);
587 BKE_world_copy_data(bmain, (World *)*r_newid, (World *)id, flag);
590 BKE_text_copy_data(bmain, (Text *)*r_newid, (Text *)id, flag);
593 BKE_group_copy_data(bmain, (Group *)*r_newid, (Group *)id, flag);
596 BKE_armature_copy_data(bmain, (bArmature *)*r_newid, (bArmature *)id, flag);
599 BKE_action_copy_data(bmain, (bAction *)*r_newid, (bAction *)id, flag);
602 BKE_node_tree_copy_data(bmain, (bNodeTree *)*r_newid, (bNodeTree *)id, flag);
605 BKE_brush_copy_data(bmain, (Brush *)*r_newid, (Brush *)id, flag);
608 BKE_particlesettings_copy_data(bmain, (ParticleSettings *)*r_newid, (ParticleSettings *)id, flag);
611 BKE_gpencil_copy_data(bmain, (bGPdata *)*r_newid, (bGPdata *)id, flag);
614 BKE_movieclip_copy_data(bmain, (MovieClip *)*r_newid, (MovieClip *)id, flag);
617 BKE_mask_copy_data(bmain, (Mask *)*r_newid, (Mask *)id, flag);
620 BKE_linestyle_copy_data(bmain, (FreestyleLineStyle *)*r_newid, (FreestyleLineStyle *)id, flag);
623 BKE_palette_copy_data(bmain, (Palette *)*r_newid, (Palette *)id, flag);
626 BKE_paint_curve_copy_data(bmain, (PaintCurve *)*r_newid, (PaintCurve *)id, flag);
629 BKE_cachefile_copy_data(bmain, (CacheFile *)*r_newid, (CacheFile *)id, flag);
632 BKE_sound_copy_data(bmain, (bSound *)*r_newid, (bSound *)id, flag);
635 BKE_vfont_copy_data(bmain, (VFont *)*r_newid, (VFont *)id, flag);
641 BLI_assert(0); /* Should have been rejected at start of function! */
645 /* Update ID refcount, remap pointers to self in new ID. */
646 struct IDCopyLibManagementData data = {.id_src=id, .flag=flag};
647 BKE_library_foreach_ID_link(bmain, *r_newid, id_copy_libmanagement_cb, &data, IDWALK_NOP);
649 /* Do not make new copy local in case we are copying outside of main...
650 * XXX TODO: is this behavior OK, or should we need own flag to control that? */
651 if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
652 BKE_id_copy_ensure_local(bmain, id, *r_newid);
659 * Invokes the appropriate copy method for the block and returns the result in
660 * newid, unless test. Returns true if the block can be copied.
662 bool id_copy(Main *bmain, const ID *id, ID **newid, bool test)
664 return BKE_id_copy_ex(bmain, id, newid, 0, test);
667 /** Does *not* set ID->newid pointer. */
668 bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
674 /* if property isn't editable, we're going to have an extra block hanging around until we save */
675 if (RNA_property_editable(ptr, prop)) {
676 if (id_copy(CTX_data_main(C), id, &newid, false) && newid) {
677 /* copy animation actions too */
678 BKE_animdata_copy_id_action(id, false);
679 /* us is 1 by convention, but RNA_property_pointer_set
680 * will also increment it, so set it to zero */
684 RNA_id_pointer_create(newid, &idptr);
685 RNA_property_pointer_set(ptr, prop, idptr);
686 RNA_property_update(C, ptr, prop);
696 static int libblock_management_us_plus(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag)
698 if (cb_flag & IDWALK_CB_USER) {
699 id_us_plus(*id_pointer);
701 if (cb_flag & IDWALK_CB_USER_ONE) {
702 id_us_ensure_real(*id_pointer);
705 return IDWALK_RET_NOP;
708 static int libblock_management_us_min(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag)
710 if (cb_flag & IDWALK_CB_USER) {
711 id_us_min(*id_pointer);
713 /* We can do nothing in IDWALK_CB_USER_ONE case! */
715 return IDWALK_RET_NOP;
718 /** Add a 'NO_MAIN' datablock to given main (also sets usercounts of its IDs if needed). */
719 void BKE_libblock_management_main_add(Main *bmain, void *idv)
723 BLI_assert(bmain != NULL);
724 if ((id->tag & LIB_TAG_NO_MAIN) == 0) {
728 if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
729 /* We cannot add non-allocated ID to Main! */
733 /* We cannot allow non-userrefcounting IDs in Main database! */
734 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
735 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
738 ListBase *lb = which_libbase(bmain, GS(id->name));
739 BKE_main_lock(bmain);
741 new_id(lb, id, NULL);
742 /* alphabetic insertion: is in new_id */
743 id->tag &= ~(LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT);
744 BKE_main_unlock(bmain);
747 /** Remove a datablock from given main (set it to 'NO_MAIN' status). */
748 void BKE_libblock_management_main_remove(Main *bmain, void *idv)
752 BLI_assert(bmain != NULL);
753 if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
757 /* For now, allow userrefcounting IDs to get out of Main - can be handy in some cases... */
759 ListBase *lb = which_libbase(bmain, GS(id->name));
760 BKE_main_lock(bmain);
762 id->tag |= LIB_TAG_NO_MAIN;
763 BKE_main_unlock(bmain);
766 void BKE_libblock_management_usercounts_set(Main *bmain, void *idv)
770 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) == 0) {
774 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
775 id->tag &= ~LIB_TAG_NO_USER_REFCOUNT;
778 void BKE_libblock_management_usercounts_clear(Main *bmain, void *idv)
782 /* We do not allow IDs in Main database to not be userrefcounting. */
783 if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0 || (id->tag & LIB_TAG_NO_MAIN) != 0) {
787 BKE_library_foreach_ID_link(bmain, id, libblock_management_us_min, NULL, IDWALK_NOP);
788 id->tag |= LIB_TAG_NO_USER_REFCOUNT;
791 ListBase *which_libbase(Main *mainlib, short type)
793 switch ((ID_Type)type) {
795 return &(mainlib->scene);
797 return &(mainlib->library);
799 return &(mainlib->object);
801 return &(mainlib->mesh);
803 return &(mainlib->curve);
805 return &(mainlib->mball);
807 return &(mainlib->mat);
809 return &(mainlib->tex);
811 return &(mainlib->image);
813 return &(mainlib->latt);
815 return &(mainlib->lamp);
817 return &(mainlib->camera);
819 return &(mainlib->ipo);
821 return &(mainlib->key);
823 return &(mainlib->world);
825 return &(mainlib->screen);
827 return &(mainlib->vfont);
829 return &(mainlib->text);
831 return &(mainlib->speaker);
833 return &(mainlib->sound);
835 return &(mainlib->group);
837 return &(mainlib->armature);
839 return &(mainlib->action);
841 return &(mainlib->nodetree);
843 return &(mainlib->brush);
845 return &(mainlib->particle);
847 return &(mainlib->wm);
849 return &(mainlib->gpencil);
851 return &(mainlib->movieclip);
853 return &(mainlib->mask);
855 return &(mainlib->linestyle);
857 return &(mainlib->palettes);
859 return &(mainlib->paintcurves);
861 return &(mainlib->cachefiles);
867 * Clear or set given tags for all ids in listbase (runtime tags).
869 void BKE_main_id_tag_listbase(ListBase *lb, const int tag, const bool value)
873 for (id = lb->first; id; id = id->next) {
878 const int ntag = ~tag;
879 for (id = lb->first; id; id = id->next) {
886 * Clear or set given tags for all ids of given type in bmain (runtime tags).
888 void BKE_main_id_tag_idcode(struct Main *mainvar, const short type, const int tag, const bool value)
890 ListBase *lb = which_libbase(mainvar, type);
892 BKE_main_id_tag_listbase(lb, tag, value);
896 * Clear or set given tags for all ids in bmain (runtime tags).
898 void BKE_main_id_tag_all(struct Main *mainvar, const int tag, const bool value)
900 ListBase *lbarray[MAX_LIBARRAY];
903 a = set_listbasepointers(mainvar, lbarray);
905 BKE_main_id_tag_listbase(lbarray[a], tag, value);
911 * Clear or set given flags for all ids in listbase (persistent flags).
913 void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value)
917 for (id = lb->first; id; id = id->next)
921 const int nflag = ~flag;
922 for (id = lb->first; id; id = id->next)
928 * Clear or set given flags for all ids in bmain (persistent flags).
930 void BKE_main_id_flag_all(Main *bmain, const int flag, const bool value)
932 ListBase *lbarray[MAX_LIBARRAY];
934 a = set_listbasepointers(bmain, lbarray);
936 BKE_main_id_flag_listbase(lbarray[a], flag, value);
940 void BKE_main_lib_objects_recalc_all(Main *bmain)
944 /* flag for full recalc */
945 for (ob = bmain->object.first; ob; ob = ob->id.next) {
946 if (ID_IS_LINKED_DATABLOCK(ob)) {
947 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
951 DAG_id_type_tag(bmain, ID_OB);
955 * puts into array *lb pointers to all the ListBase structs in main,
956 * and returns the number of them as the function result. This is useful for
957 * generic traversal of all the blocks in a Main (by traversing all the
958 * lists in turn), without worrying about block types.
960 * \note MAX_LIBARRAY define should match this code */
961 int set_listbasepointers(Main *main, ListBase **lb)
963 /* BACKWARDS! also watch order of free-ing! (mesh<->mat), first items freed last.
964 * This is important because freeing data decreases usercounts of other datablocks,
965 * if this data is its self freed it can crash. */
966 lb[INDEX_ID_LI] = &(main->library); /* Libraries may be accessed from pretty much any other ID... */
967 lb[INDEX_ID_IP] = &(main->ipo);
968 lb[INDEX_ID_AC] = &(main->action); /* moved here to avoid problems when freeing with animato (aligorith) */
969 lb[INDEX_ID_KE] = &(main->key);
970 lb[INDEX_ID_GD] = &(main->gpencil); /* referenced by nodes, objects, view, scene etc, before to free after. */
971 lb[INDEX_ID_NT] = &(main->nodetree);
972 lb[INDEX_ID_IM] = &(main->image);
973 lb[INDEX_ID_TE] = &(main->tex);
974 lb[INDEX_ID_MA] = &(main->mat);
975 lb[INDEX_ID_VF] = &(main->vfont);
977 /* Important!: When adding a new object type,
978 * the specific data should be inserted here
981 lb[INDEX_ID_AR] = &(main->armature);
983 lb[INDEX_ID_CF] = &(main->cachefiles);
984 lb[INDEX_ID_ME] = &(main->mesh);
985 lb[INDEX_ID_CU] = &(main->curve);
986 lb[INDEX_ID_MB] = &(main->mball);
988 lb[INDEX_ID_LT] = &(main->latt);
989 lb[INDEX_ID_LA] = &(main->lamp);
990 lb[INDEX_ID_CA] = &(main->camera);
992 lb[INDEX_ID_TXT] = &(main->text);
993 lb[INDEX_ID_SO] = &(main->sound);
994 lb[INDEX_ID_GR] = &(main->group);
995 lb[INDEX_ID_PAL] = &(main->palettes);
996 lb[INDEX_ID_PC] = &(main->paintcurves);
997 lb[INDEX_ID_BR] = &(main->brush);
998 lb[INDEX_ID_PA] = &(main->particle);
999 lb[INDEX_ID_SPK] = &(main->speaker);
1001 lb[INDEX_ID_WO] = &(main->world);
1002 lb[INDEX_ID_MC] = &(main->movieclip);
1003 lb[INDEX_ID_SCR] = &(main->screen);
1004 lb[INDEX_ID_OB] = &(main->object);
1005 lb[INDEX_ID_LS] = &(main->linestyle); /* referenced by scenes */
1006 lb[INDEX_ID_SCE] = &(main->scene);
1007 lb[INDEX_ID_WM] = &(main->wm);
1008 lb[INDEX_ID_MSK] = &(main->mask);
1010 lb[INDEX_ID_NULL] = NULL;
1012 return (MAX_LIBARRAY - 1);
1015 /* *********** ALLOC AND FREE *****************
1017 * BKE_libblock_free(ListBase *lb, ID *id )
1018 * provide a list-basis and datablock, but only ID is read
1020 * void *BKE_libblock_alloc(ListBase *lb, type, name)
1021 * inserts in list and returns a new ID
1023 * **************************** */
1026 * Get allocation size fo a given datablock type and optionally allocation name.
1028 size_t BKE_libblock_get_alloc_info(short type, const char **name)
1030 #define CASE_RETURN(id_code, type) \
1033 if (name != NULL) { \
1036 return sizeof(type); \
1039 switch ((ID_Type)type) {
1040 CASE_RETURN(ID_SCE, Scene);
1041 CASE_RETURN(ID_LI, Library);
1042 CASE_RETURN(ID_OB, Object);
1043 CASE_RETURN(ID_ME, Mesh);
1044 CASE_RETURN(ID_CU, Curve);
1045 CASE_RETURN(ID_MB, MetaBall);
1046 CASE_RETURN(ID_MA, Material);
1047 CASE_RETURN(ID_TE, Tex);
1048 CASE_RETURN(ID_IM, Image);
1049 CASE_RETURN(ID_LT, Lattice);
1050 CASE_RETURN(ID_LA, Lamp);
1051 CASE_RETURN(ID_CA, Camera);
1052 CASE_RETURN(ID_IP, Ipo);
1053 CASE_RETURN(ID_KE, Key);
1054 CASE_RETURN(ID_WO, World);
1055 CASE_RETURN(ID_SCR, bScreen);
1056 CASE_RETURN(ID_VF, VFont);
1057 CASE_RETURN(ID_TXT, Text);
1058 CASE_RETURN(ID_SPK, Speaker);
1059 CASE_RETURN(ID_SO, bSound);
1060 CASE_RETURN(ID_GR, Group);
1061 CASE_RETURN(ID_AR, bArmature);
1062 CASE_RETURN(ID_AC, bAction);
1063 CASE_RETURN(ID_NT, bNodeTree);
1064 CASE_RETURN(ID_BR, Brush);
1065 CASE_RETURN(ID_PA, ParticleSettings);
1066 CASE_RETURN(ID_WM, wmWindowManager);
1067 CASE_RETURN(ID_GD, bGPdata);
1068 CASE_RETURN(ID_MC, MovieClip);
1069 CASE_RETURN(ID_MSK, Mask);
1070 CASE_RETURN(ID_LS, FreestyleLineStyle);
1071 CASE_RETURN(ID_PAL, Palette);
1072 CASE_RETURN(ID_PC, PaintCurve);
1073 CASE_RETURN(ID_CF, CacheFile);
1080 * Allocates and returns memory of the right size for the specified block type,
1081 * initialized to zero.
1083 void *BKE_libblock_alloc_notest(short type)
1086 size_t size = BKE_libblock_get_alloc_info(type, &name);
1088 return MEM_callocN(size, name);
1090 BLI_assert(!"Request to allocate unknown data type");
1095 * Allocates and returns a block of the specified type, with the specified name
1096 * (adjusted as necessary to ensure uniqueness), and appended to the specified list.
1097 * The user count is set to 1, all other content (apart from name and links) being
1098 * initialized to zero.
1100 void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int flag)
1102 BLI_assert((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1104 ID *id = BKE_libblock_alloc_notest(type);
1107 if ((flag & LIB_ID_CREATE_NO_MAIN) != 0) {
1108 id->tag |= LIB_TAG_NO_MAIN;
1110 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0) {
1111 id->tag |= LIB_TAG_NO_USER_REFCOUNT;
1115 *((short *)id->name) = type;
1116 if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1119 if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1120 ListBase *lb = which_libbase(bmain, type);
1122 BKE_main_lock(bmain);
1123 BLI_addtail(lb, id);
1124 new_id(lb, id, name);
1125 /* alphabetic insertion: is in new_id */
1126 BKE_main_unlock(bmain);
1128 /* TODO to be removed from here! */
1129 if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) {
1130 DAG_id_type_tag(bmain, type);
1134 BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
1142 * Initialize an ID of given type, such that it has valid 'empty' data.
1143 * ID is assumed to be just calloc'ed.
1145 void BKE_libblock_init_empty(ID *id)
1147 /* Note that only ID types that are not valid when filled of zero should have a callback here. */
1148 switch ((ID_Type)GS(id->name)) {
1150 BKE_scene_init((Scene *)id);
1153 /* Nothing to do. */
1157 Object *ob = (Object *)id;
1158 ob->type = OB_EMPTY;
1159 BKE_object_init(ob);
1163 BKE_mesh_init((Mesh *)id);
1166 BKE_curve_init((Curve *)id);
1169 BKE_mball_init((MetaBall *)id);
1172 BKE_material_init((Material *)id);
1175 BKE_texture_default((Tex *)id);
1178 BKE_image_init((Image *)id);
1181 BKE_lattice_init((Lattice *)id);
1184 BKE_lamp_init((Lamp *)id);
1187 BKE_speaker_init((Speaker *)id);
1190 BKE_camera_init((Camera *)id);
1193 BKE_world_init((World *)id);
1196 /* Nothing to do. */
1199 BKE_vfont_init((VFont *)id);
1202 BKE_text_init((Text *)id);
1205 /* Another fuzzy case, think NULLified content is OK here... */
1208 /* Nothing to do. */
1211 /* Nothing to do. */
1214 /* Nothing to do. */
1217 ntreeInitDefault((bNodeTree *)id);
1220 BKE_brush_init((Brush *)id);
1223 /* Nothing to do. */
1226 /* Nothing to do. */
1229 /* Nothing to do. */
1232 /* Nothing to do. */
1235 BKE_linestyle_init((FreestyleLineStyle *)id);
1238 BKE_cachefile_init((CacheFile *)id);
1241 /* Shapekeys are a complex topic too - they depend on their 'user' data type...
1242 * They are not linkable, though, so it should never reach here anyway. */
1246 /* We should never reach this. */
1250 /* Should not be needed - animation from lib pre-2.5 is broken anyway. */
1254 BLI_assert(0); /* Should never reach this point... */
1258 /* by spec, animdata is first item after ID */
1259 /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
1260 static void id_copy_animdata(Main *bmain, ID *id, const bool do_action)
1262 AnimData *adt = BKE_animdata_from_id(id);
1265 IdAdtTemplate *iat = (IdAdtTemplate *)id;
1266 iat->adt = BKE_animdata_copy(bmain, iat->adt, do_action); /* could be set to false, need to investigate */
1270 void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag)
1272 ID *new_id = *r_newid;
1274 /* Grrrrrrrrr... Not adding 'root' nodetrees to bmain.... grrrrrrrrrrrrrrrrrrrr! */
1275 /* This is taken from original ntree copy code, might be weak actually? */
1276 const bool use_nodetree_alloc_exception = ((GS(id->name) == ID_NT) && (bmain != NULL) &&
1277 (BLI_findindex(&bmain->nodetree, id) < 0));
1279 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL);
1280 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
1281 BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 || (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0);
1283 if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) {
1284 /* r_newid already contains pointer to allocated memory. */
1285 /* TODO do we want to memset(0) whole mem before filling it? */
1286 BLI_strncpy(new_id->name, id->name, sizeof(new_id->name));
1288 new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT;
1289 /* TODO Do we want/need to copy more from ID struct itself? */
1292 new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag | (use_nodetree_alloc_exception ? LIB_ID_CREATE_NO_MAIN : 0));
1294 BLI_assert(new_id != NULL);
1296 const size_t id_len = BKE_libblock_get_alloc_info(GS(new_id->name), NULL);
1297 const size_t id_offset = sizeof(ID);
1298 if ((int)id_len - (int)id_offset > 0) { /* signed to allow neg result */ /* XXX ????? */
1299 const char *cp = (const char *)id;
1300 char *cpn = (char *)new_id;
1302 memcpy(cpn + id_offset, cp + id_offset, id_len - id_offset);
1305 if (id->properties) {
1306 new_id->properties = IDP_CopyProperty_ex(id->properties, flag);
1309 /* the duplicate should get a copy of the animdata */
1310 id_copy_animdata(bmain, new_id, (flag & LIB_ID_COPY_ACTIONS) != 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0);
1312 if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0) {
1313 DAG_id_type_tag(bmain, GS(new_id->name));
1319 /* used everywhere in blenkernel */
1320 void *BKE_libblock_copy(Main *bmain, const ID *id)
1324 BKE_libblock_copy_ex(bmain, id, &idn, 0);
1329 void *BKE_libblock_copy_nolib(const ID *id, const bool do_action)
1333 BKE_libblock_copy_ex(NULL, id, &idn, LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | (do_action ? LIB_ID_COPY_ACTIONS : 0));
1338 void BKE_library_free(Library *lib)
1340 if (lib->packedfile)
1341 freePackedFile(lib->packedfile);
1344 Main *BKE_main_new(void)
1346 Main *bmain = MEM_callocN(sizeof(Main), "new main");
1347 bmain->eval_ctx = DEG_evaluation_context_new(DAG_EVAL_VIEWPORT);
1348 bmain->lock = MEM_mallocN(sizeof(SpinLock), "main lock");
1349 BLI_spin_init((SpinLock *)bmain->lock);
1353 void BKE_main_free(Main *mainvar)
1355 /* also call when reading a file, erase all, etc */
1356 ListBase *lbarray[MAX_LIBARRAY];
1359 MEM_SAFE_FREE(mainvar->blen_thumb);
1361 a = set_listbasepointers(mainvar, lbarray);
1363 ListBase *lb = lbarray[a];
1366 while ( (id = lb->first) ) {
1368 BKE_libblock_free_ex(mainvar, id, false, false);
1370 /* errors freeing ID's can be hard to track down,
1371 * enable this so valgrind will give the line number in its error log */
1373 case 0: BKE_libblock_free_ex(mainvar, id, false, false); break;
1374 case 1: BKE_libblock_free_ex(mainvar, id, false, false); break;
1375 case 2: BKE_libblock_free_ex(mainvar, id, false, false); break;
1376 case 3: BKE_libblock_free_ex(mainvar, id, false, false); break;
1377 case 4: BKE_libblock_free_ex(mainvar, id, false, false); break;
1378 case 5: BKE_libblock_free_ex(mainvar, id, false, false); break;
1379 case 6: BKE_libblock_free_ex(mainvar, id, false, false); break;
1380 case 7: BKE_libblock_free_ex(mainvar, id, false, false); break;
1381 case 8: BKE_libblock_free_ex(mainvar, id, false, false); break;
1382 case 9: BKE_libblock_free_ex(mainvar, id, false, false); break;
1383 case 10: BKE_libblock_free_ex(mainvar, id, false, false); break;
1384 case 11: BKE_libblock_free_ex(mainvar, id, false, false); break;
1385 case 12: BKE_libblock_free_ex(mainvar, id, false, false); break;
1386 case 13: BKE_libblock_free_ex(mainvar, id, false, false); break;
1387 case 14: BKE_libblock_free_ex(mainvar, id, false, false); break;
1388 case 15: BKE_libblock_free_ex(mainvar, id, false, false); break;
1389 case 16: BKE_libblock_free_ex(mainvar, id, false, false); break;
1390 case 17: BKE_libblock_free_ex(mainvar, id, false, false); break;
1391 case 18: BKE_libblock_free_ex(mainvar, id, false, false); break;
1392 case 19: BKE_libblock_free_ex(mainvar, id, false, false); break;
1393 case 20: BKE_libblock_free_ex(mainvar, id, false, false); break;
1394 case 21: BKE_libblock_free_ex(mainvar, id, false, false); break;
1395 case 22: BKE_libblock_free_ex(mainvar, id, false, false); break;
1396 case 23: BKE_libblock_free_ex(mainvar, id, false, false); break;
1397 case 24: BKE_libblock_free_ex(mainvar, id, false, false); break;
1398 case 25: BKE_libblock_free_ex(mainvar, id, false, false); break;
1399 case 26: BKE_libblock_free_ex(mainvar, id, false, false); break;
1400 case 27: BKE_libblock_free_ex(mainvar, id, false, false); break;
1401 case 28: BKE_libblock_free_ex(mainvar, id, false, false); break;
1402 case 29: BKE_libblock_free_ex(mainvar, id, false, false); break;
1403 case 30: BKE_libblock_free_ex(mainvar, id, false, false); break;
1404 case 31: BKE_libblock_free_ex(mainvar, id, false, false); break;
1405 case 32: BKE_libblock_free_ex(mainvar, id, false, false); break;
1406 case 33: BKE_libblock_free_ex(mainvar, id, false, false); break;
1407 case 34: BKE_libblock_free_ex(mainvar, id, false, false); break;
1416 if (mainvar->relations) {
1417 BKE_main_relations_free(mainvar);
1420 BLI_spin_end((SpinLock *)mainvar->lock);
1421 MEM_freeN(mainvar->lock);
1422 DEG_evaluation_context_free(mainvar->eval_ctx);
1426 void BKE_main_lock(struct Main *bmain)
1428 BLI_spin_lock((SpinLock *) bmain->lock);
1431 void BKE_main_unlock(struct Main *bmain)
1433 BLI_spin_unlock((SpinLock *) bmain->lock);
1437 static int main_relations_create_cb(void *user_data, ID *id_self, ID **id_pointer, int cb_flag)
1439 MainIDRelations *rel = user_data;
1442 MainIDRelationsEntry *entry, **entry_p;
1444 entry = BLI_mempool_alloc(rel->entry_pool);
1445 if (BLI_ghash_ensure_p(rel->id_user_to_used, id_self, (void ***)&entry_p)) {
1446 entry->next = *entry_p;
1451 entry->id_pointer = id_pointer;
1452 entry->usage_flag = cb_flag;
1455 entry = BLI_mempool_alloc(rel->entry_pool);
1456 if (BLI_ghash_ensure_p(rel->id_used_to_user, *id_pointer, (void ***)&entry_p)) {
1457 entry->next = *entry_p;
1462 entry->id_pointer = (ID **)id_self;
1463 entry->usage_flag = cb_flag;
1467 return IDWALK_RET_NOP;
1470 /** Generate the mappings between used IDs and their users, and vice-versa. */
1471 void BKE_main_relations_create(Main *bmain)
1473 ListBase *lbarray[MAX_LIBARRAY];
1477 if (bmain->relations != NULL) {
1478 BKE_main_relations_free(bmain);
1481 bmain->relations = MEM_mallocN(sizeof(*bmain->relations), __func__);
1482 bmain->relations->id_used_to_user = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
1483 bmain->relations->id_user_to_used = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__);
1484 bmain->relations->entry_pool = BLI_mempool_create(sizeof(MainIDRelationsEntry), 128, 128, BLI_MEMPOOL_NOP);
1486 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1487 for (id = lbarray[a]->first; id; id = id->next) {
1488 BKE_library_foreach_ID_link(NULL, id, main_relations_create_cb, bmain->relations, IDWALK_READONLY);
1493 void BKE_main_relations_free(Main *bmain)
1495 if (bmain->relations) {
1496 if (bmain->relations->id_used_to_user) {
1497 BLI_ghash_free(bmain->relations->id_used_to_user, NULL, NULL);
1499 if (bmain->relations->id_user_to_used) {
1500 BLI_ghash_free(bmain->relations->id_user_to_used, NULL, NULL);
1502 BLI_mempool_destroy(bmain->relations->entry_pool);
1503 MEM_freeN(bmain->relations);
1504 bmain->relations = NULL;
1509 * Generates a raw .blend file thumbnail data from given image.
1511 * \param bmain If not NULL, also store generated data in this Main.
1512 * \param img ImBuf image to generate thumbnail data from.
1513 * \return The generated .blend file raw thumbnail data.
1515 BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img)
1517 BlendThumbnail *data = NULL;
1520 MEM_SAFE_FREE(bmain->blen_thumb);
1524 const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y);
1525 data = MEM_mallocN(sz, __func__);
1527 IMB_rect_from_float(img); /* Just in case... */
1528 data->width = img->x;
1529 data->height = img->y;
1530 memcpy(data->rect, img->rect, sz - sizeof(*data));
1534 bmain->blen_thumb = data;
1540 * Generates an image from raw .blend file thumbnail \a data.
1542 * \param bmain Use this bmain->blen_thumb data if given \a data is NULL.
1543 * \param data Raw .blend file thumbnail data.
1544 * \return An ImBuf from given data, or NULL if invalid.
1546 ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data)
1550 if (!data && bmain) {
1551 data = bmain->blen_thumb;
1555 /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail
1556 * here (we do not want to pass the first two ints!). */
1557 img = IMB_allocImBuf((unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata);
1558 memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data));
1565 * Generates an empty (black) thumbnail for given Main.
1567 void BKE_main_thumbnail_create(struct Main *bmain)
1569 MEM_SAFE_FREE(bmain->blen_thumb);
1571 bmain->blen_thumb = MEM_callocN(BLEN_THUMB_MEMSIZE(BLEN_THUMB_SIZE, BLEN_THUMB_SIZE), __func__);
1572 bmain->blen_thumb->width = BLEN_THUMB_SIZE;
1573 bmain->blen_thumb->height = BLEN_THUMB_SIZE;
1576 /* ***************** ID ************************ */
1577 ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const char *name)
1579 ListBase *lb = which_libbase(bmain, type);
1580 BLI_assert(lb != NULL);
1581 return BLI_findstring(lb, name, offsetof(ID, name) + 2);
1583 ID *BKE_libblock_find_name(const short type, const char *name)
1585 return BKE_libblock_find_name_ex(G.main, type, name);
1589 void id_sort_by_name(ListBase *lb, ID *id)
1593 /* insert alphabetically */
1594 if (lb->first != lb->last) {
1595 BLI_remlink(lb, id);
1599 if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) {
1600 BLI_insertlinkbefore(lb, idtest, id);
1603 idtest = idtest->next;
1606 if (idtest == NULL) {
1607 BLI_addtail(lb, id);
1614 * Check to see if there is an ID with the same name as 'name'.
1615 * Returns the ID if so, if not, returns NULL
1617 static ID *is_dupid(ListBase *lb, ID *id, const char *name)
1621 for (idtest = lb->first; idtest; idtest = idtest->next) {
1622 /* if idtest is not a lib */
1623 if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
1624 /* do not test alphabetic! */
1626 if (idtest->name[2] == name[0]) {
1627 if (STREQ(name, idtest->name + 2)) break;
1636 * Check to see if an ID name is already used, and find a new one if so.
1637 * Return true if created a new name (returned in name).
1639 * Normally the ID that's being check is already in the ListBase, so ID *id
1640 * points at the new entry. The Python Library module needs to know what
1641 * the name of a datablock will be before it is appended; in this case ID *id
1645 static bool check_for_dupid(ListBase *lb, ID *id, char *name)
1650 #define MAX_IN_USE 64
1651 bool in_use[MAX_IN_USE];
1652 /* to speed up finding unused numbers within [1 .. MAX_IN_USE - 1] */
1654 char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8];
1658 /* phase 1: id already exists? */
1659 idtest = is_dupid(lb, id, name);
1661 /* if there is no double, done */
1662 if (idtest == NULL) return false;
1664 /* we have a dup; need to make a new name */
1665 /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */
1666 memset(in_use, false, sizeof(in_use));
1668 /* get name portion, number portion ("name.number") */
1669 left_len = BLI_split_name_num(left, &nr, name, '.');
1671 /* if new name will be too long, truncate it */
1672 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* assumption: won't go beyond 9999 */
1673 left[MAX_ID_NAME - 8] = '\0';
1674 left_len = MAX_ID_NAME - 8;
1676 else if (left_len > (MAX_ID_NAME - 7)) {
1677 left[MAX_ID_NAME - 7] = '\0';
1678 left_len = MAX_ID_NAME - 7;
1681 /* Code above may have generated invalid utf-8 string, due to raw truncation.
1682 * Ensure we get a valid one now! */
1683 left_len -= (size_t)BLI_utf8_invalid_strip(left, left_len);
1685 for (idtest = lb->first; idtest; idtest = idtest->next) {
1687 if ( (id != idtest) &&
1688 !ID_IS_LINKED_DATABLOCK(idtest) &&
1689 (*name == *(idtest->name + 2)) &&
1690 STREQLEN(name, idtest->name + 2, left_len) &&
1691 (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
1694 /* will get here at least once, otherwise is_dupid call above would have returned NULL */
1695 if (nrtest < MAX_IN_USE)
1696 in_use[nrtest] = true; /* mark as used */
1698 nr = nrtest + 1; /* track largest unused */
1701 /* At this point, 'nr' will typically be at least 1. (but not always) */
1702 // BLI_assert(nr >= 1);
1704 /* decide which value of nr to use */
1705 for (a = 0; a < MAX_IN_USE; a++) {
1706 if (a >= nr) break; /* stop when we've checked up to biggest */ /* redundant check */
1707 if (!in_use[a]) { /* found an unused value */
1709 /* can only be zero if all potential duplicate names had
1710 * nonzero numeric suffixes, which means name itself has
1711 * nonzero numeric suffix (else no name conflict and wouldn't
1712 * have got here), which means name[left_len] is not a null */
1716 /* At this point, nr is either the lowest unused number within [0 .. MAX_IN_USE - 1],
1717 * or 1 greater than the largest used number if all those low ones are taken.
1718 * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */
1720 /* If the original name has no numeric suffix,
1721 * rather than just chopping and adding numbers,
1722 * shave off the end chars until we have a unique name.
1723 * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */
1724 if (nr == 0 && name[left_len] == '\0') {
1726 /* FIXME: this code will never be executed, because either nr will be
1727 * at least 1, or name will not end at left_len! */
1731 idtest = is_dupid(lb, id, name);
1733 while (idtest && len > 1) {
1735 idtest = is_dupid(lb, id, name);
1737 if (idtest == NULL) return true;
1738 /* otherwise just continue and use a number suffix */
1741 if (nr > 999 && left_len > (MAX_ID_NAME - 8)) {
1742 /* this would overflow name buffer */
1743 left[MAX_ID_NAME - 8] = 0;
1744 /* left_len = MAX_ID_NAME - 8; */ /* for now this isn't used again */
1745 memcpy(name, left, sizeof(char) * (MAX_ID_NAME - 7));
1748 /* this format specifier is from hell... */
1749 BLI_snprintf(name, sizeof(id->name) - 2, "%s.%.3d", left, nr);
1758 * Only for local blocks: external en indirect blocks already have a
1761 * return true: created a new name
1764 bool new_id(ListBase *lb, ID *id, const char *tname)
1767 char name[MAX_ID_NAME - 2];
1769 /* if library, don't rename */
1770 if (ID_IS_LINKED_DATABLOCK(id))
1773 /* if no libdata given, look up based on ID */
1775 lb = which_libbase(G.main, GS(id->name));
1777 /* if no name given, use name of current ID
1778 * else make a copy (tname args can be const) */
1780 tname = id->name + 2;
1782 BLI_strncpy(name, tname, sizeof(name));
1784 if (name[0] == '\0') {
1785 /* disallow empty names */
1786 BLI_strncpy(name, DATA_(ID_FALLBACK_NAME), sizeof(name));
1789 /* disallow non utf8 chars,
1790 * the interface checks for this but new ID's based on file names don't */
1791 BLI_utf8_invalid_strip(name, strlen(name));
1794 result = check_for_dupid(lb, id, name);
1795 strcpy(id->name + 2, name);
1797 /* This was in 2.43 and previous releases
1798 * however all data in blender should be sorted, not just duplicate names
1799 * sorting should not hurt, but noting just incase it alters the way other
1800 * functions work, so sort every time */
1803 id_sort_by_name(lb, id);
1806 id_sort_by_name(lb, id);
1812 * Pull an ID out of a library (make it local). Only call this for IDs that
1813 * don't have other library users.
1815 void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist)
1817 bNodeTree *ntree = NULL;
1820 BKE_id_lib_local_paths(bmain, id->lib, id);
1822 id_fake_user_clear(id);
1825 id->tag &= ~(LIB_TAG_INDIRECT | LIB_TAG_EXTERN);
1827 new_id(which_libbase(bmain, GS(id->name)), id, NULL);
1829 /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */
1830 if ((ntree = ntreeFromID(id))) {
1831 id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */
1834 /* Same goes for shapekeys. */
1835 if ((key = BKE_key_from_id(id))) {
1836 id_clear_lib_data_ex(bmain, &key->id, id_in_mainlist); /* sigh, why are keys in Main? */
1840 void id_clear_lib_data(Main *bmain, ID *id)
1842 id_clear_lib_data_ex(bmain, id, true);
1845 /* next to indirect usage in read/writefile also in editobject.c scene.c */
1846 void BKE_main_id_clear_newpoins(Main *bmain)
1848 ListBase *lbarray[MAX_LIBARRAY];
1852 a = set_listbasepointers(bmain, lbarray);
1854 id = lbarray[a]->first;
1857 id->tag &= ~LIB_TAG_NEW;
1864 static void library_make_local_copying_check(ID *id, GSet *loop_tags, MainIDRelations *id_relations, GSet *done_ids)
1866 if (BLI_gset_haskey(done_ids, id)) {
1867 return; /* Already checked, nothing else to do. */
1870 MainIDRelationsEntry *entry = BLI_ghash_lookup(id_relations->id_used_to_user, id);
1871 BLI_gset_insert(loop_tags, id);
1872 for (; entry != NULL; entry = entry->next) {
1873 ID *par_id = (ID *)entry->id_pointer; /* used_to_user stores ID pointer, not pointer to ID pointer... */
1875 /* Our oh-so-beloved 'from' pointers... */
1876 if (entry->usage_flag & IDWALK_CB_LOOPBACK) {
1877 /* We totally disregard Object->proxy_from 'usage' here, this one would only generate fake positives. */
1878 if (GS(par_id->name) == ID_OB) {
1879 BLI_assert(((Object *)par_id)->proxy_from == (Object *)id);
1883 /* Shapekeys are considered 'private' to their owner ID here, and never tagged (since they cannot be linked),
1884 * so we have to switch effective parent to their owner. */
1885 if (GS(par_id->name) == ID_KE) {
1886 par_id = ((Key *)par_id)->from;
1890 if (par_id->lib == NULL) {
1891 /* Local user, early out to avoid some gset querying... */
1894 if (!BLI_gset_haskey(done_ids, par_id)) {
1895 if (BLI_gset_haskey(loop_tags, par_id)) {
1896 /* We are in a 'dependency loop' of IDs, this does not say us anything, skip it.
1897 * Note that this is the situation that can lead to archipelagoes of linked data-blocks
1898 * (since all of them have non-local users, they would all be duplicated, leading to a loop of unused
1899 * linked data-blocks that cannot be freed since they all use each other...). */
1902 /* Else, recursively check that user ID. */
1903 library_make_local_copying_check(par_id, loop_tags, id_relations, done_ids);
1906 if (par_id->tag & LIB_TAG_DOIT) {
1907 /* This user will be fully local in future, so far so good, nothing to do here but check next user. */
1910 /* This user won't be fully local in future, so current ID won't be either. And we are done checking it. */
1911 id->tag &= ~LIB_TAG_DOIT;
1915 BLI_gset_add(done_ids, id);
1916 BLI_gset_remove(loop_tags, id, NULL);
1919 /** Make linked datablocks local.
1921 * \param bmain Almost certainly G.main.
1922 * \param lib If not NULL, only make local datablocks from this library.
1923 * \param untagged_only If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING.
1924 * \param set_fake If true, set fake user on all localized datablocks (except group and objects ones).
1926 /* Note: Old (2.77) version was simply making (tagging) datablocks as local, without actually making any check whether
1927 * they were also indirectly used or not...
1929 * Current version uses regular id_make_local callback, with advanced pre-processing step to detect all cases of
1930 * IDs currently indirectly used, but which will be used by local data only once this function is finished.
1931 * This allows to avoid any uneeded duplication of IDs, and hence all time lost afterwards to remove
1932 * orphaned linked data-blocks...
1934 void BKE_library_make_local(
1935 Main *bmain, const Library *lib, GHash *old_to_new_ids, const bool untagged_only, const bool set_fake)
1937 ListBase *lbarray[MAX_LIBARRAY];
1941 LinkNode *todo_ids = NULL;
1942 LinkNode *copied_ids = NULL;
1943 MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
1945 GSet *done_ids = BLI_gset_ptr_new(__func__);
1948 TIMEIT_START(make_local);
1951 BKE_main_relations_create(bmain);
1954 printf("Pre-compute current ID relations: Done.\n");
1955 TIMEIT_VALUE_PRINT(make_local);
1958 /* Step 1: Detect datablocks to make local. */
1959 for (a = set_listbasepointers(bmain, lbarray); a--; ) {
1960 id = lbarray[a]->first;
1962 /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), they are assumed to be handled
1963 * by real datablocks responsible of them. */
1964 const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name)));
1966 for (; id; id = id->next) {
1967 ID *ntree = (ID *)ntreeFromID(id);
1969 id->tag &= ~LIB_TAG_DOIT;
1970 if (ntree != NULL) {
1971 ntree->tag &= ~LIB_TAG_DOIT;
1974 if (id->lib == NULL) {
1975 id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW);
1977 /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so its possible to tag data you don't want to
1978 * be made local, used for appending data, so any libdata already linked wont become local (very nasty
1979 * to discover all your links are lost after appending).
1980 * Also, never ever make proxified objects local, would not make any sense. */
1982 * - Shapekeys are never tagged here (since they are not linkable).
1983 * - Nodetrees used in materials etc. have to be tagged manually, since they do not exist in Main (!).
1984 * This is ok-ish on 'make local' side of things (since those are handled by their 'owner' IDs),
1985 * but complicates slightly the pre-processing of relations between IDs at step 2... */
1986 else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) &&
1987 ELEM(lib, NULL, id->lib) &&
1988 !(GS(id->name) == ID_OB && ((Object *)id)->proxy_from != NULL) &&
1989 ((untagged_only == false) || !(id->tag & LIB_TAG_PRE_EXISTING)))
1991 BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem);
1992 id->tag |= LIB_TAG_DOIT;
1994 /* Tag those nasty non-ID nodetrees, but do not add them to todo list, making them local is handled
1995 * by 'owner' ID. This is needed for library_make_local_copying_check() to work OK at step 2. */
1996 if (ntree != NULL) {
1997 ntree->tag |= LIB_TAG_DOIT;
2001 /* Linked ID that we won't be making local (needed info for step 2, see below). */
2002 BLI_gset_add(done_ids, id);
2008 printf("Step 1: Detect datablocks to make local: Done.\n");
2009 TIMEIT_VALUE_PRINT(make_local);
2012 /* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future,
2013 * local data), others will need to be duplicated. */
2014 GSet *loop_tags = BLI_gset_ptr_new(__func__);
2015 for (LinkNode *it = todo_ids; it; it = it->next) {
2016 library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids);
2017 BLI_assert(BLI_gset_size(loop_tags) == 0);
2019 BLI_gset_free(loop_tags, NULL);
2020 BLI_gset_free(done_ids, NULL);
2022 /* Next step will most likely add new IDs, better to get rid of this mapping now. */
2023 BKE_main_relations_free(bmain);
2026 printf("Step 2: Check which datablocks we can directly make local: Done.\n");
2027 TIMEIT_VALUE_PRINT(make_local);
2030 /* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
2031 * which involves more complex checks and might instead create a local copy of original linked ID. */
2032 for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
2036 if (id->tag & LIB_TAG_DOIT) {
2037 /* We know all users of this object are local or will be made fully local, even if currently there are
2038 * some indirect usages. So instead of making a copy that we'll likely get rid of later, directly make
2039 * that data block local. Saves a tremendous amount of time with complex scenes... */
2040 id_clear_lib_data_ex(bmain, id, true);
2041 BKE_id_expand_local(bmain, id);
2042 id->tag &= ~LIB_TAG_DOIT;
2045 /* In this specific case, we do want to make ID local even if it has no local usage yet... */
2046 if (GS(id->name) == ID_OB) {
2047 /* Special case for objects because we don't want proxy pointers to be
2048 * cleared yet. This will happen down the road in this function.
2050 BKE_object_make_local_ex(bmain, (Object *)id, true, false);
2053 id_make_local(bmain, id, false, true);
2057 /* Reuse already allocated LinkNode (transferring it from todo_ids to copied_ids). */
2058 BLI_linklist_prepend_nlink(&copied_ids, id, it);
2063 if (!ELEM(GS(id->name), ID_OB, ID_GR)) {
2064 /* do not set fake user on objects, groups (instancing) */
2065 id_fake_user_set(id);
2071 printf("Step 3: Make IDs local: Done.\n");
2072 TIMEIT_VALUE_PRINT(make_local);
2075 /* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their
2076 * remaining linked original counterpart may not be needed anymore... */
2079 /* Step 4: We have to remap local usages of old (linked) ID to new (local) ID in a separated loop,
2080 * as lbarray ordering is not enough to ensure us we did catch all dependencies
2081 * (e.g. if making local a parent object before its child...). See T48907. */
2082 /* TODO This is now the biggest step by far (in term of processing time). We may be able to gain here by
2083 * using again main->relations mapping, but... this implies BKE_libblock_remap & co to be able to update
2084 * main->relations on the fly. Have to think about it a bit more, and see whether new code is OK first, anyway. */
2085 for (LinkNode *it = copied_ids; it; it = it->next) {
2088 BLI_assert(id->newid != NULL);
2089 BLI_assert(id->lib != NULL);
2091 BKE_libblock_remap(bmain, id, id->newid, ID_REMAP_SKIP_INDIRECT_USAGE);
2092 if (old_to_new_ids) {
2093 BLI_ghash_insert(old_to_new_ids, id, id->newid);
2096 /* Special hack for groups... Thing is, since we can't instantiate them here, we need to ensure
2097 * they remain 'alive' (only instantiation is a real group 'user'... *sigh* See T49722. */
2098 if (GS(id->name) == ID_GR && (id->tag & LIB_TAG_INDIRECT) != 0) {
2099 id_us_ensure_real(id->newid);
2104 printf("Step 4: Remap local usages of old (linked) ID to new (local) ID: Done.\n");
2105 TIMEIT_VALUE_PRINT(make_local);
2108 /* Note: Keeping both version of the code (old one being safer, since it still has checks against unused IDs)
2109 * for now, we can remove old one once it has been tested for some time in master... */
2111 /* Step 5: proxy 'remapping' hack. */
2112 for (LinkNode *it = copied_ids; it; it = it->next) {
2113 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
2114 * from another blend file into this one, even when that blend file contains proxified
2115 * armatures that have local references. Since the proxified object needs to be linked
2116 * (not local), this will only work when the "Localize all" checkbox is disabled.
2117 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
2118 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
2119 Object *ob = (Object *)id;
2120 Object *ob_new = (Object *)id->newid;
2121 bool is_local = false, is_lib = false;
2123 /* Proxies only work when the proxified object is linked-in from a library. */
2124 if (ob->proxy->id.lib == NULL) {
2125 printf("Warning, proxy object %s will loose its link to %s, because the "
2126 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
2130 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
2132 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
2133 * referred to from a library. Not checking for local use; if new local proxy
2134 * was not used locally would be a nasty bug! */
2135 if (is_local || is_lib) {
2136 printf("Warning, made-local proxy object %s will loose its link to %s, "
2137 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
2138 id->newid->name, ob->proxy->id.name, is_local, is_lib);
2141 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
2142 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
2143 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
2144 ob_new->proxy = ob->proxy;
2145 ob_new->proxy_group = ob->proxy_group;
2146 ob_new->proxy_from = ob->proxy_from;
2147 ob_new->proxy->proxy_from = ob_new;
2148 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
2154 printf("Step 5: Proxy 'remapping' hack: Done.\n");
2155 TIMEIT_VALUE_PRINT(make_local);
2159 LinkNode *linked_loop_candidates = NULL;
2161 /* Step 5: remove datablocks that have been copied to be localized and are no more used in the end...
2162 * Note that we may have to loop more than once here, to tackle dependencies between linked objects... */
2163 bool do_loop = true;
2166 for (LinkNode *it = copied_ids; it; it = it->next) {
2167 if ((id = it->link) == NULL) {
2171 bool is_local = false, is_lib = false;
2173 BKE_library_ID_test_usages(bmain, id, &is_local, &is_lib);
2175 /* Attempt to re-link copied proxy objects. This allows appending of an entire scene
2176 * from another blend file into this one, even when that blend file contains proxified
2177 * armatures that have local references. Since the proxified object needs to be linked
2178 * (not local), this will only work when the "Localize all" checkbox is disabled.
2179 * TL;DR: this is a dirty hack on top of an already weak feature (proxies). */
2180 if (GS(id->name) == ID_OB && ((Object *)id)->proxy != NULL) {
2181 Object *ob = (Object *)id;
2182 Object *ob_new = (Object *)id->newid;
2184 /* Proxies only work when the proxified object is linked-in from a library. */
2185 if (ob->proxy->id.lib == NULL) {
2186 printf("Warning, proxy object %s will loose its link to %s, because the "
2187 "proxified object is local.\n", id->newid->name, ob->proxy->id.name);
2189 /* We can only switch the proxy'ing to a made-local proxy if it is no longer
2190 * referred to from a library. Not checking for local use; if new local proxy
2191 * was not used locally would be a nasty bug! */
2192 else if (is_local || is_lib) {
2193 printf("Warning, made-local proxy object %s will loose its link to %s, "
2194 "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
2195 id->newid->name, ob->proxy->id.name, is_local, is_lib);
2198 /* we can switch the proxy'ing from the linked-in to the made-local proxy.
2199 * BKE_object_make_proxy() shouldn't be used here, as it allocates memory that
2200 * was already allocated by BKE_object_make_local_ex() (which called BKE_object_copy_ex). */
2201 ob_new->proxy = ob->proxy;
2202 ob_new->proxy_group = ob->proxy_group;
2203 ob_new->proxy_from = ob->proxy_from;
2204 ob_new->proxy->proxy_from = ob_new;
2205 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
2210 if (!is_lib) { /* Not used at all, we can free it! */
2211 BLI_assert(!"Unused linked data copy remaining from MakeLibLocal process, should not happen anymore");
2212 printf("\t%s (from %s)\n", id->name, id->lib->id.name);
2213 BKE_libblock_free(bmain, id);
2217 /* Only used by linked data, potential candidate to ugly lib-only dependency cycles... */
2218 else if ((id->tag & LIB_TAG_DOIT) == 0) { /* Check TAG_DOIT to avoid adding same ID several times... */
2219 /* Note that we store the node, not directly ID pointer, that way if it->link is set to NULL
2220 * later we can skip it in lib-dependency cycles search later. */
2221 BLI_linklist_prepend_arena(&linked_loop_candidates, it, linklist_mem);
2222 id->tag |= LIB_TAG_DOIT;
2224 /* Grrrrrrr... those half-datablocks-stuff... grrrrrrrrrrr...
2225 * Here we have to also tag them as potential candidates, otherwise they would falsy report
2226 * ID they used as 'directly used' in sixth step. */
2227 ID *ntree = (ID *)ntreeFromID(id);
2228 if (ntree != NULL) {
2229 ntree->tag |= LIB_TAG_DOIT;
2237 printf("Step 5: Remove linked datablocks that have been copied and ended fully localized: Done.\n");
2238 TIMEIT_VALUE_PRINT(make_local);
2241 /* Step 6: Try to find circle dependencies between indirectly-linked-only datablocks.
2242 * Those are fake 'usages' that prevent their deletion. See T49775 for nice ugly case. */
2243 BKE_library_unused_linked_data_set_tag(bmain, false);
2244 for (LinkNode *it = linked_loop_candidates; it; it = it->next) {
2245 if (it->link == NULL) {
2248 if ((id = ((LinkNode *)it->link)->link) == NULL) {
2253 /* Note: in theory here we are only handling datablocks forming exclusive linked dependency-cycles-based
2254 * archipelagos, so no need to check again after we have deleted one, as done in previous step. */
2255 if (id->tag & LIB_TAG_DOIT) {
2256 BLI_assert(!"Unused linked data copy remaining from MakeLibLocal process (archipelago case), should not happen anymore");
2257 /* Object's deletion rely on valid ob->data, but ob->data may have already been freed here...
2258 * Setting it to NULL may not be 100% correct, but should be safe and do the work. */
2259 if (GS(id->name) == ID_OB) {
2260 ((Object *)id)->data = NULL;
2263 /* Note: *in theory* IDs tagged here are fully *outside* of file scope, totally unused, so we can
2264 * directly wipe them out without caring about clearing their usages.
2265 * However, this is a highly-risky presumption, and nice crasher in case something goes wrong here.
2266 * So for 2.78a will keep the safe option, and switch to more efficient one in master later. */
2268 BKE_libblock_free_ex(bmain, id, false, true);
2270 BKE_libblock_unlink(bmain, id, false, false);
2271 BKE_libblock_free(bmain, id);
2273 ((LinkNode *)it->link)->link = NULL; /* Not strictly necessary, but safer (see T49903)... */
2279 printf("Step 6: Try to find circle dependencies between indirectly-linked-only datablocks: Done.\n");
2280 TIMEIT_VALUE_PRINT(make_local);
2285 /* This is probably more of a hack than something we should do here, but...
2286 * Issue is, the whole copying + remapping done in complex cases above may leave pose channels of armatures
2287 * in complete invalid state (more precisely, the bone pointers of the pchans - very crappy cross-datablocks
2288 * relationship), se we tag it to be fully recomputed, but this does not seems to be enough in some cases,
2289 * and evaluation code ends up trying to evaluate a not-yet-updated armature object's deformations.
2290 * Try "make all local" in 04_01_H.lighting.blend from Agent327 without this, e.g. */
2291 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
2292 if (ob->data != NULL && ob->type == OB_ARMATURE && ob->pose != NULL && ob->pose->flag & POSE_RECALC) {
2293 BKE_pose_rebuild(ob, ob->data);
2298 printf("Hack: Forcefully rebuild armature object poses: Done.\n");
2299 TIMEIT_VALUE_PRINT(make_local);
2302 BKE_main_id_clear_newpoins(bmain);
2303 BLI_memarena_free(linklist_mem);
2306 printf("Cleanup and finish: Done.\n");
2307 TIMEIT_END(make_local);
2312 * Use after setting the ID's name
2313 * When name exists: call 'new_id'
2315 void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
2321 lb = which_libbase(bmain, GS(name));
2322 if (lb == NULL) return;
2325 idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2);
2327 if (idtest && !new_id(lb, idtest, idtest->name + 2)) {
2328 id_sort_by_name(lb, idtest);
2333 * Sets the name of a block to name, suitably adjusted for uniqueness.
2335 void BKE_libblock_rename(Main *bmain, ID *id, const char *name)
2337 ListBase *lb = which_libbase(bmain, GS(id->name));
2338 new_id(lb, id, name);
2342 * Returns in name the name of the block, with a 3-character prefix prepended
2343 * indicating whether it comes from a library, has a fake user, or no users.
2345 void BKE_id_ui_prefix(char name[MAX_ID_NAME + 1], const ID *id)
2347 name[0] = id->lib ? (ID_MISSING(id) ? 'M' : 'L') : ' ';
2348 name[1] = (id->flag & LIB_FAKEUSER) ? 'F' : ((id->us == 0) ? '0' : ' ');
2351 strcpy(name + 3, id->name + 2);
2354 void BKE_library_filepath_set(Library *lib, const char *filepath)
2356 /* in some cases this is used to update the absolute path from the
2358 if (lib->name != filepath) {
2359 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
2362 BLI_strncpy(lib->filepath, filepath, sizeof(lib->filepath));
2364 /* not essential but set filepath is an absolute copy of value which
2365 * is more useful if its kept in sync */
2366 if (BLI_path_is_rel(lib->filepath)) {
2367 /* note that the file may be unsaved, in this case, setting the
2368 * filepath on an indirectly linked path is not allowed from the
2369 * outliner, and its not really supported but allow from here for now
2370 * since making local could cause this to be directly linked - campbell
2372 const char *basepath = lib->parent ? lib->parent->filepath : G.main->name;
2373 BLI_path_abs(lib->filepath, basepath);
2377 void BKE_id_tag_set_atomic(ID *id, int tag)
2379 atomic_fetch_and_or_uint32((uint32_t *)&id->tag, tag);
2382 void BKE_id_tag_clear_atomic(ID *id, int tag)
2384 atomic_fetch_and_and_uint32((uint32_t *)&id->tag, ~tag);