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