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