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