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