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