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