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