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