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