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