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