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