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