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