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