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