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.
22 * Contributor(s): Blender Foundation
24 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenloader/intern/readfile.c
36 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
37 #include <stdlib.h> // for getenv atoi
38 #include <stddef.h> // for offsetof
39 #include <fcntl.h> // for open
40 #include <string.h> // for strrchr strncmp strstr
41 #include <math.h> // for fabs
42 #include <stdarg.h> /* for va_start/end */
43 #include <time.h> /* for gmtime */
45 #include "BLI_utildefines.h"
47 # include <unistd.h> // for read close
49 # include <io.h> // for open close read
50 # include "winsock2.h"
51 # include "BLI_winstuff.h"
54 /* allow readfile to use deprecated functionality */
55 #define DNA_DEPRECATED_ALLOW
57 #include "DNA_anim_types.h"
58 #include "DNA_armature_types.h"
59 #include "DNA_actuator_types.h"
60 #include "DNA_brush_types.h"
61 #include "DNA_camera_types.h"
62 #include "DNA_cloth_types.h"
63 #include "DNA_controller_types.h"
64 #include "DNA_constraint_types.h"
65 #include "DNA_dynamicpaint_types.h"
66 #include "DNA_effect_types.h"
67 #include "DNA_fileglobal_types.h"
68 #include "DNA_genfile.h"
69 #include "DNA_group_types.h"
70 #include "DNA_gpencil_types.h"
71 #include "DNA_ipo_types.h"
72 #include "DNA_key_types.h"
73 #include "DNA_lattice_types.h"
74 #include "DNA_lamp_types.h"
75 #include "DNA_linestyle_types.h"
76 #include "DNA_meta_types.h"
77 #include "DNA_material_types.h"
78 #include "DNA_mesh_types.h"
79 #include "DNA_meshdata_types.h"
80 #include "DNA_nla_types.h"
81 #include "DNA_node_types.h"
82 #include "DNA_object_fluidsim.h" // NT
83 #include "DNA_object_force.h"
84 #include "DNA_object_types.h"
85 #include "DNA_packedFile_types.h"
86 #include "DNA_property_types.h"
87 #include "DNA_rigidbody_types.h"
88 #include "DNA_text_types.h"
89 #include "DNA_view3d_types.h"
90 #include "DNA_screen_types.h"
91 #include "DNA_sensor_types.h"
92 #include "DNA_sdna_types.h"
93 #include "DNA_scene_types.h"
94 #include "DNA_sequence_types.h"
95 #include "DNA_smoke_types.h"
96 #include "DNA_speaker_types.h"
97 #include "DNA_sound_types.h"
98 #include "DNA_space_types.h"
99 #include "DNA_vfont_types.h"
100 #include "DNA_world_types.h"
101 #include "DNA_movieclip_types.h"
102 #include "DNA_mask_types.h"
104 #include "MEM_guardedalloc.h"
106 #include "BLI_endian_switch.h"
107 #include "BLI_blenlib.h"
108 #include "BLI_math.h"
109 #include "BLI_threads.h"
110 #include "BLI_mempool.h"
112 #include "BLT_translation.h"
114 #include "BKE_action.h"
115 #include "BKE_armature.h"
116 #include "BKE_brush.h"
117 #include "BKE_cloth.h"
118 #include "BKE_constraint.h"
119 #include "BKE_context.h"
120 #include "BKE_curve.h"
121 #include "BKE_depsgraph.h"
122 #include "BKE_effect.h"
123 #include "BKE_fcurve.h"
124 #include "BKE_global.h" // for G
125 #include "BKE_group.h"
126 #include "BKE_library.h" // for which_libbase
127 #include "BKE_library_query.h"
128 #include "BKE_idcode.h"
129 #include "BKE_material.h"
130 #include "BKE_main.h" // for Main
131 #include "BKE_mesh.h" // for ME_ defines (patching)
132 #include "BKE_modifier.h"
133 #include "BKE_multires.h"
134 #include "BKE_node.h" // for tree type defines
135 #include "BKE_object.h"
136 #include "BKE_paint.h"
137 #include "BKE_report.h"
138 #include "BKE_sca.h" // for init_actuator
139 #include "BKE_scene.h"
140 #include "BKE_screen.h"
141 #include "BKE_sequencer.h"
142 #include "BKE_outliner_treehash.h"
143 #include "BKE_sound.h"
146 #include "NOD_common.h"
147 #include "NOD_socket.h"
149 #include "BLO_readfile.h"
150 #include "BLO_undofile.h"
151 #include "BLO_blend_defs.h"
153 #include "RE_engine.h"
155 #include "readfile.h"
161 * Remark: still a weak point is the newaddress() function, that doesnt solve reading from
162 * multiple files at the same time
164 * (added remark: oh, i thought that was solved? will look at that... (ton)
167 * - Existing Library (Main) push or free
168 * - allocate new Main
171 * - for each LibBlock
175 * - attach ID's to it
177 * - read associated 'direct data'
178 * - link direct data (internal and to LibBlock)
180 * - read USER data, only when indicated (file is ~/X.XX/startup.blend)
182 * - per Library (per Main)
185 * - find LibBlocks and attach IDs to Main
186 * - if external LibBlock
187 * - search all Main's
188 * - or it's already read,
193 * - read associated direct data
194 * - link direct data (internal and to LibBlock)
196 * - per Library with unread LibBlocks
201 * - read associated direct data
202 * - link direct data (internal and to LibBlock)
205 * - link all LibBlocks and indirect pointers to libblocks
206 * - initialize FileGlobal and copy pointers to Global
209 /* use GHash for BHead name-based lookups (speeds up linking) */
210 #define USE_GHASH_BHEAD
214 typedef struct OldNew {
220 typedef struct OldNewMap {
222 int nentries, entriessize;
228 /* local prototypes */
229 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
230 static void direct_link_modifiers(FileData *fd, ListBase *lb);
231 static void convert_tface_mt(FileData *fd, Main *main);
232 static BHead *find_bhead_from_code_name(FileData *fd, const short idcode, const char *name);
233 static BHead *find_bhead_from_idname(FileData *fd, const char *idname);
235 /* this function ensures that reports are printed,
236 * in the case of libraray linking errors this is important!
238 * bit kludge but better then doubling up on prints,
239 * we could alternatively have a versions of a report function which forces printing - campbell
242 void blo_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
244 char fixed_buf[1024]; /* should be long enough */
248 va_start(args, format);
249 vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
252 fixed_buf[sizeof(fixed_buf) - 1] = '\0';
254 BKE_report(reports, type, fixed_buf);
256 if (G.background == 0) {
257 printf("%s: %s\n", BKE_report_type_str(type), fixed_buf);
261 /* for reporting linking messages */
262 static const char *library_parent_filepath(Library *lib)
264 return lib->parent ? lib->parent->filepath : "<direct>";
267 static OldNewMap *oldnewmap_new(void)
269 OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
271 onm->entriessize = 1024;
272 onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
277 static int verg_oldnewmap(const void *v1, const void *v2)
279 const struct OldNew *x1=v1, *x2=v2;
281 if (x1->old > x2->old) return 1;
282 else if (x1->old < x2->old) return -1;
287 static void oldnewmap_sort(FileData *fd)
289 BLI_assert(fd->libmap->sorted == false);
290 qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
291 fd->libmap->sorted = 1;
294 /* nr is zero for data, and ID code for libdata */
295 static void oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
299 if (oldaddr==NULL || newaddr==NULL) return;
301 if (UNLIKELY(onm->nentries == onm->entriessize)) {
302 onm->entriessize *= 2;
303 onm->entries = MEM_reallocN(onm->entries, sizeof(*onm->entries) * onm->entriessize);
306 entry = &onm->entries[onm->nentries++];
307 entry->old = oldaddr;
308 entry->newp = newaddr;
312 void blo_do_versions_oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
314 oldnewmap_insert(onm, oldaddr, newaddr, nr);
318 * Do a full search (no state).
320 * \param lasthit: Use as a reference position to avoid a full search
321 * from either end of the array, giving more efficient lookups.
323 * \note This would seem an ideal case for hash or btree lookups.
324 * However the data is written in-order, using the \a lasthit will normally avoid calling this function.
325 * Creating a btree/hash structure adds overhead for the common-case to optimize the corner-case
326 * (since most entries will never be retrieved).
327 * So just keep full lookups as a fall-back.
329 static int oldnewmap_lookup_entry_full(const OldNewMap *onm, const void *addr, int lasthit)
331 const int nentries = onm->nentries;
332 const OldNew *entries = onm->entries;
335 /* search relative to lasthit where possible */
336 if (lasthit >= 0 && lasthit < nentries) {
338 /* search forwards */
340 while (++i != nentries) {
341 if (entries[i].old == addr) {
346 /* search backwards */
349 if (entries[i].old == addr) {
355 /* search backwards (full) */
358 if (entries[i].old == addr) {
367 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool increase_users)
371 if (addr == NULL) return NULL;
373 if (onm->lasthit < onm->nentries-1) {
374 OldNew *entry = &onm->entries[++onm->lasthit];
376 if (entry->old == addr) {
383 i = oldnewmap_lookup_entry_full(onm, addr, onm->lasthit);
385 OldNew *entry = &onm->entries[i];
386 BLI_assert(entry->old == addr);
396 /* for libdata, nr has ID code, no increment */
397 static void *oldnewmap_liblookup(OldNewMap *onm, const void *addr, const void *lib)
403 /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
405 const OldNew entry_s = {.old = addr};
406 OldNew *entry = bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
408 ID *id = entry->newp;
410 if (id && (!lib || id->lib)) {
416 /* note, this can be a bottle neck when loading some files */
417 const int i = oldnewmap_lookup_entry_full(onm, addr, -1);
419 OldNew *entry = &onm->entries[i];
420 ID *id = entry->newp;
421 BLI_assert(entry->old == addr);
422 if (id && (!lib || id->lib)) {
431 static void oldnewmap_free_unused(OldNewMap *onm)
435 for (i = 0; i < onm->nentries; i++) {
436 OldNew *entry = &onm->entries[i];
437 if (entry->nr == 0) {
438 MEM_freeN(entry->newp);
444 static void oldnewmap_clear(OldNewMap *onm)
450 static void oldnewmap_free(OldNewMap *onm)
452 MEM_freeN(onm->entries);
458 static void read_libraries(FileData *basefd, ListBase *mainlist);
460 /* ************ help functions ***************** */
462 static void add_main_to_main(Main *mainvar, Main *from)
464 ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
467 set_listbasepointers(mainvar, lbarray);
468 a = set_listbasepointers(from, fromarray);
470 BLI_movelisttolist(lbarray[a], fromarray[a]);
474 void blo_join_main(ListBase *mainlist)
476 Main *tojoin, *mainl;
478 mainl = mainlist->first;
479 while ((tojoin = mainl->next)) {
480 add_main_to_main(mainl, tojoin);
481 BLI_remlink(mainlist, tojoin);
482 BKE_main_free(tojoin);
486 static void split_libdata(ListBase *lb_src, Main **lib_main_array, const unsigned int lib_main_array_len)
488 for (ID *id = lb_src->first, *idnext; id; id = idnext) {
492 if (((unsigned int)id->lib->temp_index < lib_main_array_len) &&
493 /* this check should never fail, just incase 'id->lib' is a dangling pointer. */
494 (lib_main_array[id->lib->temp_index]->curlib == id->lib))
496 Main *mainvar = lib_main_array[id->lib->temp_index];
497 ListBase *lb_dst = which_libbase(mainvar, GS(id->name));
498 BLI_remlink(lb_src, id);
499 BLI_addtail(lb_dst, id);
502 printf("%s: invalid library for '%s'\n", __func__, id->name);
509 void blo_split_main(ListBase *mainlist, Main *main)
511 mainlist->first = mainlist->last = main;
514 if (BLI_listbase_is_empty(&main->library))
517 /* (Library.temp_index -> Main), lookup table */
518 const unsigned int lib_main_array_len = BLI_listbase_count(&main->library);
519 Main **lib_main_array = MEM_mallocN(lib_main_array_len * sizeof(*lib_main_array), __func__);
522 for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) {
523 Main *libmain = BKE_main_new();
524 libmain->curlib = lib;
525 BLI_addtail(mainlist, libmain);
527 lib_main_array[i] = libmain;
530 ListBase *lbarray[MAX_LIBARRAY];
531 i = set_listbasepointers(main, lbarray);
533 split_libdata(lbarray[i], lib_main_array, lib_main_array_len);
536 MEM_freeN(lib_main_array);
539 static void read_file_version(FileData *fd, Main *main)
543 for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
544 if (bhead->code == GLOB) {
545 FileGlobal *fg= read_struct(fd, bhead, "Global");
547 main->subversionfile= fg->subversion;
548 main->minversionfile= fg->minversion;
549 main->minsubversionfile= fg->minsubversion;
552 else if (bhead->code == ENDB)
558 #ifdef USE_GHASH_BHEAD
559 static void read_file_bhead_idname_map_create(FileData *fd)
564 bool is_link = false;
565 int code_prev = ENDB;
566 unsigned int reserve = 0;
568 for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
569 if (code_prev != bhead->code) {
570 code_prev = bhead->code;
571 is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
579 BLI_assert(fd->bhead_idname_hash == NULL);
581 fd->bhead_idname_hash = BLI_ghash_str_new_ex(__func__, reserve);
583 for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
584 if (code_prev != bhead->code) {
585 code_prev = bhead->code;
586 is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
590 BLI_ghash_insert(fd->bhead_idname_hash, (void *)bhead_id_name(fd, bhead), bhead);
597 static Main *blo_find_main(FileData *fd, const char *filepath, const char *relabase)
599 ListBase *mainlist = fd->mainlist;
602 char name1[FILE_MAX];
604 BLI_strncpy(name1, filepath, sizeof(name1));
605 BLI_cleanup_path(relabase, name1);
607 // printf("blo_find_main: relabase %s\n", relabase);
608 // printf("blo_find_main: original in %s\n", filepath);
609 // printf("blo_find_main: converted to %s\n", name1);
611 for (m = mainlist->first; m; m = m->next) {
612 const char *libname = (m->curlib) ? m->curlib->filepath : m->name;
614 if (BLI_path_cmp(name1, libname) == 0) {
615 if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
621 BLI_addtail(mainlist, m);
623 /* Add library datablock itself to 'main' Main, since libraries are **never** linked data.
624 * Fixes bug where you could end with all ID_LI datablocks having the same name... */
625 lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib");
626 lib->id.us = ID_FAKE_USERS(lib); /* Important, consistency with main ID reading code from read_libblock(). */
627 BLI_strncpy(lib->name, filepath, sizeof(lib->name));
628 BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
632 read_file_version(fd, m);
634 if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
639 /* ************ FILE PARSING ****************** */
641 static void switch_endian_bh4(BHead4 *bhead)
643 /* the ID_.. codes */
644 if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
646 if (bhead->code != ENDB) {
647 BLI_endian_switch_int32(&bhead->len);
648 BLI_endian_switch_int32(&bhead->SDNAnr);
649 BLI_endian_switch_int32(&bhead->nr);
653 static void switch_endian_bh8(BHead8 *bhead)
655 /* the ID_.. codes */
656 if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
658 if (bhead->code != ENDB) {
659 BLI_endian_switch_int32(&bhead->len);
660 BLI_endian_switch_int32(&bhead->SDNAnr);
661 BLI_endian_switch_int32(&bhead->nr);
665 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
667 BHead4 *bhead4 = (BHead4 *) bhead;
670 bhead4->code = bhead8->code;
671 bhead4->len = bhead8->len;
673 if (bhead4->code != ENDB) {
674 /* perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
675 * 0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
677 if (do_endian_swap) {
678 BLI_endian_switch_int64(&bhead8->old);
681 /* this patch is to avoid a long long being read from not-eight aligned positions
682 * is necessary on any modern 64bit architecture) */
683 memcpy(&old, &bhead8->old, 8);
684 bhead4->old = (int) (old >> 3);
686 bhead4->SDNAnr = bhead8->SDNAnr;
687 bhead4->nr = bhead8->nr;
691 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
693 BHead8 *bhead8 = (BHead8 *) bhead;
695 bhead8->code = bhead4->code;
696 bhead8->len = bhead4->len;
698 if (bhead8->code != ENDB) {
699 bhead8->old = bhead4->old;
700 bhead8->SDNAnr = bhead4->SDNAnr;
701 bhead8->nr= bhead4->nr;
705 static BHeadN *get_bhead(FileData *fd)
707 BHeadN *new_bhead = NULL;
712 /* initializing to zero isn't strictly needed but shuts valgrind up
713 * since uninitialized memory gets compared */
718 /* First read the bhead structure.
719 * Depending on the platform the file was written on this can
720 * be a big or little endian BHead4 or BHead8 structure.
722 * As usual 'ENDB' (the last *partial* bhead of the file)
723 * needs some special handling. We don't want to EOF just yet.
725 if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
727 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
729 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
730 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
731 switch_endian_bh4(&bhead4);
734 if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
735 bh8_from_bh4(&bhead, &bhead4);
738 memcpy(&bhead, &bhead4, sizeof(bhead));
748 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
750 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
751 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
752 switch_endian_bh8(&bhead8);
755 if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
756 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
759 memcpy(&bhead, &bhead8, sizeof(bhead));
768 /* make sure people are not trying to pass bad blend files */
769 if (bhead.len < 0) fd->eof = 1;
771 /* bhead now contains the (converted) bhead structure. Now read
772 * the associated data and put everything in a BHeadN (creative naming !)
775 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
777 new_bhead->next = new_bhead->prev = NULL;
778 new_bhead->bhead = bhead;
780 readsize = fd->read(fd, new_bhead + 1, bhead.len);
782 if (readsize != bhead.len) {
784 MEM_freeN(new_bhead);
795 /* We've read a new block. Now add it to the list
799 BLI_addtail(&fd->listbase, new_bhead);
805 BHead *blo_firstbhead(FileData *fd)
811 * Read in a new block if necessary
813 new_bhead = fd->listbase.first;
814 if (new_bhead == NULL) {
815 new_bhead = get_bhead(fd);
819 bhead = &new_bhead->bhead;
825 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
827 BHeadN *bheadn = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
828 BHeadN *prev = bheadn->prev;
830 return (prev) ? &prev->bhead : NULL;
833 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
835 BHeadN *new_bhead = NULL;
839 /* bhead is actually a sub part of BHeadN
840 * We calculate the BHeadN pointer from the BHead pointer below */
841 new_bhead = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
843 /* get the next BHeadN. If it doesn't exist we read in the next one */
844 new_bhead = new_bhead->next;
845 if (new_bhead == NULL) {
846 new_bhead = get_bhead(fd);
851 /* here we do the reverse:
852 * go from the BHeadN pointer to the BHead pointer */
853 bhead = &new_bhead->bhead;
859 /* Warning! Caller's responsability to ensure given bhead **is** and ID one! */
860 const char *bhead_id_name(const FileData *fd, const BHead *bhead)
862 return (const char *)POINTER_OFFSET(bhead, sizeof(*bhead) + fd->id_name_offs);
865 static void decode_blender_header(FileData *fd)
867 char header[SIZEOFBLENDERHEADER], num[4];
870 /* read in the header data */
871 readsize = fd->read(fd, header, sizeof(header));
873 if (readsize == sizeof(header)) {
874 if (STREQLEN(header, "BLENDER", 7)) {
875 int remove_this_endian_test = 1;
877 fd->flags |= FD_FLAGS_FILE_OK;
879 /* what size are pointers in the file ? */
880 if (header[7]=='_') {
881 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
882 if (sizeof(void *) != 4) {
883 fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
887 if (sizeof(void *) != 8) {
888 fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
892 /* is the file saved in a different endian
895 if (((((char *)&remove_this_endian_test)[0] == 1) ? L_ENDIAN : B_ENDIAN) != ((header[8] == 'v') ? L_ENDIAN : B_ENDIAN)) {
896 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
899 /* get the version number */
900 memcpy(num, header + 9, 3);
902 fd->fileversion = atoi(num);
907 static int read_file_dna(FileData *fd)
911 for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
912 if (bhead->code == DNA1) {
913 const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
915 fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
917 fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
918 /* used to retrieve ID names from (bhead+1) */
919 fd->id_name_offs = DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
924 else if (bhead->code == ENDB)
931 static int *read_file_thumbnail(FileData *fd)
934 int *blend_thumb = NULL;
936 for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
937 if (bhead->code == TEST) {
938 const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
939 int *data = (int *)(bhead + 1);
941 if (bhead->len < (2 * sizeof(int))) {
945 if (do_endian_swap) {
946 BLI_endian_switch_int32(&data[0]);
947 BLI_endian_switch_int32(&data[1]);
950 if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(data[0], data[1])) {
957 else if (bhead->code != REND) {
958 /* Thumbnail is stored in TEST immediately after first REND... */
966 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
968 int readsize = read(filedata->filedes, buffer, size);
974 filedata->seek += readsize;
980 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
982 int readsize = gzread(filedata->gzfiledes, buffer, size);
988 filedata->seek += readsize;
994 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
996 /* don't read more bytes then there are available in the buffer */
997 int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
999 memcpy(buffer, filedata->buffer + filedata->seek, readsize);
1000 filedata->seek += readsize;
1005 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
1007 static unsigned int seek = (1<<30); /* the current position */
1008 static unsigned int offset = 0; /* size of previous chunks */
1009 static MemFileChunk *chunk = NULL;
1010 unsigned int chunkoffset, readsize, totread;
1012 if (size == 0) return 0;
1014 if (seek != (unsigned int)filedata->seek) {
1015 chunk = filedata->memfile->chunks.first;
1019 if (seek + chunk->size > (unsigned) filedata->seek) break;
1020 seek += chunk->size;
1021 chunk = chunk->next;
1024 seek = filedata->seek;
1031 /* first check if it's on the end if current chunk */
1032 if (seek-offset == chunk->size) {
1033 offset += chunk->size;
1034 chunk = chunk->next;
1037 /* debug, should never happen */
1038 if (chunk == NULL) {
1039 printf("illegal read, chunk zero\n");
1043 chunkoffset = seek-offset;
1044 readsize = size-totread;
1046 /* data can be spread over multiple chunks, so clamp size
1047 * to within this chunk, and then it will read further in
1049 if (chunkoffset+readsize > chunk->size)
1050 readsize= chunk->size-chunkoffset;
1052 memcpy(POINTER_OFFSET(buffer, totread), chunk->buf + chunkoffset, readsize);
1053 totread += readsize;
1054 filedata->seek += readsize;
1056 } while (totread < size);
1064 static FileData *filedata_new(void)
1066 FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
1069 fd->gzfiledes = NULL;
1071 /* XXX, this doesn't need to be done all the time,
1072 * but it keeps us re-entrant, remove once we have
1073 * a lib that provides a nice lock. - zr
1075 fd->memsdna = DNA_sdna_from_data(DNAstr, DNAlen, false);
1077 fd->datamap = oldnewmap_new();
1078 fd->globmap = oldnewmap_new();
1079 fd->libmap = oldnewmap_new();
1084 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
1086 decode_blender_header(fd);
1088 if (fd->flags & FD_FLAGS_FILE_OK) {
1089 if (!read_file_dna(fd)) {
1090 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', incomplete", fd->relabase);
1091 blo_freefiledata(fd);
1096 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', not a blend file", fd->relabase);
1097 blo_freefiledata(fd);
1104 /* cannot be called with relative paths anymore! */
1105 /* on each new library added, it now checks for the current FileData and expands relativeness */
1106 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
1110 gzfile = BLI_gzopen(filepath, "rb");
1112 if (gzfile == (gzFile)Z_NULL) {
1113 BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s",
1114 filepath, errno ? strerror(errno) : TIP_("unknown error reading file"));
1118 FileData *fd = filedata_new();
1119 fd->gzfiledes = gzfile;
1120 fd->read = fd_read_gzip_from_file;
1122 /* needed for library_append and read_libraries */
1123 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
1125 return blo_decode_and_check(fd, reports);
1130 * Same as blo_openblenderfile(), but does not reads DNA data, only header. Use it for light access
1131 * (e.g. thumbnail reading).
1133 static FileData *blo_openblenderfile_minimal(const char *filepath)
1137 gzfile = BLI_gzopen(filepath, "rb");
1139 if (gzfile != (gzFile)Z_NULL) {
1140 FileData *fd = filedata_new();
1141 fd->gzfiledes = gzfile;
1142 fd->read = fd_read_gzip_from_file;
1144 decode_blender_header(fd);
1146 if (fd->flags & FD_FLAGS_FILE_OK) {
1150 blo_freefiledata(fd);
1156 static int fd_read_gzip_from_memory(FileData *filedata, void *buffer, unsigned int size)
1160 filedata->strm.next_out = (Bytef *) buffer;
1161 filedata->strm.avail_out = size;
1163 // Inflate another chunk.
1164 err = inflate (&filedata->strm, Z_SYNC_FLUSH);
1166 if (err == Z_STREAM_END) {
1169 else if (err != Z_OK) {
1170 printf("fd_read_gzip_from_memory: zlib error\n");
1174 filedata->seek += size;
1179 static int fd_read_gzip_from_memory_init(FileData *fd)
1182 fd->strm.next_in = (Bytef *) fd->buffer;
1183 fd->strm.avail_in = fd->buffersize;
1184 fd->strm.total_out = 0;
1185 fd->strm.zalloc = Z_NULL;
1186 fd->strm.zfree = Z_NULL;
1188 if (inflateInit2(&fd->strm, (16+MAX_WBITS)) != Z_OK)
1191 fd->read = fd_read_gzip_from_memory;
1196 FileData *blo_openblendermemory(const void *mem, int memsize, ReportList *reports)
1198 if (!mem || memsize<SIZEOFBLENDERHEADER) {
1199 BKE_report(reports, RPT_WARNING, (mem) ? TIP_("Unable to read"): TIP_("Unable to open"));
1203 FileData *fd = filedata_new();
1204 const char *cp = mem;
1207 fd->buffersize = memsize;
1210 if (cp[0] == 0x1f && cp[1] == 0x8b) {
1211 if (0 == fd_read_gzip_from_memory_init(fd)) {
1212 blo_freefiledata(fd);
1217 fd->read = fd_read_from_memory;
1219 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1221 return blo_decode_and_check(fd, reports);
1225 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
1228 BKE_report(reports, RPT_WARNING, "Unable to open blend <memory>");
1232 FileData *fd = filedata_new();
1233 fd->memfile = memfile;
1235 fd->read = fd_read_from_memfile;
1236 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1238 return blo_decode_and_check(fd, reports);
1243 void blo_freefiledata(FileData *fd)
1246 if (fd->filedes != -1) {
1250 if (fd->gzfiledes != NULL) {
1251 gzclose(fd->gzfiledes);
1254 if (fd->strm.next_in) {
1255 if (inflateEnd (&fd->strm) != Z_OK) {
1256 printf("close gzip stream error\n");
1260 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1261 MEM_freeN((void *)fd->buffer);
1265 // Free all BHeadN data blocks
1266 BLI_freelistN(&fd->listbase);
1269 DNA_sdna_free(fd->memsdna);
1271 DNA_sdna_free(fd->filesdna);
1273 MEM_freeN(fd->compflags);
1276 oldnewmap_free(fd->datamap);
1278 oldnewmap_free(fd->globmap);
1280 oldnewmap_free(fd->imamap);
1281 if (fd->movieclipmap)
1282 oldnewmap_free(fd->movieclipmap);
1284 oldnewmap_free(fd->soundmap);
1286 oldnewmap_free(fd->packedmap);
1287 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1288 oldnewmap_free(fd->libmap);
1290 MEM_freeN(fd->bheadmap);
1292 #ifdef USE_GHASH_BHEAD
1293 if (fd->bhead_idname_hash) {
1294 BLI_ghash_free(fd->bhead_idname_hash, NULL, NULL);
1302 /* ************ DIV ****************** */
1305 * Check whether given path ends with a blend file compatible extension (.blend, .ble or .blend.gz).
1307 * \param str The path to check.
1308 * \return true is this path ends with a blender file extension.
1310 bool BLO_has_bfile_extension(const char *str)
1312 const char *ext_test[4] = {".blend", ".ble", ".blend.gz", NULL};
1313 return BLI_testextensie_array(str, ext_test);
1317 * Try to explode given path into its 'library components' (i.e. a .blend file, id type/group, and datablock itself).
1319 * \param path the full path to explode.
1320 * \param r_dir the string that'll contain path up to blend file itself ('library' path).
1321 * \param r_group the string that'll contain 'group' part of the path, if any. May be NULL.
1322 * \param r_name the string that'll contain data's name part of the path, if any. May be NULL.
1323 * \return true if path contains a blend file.
1325 bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, char **r_name)
1327 /* We might get some data names with slashes, so we have to go up in path until we find blend file itself,
1328 * then we now next path item is group, and everything else is data name. */
1329 char *slash = NULL, *prev_slash = NULL, c = '\0';
1339 /* if path leads to an existing directory, we can be sure we're not (in) a library */
1340 if (BLI_is_dir(path)) {
1344 strcpy(r_dir, path);
1346 while ((slash = (char *)BLI_last_slash(r_dir))) {
1349 if (BLO_has_bfile_extension(r_dir) && BLI_is_file(r_dir)) {
1364 if (slash[1] != '\0') {
1365 BLI_assert(strlen(slash + 1) < BLO_GROUP_MAX);
1367 *r_group = slash + 1;
1371 if (prev_slash && (prev_slash[1] != '\0')) {
1372 BLI_assert(strlen(prev_slash + 1) < MAX_ID_NAME - 2);
1374 *r_name = prev_slash + 1;
1382 * Does a very light reading of given .blend file to extract its stored thumbnail.
1384 * \param filepath The path of the file to extract thumbnail from.
1385 * \return The raw thumbnail
1386 * (MEM-allocated, as stored in file, use BKE_main_thumbnail_to_imbuf() to convert it to ImBuf image).
1388 BlendThumbnail *BLO_thumbnail_from_file(const char *filepath)
1391 BlendThumbnail *data;
1394 fd = blo_openblenderfile_minimal(filepath);
1395 fd_data = fd ? read_file_thumbnail(fd) : NULL;
1398 const size_t sz = BLEN_THUMB_MEMSIZE(fd_data[0], fd_data[1]);
1399 data = MEM_mallocN(sz, __func__);
1401 BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(fd_data[0], fd_data[1]) - (sizeof(*fd_data) * 2)));
1402 data->width = fd_data[0];
1403 data->height = fd_data[1];
1404 memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
1410 blo_freefiledata(fd);
1415 /* ************** OLD POINTERS ******************* */
1417 static void *newdataadr(FileData *fd, const void *adr) /* only direct databocks */
1419 return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1422 /* This is a special version of newdataadr() which allows us to keep lasthit of
1423 * map unchanged. In certain cases this makes file loading time significantly
1426 * Use this function in cases like restoring pointer from one list element to
1427 * another list element, but keep lasthit value so we can continue restoring
1428 * pointers efficiently.
1430 * Example of this could be found in direct_link_fcurves() which restores the
1431 * fcurve group pointer and keeps lasthit optimal for linking all further
1434 static void *newdataadr_ex(FileData *fd, const void *adr, bool increase_lasthit) /* only direct databocks */
1436 if (increase_lasthit) {
1437 return newdataadr(fd, adr);
1440 int lasthit = fd->datamap->lasthit;
1441 void *newadr = newdataadr(fd, adr);
1442 fd->datamap->lasthit = lasthit;
1447 static void *newdataadr_no_us(FileData *fd, const void *adr) /* only direct databocks */
1449 return oldnewmap_lookup_and_inc(fd->datamap, adr, false);
1452 static void *newglobadr(FileData *fd, const void *adr) /* direct datablocks with global linking */
1454 return oldnewmap_lookup_and_inc(fd->globmap, adr, true);
1457 static void *newimaadr(FileData *fd, const void *adr) /* used to restore image data after undo */
1459 if (fd->imamap && adr)
1460 return oldnewmap_lookup_and_inc(fd->imamap, adr, true);
1464 static void *newmclipadr(FileData *fd, const void *adr) /* used to restore movie clip data after undo */
1466 if (fd->movieclipmap && adr)
1467 return oldnewmap_lookup_and_inc(fd->movieclipmap, adr, true);
1471 static void *newsoundadr(FileData *fd, const void *adr) /* used to restore sound data after undo */
1473 if (fd->soundmap && adr)
1474 return oldnewmap_lookup_and_inc(fd->soundmap, adr, true);
1478 static void *newpackedadr(FileData *fd, const void *adr) /* used to restore packed data after undo */
1480 if (fd->packedmap && adr)
1481 return oldnewmap_lookup_and_inc(fd->packedmap, adr, true);
1483 return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1487 static void *newlibadr(FileData *fd, const void *lib, const void *adr) /* only lib data */
1489 return oldnewmap_liblookup(fd->libmap, adr, lib);
1492 void *blo_do_versions_newlibadr(FileData *fd, const void *lib, const void *adr) /* only lib data */
1494 return newlibadr(fd, lib, adr);
1497 static void *newlibadr_us(FileData *fd, const void *lib, const void *adr) /* increases user number */
1499 ID *id = newlibadr(fd, lib, adr);
1501 id_us_plus_no_lib(id);
1506 void *blo_do_versions_newlibadr_us(FileData *fd, const void *lib, const void *adr) /* increases user number */
1508 return newlibadr_us(fd, lib, adr);
1511 static void change_idid_adr_fd(FileData *fd, const void *old, void *new)
1515 /* use a binary search if we have a sorted libmap, for now it's not needed. */
1516 BLI_assert(fd->libmap->sorted == false);
1518 for (i = 0; i < fd->libmap->nentries; i++) {
1519 OldNew *entry = &fd->libmap->entries[i];
1521 if (old==entry->newp && entry->nr==ID_ID) {
1523 if (new) entry->nr = GS( ((ID *)new)->name );
1528 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1532 for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) {
1535 if (mainptr->curlib)
1536 fd = mainptr->curlib->filedata;
1541 change_idid_adr_fd(fd, old, new);
1546 /* lib linked proxy objects point to our local data, we need
1547 * to clear that pointer before reading the undo memfile since
1548 * the object might be removed, it is set again in reading
1549 * if the local object still exists */
1550 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
1552 Object *ob = oldmain->object.first;
1554 for (; ob; ob= ob->id.next) {
1556 ob->proxy_from = NULL;
1560 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1562 Image *ima = oldmain->image.first;
1563 Scene *sce = oldmain->scene.first;
1566 fd->imamap = oldnewmap_new();
1568 for (; ima; ima = ima->id.next) {
1570 oldnewmap_insert(fd->imamap, ima->cache, ima->cache, 0);
1571 for (a = 0; a < TEXTARGET_COUNT; a++)
1572 if (ima->gputexture[a])
1573 oldnewmap_insert(fd->imamap, ima->gputexture[a], ima->gputexture[a], 0);
1575 oldnewmap_insert(fd->imamap, ima->rr, ima->rr, 0);
1576 for (a=0; a < IMA_MAX_RENDER_SLOT; a++)
1577 if (ima->renders[a])
1578 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
1580 for (; sce; sce = sce->id.next) {
1581 if (sce->nodetree && sce->nodetree->previews) {
1582 bNodeInstanceHashIterator iter;
1583 NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1584 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1585 oldnewmap_insert(fd->imamap, preview, preview, 0);
1591 /* set old main image ibufs to zero if it has been restored */
1592 /* this works because freeing old main only happens after this call */
1593 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1595 OldNew *entry = fd->imamap->entries;
1596 Image *ima = oldmain->image.first;
1597 Scene *sce = oldmain->scene.first;
1600 /* used entries were restored, so we put them to zero */
1601 for (i = 0; i < fd->imamap->nentries; i++, entry++) {
1606 for (; ima; ima = ima->id.next) {
1607 ima->cache = newimaadr(fd, ima->cache);
1608 if (ima->cache == NULL) {
1609 ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
1610 for (i = 0; i < TEXTARGET_COUNT; i++) {
1611 ima->bindcode[i] = 0;
1612 ima->gputexture[i] = NULL;
1616 for (i = 0; i < IMA_MAX_RENDER_SLOT; i++)
1617 ima->renders[i] = newimaadr(fd, ima->renders[i]);
1619 for (i = 0; i < TEXTARGET_COUNT; i++)
1620 ima->gputexture[i] = newimaadr(fd, ima->gputexture[i]);
1621 ima->rr = newimaadr(fd, ima->rr);
1623 for (; sce; sce = sce->id.next) {
1624 if (sce->nodetree && sce->nodetree->previews) {
1625 bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
1626 bNodeInstanceHashIterator iter;
1628 /* reconstruct the preview hash, only using remaining pointers */
1629 NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1630 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1632 bNodePreview *new_preview = newimaadr(fd, preview);
1634 bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
1635 BKE_node_instance_hash_insert(new_previews, key, new_preview);
1639 BKE_node_instance_hash_free(sce->nodetree->previews, NULL);
1640 sce->nodetree->previews = new_previews;
1645 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
1647 MovieClip *clip = oldmain->movieclip.first;
1648 Scene *sce = oldmain->scene.first;
1650 fd->movieclipmap = oldnewmap_new();
1652 for (; clip; clip = clip->id.next) {
1654 oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
1656 if (clip->tracking.camera.intrinsics)
1657 oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
1660 for (; sce; sce = sce->id.next) {
1661 if (sce->nodetree) {
1663 for (node = sce->nodetree->nodes.first; node; node = node->next)
1664 if (node->type == CMP_NODE_MOVIEDISTORTION)
1665 oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
1670 /* set old main movie clips caches to zero if it has been restored */
1671 /* this works because freeing old main only happens after this call */
1672 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
1674 OldNew *entry = fd->movieclipmap->entries;
1675 MovieClip *clip = oldmain->movieclip.first;
1676 Scene *sce = oldmain->scene.first;
1679 /* used entries were restored, so we put them to zero */
1680 for (i=0; i < fd->movieclipmap->nentries; i++, entry++) {
1685 for (; clip; clip = clip->id.next) {
1686 clip->cache = newmclipadr(fd, clip->cache);
1687 clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics);
1690 for (; sce; sce = sce->id.next) {
1691 if (sce->nodetree) {
1693 for (node = sce->nodetree->nodes.first; node; node = node->next)
1694 if (node->type == CMP_NODE_MOVIEDISTORTION)
1695 node->storage = newmclipadr(fd, node->storage);
1700 void blo_make_sound_pointer_map(FileData *fd, Main *oldmain)
1702 bSound *sound = oldmain->sound.first;
1704 fd->soundmap = oldnewmap_new();
1706 for (; sound; sound = sound->id.next) {
1707 if (sound->waveform)
1708 oldnewmap_insert(fd->soundmap, sound->waveform, sound->waveform, 0);
1712 /* set old main sound caches to zero if it has been restored */
1713 /* this works because freeing old main only happens after this call */
1714 void blo_end_sound_pointer_map(FileData *fd, Main *oldmain)
1716 OldNew *entry = fd->soundmap->entries;
1717 bSound *sound = oldmain->sound.first;
1720 /* used entries were restored, so we put them to zero */
1721 for (i = 0; i < fd->soundmap->nentries; i++, entry++) {
1726 for (; sound; sound = sound->id.next) {
1727 sound->waveform = newsoundadr(fd, sound->waveform);
1731 /* XXX disabled this feature - packed files also belong in temp saves and quit.blend, to make restore work */
1733 static void insert_packedmap(FileData *fd, PackedFile *pf)
1735 oldnewmap_insert(fd->packedmap, pf, pf, 0);
1736 oldnewmap_insert(fd->packedmap, pf->data, pf->data, 0);
1739 void blo_make_packed_pointer_map(FileData *fd, Main *oldmain)
1746 fd->packedmap = oldnewmap_new();
1748 for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1749 ImagePackedFile *imapf;
1751 if (ima->packedfile)
1752 insert_packedmap(fd, ima->packedfile);
1754 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1755 if (imapf->packedfile)
1756 insert_packedmap(fd, imapf->packedfile);
1759 for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1760 if (vfont->packedfile)
1761 insert_packedmap(fd, vfont->packedfile);
1763 for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1764 if (sound->packedfile)
1765 insert_packedmap(fd, sound->packedfile);
1767 for (lib = oldmain->library.first; lib; lib = lib->id.next)
1768 if (lib->packedfile)
1769 insert_packedmap(fd, lib->packedfile);
1773 /* set old main packed data to zero if it has been restored */
1774 /* this works because freeing old main only happens after this call */
1775 void blo_end_packed_pointer_map(FileData *fd, Main *oldmain)
1781 OldNew *entry = fd->packedmap->entries;
1784 /* used entries were restored, so we put them to zero */
1785 for (i=0; i < fd->packedmap->nentries; i++, entry++) {
1790 for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1791 ImagePackedFile *imapf;
1793 ima->packedfile = newpackedadr(fd, ima->packedfile);
1795 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1796 imapf->packedfile = newpackedadr(fd, imapf->packedfile);
1799 for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1800 vfont->packedfile = newpackedadr(fd, vfont->packedfile);
1802 for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1803 sound->packedfile = newpackedadr(fd, sound->packedfile);
1805 for (lib = oldmain->library.first; lib; lib = lib->id.next)
1806 lib->packedfile = newpackedadr(fd, lib->packedfile);
1810 /* undo file support: add all library pointers in lookup */
1811 void blo_add_library_pointer_map(ListBase *old_mainlist, FileData *fd)
1813 Main *ptr = old_mainlist->first;
1814 ListBase *lbarray[MAX_LIBARRAY];
1816 for (ptr = ptr->next; ptr; ptr = ptr->next) {
1817 int i = set_listbasepointers(ptr, lbarray);
1820 for (id = lbarray[i]->first; id; id = id->next)
1821 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1825 fd->old_mainlist = old_mainlist;
1829 /* ********** END OLD POINTERS ****************** */
1830 /* ********** READ FILE ****************** */
1832 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1834 int blocksize, nblocks;
1837 data = (char *)(bhead+1);
1838 blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1840 nblocks = bhead->nr;
1842 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1848 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
1853 /* switch is based on file dna */
1854 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1855 switch_endian_structs(fd->filesdna, bh);
1857 if (fd->compflags[bh->SDNAnr] != SDNA_CMP_REMOVED) {
1858 if (fd->compflags[bh->SDNAnr] == SDNA_CMP_NOT_EQUAL) {
1859 temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1862 /* SDNA_CMP_EQUAL */
1863 temp = MEM_mallocN(bh->len, blockname);
1864 memcpy(temp, (bh+1), bh->len);
1872 typedef void (*link_list_cb)(FileData *fd, void *data);
1874 static void link_list_ex(FileData *fd, ListBase *lb, link_list_cb callback) /* only direct data */
1878 if (BLI_listbase_is_empty(lb)) return;
1880 lb->first = newdataadr(fd, lb->first);
1881 if (callback != NULL) {
1882 callback(fd, lb->first);
1887 ln->next = newdataadr(fd, ln->next);
1888 if (ln->next != NULL && callback != NULL) {
1889 callback(fd, ln->next);
1898 static void link_list(FileData *fd, ListBase *lb) /* only direct data */
1900 link_list_ex(fd, lb, NULL);
1903 static void link_glob_list(FileData *fd, ListBase *lb) /* for glob data */
1908 if (BLI_listbase_is_empty(lb)) return;
1909 poin = newdataadr(fd, lb->first);
1911 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1918 poin = newdataadr(fd, ln->next);
1920 oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1930 static void test_pointer_array(FileData *fd, void **mat)
1932 int64_t *lpoin, *lmat;
1936 /* manually convert the pointer array in
1937 * the old dna format to a pointer array in
1938 * the new dna format.
1941 len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1943 if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1944 ipoin=imat= MEM_mallocN(len * 4, "newmatar");
1948 if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1949 BLI_endian_switch_int64(lpoin);
1950 *ipoin = (int)((*lpoin) >> 3);
1958 if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1959 lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
1973 /* ************ READ ID Properties *************** */
1975 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1976 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1978 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1983 /* since we didn't save the extra buffer, set totallen to len */
1984 prop->totallen = prop->len;
1985 prop->data.pointer = newdataadr(fd, prop->data.pointer);
1987 array = (IDProperty *)prop->data.pointer;
1989 /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
1990 * theres not really anything we can do to correct this, at least don't crash */
1991 if (array == NULL) {
1997 for (i = 0; i < prop->len; i++)
1998 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
2001 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
2006 /* since we didn't save the extra buffer, set totallen to len */
2007 prop->totallen = prop->len;
2008 prop->data.pointer = newdataadr(fd, prop->data.pointer);
2010 if (prop->subtype == IDP_GROUP) {
2011 test_pointer_array(fd, prop->data.pointer);
2012 array = prop->data.pointer;
2014 for (i = 0; i < prop->len; i++)
2015 IDP_DirectLinkProperty(array[i], switch_endian, fd);
2017 else if (prop->subtype == IDP_DOUBLE) {
2018 if (switch_endian) {
2019 BLI_endian_switch_double_array(prop->data.pointer, prop->len);
2023 if (switch_endian) {
2024 /* also used for floats */
2025 BLI_endian_switch_int32_array(prop->data.pointer, prop->len);
2030 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
2032 /*since we didn't save the extra string buffer, set totallen to len.*/
2033 prop->totallen = prop->len;
2034 prop->data.pointer = newdataadr(fd, prop->data.pointer);
2037 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
2039 ListBase *lb = &prop->data.group;
2044 /*Link child id properties now*/
2045 for (loop=prop->data.group.first; loop; loop=loop->next) {
2046 IDP_DirectLinkProperty(loop, switch_endian, fd);
2050 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
2052 switch (prop->type) {
2054 IDP_DirectLinkGroup(prop, switch_endian, fd);
2057 IDP_DirectLinkString(prop, fd);
2060 IDP_DirectLinkArray(prop, switch_endian, fd);
2063 IDP_DirectLinkIDPArray(prop, switch_endian, fd);
2066 /* erg, stupid doubles. since I'm storing them
2067 * in the same field as int val; val2 in the
2068 * IDPropertyData struct, they have to deal with
2069 * endianness specifically
2071 * in theory, val and val2 would've already been swapped
2072 * if switch_endian is true, so we have to first unswap
2073 * them then reswap them as a single 64-bit entity.
2076 if (switch_endian) {
2077 BLI_endian_switch_int32(&prop->data.val);
2078 BLI_endian_switch_int32(&prop->data.val2);
2079 BLI_endian_switch_int64((int64_t *)&prop->data.val);
2086 #define IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd) \
2087 _IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd, __func__)
2089 static void _IDP_DirectLinkGroup_OrFree(IDProperty **prop, int switch_endian, FileData *fd,
2090 const char *caller_func_id)
2093 if ((*prop)->type == IDP_GROUP) {
2094 IDP_DirectLinkGroup(*prop, switch_endian, fd);
2098 printf("%s: found non group data, freeing type %d!\n",
2099 caller_func_id, (*prop)->type);
2100 /* don't risk id, data's likely corrupt. */
2101 // IDP_FreeProperty(*prop);
2108 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
2110 /* Should we do something here, prop should be ensured to be non-NULL first... */
2113 /* ************ READ IMAGE PREVIEW *************** */
2115 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
2117 PreviewImage *prv = newdataadr(fd, old_prv);
2121 for (i = 0; i < NUM_ICON_SIZES; ++i) {
2123 prv->rect[i] = newdataadr(fd, prv->rect[i]);
2125 prv->gputexture[i] = NULL;
2132 /* ************ READ ID *************** */
2134 static void direct_link_id(FileData *fd, ID *id)
2136 /*link direct data of ID properties*/
2137 if (id->properties) {
2138 id->properties = newdataadr(fd, id->properties);
2139 /* this case means the data was written incorrectly, it should not happen */
2140 IDP_DirectLinkGroup_OrFree(&id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2144 /* ************ READ CurveMapping *************** */
2146 /* cuma itself has been read! */
2147 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
2151 /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
2152 cumap->flag &= ~CUMA_PREMULLED;
2154 for (a = 0; a < CM_TOT; a++) {
2155 cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve);
2156 cumap->cm[a].table = NULL;
2157 cumap->cm[a].premultable = NULL;
2161 /* ************ READ Brush *************** */
2162 /* library brush linking after fileread */
2163 static void lib_link_brush(FileData *fd, Main *main)
2167 /* only link ID pointers */
2168 for (brush = main->brush.first; brush; brush = brush->id.next) {
2169 if (brush->id.tag & LIB_TAG_NEED_LINK) {
2170 brush->id.tag &= ~LIB_TAG_NEED_LINK;
2172 brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
2173 brush->mask_mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mask_mtex.tex);
2174 brush->clone.image = newlibadr_us(fd, brush->id.lib, brush->clone.image);
2175 brush->toggle_brush = newlibadr(fd, brush->id.lib, brush->toggle_brush);
2176 brush->paint_curve = newlibadr_us(fd, brush->id.lib, brush->paint_curve);
2181 static void direct_link_brush(FileData *fd, Brush *brush)
2183 /* brush itself has been read */
2186 brush->curve = newdataadr(fd, brush->curve);
2187 brush->gradient = newdataadr(fd, brush->gradient);
2190 direct_link_curvemapping(fd, brush->curve);
2192 BKE_brush_curve_preset(brush, CURVE_PRESET_SHARP);
2194 brush->preview = NULL;
2195 brush->icon_imbuf = NULL;
2198 /* ************ READ Palette *************** */
2199 static void lib_link_palette(FileData *UNUSED(fd), Main *main)
2203 /* only link ID pointers */
2204 for (palette = main->palettes.first; palette; palette = palette->id.next) {
2205 if (palette->id.tag & LIB_TAG_NEED_LINK) {
2206 palette->id.tag &= ~LIB_TAG_NEED_LINK;
2211 static void direct_link_palette(FileData *fd, Palette *palette)
2213 /* palette itself has been read */
2214 link_list(fd, &palette->colors);
2217 static void lib_link_paint_curve(FileData *UNUSED(fd), Main *main)
2221 /* only link ID pointers */
2222 for (pc = main->paintcurves.first; pc; pc = pc->id.next) {
2223 if (pc->id.tag & LIB_TAG_NEED_LINK) {
2224 pc->id.tag &= ~LIB_TAG_NEED_LINK;
2229 static void direct_link_paint_curve(FileData *fd, PaintCurve *pc)
2231 pc->points = newdataadr(fd, pc->points);
2234 /* ************ READ PACKEDFILE *************** */
2236 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
2238 PackedFile *pf = newpackedadr(fd, oldpf);
2241 pf->data = newpackedadr(fd, pf->data);
2247 /* ************ READ ANIMATION STUFF ***************** */
2249 /* Legacy Data Support (for Version Patching) ----------------------------- */
2251 // XXX deprecated - old animation system
2252 static void lib_link_ipo(FileData *fd, Main *main)
2256 for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) {
2257 if (ipo->id.tag & LIB_TAG_NEED_LINK) {
2259 for (icu = ipo->curve.first; icu; icu = icu->next) {
2261 icu->driver->ob = newlibadr(fd, ipo->id.lib, icu->driver->ob);
2263 ipo->id.tag &= ~LIB_TAG_NEED_LINK;
2268 // XXX deprecated - old animation system
2269 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2273 link_list(fd, &(ipo->curve));
2275 for (icu = ipo->curve.first; icu; icu = icu->next) {
2276 icu->bezt = newdataadr(fd, icu->bezt);
2277 icu->bp = newdataadr(fd, icu->bp);
2278 icu->driver = newdataadr(fd, icu->driver);
2282 // XXX deprecated - old animation system
2283 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
2285 bActionStrip *strip;
2286 bActionModifier *amod;
2288 for (strip=striplist->first; strip; strip=strip->next) {
2289 strip->object = newlibadr(fd, id->lib, strip->object);
2290 strip->act = newlibadr_us(fd, id->lib, strip->act);
2291 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
2292 for (amod = strip->modifiers.first; amod; amod = amod->next)
2293 amod->ob = newlibadr(fd, id->lib, amod->ob);
2297 // XXX deprecated - old animation system
2298 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
2300 bActionStrip *strip;
2302 link_list(fd, strips);
2304 for (strip = strips->first; strip; strip = strip->next)
2305 link_list(fd, &strip->modifiers);
2308 // XXX deprecated - old animation system
2309 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
2311 bConstraintChannel *chan;
2313 for (chan=chanbase->first; chan; chan=chan->next) {
2314 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
2318 /* Data Linking ----------------------------- */
2320 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
2324 for (fcm = list->first; fcm; fcm = fcm->next) {
2325 /* data for specific modifiers */
2326 switch (fcm->type) {
2327 case FMODIFIER_TYPE_PYTHON:
2329 FMod_Python *data = (FMod_Python *)fcm->data;
2330 data->script = newlibadr(fd, id->lib, data->script);
2338 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list)
2345 /* relink ID-block references... */
2346 for (fcu = list->first; fcu; fcu = fcu->next) {
2349 ChannelDriver *driver = fcu->driver;
2352 for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2353 DRIVER_TARGETS_LOOPER(dvar)
2355 /* only relink if still used */
2356 if (tarIndex < dvar->num_targets)
2357 dtar->id = newlibadr(fd, id->lib, dtar->id);
2361 DRIVER_TARGETS_LOOPER_END
2366 lib_link_fmodifiers(fd, id, &fcu->modifiers);
2371 /* NOTE: this assumes that link_list has already been called on the list */
2372 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
2376 for (fcm = list->first; fcm; fcm = fcm->next) {
2377 /* relink general data */
2378 fcm->data = newdataadr(fd, fcm->data);
2380 /* do relinking of data for specific types */
2381 switch (fcm->type) {
2382 case FMODIFIER_TYPE_GENERATOR:
2384 FMod_Generator *data = (FMod_Generator *)fcm->data;
2386 data->coefficients = newdataadr(fd, data->coefficients);
2388 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2389 BLI_endian_switch_float_array(data->coefficients, data->arraysize);
2394 case FMODIFIER_TYPE_ENVELOPE:
2396 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
2398 data->data= newdataadr(fd, data->data);
2402 case FMODIFIER_TYPE_PYTHON:
2404 FMod_Python *data = (FMod_Python *)fcm->data;
2406 data->prop = newdataadr(fd, data->prop);
2407 IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2415 /* NOTE: this assumes that link_list has already been called on the list */
2416 static void direct_link_fcurves(FileData *fd, ListBase *list)
2420 /* link F-Curve data to F-Curve again (non ID-libs) */
2421 for (fcu = list->first; fcu; fcu = fcu->next) {
2423 fcu->bezt = newdataadr(fd, fcu->bezt);
2424 fcu->fpt = newdataadr(fd, fcu->fpt);
2427 fcu->rna_path = newdataadr(fd, fcu->rna_path);
2430 fcu->grp = newdataadr_ex(fd, fcu->grp, false);
2432 /* clear disabled flag - allows disabled drivers to be tried again ([#32155]),
2433 * but also means that another method for "reviving disabled F-Curves" exists
2435 fcu->flag &= ~FCURVE_DISABLED;
2438 fcu->driver= newdataadr(fd, fcu->driver);
2440 ChannelDriver *driver= fcu->driver;
2443 /* compiled expression data will need to be regenerated (old pointer may still be set here) */
2444 driver->expr_comp = NULL;
2446 /* give the driver a fresh chance - the operating environment may be different now
2447 * (addons, etc. may be different) so the driver namespace may be sane now [#32155]
2449 driver->flag &= ~DRIVER_FLAG_INVALID;
2451 /* relink variables, targets and their paths */
2452 link_list(fd, &driver->variables);
2453 for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2454 DRIVER_TARGETS_LOOPER(dvar)
2456 /* only relink the targets being used */
2457 if (tarIndex < dvar->num_targets)
2458 dtar->rna_path = newdataadr(fd, dtar->rna_path);
2460 dtar->rna_path = NULL;
2462 DRIVER_TARGETS_LOOPER_END
2467 link_list(fd, &fcu->modifiers);
2468 direct_link_fmodifiers(fd, &fcu->modifiers);
2473 static void lib_link_action(FileData *fd, Main *main)
2476 bActionChannel *chan;
2478 for (act = main->action.first; act; act = act->id.next) {
2479 if (act->id.tag & LIB_TAG_NEED_LINK) {
2480 act->id.tag &= ~LIB_TAG_NEED_LINK;
2482 // XXX deprecated - old animation system <<<
2483 for (chan=act->chanbase.first; chan; chan=chan->next) {
2484 chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
2485 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
2487 // >>> XXX deprecated - old animation system
2489 lib_link_fcurves(fd, &act->id, &act->curves);
2494 static void direct_link_action(FileData *fd, bAction *act)
2496 bActionChannel *achan; // XXX deprecated - old animation system
2499 link_list(fd, &act->curves);
2500 link_list(fd, &act->chanbase); // XXX deprecated - old animation system
2501 link_list(fd, &act->groups);
2502 link_list(fd, &act->markers);
2504 // XXX deprecated - old animation system <<<
2505 for (achan = act->chanbase.first; achan; achan=achan->next) {
2506 achan->grp = newdataadr(fd, achan->grp);
2508 link_list(fd, &achan->constraintChannels);
2510 // >>> XXX deprecated - old animation system
2512 direct_link_fcurves(fd, &act->curves);
2514 for (agrp = act->groups.first; agrp; agrp= agrp->next) {
2515 agrp->channels.first= newdataadr(fd, agrp->channels.first);
2516 agrp->channels.last= newdataadr(fd, agrp->channels.last);
2520 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
2524 for (strip = list->first; strip; strip = strip->next) {
2525 /* check strip's children */
2526 lib_link_nladata_strips(fd, id, &strip->strips);
2528 /* check strip's F-Curves */
2529 lib_link_fcurves(fd, id, &strip->fcurves);
2531 /* reassign the counted-reference to action */
2532 strip->act = newlibadr_us(fd, id->lib, strip->act);
2534 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
2535 if ((strip->act) && (strip->act->idroot == 0))
2536 strip->act->idroot = GS(id->name);
2540 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
2544 /* we only care about the NLA strips inside the tracks */
2545 for (nlt = list->first; nlt; nlt = nlt->next) {
2546 lib_link_nladata_strips(fd, id, &nlt->strips);
2550 /* This handles Animato NLA-Strips linking
2551 * NOTE: this assumes that link_list has already been called on the list
2553 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
2557 for (strip = list->first; strip; strip = strip->next) {
2558 /* strip's child strips */
2559 link_list(fd, &strip->strips);
2560 direct_link_nladata_strips(fd, &strip->strips);
2562 /* strip's F-Curves */
2563 link_list(fd, &strip->fcurves);
2564 direct_link_fcurves(fd, &strip->fcurves);
2566 /* strip's F-Modifiers */
2567 link_list(fd, &strip->modifiers);
2568 direct_link_fmodifiers(fd, &strip->modifiers);
2572 /* NOTE: this assumes that link_list has already been called on the list */
2573 static void direct_link_nladata(FileData *fd, ListBase *list)
2577 for (nlt = list->first; nlt; nlt = nlt->next) {
2578 /* relink list of strips */
2579 link_list(fd, &nlt->strips);
2581 /* relink strip data */
2582 direct_link_nladata_strips(fd, &nlt->strips);
2588 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
2593 /* here, we're only interested in the ID pointer stored in some of the paths */
2594 for (ks = list->first; ks; ks = ks->next) {
2595 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2596 ksp->id= newlibadr(fd, id->lib, ksp->id);
2601 /* NOTE: this assumes that link_list has already been called on the list */
2602 static void direct_link_keyingsets(FileData *fd, ListBase *list)
2607 /* link KeyingSet data to KeyingSet again (non ID-libs) */
2608 for (ks = list->first; ks; ks = ks->next) {
2610 link_list(fd, &ks->paths);
2612 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2614 ksp->rna_path= newdataadr(fd, ksp->rna_path);
2621 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
2626 /* link action data */
2627 adt->action= newlibadr_us(fd, id->lib, adt->action);
2628 adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
2630 /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
2631 if ((adt->action) && (adt->action->idroot == 0))
2632 adt->action->idroot = GS(id->name);
2633 if ((adt->tmpact) && (adt->tmpact->idroot == 0))
2634 adt->tmpact->idroot = GS(id->name);
2637 lib_link_fcurves(fd, id, &adt->drivers);
2639 /* overrides don't have lib-link for now, so no need to do anything */
2642 lib_link_nladata(fd, id, &adt->nla_tracks);
2645 static void direct_link_animdata(FileData *fd, AnimData *adt)
2647 /* NOTE: must have called newdataadr already before doing this... */
2652 link_list(fd, &adt->drivers);
2653 direct_link_fcurves(fd, &adt->drivers);
2655 /* link overrides */
2659 link_list(fd, &adt->nla_tracks);
2660 direct_link_nladata(fd, &adt->nla_tracks);
2662 /* relink active track/strip - even though strictly speaking this should only be used
2663 * if we're in 'tweaking mode', we need to be able to have this loaded back for
2664 * undo, but also since users may not exit tweakmode before saving (#24535)
2666 // TODO: it's not really nice that anyone should be able to save the file in this
2667 // state, but it's going to be too hard to enforce this single case...
2668 adt->act_track = newdataadr(fd, adt->act_track);
2669 adt->actstrip = newdataadr(fd, adt->actstrip);
2672 /* ************ READ MOTION PATHS *************** */
2674 /* direct data for cache */
2675 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2681 /* relink points cache */
2682 mpath->points = newdataadr(fd, mpath->points);
2685 /* ************ READ NODE TREE *************** */
2687 static void lib_link_node_socket(FileData *fd, ID *UNUSED(id), bNodeSocket *sock)
2689 /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2690 * of library blocks that implement this.*/
2691 IDP_LibLinkProperty(sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2694 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2695 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2700 lib_link_animdata(fd, &ntree->id, ntree->adt);
2702 ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
2704 for (node = ntree->nodes.first; node; node = node->next) {
2705 /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2706 * of library blocks that implement this.*/
2707 IDP_LibLinkProperty(node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2709 node->id= newlibadr_us(fd, id->lib, node->id);
2711 for (sock = node->inputs.first; sock; sock = sock->next)
2712 lib_link_node_socket(fd, id, sock);
2713 for (sock = node->outputs.first; sock; sock = sock->next)
2714 lib_link_node_socket(fd, id, sock);
2717 for (sock = ntree->inputs.first; sock; sock = sock->next)
2718 lib_link_node_socket(fd, id, sock);
2719 for (sock = ntree->outputs.first; sock; sock = sock->next)
2720 lib_link_node_socket(fd, id, sock);
2723 /* library ntree linking after fileread */
2724 static void lib_link_nodetree(FileData *fd, Main *main)
2728 /* only link ID pointers */
2729 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2730 if (ntree->id.tag & LIB_TAG_NEED_LINK) {
2731 ntree->id.tag &= ~LIB_TAG_NEED_LINK;
2732 lib_link_ntree(fd, &ntree->id, ntree);
2737 /* get node tree stored locally in other IDs */
2738 static bNodeTree *nodetree_from_id(ID *id)
2742 switch (GS(id->name)) {
2743 case ID_SCE: return ((Scene *)id)->nodetree;
2744 case ID_MA: return ((Material *)id)->nodetree;
2745 case ID_WO: return ((World *)id)->nodetree;
2746 case ID_LA: return ((Lamp *)id)->nodetree;
2747 case ID_TE: return ((Tex *)id)->nodetree;
2748 case ID_LS: return ((FreestyleLineStyle *)id)->nodetree;
2753 /* updates group node socket identifier so that
2754 * external links to/from the group node are preserved.
2756 static void lib_node_do_versions_group_indices(bNode *gnode)
2758 bNodeTree *ngroup = (bNodeTree*)gnode->id;
2762 for (sock=gnode->outputs.first; sock; sock = sock->next) {
2763 int old_index = sock->to_index;
2765 for (link = ngroup->links.first; link; link = link->next) {
2766 if (link->tonode == NULL && link->fromsock->own_index == old_index) {
2767 strcpy(sock->identifier, link->fromsock->identifier);
2769 sock->own_index = link->fromsock->own_index;
2771 sock->groupsock = NULL;
2775 for (sock=gnode->inputs.first; sock; sock = sock->next) {
2776 int old_index = sock->to_index;
2778 for (link = ngroup->links.first; link; link = link->next) {
2779 if (link->fromnode == NULL && link->tosock->own_index == old_index) {
2780 strcpy(sock->identifier, link->tosock->identifier);
2782 sock->own_index = link->tosock->own_index;
2784 sock->groupsock = NULL;
2790 /* verify types for nodes and groups, all data has to be read */
2791 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2793 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2795 /* this crashes blender on undo/redo */
2798 reinit_nodesystem();
2802 /* set node->typeinfo pointers */
2803 FOREACH_NODETREE(main, ntree, id) {
2804 ntreeSetTypes(NULL, ntree);
2805 } FOREACH_NODETREE_END
2807 /* verify static socket templates */
2808 FOREACH_NODETREE(main, ntree, id) {
2810 for (node=ntree->nodes.first; node; node=node->next)
2811 node_verify_socket_templates(ntree, node);
2812 } FOREACH_NODETREE_END
2815 bool has_old_groups = false;
2816 /* XXX this should actually be part of do_versions, but since we need
2817 * finished library linking, it is not possible there. Instead in do_versions
2818 * we have set the NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2 flag, so at this point we can do the
2819 * actual group node updates.
2821 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2822 if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2) {
2827 if (has_old_groups) {
2828 FOREACH_NODETREE(main, ntree, id) {
2829 /* updates external links for all group nodes in a tree */
2831 for (node = ntree->nodes.first; node; node = node->next) {
2832 if (node->type == NODE_GROUP) {
2833 bNodeTree *ngroup = (bNodeTree*)node->id;
2834 if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2))
2835 lib_node_do_versions_group_indices(node);
2838 } FOREACH_NODETREE_END
2841 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2842 ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2;
2847 /* Convert the previously used ntree->inputs/ntree->outputs lists to interface nodes.
2848 * Pre 2.56.2 node trees automatically have all unlinked sockets exposed already
2849 * (see NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2).
2851 * XXX this should actually be part of do_versions,
2852 * but needs valid typeinfo pointers to create interface nodes.
2854 * Note: theoretically only needed in node groups (main->nodetree),
2855 * but due to a temporary bug such links could have been added in all trees,
2856 * so have to clean up all of them ...
2859 FOREACH_NODETREE(main, ntree, id) {
2860 if (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP) {
2861 bNode *input_node = NULL, *output_node = NULL;
2862 int num_inputs = 0, num_outputs = 0;
2863 bNodeLink *link, *next_link;
2864 /* Only create new interface nodes for actual older files.
2865 * New file versions already have input/output nodes with duplicate links,
2866 * in that case just remove the invalid links.
2868 const bool create_io_nodes = (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE) != 0;
2870 float input_locx = 1000000.0f, input_locy = 0.0f;
2871 float output_locx = -1000000.0f, output_locy = 0.0f;
2872 /* rough guess, not nice but we don't have access to UI constants here ... */
2873 static const float offsetx = 42 + 3*20 + 20;
2874 /*static const float offsety = 0.0f;*/
2876 if (create_io_nodes) {
2877 if (ntree->inputs.first)
2878 input_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_INPUT);
2880 if (ntree->outputs.first)
2881 output_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_OUTPUT);
2884 /* Redirect links from/to the node tree interface to input/output node.
2885 * If the fromnode/tonode pointers are NULL, this means a link from/to
2886 * the ntree interface sockets, which need to be redirected to new interface nodes.
2888 for (link = ntree->links.first; link; link = next_link) {
2889 bool free_link = false;
2890 next_link = link->next;
2892 if (link->fromnode == NULL) {
2894 link->fromnode = input_node;
2895 link->fromsock = node_group_input_find_socket(input_node, link->fromsock->identifier);
2899 if (input_locx > link->tonode->locx - offsetx)
2900 input_locx = link->tonode->locx - offsetx;
2901 input_locy += link->tonode->locy;
2909 if (link->tonode == NULL) {
2911 link->tonode = output_node;
2912 link->tosock = node_group_output_find_socket(output_node, link->tosock->identifier);
2915 if (link->fromnode) {
2916 if (output_locx < link->fromnode->locx + offsetx)
2917 output_locx = link->fromnode->locx + offsetx;
2918 output_locy += link->fromnode->locy;
2927 nodeRemLink(ntree, link);
2930 if (num_inputs > 0) {
2931 input_locy /= num_inputs;
2932 input_node->locx = input_locx;
2933 input_node->locy = input_locy;
2935 if (num_outputs > 0) {
2936 output_locy /= num_outputs;
2937 output_node->locx = output_locx;
2938 output_node->locy = output_locy;
2941 /* clear do_versions flags */
2942 ntree->flag &= ~(NTREE_DO_VERSIONS_CUSTOMNODES_GROUP | NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE);
2945 FOREACH_NODETREE_END
2948 /* verify all group user nodes */
2949 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2950 ntreeVerifyNodes(main, &ntree->id);
2953 /* make update calls where necessary */
2955 FOREACH_NODETREE(main, ntree, id) {
2956 /* make an update call for the tree */
2957 ntreeUpdateTree(main, ntree);
2958 } FOREACH_NODETREE_END
2962 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
2964 sock->prop = newdataadr(fd, sock->prop);
2965 IDP_DirectLinkGroup_OrFree(&sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2967 sock->link = newdataadr(fd, sock->link);
2968 sock->typeinfo = NULL;
2969 sock->storage = newdataadr(fd, sock->storage);
2970 sock->default_value = newdataadr(fd, sock->default_value);
2974 /* ntree itself has been read! */
2975 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2977 /* note: writing and reading goes in sync, for speed */
2982 ntree->init = 0; /* to set callbacks and force setting types */
2983 ntree->is_updating = false;
2984 ntree->typeinfo= NULL;
2985 ntree->interface_type = NULL;
2987 ntree->progress = NULL;
2988 ntree->execdata = NULL;
2989 ntree->duplilock = NULL;
2991 ntree->adt = newdataadr(fd, ntree->adt);
2992 direct_link_animdata(fd, ntree->adt);
2994 ntree->id.tag &= ~(LIB_TAG_ID_RECALC|LIB_TAG_ID_RECALC_DATA);
2996 link_list(fd, &ntree->nodes);
2997 for (node = ntree->nodes.first; node; node = node->next) {
2998 node->typeinfo = NULL;
3000 link_list(fd, &node->inputs);
3001 link_list(fd, &node->outputs);
3003 node->prop = newdataadr(fd, node->prop);
3004 IDP_DirectLinkGroup_OrFree(&node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3006 link_list(fd, &node->internal_links);
3007 for (link = node->internal_links.first; link; link = link->next) {
3008 link->fromnode = newdataadr(fd, link->fromnode);
3009 link->fromsock = newdataadr(fd, link->fromsock);
3010 link->tonode = newdataadr(fd, link->tonode);
3011 link->tosock = newdataadr(fd, link->tosock);
3014 if (node->type == CMP_NODE_MOVIEDISTORTION) {
3015 node->storage = newmclipadr(fd, node->storage);
3018 node->storage = newdataadr(fd, node->storage);
3021 if (node->storage) {
3022 /* could be handlerized at some point */
3023 if (ntree->type==NTREE_SHADER) {
3024 if (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB) {
3025 direct_link_curvemapping(fd, node->storage);
3027 else if (node->type==SH_NODE_SCRIPT) {
3028 NodeShaderScript *nss = (NodeShaderScript *) node->storage;
3029 nss->bytecode = newdataadr(fd, nss->bytecode);
3031 else if (node->type==SH_NODE_TEX_POINTDENSITY) {
3032 NodeShaderTexPointDensity *npd = (NodeShaderTexPointDensity *) node->storage;
3033 memset(&npd->pd, 0, sizeof(npd->pd));
3036 else if (ntree->type==NTREE_COMPOSIT) {
3037 if (ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
3038 direct_link_curvemapping(fd, node->storage);
3039 else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
3040 ((ImageUser *)node->storage)->ok = 1;
3042 else if ( ntree->type==NTREE_TEXTURE) {
3043 if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
3044 direct_link_curvemapping(fd, node->storage);
3045 else if (node->type==TEX_NODE_IMAGE)
3046 ((ImageUser *)node->storage)->ok = 1;
3050 link_list(fd, &ntree->links);
3052 /* and we connect the rest */
3053 for (node = ntree->nodes.first; node; node = node->next) {
3054 node->parent = newdataadr(fd, node->parent);
3057 for (sock = node->inputs.first; sock; sock = sock->next)
3058 direct_link_node_socket(fd, sock);
3059 for (sock = node->outputs.first; sock; sock = sock->next)
3060 direct_link_node_socket(fd, sock);
3063 /* interface socket lists */
3064 link_list(fd, &ntree->inputs);
3065 link_list(fd, &ntree->outputs);
3066 for (sock = ntree->inputs.first; sock; sock = sock->next)
3067 direct_link_node_socket(fd, sock);
3068 for (sock = ntree->outputs.first; sock; sock = sock->next)
3069 direct_link_node_socket(fd, sock);
3071 for (link = ntree->links.first; link; link= link->next) {
3072 link->fromnode = newdataadr(fd, link->fromnode);
3073 link->tonode = newdataadr(fd, link->tonode);
3074 link->fromsock = newdataadr(fd, link->fromsock);
3075 link->tosock = newdataadr(fd, link->tosock);
3079 if (ntree->previews) {
3080 bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
3081 bNodeInstanceHashIterator iter;
3083 NODE_INSTANCE_HASH_ITER(iter, ntree->previews) {
3084 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
3086 bNodePreview *new_preview = newimaadr(fd, preview);
3088 bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
3089 BKE_node_instance_hash_insert(new_previews, key, new_preview);
3093 BKE_node_instance_hash_free(ntree->previews, NULL);
3094 ntree->previews = new_previews;
3098 ntree->previews = NULL;
3101 /* type verification is in lib-link */
3104 /* ************ READ ARMATURE ***************** */
3106 /* temp struct used to transport needed info to lib_link_constraint_cb() */
3107 typedef struct tConstraintLinkData {
3110 } tConstraintLinkData;
3111 /* callback function used to relink constraint ID-links */
3112 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, bool is_reference, void *userdata)
3114 tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
3116 /* for reference types, we need to increment the usercounts on load... */
3118 /* reference type - with usercount */
3119 *idpoin = newlibadr_us(cld->fd, cld->id->lib, *idpoin);
3122 /* target type - no usercount needed */
3123 *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
3127 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
3129 tConstraintLinkData cld;
3133 for (con = conlist->first; con; con=con->next) {
3134 /* patch for error introduced by changing constraints (dunno how) */
3135 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
3136 if (con->data == NULL) {
3137 con->type = CONSTRAINT_TYPE_NULL;
3139 /* own ipo, all constraints have it */
3140 con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system
3143 /* relink all ID-blocks used by the constraints */
3147 BKE_constraints_id_loop(conlist, lib_link_constraint_cb, &cld);
3150 static void direct_link_constraints(FileData *fd, ListBase *lb)
3155 for (con=lb->first; con; con=con->next) {
3156 con->data = newdataadr(fd, con->data);
3158 switch (con->type) {
3159 case CONSTRAINT_TYPE_PYTHON:
3161 bPythonConstraint *data= con->data;
3163 link_list(fd, &data->targets);
3165 data->prop = newdataadr(fd, data->prop);
3166 IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3169 case CONSTRAINT_TYPE_SPLINEIK:
3171 bSplineIKConstraint *data= con->data;
3173 data->points= newdataadr(fd, data->points);
3176 case CONSTRAINT_TYPE_KINEMATIC: