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