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