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