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