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