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