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