writefile: avoid adding SDNA to every undo step
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  *
26  */
27
28 /** \file blender/blenloader/intern/readfile.c
29  *  \ingroup blenloader
30  */
31
32
33 #include "zlib.h"
34
35 #include <limits.h>
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 */
44
45 #include "BLI_utildefines.h"
46 #ifndef WIN32
47 #  include <unistd.h> // for read close
48 #else
49 #  include <io.h> // for open close read
50 #  include "winsock2.h"
51 #  include "BLI_winstuff.h"
52 #endif
53
54 /* allow readfile to use deprecated functionality */
55 #define DNA_DEPRECATED_ALLOW
56
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_types.h"
84 #include "DNA_packedFile_types.h"
85 #include "DNA_particle_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"
103
104 #include "MEM_guardedalloc.h"
105
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"
111
112 #include "BLT_translation.h"
113
114 #include "BKE_action.h"
115 #include "BKE_armature.h"
116 #include "BKE_blender_version.h"
117 #include "BKE_brush.h"
118 #include "BKE_cloth.h"
119 #include "BKE_constraint.h"
120 #include "BKE_context.h"
121 #include "BKE_curve.h"
122 #include "BKE_depsgraph.h"
123 #include "BKE_effect.h"
124 #include "BKE_fcurve.h"
125 #include "BKE_global.h" // for G
126 #include "BKE_group.h"
127 #include "BKE_library.h" // for which_libbase
128 #include "BKE_library_idmap.h"
129 #include "BKE_library_query.h"
130 #include "BKE_idcode.h"
131 #include "BKE_material.h"
132 #include "BKE_main.h" // for Main
133 #include "BKE_mesh.h" // for ME_ defines (patching)
134 #include "BKE_modifier.h"
135 #include "BKE_multires.h"
136 #include "BKE_node.h" // for tree type defines
137 #include "BKE_object.h"
138 #include "BKE_paint.h"
139 #include "BKE_particle.h"
140 #include "BKE_pointcache.h"
141 #include "BKE_report.h"
142 #include "BKE_sca.h" // for init_actuator
143 #include "BKE_scene.h"
144 #include "BKE_screen.h"
145 #include "BKE_sequencer.h"
146 #include "BKE_outliner_treehash.h"
147 #include "BKE_sound.h"
148
149
150 #include "NOD_common.h"
151 #include "NOD_socket.h"
152
153 #include "BLO_readfile.h"
154 #include "BLO_undofile.h"
155 #include "BLO_blend_defs.h"
156
157 #include "RE_engine.h"
158
159 #include "readfile.h"
160
161
162 #include <errno.h>
163
164 /**
165  * READ
166  * ====
167  *
168  * - Existing Library (#Main) push or free
169  * - allocate new #Main
170  * - load file
171  * - read #SDNA
172  * - for each LibBlock
173  *   - read LibBlock
174  *   - if a Library
175  *     - make a new #Main
176  *     - attach ID's to it
177  *   - else
178  *     - read associated 'direct data'
179  *     - link direct data (internal and to LibBlock)
180  * - read #FileGlobal
181  * - read #USER data, only when indicated (file is ``~/X.XX/startup.blend``)
182  * - free file
183  * - per Library (per #Main)
184  *   - read file
185  *   - read #SDNA
186  *   - find LibBlocks and attach #ID's to #Main
187  *     - if external LibBlock
188  *       - search all #Main's
189  *         - or it's already read,
190  *         - or not read yet
191  *         - or make new #Main
192  *   - per LibBlock
193  *     - read recursive
194  *     - read associated direct data
195  *     - link direct data (internal and to LibBlock)
196  *   - free file
197  * - per Library with unread LibBlocks
198  *   - read file
199  *   - read #SDNA
200  *   - per LibBlock
201  *     - read recursive
202  *     - read associated direct data
203  *     - link direct data (internal and to LibBlock)
204  *   - free file
205  * - join all #Main's
206  * - link all LibBlocks and indirect pointers to libblocks
207  * - initialize #FileGlobal and copy pointers to #Global
208  *
209  * \note Still a weak point is the new-address function, that doesnt solve reading from
210  * multiple files at the same time.
211  * (added remark: oh, i thought that was solved? will look at that... (ton).
212  */
213
214 /* use GHash for BHead name-based lookups (speeds up linking) */
215 #define USE_GHASH_BHEAD
216
217 /* Use GHash for restoring pointers by name */
218 #define USE_GHASH_RESTORE_POINTER
219
220 /***/
221
222 typedef struct OldNew {
223         const void *old;
224         void *newp;
225         int nr;
226 } OldNew;
227
228 typedef struct OldNewMap {
229         OldNew *entries;
230         int nentries, entriessize;
231         bool sorted;
232         int lasthit;
233 } OldNewMap;
234
235
236 /* local prototypes */
237 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
238 static void direct_link_modifiers(FileData *fd, ListBase *lb);
239 static void convert_tface_mt(FileData *fd, Main *main);
240 static BHead *find_bhead_from_code_name(FileData *fd, const short idcode, const char *name);
241 static BHead *find_bhead_from_idname(FileData *fd, const char *idname);
242
243 /* this function ensures that reports are printed,
244  * in the case of libraray linking errors this is important!
245  *
246  * bit kludge but better then doubling up on prints,
247  * we could alternatively have a versions of a report function which forces printing - campbell
248  */
249
250 void blo_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
251 {
252         char fixed_buf[1024]; /* should be long enough */
253         
254         va_list args;
255         
256         va_start(args, format);
257         vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
258         va_end(args);
259         
260         fixed_buf[sizeof(fixed_buf) - 1] = '\0';
261         
262         BKE_report(reports, type, fixed_buf);
263         
264         if (G.background == 0) {
265                 printf("%s: %s\n", BKE_report_type_str(type), fixed_buf);
266         }
267 }
268
269 /* for reporting linking messages */
270 static const char *library_parent_filepath(Library *lib)
271 {
272         return lib->parent ? lib->parent->filepath : "<direct>";
273 }
274
275 static OldNewMap *oldnewmap_new(void) 
276 {
277         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
278         
279         onm->entriessize = 1024;
280         onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
281         
282         return onm;
283 }
284
285 static int verg_oldnewmap(const void *v1, const void *v2)
286 {
287         const struct OldNew *x1=v1, *x2=v2;
288         
289         if (x1->old > x2->old) return 1;
290         else if (x1->old < x2->old) return -1;
291         return 0;
292 }
293
294
295 static void oldnewmap_sort(FileData *fd) 
296 {
297         BLI_assert(fd->libmap->sorted == false);
298         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
299         fd->libmap->sorted = 1;
300 }
301
302 /* nr is zero for data, and ID code for libdata */
303 static void oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
304 {
305         OldNew *entry;
306         
307         if (oldaddr==NULL || newaddr==NULL) return;
308         
309         if (UNLIKELY(onm->nentries == onm->entriessize)) {
310                 onm->entriessize *= 2;
311                 onm->entries = MEM_reallocN(onm->entries, sizeof(*onm->entries) * onm->entriessize);
312         }
313
314         entry = &onm->entries[onm->nentries++];
315         entry->old = oldaddr;
316         entry->newp = newaddr;
317         entry->nr = nr;
318 }
319
320 void blo_do_versions_oldnewmap_insert(OldNewMap *onm, const void *oldaddr, void *newaddr, int nr)
321 {
322         oldnewmap_insert(onm, oldaddr, newaddr, nr);
323 }
324
325 /**
326  * Do a full search (no state).
327  *
328  * \param lasthit: Use as a reference position to avoid a full search
329  * from either end of the array, giving more efficient lookups.
330  *
331  * \note This would seem an ideal case for hash or btree lookups.
332  * However the data is written in-order, using the \a lasthit will normally avoid calling this function.
333  * Creating a btree/hash structure adds overhead for the common-case to optimize the corner-case
334  * (since most entries will never be retrieved).
335  * So just keep full lookups as a fall-back.
336  */
337 static int oldnewmap_lookup_entry_full(const OldNewMap *onm, const void *addr, int lasthit)
338 {
339         const int nentries = onm->nentries;
340         const OldNew *entries = onm->entries;
341         int i;
342
343         /* search relative to lasthit where possible */
344         if (lasthit >= 0 && lasthit < nentries) {
345
346                 /* search forwards */
347                 i = lasthit;
348                 while (++i != nentries) {
349                         if (entries[i].old == addr) {
350                                 return i;
351                         }
352                 }
353
354                 /* search backwards */
355                 i = lasthit + 1;
356                 while (i--) {
357                         if (entries[i].old == addr) {
358                                 return i;
359                         }
360                 }
361         }
362         else {
363                 /* search backwards (full) */
364                 i = nentries;
365                 while (i--) {
366                         if (entries[i].old == addr) {
367                                 return i;
368                         }
369                 }
370         }
371
372         return -1;
373 }
374
375 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, const void *addr, bool increase_users)
376 {
377         int i;
378         
379         if (addr == NULL) return NULL;
380         
381         if (onm->lasthit < onm->nentries-1) {
382                 OldNew *entry = &onm->entries[++onm->lasthit];
383                 
384                 if (entry->old == addr) {
385                         if (increase_users)
386                                 entry->nr++;
387                         return entry->newp;
388                 }
389         }
390         
391         i = oldnewmap_lookup_entry_full(onm, addr, onm->lasthit);
392         if (i != -1) {
393                 OldNew *entry = &onm->entries[i];
394                 BLI_assert(entry->old == addr);
395                 onm->lasthit = i;
396                 if (increase_users)
397                         entry->nr++;
398                 return entry->newp;
399         }
400         
401         return NULL;
402 }
403
404 /* for libdata, nr has ID code, no increment */
405 static void *oldnewmap_liblookup(OldNewMap *onm, const void *addr, const void *lib)
406 {
407         if (addr == NULL) {
408                 return NULL;
409         }
410
411         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
412         if (onm->sorted) {
413                 const OldNew entry_s = {.old = addr};
414                 OldNew *entry = bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
415                 if (entry) {
416                         ID *id = entry->newp;
417
418                         if (id && (!lib || id->lib)) {
419                                 return id;
420                         }
421                 }
422         }
423         else {
424                 /* note, this can be a bottle neck when loading some files */
425                 const int i = oldnewmap_lookup_entry_full(onm, addr, -1);
426                 if (i != -1) {
427                         OldNew *entry = &onm->entries[i];
428                         ID *id = entry->newp;
429                         BLI_assert(entry->old == addr);
430                         if (id && (!lib || id->lib)) {
431                                 return id;
432                         }
433                 }
434         }
435
436         return NULL;
437 }
438
439 static void oldnewmap_free_unused(OldNewMap *onm) 
440 {
441         int i;
442
443         for (i = 0; i < onm->nentries; i++) {
444                 OldNew *entry = &onm->entries[i];
445                 if (entry->nr == 0) {
446                         MEM_freeN(entry->newp);
447                         entry->newp = NULL;
448                 }
449         }
450 }
451
452 static void oldnewmap_clear(OldNewMap *onm) 
453 {
454         onm->nentries = 0;
455         onm->lasthit = 0;
456 }
457
458 static void oldnewmap_free(OldNewMap *onm) 
459 {
460         MEM_freeN(onm->entries);
461         MEM_freeN(onm);
462 }
463
464 /***/
465
466 static void read_libraries(FileData *basefd, ListBase *mainlist);
467
468 /* ************ help functions ***************** */
469
470 static void add_main_to_main(Main *mainvar, Main *from)
471 {
472         ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
473         int a;
474         
475         set_listbasepointers(mainvar, lbarray);
476         a = set_listbasepointers(from, fromarray);
477         while (a--) {
478                 BLI_movelisttolist(lbarray[a], fromarray[a]);
479         }
480 }
481
482 void blo_join_main(ListBase *mainlist)
483 {
484         Main *tojoin, *mainl;
485         
486         mainl = mainlist->first;
487         while ((tojoin = mainl->next)) {
488                 add_main_to_main(mainl, tojoin);
489                 BLI_remlink(mainlist, tojoin);
490                 BKE_main_free(tojoin);
491         }
492 }
493
494 static void split_libdata(ListBase *lb_src, Main **lib_main_array, const unsigned int lib_main_array_len)
495 {
496         for (ID *id = lb_src->first, *idnext; id; id = idnext) {
497                 idnext = id->next;
498
499                 if (id->lib) {
500                         if (((unsigned int)id->lib->temp_index < lib_main_array_len) &&
501                             /* this check should never fail, just incase 'id->lib' is a dangling pointer. */
502                             (lib_main_array[id->lib->temp_index]->curlib == id->lib))
503                         {
504                                 Main *mainvar = lib_main_array[id->lib->temp_index];
505                                 ListBase *lb_dst = which_libbase(mainvar, GS(id->name));
506                                 BLI_remlink(lb_src, id);
507                                 BLI_addtail(lb_dst, id);
508                         }
509                         else {
510                                 printf("%s: invalid library for '%s'\n", __func__, id->name);
511                                 BLI_assert(0);
512                         }
513                 }
514         }
515 }
516
517 void blo_split_main(ListBase *mainlist, Main *main)
518 {
519         mainlist->first = mainlist->last = main;
520         main->next = NULL;
521         
522         if (BLI_listbase_is_empty(&main->library))
523                 return;
524         
525         /* (Library.temp_index -> Main), lookup table */
526         const unsigned int lib_main_array_len = BLI_listbase_count(&main->library);
527         Main             **lib_main_array     = MEM_mallocN(lib_main_array_len * sizeof(*lib_main_array), __func__);
528
529         int i = 0;
530         for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) {
531                 Main *libmain = BKE_main_new();
532                 libmain->curlib = lib;
533                 BLI_addtail(mainlist, libmain);
534                 lib->temp_index = i;
535                 lib_main_array[i] = libmain;
536         }
537         
538         ListBase *lbarray[MAX_LIBARRAY];
539         i = set_listbasepointers(main, lbarray);
540         while (i--) {
541                 split_libdata(lbarray[i], lib_main_array, lib_main_array_len);
542         }
543
544         MEM_freeN(lib_main_array);
545 }
546
547 static void read_file_version(FileData *fd, Main *main)
548 {
549         BHead *bhead;
550         
551         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
552                 if (bhead->code == GLOB) {
553                         FileGlobal *fg= read_struct(fd, bhead, "Global");
554                         if (fg) {
555                                 main->subversionfile= fg->subversion;
556                                 main->minversionfile= fg->minversion;
557                                 main->minsubversionfile= fg->minsubversion;
558                                 MEM_freeN(fg);
559                         }
560                         else if (bhead->code == ENDB)
561                                 break;
562                 }
563         }
564 }
565
566 #ifdef USE_GHASH_BHEAD
567 static void read_file_bhead_idname_map_create(FileData *fd)
568 {
569         BHead *bhead;
570
571         /* dummy values */
572         bool is_link = false;
573         int code_prev = ENDB;
574         unsigned int reserve = 0;
575
576         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
577                 if (code_prev != bhead->code) {
578                         code_prev = bhead->code;
579                         is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
580                 }
581
582                 if (is_link) {
583                         reserve += 1;
584                 }
585         }
586
587         BLI_assert(fd->bhead_idname_hash == NULL);
588
589         fd->bhead_idname_hash = BLI_ghash_str_new_ex(__func__, reserve);
590
591         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
592                 if (code_prev != bhead->code) {
593                         code_prev = bhead->code;
594                         is_link = BKE_idcode_is_valid(code_prev) ? BKE_idcode_is_linkable(code_prev) : false;
595                 }
596
597                 if (is_link) {
598                         BLI_ghash_insert(fd->bhead_idname_hash, (void *)bhead_id_name(fd, bhead), bhead);
599                 }
600         }
601 }
602 #endif
603
604
605 static Main *blo_find_main(FileData *fd, const char *filepath, const char *relabase)
606 {
607         ListBase *mainlist = fd->mainlist;
608         Main *m;
609         Library *lib;
610         char name1[FILE_MAX];
611         
612         BLI_strncpy(name1, filepath, sizeof(name1));
613         BLI_cleanup_path(relabase, name1);
614         
615 //      printf("blo_find_main: relabase  %s\n", relabase);
616 //      printf("blo_find_main: original in  %s\n", filepath);
617 //      printf("blo_find_main: converted to %s\n", name1);
618         
619         for (m = mainlist->first; m; m = m->next) {
620                 const char *libname = (m->curlib) ? m->curlib->filepath : m->name;
621                 
622                 if (BLI_path_cmp(name1, libname) == 0) {
623                         if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
624                         return m;
625                 }
626         }
627         
628         m = BKE_main_new();
629         BLI_addtail(mainlist, m);
630         
631         /* Add library datablock itself to 'main' Main, since libraries are **never** linked data.
632          * Fixes bug where you could end with all ID_LI datablocks having the same name... */
633         lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib");
634         lib->id.us = ID_FAKE_USERS(lib);  /* Important, consistency with main ID reading code from read_libblock(). */
635         BLI_strncpy(lib->name, filepath, sizeof(lib->name));
636         BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
637         
638         m->curlib = lib;
639         
640         read_file_version(fd, m);
641         
642         if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
643         return m;
644 }
645
646
647 /* ************ FILE PARSING ****************** */
648
649 static void switch_endian_bh4(BHead4 *bhead)
650 {
651         /* the ID_.. codes */
652         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
653         
654         if (bhead->code != ENDB) {
655                 BLI_endian_switch_int32(&bhead->len);
656                 BLI_endian_switch_int32(&bhead->SDNAnr);
657                 BLI_endian_switch_int32(&bhead->nr);
658         }
659 }
660
661 static void switch_endian_bh8(BHead8 *bhead)
662 {
663         /* the ID_.. codes */
664         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
665         
666         if (bhead->code != ENDB) {
667                 BLI_endian_switch_int32(&bhead->len);
668                 BLI_endian_switch_int32(&bhead->SDNAnr);
669                 BLI_endian_switch_int32(&bhead->nr);
670         }
671 }
672
673 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
674 {
675         BHead4 *bhead4 = (BHead4 *) bhead;
676         int64_t old;
677
678         bhead4->code = bhead8->code;
679         bhead4->len = bhead8->len;
680
681         if (bhead4->code != ENDB) {
682                 /* perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
683                  * 0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
684                  */
685                 if (do_endian_swap) {
686                         BLI_endian_switch_int64(&bhead8->old);
687                 }
688                 
689                 /* this patch is to avoid a long long being read from not-eight aligned positions
690                  * is necessary on any modern 64bit architecture) */
691                 memcpy(&old, &bhead8->old, 8);
692                 bhead4->old = (int) (old >> 3);
693                 
694                 bhead4->SDNAnr = bhead8->SDNAnr;
695                 bhead4->nr = bhead8->nr;
696         }
697 }
698
699 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
700 {
701         BHead8 *bhead8 = (BHead8 *) bhead;
702         
703         bhead8->code = bhead4->code;
704         bhead8->len = bhead4->len;
705         
706         if (bhead8->code != ENDB) {
707                 bhead8->old = bhead4->old;
708                 bhead8->SDNAnr = bhead4->SDNAnr;
709                 bhead8->nr= bhead4->nr;
710         }
711 }
712
713 static BHeadN *get_bhead(FileData *fd)
714 {
715         BHeadN *new_bhead = NULL;
716         int readsize;
717         
718         if (fd) {
719                 if (!fd->eof) {
720                         /* initializing to zero isn't strictly needed but shuts valgrind up
721                          * since uninitialized memory gets compared */
722                         BHead8 bhead8 = {0};
723                         BHead4 bhead4 = {0};
724                         BHead  bhead = {0};
725                         
726                         /* First read the bhead structure.
727                          * Depending on the platform the file was written on this can
728                          * be a big or little endian BHead4 or BHead8 structure.
729                          *
730                          * As usual 'ENDB' (the last *partial* bhead of the file)
731                          * needs some special handling. We don't want to EOF just yet.
732                          */
733                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
734                                 bhead4.code = DATA;
735                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
736                                 
737                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
738                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
739                                                 switch_endian_bh4(&bhead4);
740                                         }
741                                         
742                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
743                                                 bh8_from_bh4(&bhead, &bhead4);
744                                         }
745                                         else {
746                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
747                                         }
748                                 }
749                                 else {
750                                         fd->eof = 1;
751                                         bhead.len= 0;
752                                 }
753                         }
754                         else {
755                                 bhead8.code = DATA;
756                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
757                                 
758                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
759                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
760                                                 switch_endian_bh8(&bhead8);
761                                         }
762                                         
763                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
764                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
765                                         }
766                                         else {
767                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
768                                         }
769                                 }
770                                 else {
771                                         fd->eof = 1;
772                                         bhead.len= 0;
773                                 }
774                         }
775                         
776                         /* make sure people are not trying to pass bad blend files */
777                         if (bhead.len < 0) fd->eof = 1;
778                         
779                         /* bhead now contains the (converted) bhead structure. Now read
780                          * the associated data and put everything in a BHeadN (creative naming !)
781                          */
782                         if (!fd->eof) {
783                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
784                                 if (new_bhead) {
785                                         new_bhead->next = new_bhead->prev = NULL;
786                                         new_bhead->bhead = bhead;
787                                         
788                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
789                                         
790                                         if (readsize != bhead.len) {
791                                                 fd->eof = 1;
792                                                 MEM_freeN(new_bhead);
793                                                 new_bhead = NULL;
794                                         }
795                                 }
796                                 else {
797                                         fd->eof = 1;
798                                 }
799                         }
800                 }
801         }
802
803         /* We've read a new block. Now add it to the list
804          * of blocks.
805          */
806         if (new_bhead) {
807                 BLI_addtail(&fd->listbase, new_bhead);
808         }
809         
810         return(new_bhead);
811 }
812
813 BHead *blo_firstbhead(FileData *fd)
814 {
815         BHeadN *new_bhead;
816         BHead *bhead = NULL;
817         
818         /* Rewind the file
819          * Read in a new block if necessary
820          */
821         new_bhead = fd->listbase.first;
822         if (new_bhead == NULL) {
823                 new_bhead = get_bhead(fd);
824         }
825         
826         if (new_bhead) {
827                 bhead = &new_bhead->bhead;
828         }
829         
830         return(bhead);
831 }
832
833 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
834 {
835         BHeadN *bheadn = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
836         BHeadN *prev = bheadn->prev;
837         
838         return (prev) ? &prev->bhead : NULL;
839 }
840
841 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
842 {
843         BHeadN *new_bhead = NULL;
844         BHead *bhead = NULL;
845         
846         if (thisblock) {
847                 /* bhead is actually a sub part of BHeadN
848                  * We calculate the BHeadN pointer from the BHead pointer below */
849                 new_bhead = (BHeadN *)POINTER_OFFSET(thisblock, -offsetof(BHeadN, bhead));
850                 
851                 /* get the next BHeadN. If it doesn't exist we read in the next one */
852                 new_bhead = new_bhead->next;
853                 if (new_bhead == NULL) {
854                         new_bhead = get_bhead(fd);
855                 }
856         }
857         
858         if (new_bhead) {
859                 /* here we do the reverse:
860                  * go from the BHeadN pointer to the BHead pointer */
861                 bhead = &new_bhead->bhead;
862         }
863         
864         return(bhead);
865 }
866
867 /* Warning! Caller's responsability to ensure given bhead **is** and ID one! */
868 const char *bhead_id_name(const FileData *fd, const BHead *bhead)
869 {
870         return (const char *)POINTER_OFFSET(bhead, sizeof(*bhead) + fd->id_name_offs);
871 }
872
873 static void decode_blender_header(FileData *fd)
874 {
875         char header[SIZEOFBLENDERHEADER], num[4];
876         int readsize;
877         
878         /* read in the header data */
879         readsize = fd->read(fd, header, sizeof(header));
880         
881         if (readsize == sizeof(header)) {
882                 if (STREQLEN(header, "BLENDER", 7)) {
883                         fd->flags |= FD_FLAGS_FILE_OK;
884                         
885                         /* what size are pointers in the file ? */
886                         if (header[7]=='_') {
887                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
888                                 if (sizeof(void *) != 4) {
889                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
890                                 }
891                         }
892                         else {
893                                 if (sizeof(void *) != 8) {
894                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
895                                 }
896                         }
897                         
898                         /* is the file saved in a different endian
899                          * than we need ?
900                          */
901                         if (((header[8] == 'v') ? L_ENDIAN : B_ENDIAN) != ENDIAN_ORDER) {
902                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
903                         }
904                         
905                         /* get the version number */
906                         memcpy(num, header + 9, 3);
907                         num[3] = 0;
908                         fd->fileversion = atoi(num);
909                 }
910         }
911 }
912
913 static int read_file_dna(FileData *fd)
914 {
915         BHead *bhead;
916         
917         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
918                 if (bhead->code == DNA1) {
919                         const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
920                         
921                         fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap, true);
922                         if (fd->filesdna) {
923                                 fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
924                                 /* used to retrieve ID names from (bhead+1) */
925                                 fd->id_name_offs = DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
926                         }
927                         
928                         return 1;
929                 }
930                 else if (bhead->code == ENDB)
931                         break;
932         }
933         
934         return 0;
935 }
936
937 static int *read_file_thumbnail(FileData *fd)
938 {
939         BHead *bhead;
940         int *blend_thumb = NULL;
941
942         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
943                 if (bhead->code == TEST) {
944                         const bool do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) != 0;
945                         int *data = (int *)(bhead + 1);
946
947                         if (bhead->len < (2 * sizeof(int))) {
948                                 break;
949                         }
950
951                         if (do_endian_swap) {
952                                 BLI_endian_switch_int32(&data[0]);
953                                 BLI_endian_switch_int32(&data[1]);
954                         }
955
956                         if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(data[0], data[1])) {
957                                 break;
958                         }
959
960                         blend_thumb = data;
961                         break;
962                 }
963                 else if (bhead->code != REND) {
964                         /* Thumbnail is stored in TEST immediately after first REND... */
965                         break;
966                 }
967         }
968
969         return blend_thumb;
970 }
971
972 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
973 {
974         int readsize = read(filedata->filedes, buffer, size);
975         
976         if (readsize < 0) {
977                 readsize = EOF;
978         }
979         else {
980                 filedata->seek += readsize;
981         }
982         
983         return readsize;
984 }
985
986 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
987 {
988         int readsize = gzread(filedata->gzfiledes, buffer, size);
989         
990         if (readsize < 0) {
991                 readsize = EOF;
992         }
993         else {
994                 filedata->seek += readsize;
995         }
996         
997         return (readsize);
998 }
999
1000 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
1001 {
1002         /* don't read more bytes then there are available in the buffer */
1003         int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
1004         
1005         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
1006         filedata->seek += readsize;
1007         
1008         return (readsize);
1009 }
1010
1011 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
1012 {
1013         static unsigned int seek = (1<<30);     /* the current position */
1014         static unsigned int offset = 0;         /* size of previous chunks */
1015         static MemFileChunk *chunk = NULL;
1016         unsigned int chunkoffset, readsize, totread;
1017         
1018         if (size == 0) return 0;
1019         
1020         if (seek != (unsigned int)filedata->seek) {
1021                 chunk = filedata->memfile->chunks.first;
1022                 seek = 0;
1023                 
1024                 while (chunk) {
1025                         if (seek + chunk->size > (unsigned) filedata->seek) break;
1026                         seek += chunk->size;
1027                         chunk = chunk->next;
1028                 }
1029                 offset = seek;
1030                 seek = filedata->seek;
1031         }
1032         
1033         if (chunk) {
1034                 totread = 0;
1035                 
1036                 do {
1037                         /* first check if it's on the end if current chunk */
1038                         if (seek-offset == chunk->size) {
1039                                 offset += chunk->size;
1040                                 chunk = chunk->next;
1041                         }
1042                         
1043                         /* debug, should never happen */
1044                         if (chunk == NULL) {
1045                                 printf("illegal read, chunk zero\n");
1046                                 return 0;
1047                         }
1048                         
1049                         chunkoffset = seek-offset;
1050                         readsize = size-totread;
1051                         
1052                         /* data can be spread over multiple chunks, so clamp size
1053                          * to within this chunk, and then it will read further in
1054                          * the next chunk */
1055                         if (chunkoffset+readsize > chunk->size)
1056                                 readsize= chunk->size-chunkoffset;
1057                         
1058                         memcpy(POINTER_OFFSET(buffer, totread), chunk->buf + chunkoffset, readsize);
1059                         totread += readsize;
1060                         filedata->seek += readsize;
1061                         seek += readsize;
1062                 } while (totread < size);
1063                 
1064                 return totread;
1065         }
1066         
1067         return 0;
1068 }
1069
1070 static FileData *filedata_new(void)
1071 {
1072         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
1073         
1074         fd->filedes = -1;
1075         fd->gzfiledes = NULL;
1076         
1077         /* XXX, this doesn't need to be done all the time,
1078          * but it keeps us re-entrant,  remove once we have
1079          * a lib that provides a nice lock. - zr
1080          */
1081         fd->memsdna = DNA_sdna_from_data(DNAstr, DNAlen, false, false);
1082         
1083         fd->datamap = oldnewmap_new();
1084         fd->globmap = oldnewmap_new();
1085         fd->libmap = oldnewmap_new();
1086         
1087         return fd;
1088 }
1089
1090 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
1091 {
1092         decode_blender_header(fd);
1093         
1094         if (fd->flags & FD_FLAGS_FILE_OK) {
1095                 if (!read_file_dna(fd)) {
1096                         BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', incomplete", fd->relabase);
1097                         blo_freefiledata(fd);
1098                         fd = NULL;
1099                 }
1100         }
1101         else {
1102                 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file '%s', not a blend file", fd->relabase);
1103                 blo_freefiledata(fd);
1104                 fd = NULL;
1105         }
1106         
1107         return fd;
1108 }
1109
1110 /* cannot be called with relative paths anymore! */
1111 /* on each new library added, it now checks for the current FileData and expands relativeness */
1112 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
1113 {
1114         gzFile gzfile;
1115         errno = 0;
1116         gzfile = BLI_gzopen(filepath, "rb");
1117         
1118         if (gzfile == (gzFile)Z_NULL) {
1119                 BKE_reportf(reports, RPT_WARNING, "Unable to open '%s': %s",
1120                             filepath, errno ? strerror(errno) : TIP_("unknown error reading file"));
1121                 return NULL;
1122         }
1123         else {
1124                 FileData *fd = filedata_new();
1125                 fd->gzfiledes = gzfile;
1126                 fd->read = fd_read_gzip_from_file;
1127                 
1128                 /* needed for library_append and read_libraries */
1129                 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
1130                 
1131                 return blo_decode_and_check(fd, reports);
1132         }
1133 }
1134
1135 /**
1136  * Same as blo_openblenderfile(), but does not reads DNA data, only header. Use it for light access
1137  * (e.g. thumbnail reading).
1138  */
1139 static FileData *blo_openblenderfile_minimal(const char *filepath)
1140 {
1141         gzFile gzfile;
1142         errno = 0;
1143         gzfile = BLI_gzopen(filepath, "rb");
1144
1145         if (gzfile != (gzFile)Z_NULL) {
1146                 FileData *fd = filedata_new();
1147                 fd->gzfiledes = gzfile;
1148                 fd->read = fd_read_gzip_from_file;
1149
1150                 decode_blender_header(fd);
1151
1152                 if (fd->flags & FD_FLAGS_FILE_OK) {
1153                         return fd;
1154                 }
1155
1156                 blo_freefiledata(fd);
1157         }
1158
1159         return NULL;
1160 }
1161
1162 static int fd_read_gzip_from_memory(FileData *filedata, void *buffer, unsigned int size)
1163 {
1164         int err;
1165
1166         filedata->strm.next_out = (Bytef *) buffer;
1167         filedata->strm.avail_out = size;
1168
1169         // Inflate another chunk.
1170         err = inflate (&filedata->strm, Z_SYNC_FLUSH);
1171
1172         if (err == Z_STREAM_END) {
1173                 return 0;
1174         }
1175         else if (err != Z_OK) {
1176                 printf("fd_read_gzip_from_memory: zlib error\n");
1177                 return 0;
1178         }
1179
1180         filedata->seek += size;
1181
1182         return (size);
1183 }
1184
1185 static int fd_read_gzip_from_memory_init(FileData *fd)
1186 {
1187
1188         fd->strm.next_in = (Bytef *) fd->buffer;
1189         fd->strm.avail_in = fd->buffersize;
1190         fd->strm.total_out = 0;
1191         fd->strm.zalloc = Z_NULL;
1192         fd->strm.zfree = Z_NULL;
1193         
1194         if (inflateInit2(&fd->strm, (16+MAX_WBITS)) != Z_OK)
1195                 return 0;
1196
1197         fd->read = fd_read_gzip_from_memory;
1198         
1199         return 1;
1200 }
1201
1202 FileData *blo_openblendermemory(const void *mem, int memsize, ReportList *reports)
1203 {
1204         if (!mem || memsize<SIZEOFBLENDERHEADER) {
1205                 BKE_report(reports, RPT_WARNING, (mem) ? TIP_("Unable to read"): TIP_("Unable to open"));
1206                 return NULL;
1207         }
1208         else {
1209                 FileData *fd = filedata_new();
1210                 const char *cp = mem;
1211                 
1212                 fd->buffer = mem;
1213                 fd->buffersize = memsize;
1214                 
1215                 /* test if gzip */
1216                 if (cp[0] == 0x1f && cp[1] == 0x8b) {
1217                         if (0 == fd_read_gzip_from_memory_init(fd)) {
1218                                 blo_freefiledata(fd);
1219                                 return NULL;
1220                         }
1221                 }
1222                 else
1223                         fd->read = fd_read_from_memory;
1224                         
1225                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1226
1227                 return blo_decode_and_check(fd, reports);
1228         }
1229 }
1230
1231 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
1232 {
1233         if (!memfile) {
1234                 BKE_report(reports, RPT_WARNING, "Unable to open blend <memory>");
1235                 return NULL;
1236         }
1237         else {
1238                 FileData *fd = filedata_new();
1239                 fd->memfile = memfile;
1240                 
1241                 fd->read = fd_read_from_memfile;
1242                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1243                 
1244                 return blo_decode_and_check(fd, reports);
1245         }
1246 }
1247
1248
1249 void blo_freefiledata(FileData *fd)
1250 {
1251         if (fd) {
1252                 if (fd->filedes != -1) {
1253                         close(fd->filedes);
1254                 }
1255                 
1256                 if (fd->gzfiledes != NULL) {
1257                         gzclose(fd->gzfiledes);
1258                 }
1259                 
1260                 if (fd->strm.next_in) {
1261                         if (inflateEnd(&fd->strm) != Z_OK) {
1262                                 printf("close gzip stream error\n");
1263                         }
1264                 }
1265                 
1266                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1267                         MEM_freeN((void *)fd->buffer);
1268                         fd->buffer = NULL;
1269                 }
1270                 
1271                 // Free all BHeadN data blocks
1272                 BLI_freelistN(&fd->listbase);
1273                 
1274                 if (fd->memsdna)
1275                         DNA_sdna_free(fd->memsdna);
1276                 if (fd->filesdna)
1277                         DNA_sdna_free(fd->filesdna);
1278                 if (fd->compflags)
1279                         MEM_freeN(fd->compflags);
1280                 
1281                 if (fd->datamap)
1282                         oldnewmap_free(fd->datamap);
1283                 if (fd->globmap)
1284                         oldnewmap_free(fd->globmap);
1285                 if (fd->imamap)
1286                         oldnewmap_free(fd->imamap);
1287                 if (fd->movieclipmap)
1288                         oldnewmap_free(fd->movieclipmap);
1289                 if (fd->soundmap)
1290                         oldnewmap_free(fd->soundmap);
1291                 if (fd->packedmap)
1292                         oldnewmap_free(fd->packedmap);
1293                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1294                         oldnewmap_free(fd->libmap);
1295                 if (fd->bheadmap)
1296                         MEM_freeN(fd->bheadmap);
1297                 
1298 #ifdef USE_GHASH_BHEAD
1299                 if (fd->bhead_idname_hash) {
1300                         BLI_ghash_free(fd->bhead_idname_hash, NULL, NULL);
1301                 }
1302 #endif
1303
1304                 MEM_freeN(fd);
1305         }
1306 }
1307
1308 /* ************ DIV ****************** */
1309
1310 /**
1311  * Check whether given path ends with a blend file compatible extension (.blend, .ble or .blend.gz).
1312  *
1313  * \param str The path to check.
1314  * \return true is this path ends with a blender file extension.
1315  */
1316 bool BLO_has_bfile_extension(const char *str)
1317 {
1318         const char *ext_test[4] = {".blend", ".ble", ".blend.gz", NULL};
1319         return BLI_testextensie_array(str, ext_test);
1320 }
1321
1322 /**
1323  * Try to explode given path into its 'library components' (i.e. a .blend file, id type/group, and datablock itself).
1324  *
1325  * \param path the full path to explode.
1326  * \param r_dir the string that'll contain path up to blend file itself ('library' path).
1327  *              WARNING! Must be FILE_MAX_LIBEXTRA long (it also stores group and name strings)!
1328  * \param r_group the string that'll contain 'group' part of the path, if any. May be NULL.
1329  * \param r_name the string that'll contain data's name part of the path, if any. May be NULL.
1330  * \return true if path contains a blend file.
1331  */
1332 bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, char **r_name)
1333 {
1334         /* We might get some data names with slashes, so we have to go up in path until we find blend file itself,
1335          * then we now next path item is group, and everything else is data name. */
1336         char *slash = NULL, *prev_slash = NULL, c = '\0';
1337
1338         r_dir[0] = '\0';
1339         if (r_group) {
1340                 *r_group = NULL;
1341         }
1342         if (r_name) {
1343                 *r_name = NULL;
1344         }
1345
1346         /* if path leads to an existing directory, we can be sure we're not (in) a library */
1347         if (BLI_is_dir(path)) {
1348                 return false;
1349         }
1350
1351         strcpy(r_dir, path);
1352
1353         while ((slash = (char *)BLI_last_slash(r_dir))) {
1354                 char tc = *slash;
1355                 *slash = '\0';
1356                 if (BLO_has_bfile_extension(r_dir) && BLI_is_file(r_dir)) {
1357                         break;
1358                 }
1359
1360                 if (prev_slash) {
1361                         *prev_slash = c;
1362                 }
1363                 prev_slash = slash;
1364                 c = tc;
1365         }
1366
1367         if (!slash) {
1368                 return false;
1369         }
1370
1371         if (slash[1] != '\0') {
1372                 BLI_assert(strlen(slash + 1) < BLO_GROUP_MAX);
1373                 if (r_group) {
1374                         *r_group = slash + 1;
1375                 }
1376         }
1377
1378         if (prev_slash && (prev_slash[1] != '\0')) {
1379                 BLI_assert(strlen(prev_slash + 1) < MAX_ID_NAME - 2);
1380                 if (r_name) {
1381                         *r_name = prev_slash + 1;
1382                 }
1383         }
1384
1385         return true;
1386 }
1387
1388 /**
1389  * Does a very light reading of given .blend file to extract its stored thumbnail.
1390  *
1391  * \param filepath The path of the file to extract thumbnail from.
1392  * \return The raw thumbnail
1393  *         (MEM-allocated, as stored in file, use BKE_main_thumbnail_to_imbuf() to convert it to ImBuf image).
1394  */
1395 BlendThumbnail *BLO_thumbnail_from_file(const char *filepath)
1396 {
1397         FileData *fd;
1398         BlendThumbnail *data;
1399         int *fd_data;
1400
1401         fd = blo_openblenderfile_minimal(filepath);
1402         fd_data = fd ? read_file_thumbnail(fd) : NULL;
1403
1404         if (fd_data) {
1405                 const size_t sz = BLEN_THUMB_MEMSIZE(fd_data[0], fd_data[1]);
1406                 data = MEM_mallocN(sz, __func__);
1407
1408                 BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(fd_data[0], fd_data[1]) - (sizeof(*fd_data) * 2)));
1409                 data->width = fd_data[0];
1410                 data->height = fd_data[1];
1411                 memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
1412         }
1413         else {
1414                 data = NULL;
1415         }
1416
1417         blo_freefiledata(fd);
1418
1419         return data;
1420 }
1421
1422 /* ************** OLD POINTERS ******************* */
1423
1424 static void *newdataadr(FileData *fd, const void *adr)          /* only direct databocks */
1425 {
1426         return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1427 }
1428
1429 /* This is a special version of newdataadr() which allows us to keep lasthit of
1430  * map unchanged. In certain cases this makes file loading time significantly
1431  * faster.
1432  *
1433  * Use this function in cases like restoring pointer from one list element to
1434  * another list element, but keep lasthit value so we can continue restoring
1435  * pointers efficiently.
1436  *
1437  * Example of this could be found in direct_link_fcurves() which restores the
1438  * fcurve group pointer and keeps lasthit optimal for linking all further
1439  * fcurves.
1440  */
1441 static void *newdataadr_ex(FileData *fd, const void *adr, bool increase_lasthit)                /* only direct databocks */
1442 {
1443         if (increase_lasthit) {
1444                 return newdataadr(fd, adr);
1445         }
1446         else {
1447                 int lasthit = fd->datamap->lasthit;
1448                 void *newadr = newdataadr(fd, adr);
1449                 fd->datamap->lasthit = lasthit;
1450                 return newadr;
1451         }
1452 }
1453
1454 static void *newdataadr_no_us(FileData *fd, const void *adr)            /* only direct databocks */
1455 {
1456         return oldnewmap_lookup_and_inc(fd->datamap, adr, false);
1457 }
1458
1459 static void *newglobadr(FileData *fd, const void *adr)      /* direct datablocks with global linking */
1460 {
1461         return oldnewmap_lookup_and_inc(fd->globmap, adr, true);
1462 }
1463
1464 static void *newimaadr(FileData *fd, const void *adr)               /* used to restore image data after undo */
1465 {
1466         if (fd->imamap && adr)
1467                 return oldnewmap_lookup_and_inc(fd->imamap, adr, true);
1468         return NULL;
1469 }
1470
1471 static void *newmclipadr(FileData *fd, const void *adr)      /* used to restore movie clip data after undo */
1472 {
1473         if (fd->movieclipmap && adr)
1474                 return oldnewmap_lookup_and_inc(fd->movieclipmap, adr, true);
1475         return NULL;
1476 }
1477
1478 static void *newsoundadr(FileData *fd, const void *adr)      /* used to restore sound data after undo */
1479 {
1480         if (fd->soundmap && adr)
1481                 return oldnewmap_lookup_and_inc(fd->soundmap, adr, true);
1482         return NULL;
1483 }
1484
1485 static void *newpackedadr(FileData *fd, const void *adr)      /* used to restore packed data after undo */
1486 {
1487         if (fd->packedmap && adr)
1488                 return oldnewmap_lookup_and_inc(fd->packedmap, adr, true);
1489         
1490         return oldnewmap_lookup_and_inc(fd->datamap, adr, true);
1491 }
1492
1493
1494 static void *newlibadr(FileData *fd, const void *lib, const void *adr)          /* only lib data */
1495 {
1496         return oldnewmap_liblookup(fd->libmap, adr, lib);
1497 }
1498
1499 void *blo_do_versions_newlibadr(FileData *fd, const void *lib, const void *adr)         /* only lib data */
1500 {
1501         return newlibadr(fd, lib, adr);
1502 }
1503
1504 static void *newlibadr_us(FileData *fd, const void *lib, const void *adr)       /* increases user number */
1505 {
1506         ID *id = newlibadr(fd, lib, adr);
1507         
1508         id_us_plus_no_lib(id);
1509         
1510         return id;
1511 }
1512
1513 void *blo_do_versions_newlibadr_us(FileData *fd, const void *lib, const void *adr)      /* increases user number */
1514 {
1515         return newlibadr_us(fd, lib, adr);
1516 }
1517
1518 static void *newlibadr_real_us(FileData *fd, const void *lib, const void *adr)  /* ensures real user */
1519 {
1520         ID *id = newlibadr(fd, lib, adr);
1521
1522         id_us_ensure_real(id);
1523
1524         return id;
1525 }
1526
1527 static void change_idid_adr_fd(FileData *fd, const void *old, void *new)
1528 {
1529         int i;
1530         
1531         /* use a binary search if we have a sorted libmap, for now it's not needed. */
1532         BLI_assert(fd->libmap->sorted == false);
1533
1534         for (i = 0; i < fd->libmap->nentries; i++) {
1535                 OldNew *entry = &fd->libmap->entries[i];
1536                 
1537                 if (old==entry->newp && entry->nr==ID_ID) {
1538                         entry->newp = new;
1539                         if (new) entry->nr = GS( ((ID *)new)->name );
1540                 }
1541         }
1542 }
1543
1544 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1545 {
1546         Main *mainptr;
1547         
1548         for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) {
1549                 FileData *fd;
1550                 
1551                 if (mainptr->curlib)
1552                         fd = mainptr->curlib->filedata;
1553                 else
1554                         fd = basefd;
1555                 
1556                 if (fd) {
1557                         change_idid_adr_fd(fd, old, new);
1558                 }
1559         }
1560 }
1561
1562 /* lib linked proxy objects point to our local data, we need
1563  * to clear that pointer before reading the undo memfile since
1564  * the object might be removed, it is set again in reading
1565  * if the local object still exists */
1566 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
1567 {
1568         Object *ob = oldmain->object.first;
1569         
1570         for (; ob; ob= ob->id.next) {
1571                 if (ob->id.lib)
1572                         ob->proxy_from = NULL;
1573         }
1574 }
1575
1576 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1577 {
1578         Image *ima = oldmain->image.first;
1579         Scene *sce = oldmain->scene.first;
1580         int a;
1581         
1582         fd->imamap = oldnewmap_new();
1583         
1584         for (; ima; ima = ima->id.next) {
1585                 if (ima->cache)
1586                         oldnewmap_insert(fd->imamap, ima->cache, ima->cache, 0);
1587                 for (a = 0; a < TEXTARGET_COUNT; a++)
1588                         if (ima->gputexture[a])
1589                                 oldnewmap_insert(fd->imamap, ima->gputexture[a], ima->gputexture[a], 0);
1590                 if (ima->rr)
1591                         oldnewmap_insert(fd->imamap, ima->rr, ima->rr, 0);
1592                 for (a=0; a < IMA_MAX_RENDER_SLOT; a++)
1593                         if (ima->renders[a])
1594                                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
1595         }
1596         for (; sce; sce = sce->id.next) {
1597                 if (sce->nodetree && sce->nodetree->previews) {
1598                         bNodeInstanceHashIterator iter;
1599                         NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1600                                 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1601                                 oldnewmap_insert(fd->imamap, preview, preview, 0);
1602                         }
1603                 }
1604         }
1605 }
1606
1607 /* set old main image ibufs to zero if it has been restored */
1608 /* this works because freeing old main only happens after this call */
1609 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1610 {
1611         OldNew *entry = fd->imamap->entries;
1612         Image *ima = oldmain->image.first;
1613         Scene *sce = oldmain->scene.first;
1614         int i;
1615         
1616         /* used entries were restored, so we put them to zero */
1617         for (i = 0; i < fd->imamap->nentries; i++, entry++) {
1618                 if (entry->nr > 0)
1619                         entry->newp = NULL;
1620         }
1621         
1622         for (; ima; ima = ima->id.next) {
1623                 ima->cache = newimaadr(fd, ima->cache);
1624                 if (ima->cache == NULL) {
1625                         ima->tpageflag &= ~IMA_GLBIND_IS_DATA;
1626                         for (i = 0; i < TEXTARGET_COUNT; i++) {
1627                                 ima->bindcode[i] = 0;
1628                                 ima->gputexture[i] = NULL;
1629                         }
1630                         ima->rr = NULL;
1631                 }
1632                 for (i = 0; i < IMA_MAX_RENDER_SLOT; i++)
1633                         ima->renders[i] = newimaadr(fd, ima->renders[i]);
1634                 
1635                 for (i = 0; i < TEXTARGET_COUNT; i++)
1636                         ima->gputexture[i] = newimaadr(fd, ima->gputexture[i]);
1637                 ima->rr = newimaadr(fd, ima->rr);
1638         }
1639         for (; sce; sce = sce->id.next) {
1640                 if (sce->nodetree && sce->nodetree->previews) {
1641                         bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
1642                         bNodeInstanceHashIterator iter;
1643                         
1644                         /* reconstruct the preview hash, only using remaining pointers */
1645                         NODE_INSTANCE_HASH_ITER(iter, sce->nodetree->previews) {
1646                                 bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
1647                                 if (preview) {
1648                                         bNodePreview *new_preview = newimaadr(fd, preview);
1649                                         if (new_preview) {
1650                                                 bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
1651                                                 BKE_node_instance_hash_insert(new_previews, key, new_preview);
1652                                         }
1653                                 }
1654                         }
1655                         BKE_node_instance_hash_free(sce->nodetree->previews, NULL);
1656                         sce->nodetree->previews = new_previews;
1657                 }
1658         }
1659 }
1660
1661 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
1662 {
1663         MovieClip *clip = oldmain->movieclip.first;
1664         Scene *sce = oldmain->scene.first;
1665         
1666         fd->movieclipmap = oldnewmap_new();
1667         
1668         for (; clip; clip = clip->id.next) {
1669                 if (clip->cache)
1670                         oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
1671                 
1672                 if (clip->tracking.camera.intrinsics)
1673                         oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
1674         }
1675         
1676         for (; sce; sce = sce->id.next) {
1677                 if (sce->nodetree) {
1678                         bNode *node;
1679                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1680                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1681                                         oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
1682                 }
1683         }
1684 }
1685
1686 /* set old main movie clips caches to zero if it has been restored */
1687 /* this works because freeing old main only happens after this call */
1688 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
1689 {
1690         OldNew *entry = fd->movieclipmap->entries;
1691         MovieClip *clip = oldmain->movieclip.first;
1692         Scene *sce = oldmain->scene.first;
1693         int i;
1694         
1695         /* used entries were restored, so we put them to zero */
1696         for (i=0; i < fd->movieclipmap->nentries; i++, entry++) {
1697                 if (entry->nr > 0)
1698                         entry->newp = NULL;
1699         }
1700         
1701         for (; clip; clip = clip->id.next) {
1702                 clip->cache = newmclipadr(fd, clip->cache);
1703                 clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics);
1704         }
1705         
1706         for (; sce; sce = sce->id.next) {
1707                 if (sce->nodetree) {
1708                         bNode *node;
1709                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1710                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1711                                         node->storage = newmclipadr(fd, node->storage);
1712                 }
1713         }
1714 }
1715
1716 void blo_make_sound_pointer_map(FileData *fd, Main *oldmain)
1717 {
1718         bSound *sound = oldmain->sound.first;
1719         
1720         fd->soundmap = oldnewmap_new();
1721         
1722         for (; sound; sound = sound->id.next) {
1723                 if (sound->waveform)
1724                         oldnewmap_insert(fd->soundmap, sound->waveform, sound->waveform, 0);                    
1725         }
1726 }
1727
1728 /* set old main sound caches to zero if it has been restored */
1729 /* this works because freeing old main only happens after this call */
1730 void blo_end_sound_pointer_map(FileData *fd, Main *oldmain)
1731 {
1732         OldNew *entry = fd->soundmap->entries;
1733         bSound *sound = oldmain->sound.first;
1734         int i;
1735         
1736         /* used entries were restored, so we put them to zero */
1737         for (i = 0; i < fd->soundmap->nentries; i++, entry++) {
1738                 if (entry->nr > 0)
1739                         entry->newp = NULL;
1740         }
1741         
1742         for (; sound; sound = sound->id.next) {
1743                 sound->waveform = newsoundadr(fd, sound->waveform);
1744         }
1745 }
1746
1747 /* XXX disabled this feature - packed files also belong in temp saves and quit.blend, to make restore work */
1748
1749 static void insert_packedmap(FileData *fd, PackedFile *pf)
1750 {
1751         oldnewmap_insert(fd->packedmap, pf, pf, 0);
1752         oldnewmap_insert(fd->packedmap, pf->data, pf->data, 0);
1753 }
1754
1755 void blo_make_packed_pointer_map(FileData *fd, Main *oldmain)
1756 {
1757         Image *ima;
1758         VFont *vfont;
1759         bSound *sound;
1760         Library *lib;
1761         
1762         fd->packedmap = oldnewmap_new();
1763         
1764         for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1765                 ImagePackedFile *imapf;
1766
1767                 if (ima->packedfile)
1768                         insert_packedmap(fd, ima->packedfile);
1769
1770                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1771                         if (imapf->packedfile)
1772                                 insert_packedmap(fd, imapf->packedfile);
1773         }
1774                         
1775         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1776                 if (vfont->packedfile)
1777                         insert_packedmap(fd, vfont->packedfile);
1778         
1779         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1780                 if (sound->packedfile)
1781                         insert_packedmap(fd, sound->packedfile);
1782         
1783         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1784                 if (lib->packedfile)
1785                         insert_packedmap(fd, lib->packedfile);
1786
1787 }
1788
1789 /* set old main packed data to zero if it has been restored */
1790 /* this works because freeing old main only happens after this call */
1791 void blo_end_packed_pointer_map(FileData *fd, Main *oldmain)
1792 {
1793         Image *ima;
1794         VFont *vfont;
1795         bSound *sound;
1796         Library *lib;
1797         OldNew *entry = fd->packedmap->entries;
1798         int i;
1799         
1800         /* used entries were restored, so we put them to zero */
1801         for (i=0; i < fd->packedmap->nentries; i++, entry++) {
1802                 if (entry->nr > 0)
1803                         entry->newp = NULL;
1804         }
1805         
1806         for (ima = oldmain->image.first; ima; ima = ima->id.next) {
1807                 ImagePackedFile *imapf;
1808
1809                 ima->packedfile = newpackedadr(fd, ima->packedfile);
1810
1811                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next)
1812                         imapf->packedfile = newpackedadr(fd, imapf->packedfile);
1813         }
1814         
1815         for (vfont = oldmain->vfont.first; vfont; vfont = vfont->id.next)
1816                 vfont->packedfile = newpackedadr(fd, vfont->packedfile);
1817
1818         for (sound = oldmain->sound.first; sound; sound = sound->id.next)
1819                 sound->packedfile = newpackedadr(fd, sound->packedfile);
1820                 
1821         for (lib = oldmain->library.first; lib; lib = lib->id.next)
1822                 lib->packedfile = newpackedadr(fd, lib->packedfile);
1823 }
1824
1825
1826 /* undo file support: add all library pointers in lookup */
1827 void blo_add_library_pointer_map(ListBase *old_mainlist, FileData *fd)
1828 {
1829         Main *ptr = old_mainlist->first;
1830         ListBase *lbarray[MAX_LIBARRAY];
1831         
1832         for (ptr = ptr->next; ptr; ptr = ptr->next) {
1833                 int i = set_listbasepointers(ptr, lbarray);
1834                 while (i--) {
1835                         ID *id;
1836                         for (id = lbarray[i]->first; id; id = id->next)
1837                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1838                 }
1839         }
1840
1841         fd->old_mainlist = old_mainlist;
1842 }
1843
1844
1845 /* ********** END OLD POINTERS ****************** */
1846 /* ********** READ FILE ****************** */
1847
1848 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1849 {
1850         int blocksize, nblocks;
1851         char *data;
1852         
1853         data = (char *)(bhead+1);
1854         blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1855         
1856         nblocks = bhead->nr;
1857         while (nblocks--) {
1858                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1859                 
1860                 data += blocksize;
1861         }
1862 }
1863
1864 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
1865 {
1866         void *temp = NULL;
1867         
1868         if (bh->len) {
1869                 /* switch is based on file dna */
1870                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1871                         switch_endian_structs(fd->filesdna, bh);
1872                 
1873                 if (fd->compflags[bh->SDNAnr] != SDNA_CMP_REMOVED) {
1874                         if (fd->compflags[bh->SDNAnr] == SDNA_CMP_NOT_EQUAL) {
1875                                 temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1876                         }
1877                         else {
1878                                 /* SDNA_CMP_EQUAL */
1879                                 temp = MEM_mallocN(bh->len, blockname);
1880                                 memcpy(temp, (bh+1), bh->len);
1881                         }
1882                 }
1883         }
1884
1885         return temp;
1886 }
1887
1888 typedef void (*link_list_cb)(FileData *fd, void *data);
1889
1890 static void link_list_ex(FileData *fd, ListBase *lb, link_list_cb callback)             /* only direct data */
1891 {
1892         Link *ln, *prev;
1893         
1894         if (BLI_listbase_is_empty(lb)) return;
1895         
1896         lb->first = newdataadr(fd, lb->first);
1897         if (callback != NULL) {
1898                 callback(fd, lb->first);
1899         }
1900         ln = lb->first;
1901         prev = NULL;
1902         while (ln) {
1903                 ln->next = newdataadr(fd, ln->next);
1904                 if (ln->next != NULL && callback != NULL) {
1905                         callback(fd, ln->next);
1906                 }
1907                 ln->prev = prev;
1908                 prev = ln;
1909                 ln = ln->next;
1910         }
1911         lb->last = prev;
1912 }
1913
1914 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1915 {
1916         link_list_ex(fd, lb, NULL);
1917 }
1918
1919 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1920 {
1921         Link *ln, *prev;
1922         void *poin;
1923
1924         if (BLI_listbase_is_empty(lb)) return;
1925         poin = newdataadr(fd, lb->first);
1926         if (lb->first) {
1927                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1928         }
1929         lb->first = poin;
1930         
1931         ln = lb->first;
1932         prev = NULL;
1933         while (ln) {
1934                 poin = newdataadr(fd, ln->next);
1935                 if (ln->next) {
1936                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1937                 }
1938                 ln->next = poin;
1939                 ln->prev = prev;
1940                 prev = ln;
1941                 ln = ln->next;
1942         }
1943         lb->last = prev;
1944 }
1945
1946 static void test_pointer_array(FileData *fd, void **mat)
1947 {
1948         int64_t *lpoin, *lmat;
1949         int *ipoin, *imat;
1950         size_t len;
1951
1952                 /* manually convert the pointer array in
1953                  * the old dna format to a pointer array in
1954                  * the new dna format.
1955                  */
1956         if (*mat) {
1957                 len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1958                         
1959                 if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1960                         ipoin=imat= MEM_mallocN(len * 4, "newmatar");
1961                         lpoin= *mat;
1962                         
1963                         while (len-- > 0) {
1964                                 if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1965                                         BLI_endian_switch_int64(lpoin);
1966                                 *ipoin = (int)((*lpoin) >> 3);
1967                                 ipoin++;
1968                                 lpoin++;
1969                         }
1970                         MEM_freeN(*mat);
1971                         *mat = imat;
1972                 }
1973                 
1974                 if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1975                         lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
1976                         ipoin = *mat;
1977                         
1978                         while (len-- > 0) {
1979                                 *lpoin = *ipoin;
1980                                 ipoin++;
1981                                 lpoin++;
1982                         }
1983                         MEM_freeN(*mat);
1984                         *mat= lmat;
1985                 }
1986         }
1987 }
1988
1989 /* ************ READ ID Properties *************** */
1990
1991 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1992 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1993
1994 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1995 {
1996         IDProperty *array;
1997         int i;
1998         
1999         /* since we didn't save the extra buffer, set totallen to len */
2000         prop->totallen = prop->len;
2001         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2002
2003         array = (IDProperty *)prop->data.pointer;
2004         
2005         /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
2006          * theres not really anything we can do to correct this, at least don't crash */
2007         if (array == NULL) {
2008                 prop->len = 0;
2009                 prop->totallen = 0;
2010         }
2011         
2012         
2013         for (i = 0; i < prop->len; i++)
2014                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
2015 }
2016
2017 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
2018 {
2019         IDProperty **array;
2020         int i;
2021         
2022         /* since we didn't save the extra buffer, set totallen to len */
2023         prop->totallen = prop->len;
2024         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2025         
2026         if (prop->subtype == IDP_GROUP) {
2027                 test_pointer_array(fd, prop->data.pointer);
2028                 array = prop->data.pointer;
2029                 
2030                 for (i = 0; i < prop->len; i++)
2031                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
2032         }
2033         else if (prop->subtype == IDP_DOUBLE) {
2034                 if (switch_endian) {
2035                         BLI_endian_switch_double_array(prop->data.pointer, prop->len);
2036                 }
2037         }
2038         else {
2039                 if (switch_endian) {
2040                         /* also used for floats */
2041                         BLI_endian_switch_int32_array(prop->data.pointer, prop->len);
2042                 }
2043         }
2044 }
2045
2046 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
2047 {
2048         /*since we didn't save the extra string buffer, set totallen to len.*/
2049         prop->totallen = prop->len;
2050         prop->data.pointer = newdataadr(fd, prop->data.pointer);
2051 }
2052
2053 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
2054 {
2055         ListBase *lb = &prop->data.group;
2056         IDProperty *loop;
2057         
2058         link_list(fd, lb);
2059         
2060         /*Link child id properties now*/
2061         for (loop=prop->data.group.first; loop; loop=loop->next) {
2062                 IDP_DirectLinkProperty(loop, switch_endian, fd);
2063         }
2064 }
2065
2066 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
2067 {
2068         switch (prop->type) {
2069                 case IDP_GROUP:
2070                         IDP_DirectLinkGroup(prop, switch_endian, fd);
2071                         break;
2072                 case IDP_STRING:
2073                         IDP_DirectLinkString(prop, fd);
2074                         break;
2075                 case IDP_ARRAY:
2076                         IDP_DirectLinkArray(prop, switch_endian, fd);
2077                         break;
2078                 case IDP_IDPARRAY:
2079                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
2080                         break;
2081                 case IDP_DOUBLE:
2082                         /* erg, stupid doubles.  since I'm storing them
2083                          * in the same field as int val; val2 in the
2084                          * IDPropertyData struct, they have to deal with
2085                          * endianness specifically
2086                          *
2087                          * in theory, val and val2 would've already been swapped
2088                          * if switch_endian is true, so we have to first unswap
2089                          * them then reswap them as a single 64-bit entity.
2090                          */
2091                         
2092                         if (switch_endian) {
2093                                 BLI_endian_switch_int32(&prop->data.val);
2094                                 BLI_endian_switch_int32(&prop->data.val2);
2095                                 BLI_endian_switch_int64((int64_t *)&prop->data.val);
2096                         }
2097                         
2098                         break;
2099         }
2100 }
2101
2102 #define IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd) \
2103        _IDP_DirectLinkGroup_OrFree(prop, switch_endian, fd, __func__)
2104
2105 static void _IDP_DirectLinkGroup_OrFree(IDProperty **prop, int switch_endian, FileData *fd,
2106                                         const char *caller_func_id)
2107 {
2108         if (*prop) {
2109                 if ((*prop)->type == IDP_GROUP) {
2110                         IDP_DirectLinkGroup(*prop, switch_endian, fd);
2111                 }
2112                 else {
2113                         /* corrupt file! */
2114                         printf("%s: found non group data, freeing type %d!\n",
2115                                caller_func_id, (*prop)->type);
2116                         /* don't risk id, data's likely corrupt. */
2117                         // IDP_FreeProperty(*prop);
2118                         *prop = NULL;
2119                 }
2120         }
2121 }
2122
2123 /* stub function */
2124 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
2125 {
2126         /* Should we do something here, prop should be ensured to be non-NULL first... */
2127 }
2128
2129 /* ************ READ IMAGE PREVIEW *************** */
2130
2131 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
2132 {
2133         PreviewImage *prv = newdataadr(fd, old_prv);
2134         
2135         if (prv) {
2136                 int i;
2137                 for (i = 0; i < NUM_ICON_SIZES; ++i) {
2138                         if (prv->rect[i]) {
2139                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
2140                         }
2141                         prv->gputexture[i] = NULL;
2142                 }
2143         }
2144         
2145         return prv;
2146 }
2147
2148 /* ************ READ ID *************** */
2149
2150 static void direct_link_id(FileData *fd, ID *id)
2151 {
2152         /*link direct data of ID properties*/
2153         if (id->properties) {
2154                 id->properties = newdataadr(fd, id->properties);
2155                 /* this case means the data was written incorrectly, it should not happen */
2156                 IDP_DirectLinkGroup_OrFree(&id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2157         }
2158 }
2159
2160 /* ************ READ CurveMapping *************** */
2161
2162 /* cuma itself has been read! */
2163 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
2164 {
2165         int a;
2166         
2167         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
2168         cumap->flag &= ~CUMA_PREMULLED;
2169         
2170         for (a = 0; a < CM_TOT; a++) {
2171                 cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve);
2172                 cumap->cm[a].table = NULL;
2173                 cumap->cm[a].premultable = NULL;
2174         }
2175 }
2176
2177 /* ************ READ Brush *************** */
2178 /* library brush linking after fileread */
2179 static void lib_link_brush(FileData *fd, Main *main)
2180 {
2181         Brush *brush;
2182         
2183         /* only link ID pointers */
2184         for (brush = main->brush.first; brush; brush = brush->id.next) {
2185                 if (brush->id.tag & LIB_TAG_NEED_LINK) {
2186                         brush->id.tag &= ~LIB_TAG_NEED_LINK;
2187                         
2188                         /* brush->(mask_)mtex.obj is ignored on purpose? */
2189                         brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
2190                         brush->mask_mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mask_mtex.tex);
2191                         brush->clone.image = newlibadr(fd, brush->id.lib, brush->clone.image);
2192                         brush->toggle_brush = newlibadr(fd, brush->id.lib, brush->toggle_brush);
2193                         brush->paint_curve = newlibadr_us(fd, brush->id.lib, brush->paint_curve);
2194                 }
2195         }
2196 }
2197
2198 static void direct_link_brush(FileData *fd, Brush *brush)
2199 {
2200         /* brush itself has been read */
2201
2202         /* fallof curve */
2203         brush->curve = newdataadr(fd, brush->curve);
2204         brush->gradient = newdataadr(fd, brush->gradient);
2205
2206         if (brush->curve)
2207                 direct_link_curvemapping(fd, brush->curve);
2208         else
2209                 BKE_brush_curve_preset(brush, CURVE_PRESET_SHARP);
2210
2211         brush->preview = NULL;
2212         brush->icon_imbuf = NULL;
2213 }
2214
2215 /* ************ READ Palette *************** */
2216 static void lib_link_palette(FileData *UNUSED(fd), Main *main)
2217 {
2218         Palette *palette;
2219
2220         /* only link ID pointers */
2221         for (palette = main->palettes.first; palette; palette = palette->id.next) {
2222                 if (palette->id.tag & LIB_TAG_NEED_LINK) {
2223                         palette->id.tag &= ~LIB_TAG_NEED_LINK;
2224                 }
2225         }
2226 }
2227
2228 static void direct_link_palette(FileData *fd, Palette *palette)
2229 {
2230         /* palette itself has been read */
2231         link_list(fd, &palette->colors);
2232 }
2233
2234 static void lib_link_paint_curve(FileData *UNUSED(fd), Main *main)
2235 {
2236         PaintCurve *pc;
2237
2238         /* only link ID pointers */
2239         for (pc = main->paintcurves.first; pc; pc = pc->id.next) {
2240                 if (pc->id.tag & LIB_TAG_NEED_LINK) {
2241                         pc->id.tag &= ~LIB_TAG_NEED_LINK;
2242                 }
2243         }
2244 }
2245
2246 static void direct_link_paint_curve(FileData *fd, PaintCurve *pc)
2247 {
2248         pc->points = newdataadr(fd, pc->points);
2249 }
2250
2251 /* ************ READ PACKEDFILE *************** */
2252
2253 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
2254 {
2255         PackedFile *pf = newpackedadr(fd, oldpf);
2256
2257         if (pf) {
2258                 pf->data = newpackedadr(fd, pf->data);
2259         }
2260         
2261         return pf;
2262 }
2263
2264 /* ************ READ ANIMATION STUFF ***************** */
2265
2266 /* Legacy Data Support (for Version Patching) ----------------------------- */
2267
2268 // XXX deprecated - old animation system
2269 static void lib_link_ipo(FileData *fd, Main *main)
2270 {
2271         Ipo *ipo;
2272         
2273         for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) {
2274                 if (ipo->id.tag & LIB_TAG_NEED_LINK) {
2275                         IpoCurve *icu;
2276                         for (icu = ipo->curve.first; icu; icu = icu->next) {
2277                                 if (icu->driver)
2278                                         icu->driver->ob = newlibadr(fd, ipo->id.lib, icu->driver->ob);
2279                         }
2280                         ipo->id.tag &= ~LIB_TAG_NEED_LINK;
2281                 }
2282         }
2283 }
2284
2285 // XXX deprecated - old animation system
2286 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2287 {
2288         IpoCurve *icu;
2289
2290         link_list(fd, &(ipo->curve));
2291         
2292         for (icu = ipo->curve.first; icu; icu = icu->next) {
2293                 icu->bezt = newdataadr(fd, icu->bezt);
2294                 icu->bp = newdataadr(fd, icu->bp);
2295                 icu->driver = newdataadr(fd, icu->driver);
2296         }
2297 }
2298
2299 // XXX deprecated - old animation system
2300 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
2301 {
2302         bActionStrip *strip;
2303         bActionModifier *amod;
2304         
2305         for (strip=striplist->first; strip; strip=strip->next) {
2306                 strip->object = newlibadr(fd, id->lib, strip->object);
2307                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2308                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
2309                 for (amod = strip->modifiers.first; amod; amod = amod->next)
2310                         amod->ob = newlibadr(fd, id->lib, amod->ob);
2311         }
2312 }
2313
2314 // XXX deprecated - old animation system
2315 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
2316 {
2317         bActionStrip *strip;
2318         
2319         link_list(fd, strips);
2320         
2321         for (strip = strips->first; strip; strip = strip->next)
2322                 link_list(fd, &strip->modifiers);
2323 }
2324
2325 // XXX deprecated - old animation system
2326 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
2327 {
2328         bConstraintChannel *chan;
2329
2330         for (chan=chanbase->first; chan; chan=chan->next) {
2331                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
2332         }
2333 }
2334
2335 /* Data Linking ----------------------------- */
2336
2337 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
2338 {
2339         FModifier *fcm;
2340         
2341         for (fcm = list->first; fcm; fcm = fcm->next) {
2342                 /* data for specific modifiers */
2343                 switch (fcm->type) {
2344                         case FMODIFIER_TYPE_PYTHON:
2345                         {
2346                                 FMod_Python *data = (FMod_Python *)fcm->data;
2347                                 data->script = newlibadr(fd, id->lib, data->script);
2348
2349                                 break;
2350                         }
2351                 }
2352         }
2353 }
2354
2355 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
2356 {
2357         FCurve *fcu;
2358         
2359         if (list == NULL)
2360                 return;
2361         
2362         /* relink ID-block references... */
2363         for (fcu = list->first; fcu; fcu = fcu->next) {
2364                 /* driver data */
2365                 if (fcu->driver) {
2366                         ChannelDriver *driver = fcu->driver;
2367                         DriverVar *dvar;
2368                         
2369                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2370                                 DRIVER_TARGETS_LOOPER(dvar)
2371                                 {
2372                                         /* only relink if still used */
2373                                         if (tarIndex < dvar->num_targets)
2374                                                 dtar->id = newlibadr(fd, id->lib, dtar->id); 
2375                                         else
2376                                                 dtar->id = NULL;
2377                                 }
2378                                 DRIVER_TARGETS_LOOPER_END
2379                         }
2380                 }
2381                 
2382                 /* modifiers */
2383                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
2384         }
2385 }
2386
2387
2388 /* NOTE: this assumes that link_list has already been called on the list */
2389 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
2390 {
2391         FModifier *fcm;
2392         
2393         for (fcm = list->first; fcm; fcm = fcm->next) {
2394                 /* relink general data */
2395                 fcm->data  = newdataadr(fd, fcm->data);
2396                 
2397                 /* do relinking of data for specific types */
2398                 switch (fcm->type) {
2399                         case FMODIFIER_TYPE_GENERATOR:
2400                         {
2401                                 FMod_Generator *data = (FMod_Generator *)fcm->data;
2402                                 
2403                                 data->coefficients = newdataadr(fd, data->coefficients);
2404                                 
2405                                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2406                                         BLI_endian_switch_float_array(data->coefficients, data->arraysize);
2407                                 }
2408
2409                                 break;
2410                         }
2411                         case FMODIFIER_TYPE_ENVELOPE:
2412                         {
2413                                 FMod_Envelope *data=  (FMod_Envelope *)fcm->data;
2414                                 
2415                                 data->data= newdataadr(fd, data->data);
2416
2417                                 break;
2418                         }
2419                         case FMODIFIER_TYPE_PYTHON:
2420                         {
2421                                 FMod_Python *data = (FMod_Python *)fcm->data;
2422                                 
2423                                 data->prop = newdataadr(fd, data->prop);
2424                                 IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2425
2426                                 break;
2427                         }
2428                 }
2429         }
2430 }
2431
2432 /* NOTE: this assumes that link_list has already been called on the list */
2433 static void direct_link_fcurves(FileData *fd, ListBase *list)
2434 {
2435         FCurve *fcu;
2436         
2437         /* link F-Curve data to F-Curve again (non ID-libs) */
2438         for (fcu = list->first; fcu; fcu = fcu->next) {
2439                 /* curve data */
2440                 fcu->bezt = newdataadr(fd, fcu->bezt);
2441                 fcu->fpt = newdataadr(fd, fcu->fpt);
2442                 
2443                 /* rna path */
2444                 fcu->rna_path = newdataadr(fd, fcu->rna_path);
2445                 
2446                 /* group */
2447                 fcu->grp = newdataadr_ex(fd, fcu->grp, false);
2448                 
2449                 /* clear disabled flag - allows disabled drivers to be tried again ([#32155]),
2450                  * but also means that another method for "reviving disabled F-Curves" exists
2451                  */
2452                 fcu->flag &= ~FCURVE_DISABLED;
2453                 
2454                 /* driver */
2455                 fcu->driver= newdataadr(fd, fcu->driver);
2456                 if (fcu->driver) {
2457                         ChannelDriver *driver= fcu->driver;
2458                         DriverVar *dvar;
2459                         
2460                         /* compiled expression data will need to be regenerated (old pointer may still be set here) */
2461                         driver->expr_comp = NULL;
2462                         
2463                         /* give the driver a fresh chance - the operating environment may be different now 
2464                          * (addons, etc. may be different) so the driver namespace may be sane now [#32155]
2465                          */
2466                         driver->flag &= ~DRIVER_FLAG_INVALID;
2467                         
2468                         /* relink variables, targets and their paths */
2469                         link_list(fd, &driver->variables);
2470                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
2471                                 DRIVER_TARGETS_LOOPER(dvar)
2472                                 {
2473                                         /* only relink the targets being used */
2474                                         if (tarIndex < dvar->num_targets)
2475                                                 dtar->rna_path = newdataadr(fd, dtar->rna_path);
2476                                         else
2477                                                 dtar->rna_path = NULL;
2478                                 }
2479                                 DRIVER_TARGETS_LOOPER_END
2480                         }
2481                 }
2482                 
2483                 /* modifiers */
2484                 link_list(fd, &fcu->modifiers);
2485                 direct_link_fmodifiers(fd, &fcu->modifiers);
2486         }
2487 }
2488
2489
2490 static void lib_link_action(FileData *fd, Main *main)
2491 {
2492         bAction *act;
2493         bActionChannel *chan;
2494
2495         for (act = main->action.first; act; act = act->id.next) {
2496                 if (act->id.tag & LIB_TAG_NEED_LINK) {
2497                         act->id.tag &= ~LIB_TAG_NEED_LINK;
2498                         
2499 // XXX deprecated - old animation system <<<
2500                         for (chan=act->chanbase.first; chan; chan=chan->next) {
2501                                 chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
2502                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
2503                         }
2504 // >>> XXX deprecated - old animation system
2505                         
2506                         lib_link_fcurves(fd, &act->id, &act->curves);
2507                 }
2508         }
2509 }
2510
2511 static void direct_link_action(FileData *fd, bAction *act)
2512 {
2513         bActionChannel *achan; // XXX deprecated - old animation system
2514         bActionGroup *agrp;
2515
2516         link_list(fd, &act->curves);
2517         link_list(fd, &act->chanbase); // XXX deprecated - old animation system
2518         link_list(fd, &act->groups);
2519         link_list(fd, &act->markers);
2520
2521 // XXX deprecated - old animation system <<<
2522         for (achan = act->chanbase.first; achan; achan=achan->next) {
2523                 achan->grp = newdataadr(fd, achan->grp);
2524                 
2525                 link_list(fd, &achan->constraintChannels);
2526         }
2527 // >>> XXX deprecated - old animation system
2528
2529         direct_link_fcurves(fd, &act->curves);
2530         
2531         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
2532                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
2533                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
2534         }
2535 }
2536
2537 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
2538 {
2539         NlaStrip *strip;
2540         
2541         for (strip = list->first; strip; strip = strip->next) {
2542                 /* check strip's children */
2543                 lib_link_nladata_strips(fd, id, &strip->strips);
2544                 
2545                 /* check strip's F-Curves */
2546                 lib_link_fcurves(fd, id, &strip->fcurves);
2547                 
2548                 /* reassign the counted-reference to action */
2549                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2550                 
2551                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
2552                 if ((strip->act) && (strip->act->idroot == 0))
2553                         strip->act->idroot = GS(id->name);
2554         }
2555 }
2556
2557 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
2558 {
2559         NlaTrack *nlt;
2560         
2561         /* we only care about the NLA strips inside the tracks */
2562         for (nlt = list->first; nlt; nlt = nlt->next) {
2563                 lib_link_nladata_strips(fd, id, &nlt->strips);
2564         }
2565 }
2566
2567 /* This handles Animato NLA-Strips linking 
2568  * NOTE: this assumes that link_list has already been called on the list 
2569  */
2570 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
2571 {
2572         NlaStrip *strip;
2573         
2574         for (strip = list->first; strip; strip = strip->next) {
2575                 /* strip's child strips */
2576                 link_list(fd, &strip->strips);
2577                 direct_link_nladata_strips(fd, &strip->strips);
2578                 
2579                 /* strip's F-Curves */
2580                 link_list(fd, &strip->fcurves);
2581                 direct_link_fcurves(fd, &strip->fcurves);
2582                 
2583                 /* strip's F-Modifiers */
2584                 link_list(fd, &strip->modifiers);
2585                 direct_link_fmodifiers(fd, &strip->modifiers);
2586         }
2587 }
2588
2589 /* NOTE: this assumes that link_list has already been called on the list */
2590 static void direct_link_nladata(FileData *fd, ListBase *list)
2591 {
2592         NlaTrack *nlt;
2593         
2594         for (nlt = list->first; nlt; nlt = nlt->next) {
2595                 /* relink list of strips */
2596                 link_list(fd, &nlt->strips);
2597                 
2598                 /* relink strip data */
2599                 direct_link_nladata_strips(fd, &nlt->strips);
2600         }
2601 }
2602
2603 /* ------- */
2604
2605 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
2606 {
2607         KeyingSet *ks;
2608         KS_Path *ksp;
2609         
2610         /* here, we're only interested in the ID pointer stored in some of the paths */
2611         for (ks = list->first; ks; ks = ks->next) {
2612                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2613                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
2614                 }
2615         }
2616 }
2617
2618 /* NOTE: this assumes that link_list has already been called on the list */
2619 static void direct_link_keyingsets(FileData *fd, ListBase *list)
2620 {
2621         KeyingSet *ks;
2622         KS_Path *ksp;
2623         
2624         /* link KeyingSet data to KeyingSet again (non ID-libs) */
2625         for (ks = list->first; ks; ks = ks->next) {
2626                 /* paths */
2627                 link_list(fd, &ks->paths);
2628                 
2629                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2630                         /* rna path */
2631                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
2632                 }
2633         }
2634 }
2635
2636 /* ------- */
2637
2638 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
2639 {
2640         if (adt == NULL)
2641                 return;
2642         
2643         /* link action data */
2644         adt->action= newlibadr_us(fd, id->lib, adt->action);
2645         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
2646         
2647         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
2648         if ((adt->action) && (adt->action->idroot == 0))
2649                 adt->action->idroot = GS(id->name);
2650         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
2651                 adt->tmpact->idroot = GS(id->name);
2652         
2653         /* link drivers */
2654         lib_link_fcurves(fd, id, &adt->drivers);
2655         
2656         /* overrides don't have lib-link for now, so no need to do anything */
2657         
2658         /* link NLA-data */
2659         lib_link_nladata(fd, id, &adt->nla_tracks);
2660 }
2661
2662 static void direct_link_animdata(FileData *fd, AnimData *adt)
2663 {
2664         /* NOTE: must have called newdataadr already before doing this... */
2665         if (adt == NULL)
2666                 return;
2667         
2668         /* link drivers */
2669         link_list(fd, &adt->drivers);
2670         direct_link_fcurves(fd, &adt->drivers);
2671         
2672         /* link overrides */
2673         // TODO...
2674         
2675         /* link NLA-data */
2676         link_list(fd, &adt->nla_tracks);
2677         direct_link_nladata(fd, &adt->nla_tracks);
2678         
2679         /* relink active track/strip - even though strictly speaking this should only be used
2680          * if we're in 'tweaking mode', we need to be able to have this loaded back for
2681          * undo, but also since users may not exit tweakmode before saving (#24535)
2682          */
2683         // TODO: it's not really nice that anyone should be able to save the file in this
2684         //              state, but it's going to be too hard to enforce this single case...
2685         adt->act_track = newdataadr(fd, adt->act_track);
2686         adt->actstrip = newdataadr(fd, adt->actstrip);
2687 }       
2688
2689 /* ************ READ MOTION PATHS *************** */
2690
2691 /* direct data for cache */
2692 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2693 {
2694         /* sanity check */
2695         if (mpath == NULL)
2696                 return;
2697         
2698         /* relink points cache */
2699         mpath->points = newdataadr(fd, mpath->points);
2700 }
2701
2702 /* ************ READ NODE TREE *************** */
2703
2704 static void lib_link_node_socket(FileData *fd, ID *UNUSED(id), bNodeSocket *sock)
2705 {
2706         /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2707          * of library blocks that implement this.*/
2708         IDP_LibLinkProperty(sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2709 }
2710
2711 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2712 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2713 {
2714         bNode *node;
2715         bNodeSocket *sock;
2716         
2717         lib_link_animdata(fd, &ntree->id, ntree->adt);
2718         
2719         ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
2720         
2721         for (node = ntree->nodes.first; node; node = node->next) {
2722                 /* Link ID Properties -- and copy this comment EXACTLY for easy finding
2723                  * of library blocks that implement this.*/
2724                 IDP_LibLinkProperty(node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2725                 
2726                 node->id= newlibadr_us(fd, id->lib, node->id);
2727
2728                 for (sock = node->inputs.first; sock; sock = sock->next)
2729                         lib_link_node_socket(fd, id, sock);
2730                 for (sock = node->outputs.first; sock; sock = sock->next)
2731                         lib_link_node_socket(fd, id, sock);
2732         }
2733         
2734         for (sock = ntree->inputs.first; sock; sock = sock->next)
2735                 lib_link_node_socket(fd, id, sock);
2736         for (sock = ntree->outputs.first; sock; sock = sock->next)
2737                 lib_link_node_socket(fd, id, sock);
2738 }
2739
2740 /* library ntree linking after fileread */
2741 static void lib_link_nodetree(FileData *fd, Main *main)
2742 {
2743         bNodeTree *ntree;
2744         
2745         /* only link ID pointers */
2746         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2747                 if (ntree->id.tag & LIB_TAG_NEED_LINK) {
2748                         ntree->id.tag &= ~LIB_TAG_NEED_LINK;
2749                         lib_link_ntree(fd, &ntree->id, ntree);
2750                 }
2751         }
2752 }
2753
2754 /* get node tree stored locally in other IDs */
2755 static bNodeTree *nodetree_from_id(ID *id)
2756 {
2757         if (!id)
2758                 return NULL;
2759         switch (GS(id->name)) {
2760                 case ID_SCE: return ((Scene *)id)->nodetree;
2761                 case ID_MA: return ((Material *)id)->nodetree;
2762                 case ID_WO: return ((World *)id)->nodetree;
2763                 case ID_LA: return ((Lamp *)id)->nodetree;
2764                 case ID_TE: return ((Tex *)id)->nodetree;
2765                 case ID_LS: return ((FreestyleLineStyle *)id)->nodetree;
2766         }
2767         return NULL;
2768 }
2769
2770 /* updates group node socket identifier so that
2771  * external links to/from the group node are preserved.
2772  */
2773 static void lib_node_do_versions_group_indices(bNode *gnode)
2774 {
2775         bNodeTree *ngroup = (bNodeTree*)gnode->id;
2776         bNodeSocket *sock;
2777         bNodeLink *link;
2778         
2779         for (sock=gnode->outputs.first; sock; sock = sock->next) {
2780                 int old_index = sock->to_index;
2781                 
2782                 for (link = ngroup->links.first; link; link = link->next) {
2783                         if (link->tonode == NULL && link->fromsock->own_index == old_index) {
2784                                 strcpy(sock->identifier, link->fromsock->identifier);
2785                                 /* deprecated */
2786                                 sock->own_index = link->fromsock->own_index;
2787                                 sock->to_index = 0;
2788                                 sock->groupsock = NULL;
2789                         }
2790                 }
2791         }
2792         for (sock=gnode->inputs.first; sock; sock = sock->next) {
2793                 int old_index = sock->to_index;
2794                 
2795                 for (link = ngroup->links.first; link; link = link->next) {
2796                         if (link->fromnode == NULL && link->tosock->own_index == old_index) {
2797                                 strcpy(sock->identifier, link->tosock->identifier);
2798                                 /* deprecated */
2799                                 sock->own_index = link->tosock->own_index;
2800                                 sock->to_index = 0;
2801                                 sock->groupsock = NULL;
2802                         }
2803                 }
2804         }
2805 }
2806
2807 /* verify types for nodes and groups, all data has to be read */
2808 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2809  * typedefs */
2810 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2811 {
2812         /* this crashes blender on undo/redo */
2813 #if 0
2814                 if (open == 1) {
2815                         reinit_nodesystem();
2816                 }
2817 #endif
2818         
2819         /* set node->typeinfo pointers */
2820         FOREACH_NODETREE(main, ntree, id) {
2821                 ntreeSetTypes(NULL, ntree);
2822         } FOREACH_NODETREE_END
2823         
2824         /* verify static socket templates */
2825         FOREACH_NODETREE(main, ntree, id) {
2826                 bNode *node;
2827                 for (node=ntree->nodes.first; node; node=node->next)
2828                         node_verify_socket_templates(ntree, node);
2829         } FOREACH_NODETREE_END
2830         
2831         {
2832                 bool has_old_groups = false;
2833                 /* XXX this should actually be part of do_versions, but since we need
2834                  * finished library linking, it is not possible there. Instead in do_versions
2835                  * we have set the NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2 flag, so at this point we can do the
2836                  * actual group node updates.
2837                  */
2838                 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2839                         if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2) {
2840                                 has_old_groups = 1;
2841                         }
2842                 }
2843                 
2844                 if (has_old_groups) {
2845                         FOREACH_NODETREE(main, ntree, id) {
2846                                 /* updates external links for all group nodes in a tree */
2847                                 bNode *node;
2848                                 for (node = ntree->nodes.first; node; node = node->next) {
2849                                         if (node->type == NODE_GROUP) {
2850                                                 bNodeTree *ngroup = (bNodeTree*)node->id;
2851                                                 if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2))
2852                                                         lib_node_do_versions_group_indices(node);
2853                                         }
2854                                 }
2855                         } FOREACH_NODETREE_END
2856                 }
2857                 
2858                 for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2859                         ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2;
2860                 }
2861         }
2862         
2863         {
2864                 /* Convert the previously used ntree->inputs/ntree->outputs lists to interface nodes.
2865                  * Pre 2.56.2 node trees automatically have all unlinked sockets exposed already
2866                  * (see NTREE_DO_VERSIONS_GROUP_EXPOSE_2_56_2).
2867                  *
2868                  * XXX this should actually be part of do_versions,
2869                  * but needs valid typeinfo pointers to create interface nodes.
2870                  *
2871                  * Note: theoretically only needed in node groups (main->nodetree),
2872                  * but due to a temporary bug such links could have been added in all trees,
2873                  * so have to clean up all of them ...
2874                  */
2875                 
2876                 FOREACH_NODETREE(main, ntree, id) {
2877                         if (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP) {
2878                                 bNode *input_node = NULL, *output_node = NULL;
2879                                 int num_inputs = 0, num_outputs = 0;
2880                                 bNodeLink *link, *next_link;
2881                                 /* Only create new interface nodes for actual older files.
2882                                  * New file versions already have input/output nodes with duplicate links,
2883                                  * in that case just remove the invalid links.
2884                                  */
2885                                 const bool create_io_nodes = (ntree->flag & NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE) != 0;
2886                                 
2887                                 float input_locx = 1000000.0f, input_locy = 0.0f;
2888                                 float output_locx = -1000000.0f, output_locy = 0.0f;
2889                                 /* rough guess, not nice but we don't have access to UI constants here ... */
2890                                 static const float offsetx = 42 + 3*20 + 20;
2891                                 /*static const float offsety = 0.0f;*/
2892                                 
2893                                 if (create_io_nodes) {
2894                                         if (ntree->inputs.first)
2895                                                 input_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_INPUT);
2896                                         
2897                                         if (ntree->outputs.first)
2898                                                 output_node = nodeAddStaticNode(NULL, ntree, NODE_GROUP_OUTPUT);
2899                                 }
2900                                 
2901                                 /* Redirect links from/to the node tree interface to input/output node.
2902                                  * If the fromnode/tonode pointers are NULL, this means a link from/to
2903                                  * the ntree interface sockets, which need to be redirected to new interface nodes.
2904                                  */
2905                                 for (link = ntree->links.first; link; link = next_link) {
2906                                         bool free_link = false;
2907                                         next_link = link->next;
2908                                         
2909                                         if (link->fromnode == NULL) {
2910                                                 if (input_node) {
2911                                                         link->fromnode = input_node;
2912                                                         link->fromsock = node_group_input_find_socket(input_node, link->fromsock->identifier);
2913                                                         ++num_inputs;
2914                                                         
2915                                                         if (link->tonode) {
2916                                                                 if (input_locx > link->tonode->locx - offsetx)
2917                                                                         input_locx = link->tonode->locx - offsetx;
2918                                                                 input_locy += link->tonode->locy;
2919                                                         }
2920                                                 }
2921                                                 else {
2922                                                         free_link = true;
2923                                                 }
2924                                         }
2925                                         
2926                                         if (link->tonode == NULL) {
2927                                                 if (output_node) {
2928                                                         link->tonode = output_node;
2929                                                         link->tosock = node_group_output_find_socket(output_node, link->tosock->identifier);
2930                                                         ++num_outputs;
2931                                                         
2932                                                         if (link->fromnode) {
2933                                                                 if (output_locx < link->fromnode->locx + offsetx)
2934                                                                         output_locx = link->fromnode->locx + offsetx;
2935                                                                 output_locy += link->fromnode->locy;
2936                                                         }
2937                                                 }
2938                                                 else {
2939                                                         free_link = true;
2940                                                 }
2941                                         }
2942                                         
2943                                         if (free_link)
2944                                                 nodeRemLink(ntree, link);
2945                                 }
2946                                 
2947                                 if (num_inputs > 0) {
2948                                         input_locy /= num_inputs;
2949                                         input_node->locx = input_locx;
2950                                         input_node->locy = input_locy;
2951                                 }
2952                                 if (num_outputs > 0) {
2953                                         output_locy /= num_outputs;
2954                                         output_node->locx = output_locx;
2955                                         output_node->locy = output_locy;
2956                                 }
2957                                 
2958                                 /* clear do_versions flags */
2959                                 ntree->flag &= ~(NTREE_DO_VERSIONS_CUSTOMNODES_GROUP | NTREE_DO_VERSIONS_CUSTOMNODES_GROUP_CREATE_INTERFACE);
2960                         }
2961                 }
2962                 FOREACH_NODETREE_END
2963         }
2964         
2965         /* verify all group user nodes */
2966         for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2967                 ntreeVerifyNodes(main, &ntree->id);
2968         }
2969         
2970         /* make update calls where necessary */
2971         {
2972                 FOREACH_NODETREE(main, ntree, id) {
2973                         /* make an update call for the tree */
2974                         ntreeUpdateTree(main, ntree);
2975                 } FOREACH_NODETREE_END
2976         }
2977 }
2978
2979 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
2980 {
2981         sock->prop = newdataadr(fd, sock->prop);
2982         IDP_DirectLinkGroup_OrFree(&sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2983         
2984         sock->link = newdataadr(fd, sock->link);
2985         sock->typeinfo = NULL;
2986         sock->storage = newdataadr(fd, sock->storage);
2987         sock->default_value = newdataadr(fd, sock->default_value);
2988         sock->cache = NULL;
2989 }
2990
2991 /* ntree itself has been read! */
2992 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2993 {
2994         /* note: writing and reading goes in sync, for speed */
2995         bNode *node;
2996         bNodeSocket *sock;
2997         bNodeLink *link;
2998         
2999         ntree->init = 0;                /* to set callbacks and force setting types */
3000         ntree->is_updating = false;
3001         ntree->typeinfo= NULL;
3002         ntree->interface_type = NULL;
3003         
3004         ntree->progress = NULL;
3005         ntree->execdata = NULL;
3006         ntree->duplilock = NULL;
3007
3008         ntree->adt = newdataadr(fd, ntree->adt);
3009         direct_link_animdata(fd, ntree->adt);
3010         
3011         ntree->id.tag &= ~(LIB_TAG_ID_RECALC|LIB_TAG_ID_RECALC_DATA);
3012
3013         link_list(fd, &ntree->nodes);
3014         for (node = ntree->nodes.first; node; node = node->next) {
3015                 node->typeinfo = NULL;
3016                 
3017                 link_list(fd, &node->inputs);
3018                 link_list(fd, &node->outputs);
3019                 
3020                 node->prop = newdataadr(fd, node->prop);
3021                 IDP_DirectLinkGroup_OrFree(&node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3022                 
3023                 link_list(fd, &node->internal_links);
3024                 for (link = node->internal_links.first; link; link = link->next) {
3025                         link->fromnode = newdataadr(fd, link->fromnode);
3026                         link->fromsock = newdataadr(fd, link->fromsock);
3027                         link->tonode = newdataadr(fd, link->tonode);
3028                         link->tosock = newdataadr(fd, link->tosock);
3029                 }
3030                 
3031                 if (node->type == CMP_NODE_MOVIEDISTORTION) {
3032                         node->storage = newmclipadr(fd, node->storage);
3033                 }
3034                 else {
3035                         node->storage = newdataadr(fd, node->storage);
3036                 }
3037                 
3038                 if (node->storage) {
3039                         /* could be handlerized at some point */
3040                         if (ntree->type==NTREE_SHADER) {
3041                                 if (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB) {
3042                                         direct_link_curvemapping(fd, node->storage);
3043                                 }
3044                                 else if (node->type==SH_NODE_SCRIPT) {
3045                                         NodeShaderScript *nss = (NodeShaderScript *) node->storage;
3046                                         nss->bytecode = newdataadr(fd, nss->bytecode);
3047                                 }
3048                                 else if (node->type==SH_NODE_TEX_POINTDENSITY) {
3049                                         NodeShaderTexPointDensity *npd = (NodeShaderTexPointDensity *) node->storage;
3050                                         memset(&npd->pd, 0, sizeof(npd->pd));
3051                                 }
3052                         }
3053                         else if (ntree->type==NTREE_COMPOSIT) {
3054                                 if (ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
3055                                         direct_link_curvemapping(fd, node->storage);
3056                                 else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
3057                                         ((ImageUser *)node->storage)->ok = 1;
3058                         }
3059                         else if ( ntree->type==NTREE_TEXTURE) {
3060                                 if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
3061                                         direct_link_curvemapping(fd, node->storage);
3062                                 else if (node->type==TEX_NODE_IMAGE)
3063                                         ((ImageUser *)node->storage)->ok = 1;
3064                         }
3065                 }
3066         }
3067         link_list(fd, &ntree->links);
3068         
3069         /* and we connect the rest */
3070         for (node = ntree->nodes.first; node; node = node->next) {
3071                 node->parent = newdataadr(fd, node->parent);
3072                 node->lasty = 0;
3073                 
3074                 for (sock = node->inputs.first; sock; sock = sock->next)
3075                         direct_link_node_socket(fd, sock);
3076                 for (sock = node->outputs.first; sock; sock = sock->next)
3077                         direct_link_node_socket(fd, sock);
3078         }
3079         
3080         /* interface socket lists */
3081         link_list(fd, &ntree->inputs);
3082         link_list(fd, &ntree->outputs);
3083         for (sock = ntree->inputs.first; sock; sock = sock->next)
3084                 direct_link_node_socket(fd, sock);
3085         for (sock = ntree->outputs.first; sock; sock = sock->next)
3086                 direct_link_node_socket(fd, sock);
3087         
3088         for (link = ntree->links.first; link; link= link->next) {
3089                 link->fromnode = newdataadr(fd, link->fromnode);
3090                 link->tonode = newdataadr(fd, link->tonode);
3091                 link->fromsock = newdataadr(fd, link->fromsock);
3092                 link->tosock = newdataadr(fd, link->tosock);
3093         }
3094         
3095 #if 0
3096         if (ntree->previews) {
3097                 bNodeInstanceHash *new_previews = BKE_node_instance_hash_new("node previews");
3098                 bNodeInstanceHashIterator iter;
3099                 
3100                 NODE_INSTANCE_HASH_ITER(iter, ntree->previews) {
3101                         bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
3102                         if (preview) {
3103                                 bNodePreview *new_preview = newimaadr(fd, preview);
3104                                 if (new_preview) {
3105                                         bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
3106                                         BKE_node_instance_hash_insert(new_previews, key, new_preview);
3107                                 }
3108                         }
3109                 }
3110                 BKE_node_instance_hash_free(ntree->previews, NULL);
3111                 ntree->previews = new_previews;
3112         }
3113 #else
3114         /* XXX TODO */
3115         ntree->previews = NULL;
3116 #endif
3117         
3118         /* type verification is in lib-link */
3119 }
3120
3121 /* ************ READ ARMATURE ***************** */
3122
3123 /* temp struct used to transport needed info to lib_link_constraint_cb() */
3124 typedef struct tConstraintLinkData {
3125         FileData *fd;
3126         ID *id;
3127 } tConstraintLinkData;
3128 /* callback function used to relink constraint ID-links */
3129 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, bool is_reference, void *userdata)
3130 {
3131         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
3132         
3133         /* for reference types, we need to increment the usercounts on load... */
3134         if (is_reference) {
3135                 /* reference type - with usercount */
3136                 *idpoin = newlibadr_us(cld->fd, cld->id->lib, *idpoin);
3137         }
3138         else {
3139                 /* target type - no usercount needed */
3140                 *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
3141         }
3142 }
3143
3144 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
3145 {
3146         tConstraintLinkData cld;
3147         bConstraint *con;
3148         
3149         /* legacy fixes */
3150         for (con = conlist->first; con; con=con->next) {
3151                 /* patch for error introduced by changing constraints (dunno how) */
3152                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
3153                 if (con->data == NULL) {
3154                         con->type = CONSTRAINT_TYPE_NULL;
3155                 }
3156                 /* own ipo, all constraints have it */
3157                 con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX deprecated - old animation system
3158         }
3159         
3160         /* relink all ID-blocks used by the constraints */
3161         cld.fd = fd;
3162         cld.id = id;
3163         
3164         BKE_constraints_id_loop(conlist, lib_link_constraint_cb, &cld);
3165 }
3166
3167 static void direct_link_constraints(FileData *fd, ListBase *lb)
3168 {
3169         bConstraint *con;
3170         
3171         link_list(fd, lb);
3172         for (con=lb->first; con; con=con->next) {
3173                 con->data = newdataadr(fd, con->data);
3174                 
3175                 switch (con->type) {
3176                         case CONSTRAINT_TYPE_PYTHON:
3177                         {
3178                                 bPythonConstraint *data= con->data;
3179                                 
3180                                 link_list(fd, &data->targets);
3181                                 
3182                                 data->prop = newdataadr(fd, data->prop);
3183                                 IDP_DirectLinkGroup_OrFree(&data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);