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