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