aff8c07c9907690788a9bfd1b6fdbaf7bc52305b
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include "zlib.h"
36
37 #ifdef WIN32
38 #include "winsock2.h"
39 #include "BLI_winstuff.h"
40 #endif
41
42 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
43 #include <stdlib.h> // for getenv atoi
44 #include <fcntl.h> // for open
45 #include <string.h> // for strrchr strncmp strstr
46 #include <math.h> // for fabs
47
48 #ifndef WIN32
49     #include <unistd.h> // for read close
50     #include <sys/param.h> // for MAXPATHLEN
51 #else
52     #include <io.h> // for open close read
53 #endif
54
55 #include "nla.h"
56
57 #include "DNA_action_types.h"
58 #include "DNA_armature_types.h"
59 #include "DNA_ID.h"
60 #include "DNA_actuator_types.h"
61 #include "DNA_camera_types.h"
62 #include "DNA_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) 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_group.h"
118 #include "BKE_property.h" // for get_property
119 #include "BKE_lattice.h"
120 #include "BKE_library.h" // for wich_libbase
121 #include "BKE_main.h" // for Main
122 #include "BKE_mesh.h" // for ME_ defines (patching)
123 #include "BKE_modifier.h"
124 #include "BKE_node.h" // for tree type defines
125 #include "BKE_object.h"
126 #include "BKE_sca.h" // for init_actuator
127 #include "BKE_scene.h"
128 #include "BKE_softbody.h"       // sbNew()
129 #include "BKE_texture.h" // for open_plugin_tex
130 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
131
132 #include "BIF_butspace.h" // for do_versions, patching event codes
133 #include "BIF_previewrender.h" // for struct RenderInfo
134 #include "BLO_readfile.h"
135 #include "BLO_undofile.h"
136 #include "BLO_readblenfile.h" // streaming read pipe, for BLO_readblenfile BLO_readblenfilememory
137
138 #include "readfile.h"
139
140 #include "genfile.h"
141
142 #include "mydevice.h"
143 #include "blendef.h"
144
145 #include <errno.h>
146
147 /*
148  Remark: still a weak point is the newadress() function, that doesnt solve reading from
149  multiple files at the same time
150
151  (added remark: oh, i thought that was solved? will look at that... (ton)
152
153 READ
154 - Existing Library (Main) push or free
155 - allocate new Main
156 - load file
157 - read SDNA
158 - for each LibBlock
159         - read LibBlock
160         - if a Library
161                 - make a new Main
162                 - attach ID's to it
163         - else
164                 - read associated 'direct data'
165                 - link direct data (internal and to LibBlock)
166 - read FileGlobal
167 - read USER data, only when indicated (file is ~/.B.blend)
168 - free file
169 - per Library (per Main)
170         - read file
171         - read SDNA
172         - find LibBlocks and attach IDs to Main
173                 - if external LibBlock
174                         - search all Main's
175                                 - or it's already read,
176                                 - or not read yet
177                                 - or make new Main
178         - per LibBlock
179                 - read recursive
180                 - read associated direct data
181                 - link direct data (internal and to LibBlock)
182         - free file
183 - per Library with unread LibBlocks
184         - read file
185         - read SDNA
186         - per LibBlock
187                - read recursive
188                - read associated direct data
189                - link direct data (internal and to LibBlock)
190         - free file
191 - join all Mains
192 - link all LibBlocks and indirect pointers to libblocks
193 - initialize FileGlobal and copy pointers to Global
194 */
195
196 /* also occurs in library.c */
197 /* GS reads the memory pointed at in a specific ordering. There are,
198  * however two definitions for it. I have jotted them down here, both,
199  * but I think the first one is actually used. The thing is that
200  * big-endian systems might read this the wrong way round. OTOH, we
201  * constructed the IDs that are read out with this macro explicitly as
202  * well. I expect we'll sort it out soon... */
203
204 /* from blendef: */
205 #define GS(a)   (*((short *)(a)))
206
207 /* from misc_util: flip the bytes from x  */
208 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
209
210 // only used here in readfile.c
211 #define SWITCH_LONGINT(a) { \
212     char s_i, *p_i; \
213     p_i= (char *)&(a);  \
214     s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
215     s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
216     s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
217     s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
218 // only used here in readfile.c
219 #define SWITCH_SHORT(a) { \
220     char s_i, *p_i; \
221     p_i= (char *)&(a); \
222     s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
223
224
225 /***/
226
227 typedef struct OldNew {
228         void *old, *newp;
229         int nr;
230 } OldNew;
231
232 typedef struct OldNewMap {
233         OldNew *entries;
234         int nentries, entriessize;
235         int sorted;
236         int lasthit;
237 } OldNewMap;
238
239
240 /* local prototypes */
241 extern          short freeN(void *vmemh); /* defined in util.h */  
242
243
244 static OldNewMap *oldnewmap_new(void) 
245 {
246         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
247         
248         onm->entriessize= 1024;
249         onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
250         
251         return onm;
252 }
253
254 static int verg_oldnewmap(const void *v1, const void *v2)
255 {
256         const struct OldNew *x1=v1, *x2=v2;
257         
258         if( x1->old > x2->old) return 1;
259         else if( x1->old < x2->old) return -1;
260         return 0;
261 }
262
263
264 static void oldnewmap_sort(FileData *fd) 
265 {
266         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
267         fd->libmap->sorted= 1;
268 }
269
270 /* nr is zero for data, and ID code for libdata */
271 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) 
272 {
273         OldNew *entry;
274
275         if(oldaddr==NULL || newaddr==NULL) return;
276         
277         if (onm->nentries==onm->entriessize) {
278                 int osize= onm->entriessize;
279                 OldNew *oentries= onm->entries;
280
281                 onm->entriessize*= 2;
282                 onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
283
284                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
285                 MEM_freeN(oentries);
286         }
287
288         entry= &onm->entries[onm->nentries++];
289         entry->old= oldaddr;
290         entry->newp= newaddr;
291         entry->nr= nr;
292 }
293
294 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) 
295 {
296         int i;
297
298         if (onm->lasthit<onm->nentries-1) {
299                 OldNew *entry= &onm->entries[++onm->lasthit];
300
301                 if (entry->old==addr) {
302                         entry->nr++;
303                         return entry->newp;
304                 }
305         }
306
307         for (i=0; i<onm->nentries; i++) {
308                 OldNew *entry= &onm->entries[i];
309
310                 if (entry->old==addr) {
311                         onm->lasthit= i;
312
313                         entry->nr++;
314                         return entry->newp;
315                 }
316         }
317
318         return NULL;
319 }
320
321 /* for libdate, nr has ID code, no increment */
322 static void *oldnewmap_liblookup(OldNewMap *onm, void *addr, void *lib) 
323 {
324         int i;
325         
326         if(addr==NULL) return NULL;
327         
328         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
329         if(onm->sorted) {
330                 OldNew entry_s, *entry;
331                 
332                 entry_s.old= addr;
333                 
334                 entry= bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
335                 if(entry) {
336                         ID *id= entry->newp;
337                         
338                         if (id && (!lib || id->lib)) {
339                                 return entry->newp;
340                         }
341                 }
342         }
343         
344         for (i=0; i<onm->nentries; i++) {
345                 OldNew *entry= &onm->entries[i];
346
347                 if (entry->old==addr) {
348                         ID *id= entry->newp;
349
350                         if (id && (!lib || id->lib)) {
351                                 return entry->newp;
352                         }
353                 }
354         }
355
356         return NULL;
357 }
358
359 static void oldnewmap_free_unused(OldNewMap *onm) 
360 {
361         int i;
362
363         for (i=0; i<onm->nentries; i++) {
364                 OldNew *entry= &onm->entries[i];
365                 if (entry->nr==0) {
366                         MEM_freeN(entry->newp);
367                         entry->newp= NULL;
368                 }
369         }
370 }
371
372 static void oldnewmap_clear(OldNewMap *onm) 
373 {
374         onm->nentries= 0;
375         onm->lasthit= 0;
376 }
377
378 static void oldnewmap_free(OldNewMap *onm) 
379 {
380         MEM_freeN(onm->entries);
381         MEM_freeN(onm);
382 }
383
384 /***/
385
386 static void read_libraries(FileData *basefd, ListBase *mainlist);
387
388 /* ************ help functions ***************** */
389
390 static void add_main_to_main(Main *mainvar, Main *from)
391 {
392         ListBase *lbarray[100], *fromarray[100];        // define in library.c too
393         int a;
394
395         a= set_listbasepointers(mainvar, lbarray);
396         a= set_listbasepointers(from, fromarray);
397         while(a--) {
398                 addlisttolist(lbarray[a], fromarray[a]);
399         }
400 }
401
402 void blo_join_main(ListBase *mainlist)
403 {
404         Main *tojoin, *mainl= mainlist->first;
405
406         while ((tojoin= mainl->next)) {
407                 add_main_to_main(mainl, tojoin);
408                 BLI_remlink(mainlist, tojoin);
409                 MEM_freeN(tojoin);
410         }
411 }
412
413 static void split_libdata(ListBase *lb, Main *first)
414 {
415         ListBase *lbn;
416         ID *id, *idnext;
417         Main *mainvar;
418
419         id= lb->first;
420         while(id) {
421                 idnext= id->next;
422                 if(id->lib) {
423                         mainvar= first;
424                         while(mainvar) {
425                                 if(mainvar->curlib==id->lib) {
426                                         lbn= wich_libbase(mainvar, GS(id->name));
427                                         BLI_remlink(lb, id);
428                                         BLI_addtail(lbn, id);
429                                         break;
430                                 }
431                                 mainvar= mainvar->next;
432                         }
433                         if(mainvar==0) printf("error split_libdata\n");
434                 }
435                 id= idnext;
436         }
437 }
438
439 void blo_split_main(ListBase *mainlist)
440 {
441         Main *mainl= mainlist->first;
442         ListBase *lbarray[30];
443         Library *lib;
444         int i;
445
446         for (lib= mainl->library.first; lib; lib= lib->id.next) {
447                 Main *libmain= MEM_callocN(sizeof(Main), "libmain");
448                 libmain->curlib= lib;
449                 BLI_addtail(mainlist, libmain);
450         }
451
452         i= set_listbasepointers(mainl, lbarray);
453         while(i--)
454                 split_libdata(lbarray[i], mainl->next);
455 }
456
457 /* removes things like /blah/blah/../../blah/ etc, then writes in *name the full path */
458 static void cleanup_path(const char *relabase, char *name)
459 {
460         char filename[FILE_MAXFILE];
461         
462         BLI_splitdirstring(name, filename);
463         BLI_cleanup_dir(relabase, name);
464         strcat(name, filename);
465 }
466
467 static Main *blo_find_main(ListBase *mainlist, const char *name, const char *relabase)
468 {
469         Main *m;
470         Library *lib;
471         char name1[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 unsigned 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 *mainptr;
1047         
1048         for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
1049                 FileData *fd;
1050                 
1051                 if(mainptr->curlib) fd= mainptr->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 (also used for material/scene trees), 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 ntree linking after fileread */
1216 static void lib_link_nodetree(FileData *fd, Main *main)
1217 {
1218         bNodeTree *ntree;
1219         
1220         /* only link ID pointers */
1221         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1222                 if(ntree->id.flag & LIB_NEEDLINK) {
1223                         ntree->id.flag -= LIB_NEEDLINK;
1224                         lib_link_ntree(fd, &ntree->id, ntree);
1225                 }
1226         }
1227 }
1228
1229 /* verify types for nodes and groups, all data has to be read */
1230 static void lib_verify_nodetree(Main *main)
1231 {
1232         Scene *sce;
1233         Material *ma;
1234         bNodeTree *ntree;
1235         
1236         /* now create the own typeinfo structs an verify nodes */
1237         /* here we still assume no groups in groups */
1238         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1239                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
1240                 ntreeMakeOwnType(ntree);        /* for group usage */
1241         }
1242         
1243         /* now verify all types in material trees, groups are set OK now */
1244         for(ma= main->mat.first; ma; ma= ma->id.next) {
1245                 if(ma->nodetree)
1246                         ntreeVerifyTypes(ma->nodetree);
1247         }
1248         /* and scene trees */
1249         for(sce= main->scene.first; sce; sce= sce->id.next) {
1250                 if(sce->nodetree)
1251                         ntreeVerifyTypes(sce->nodetree);
1252         }
1253 }
1254
1255
1256
1257 /* ntree itself has been read! */
1258 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
1259 {
1260         /* note: writing and reading goes in sync, for speed */
1261         bNode *node;
1262         bNodeSocket *sock;
1263         bNodeLink *link;
1264         
1265         ntree->init= 0;         /* to set callbacks */
1266         ntree->owntype= NULL;
1267         ntree->timecursor= NULL;
1268         
1269         link_list(fd, &ntree->nodes);
1270         for(node= ntree->nodes.first; node; node= node->next) {
1271                 node->storage= newdataadr(fd, node->storage);
1272                 if(node->storage) {
1273                         
1274                         /* could be handlerized at some point */
1275                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
1276                                 direct_link_curvemapping(fd, node->storage);
1277                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
1278                                 direct_link_curvemapping(fd, node->storage);
1279                         
1280                 }
1281                 link_list(fd, &node->inputs);
1282                 link_list(fd, &node->outputs);
1283         }
1284         link_list(fd, &ntree->links);
1285         
1286         /* and we connect the rest */
1287         for(node= ntree->nodes.first; node; node= node->next) {
1288                 node->preview= NULL;
1289                 node->block= NULL;
1290                 node->lasty= 0;
1291                 for(sock= node->inputs.first; sock; sock= sock->next)
1292                         sock->link= newdataadr(fd, sock->link);
1293                 for(sock= node->outputs.first; sock; sock= sock->next)
1294                         sock->ns.data= NULL;
1295         }
1296         for(link= ntree->links.first; link; link= link->next) {
1297                 link->fromnode= newdataadr(fd, link->fromnode);
1298                 link->tonode= newdataadr(fd, link->tonode);
1299                 link->fromsock= newdataadr(fd, link->fromsock);
1300                 link->tosock= newdataadr(fd, link->tosock);
1301         }
1302         
1303         /* type verification is in lib-link */
1304 }
1305
1306 /* ************ READ PACKEDFILE *************** */
1307
1308 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1309 {
1310         PackedFile *pf= newdataadr(fd, oldpf);
1311
1312         if (pf) {
1313                 pf->data= newdataadr(fd, pf->data);
1314         }
1315
1316         return pf;
1317 }
1318
1319 /* ************ READ SCRIPTLINK *************** */
1320
1321 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1322 {
1323         int i;
1324
1325         for(i=0; i<slink->totscript; i++) {
1326                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1327         }
1328 }
1329
1330 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1331 {
1332         slink->scripts= newdataadr(fd, slink->scripts);
1333         test_pointer_array(fd, (void **)&slink->scripts);
1334         
1335         slink->flag= newdataadr(fd, slink->flag);
1336
1337         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1338                 int a;
1339
1340                 for(a=0; a<slink->totscript; a++) {
1341                         SWITCH_SHORT(slink->flag[a]);
1342                 }
1343         }
1344 }
1345
1346 /* ************ READ ARMATURE ***************** */
1347
1348 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1349 {
1350         bActionStrip *strip;
1351
1352         for (strip=striplist->first; strip; strip=strip->next){
1353                 strip->object = newlibadr(fd, id->lib, strip->object);
1354                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1355                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1356         }
1357 }
1358
1359 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1360 {
1361         bConstraintChannel *chan;
1362
1363         for (chan=chanbase->first; chan; chan=chan->next){
1364                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1365         }
1366 }
1367
1368 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1369 {
1370         bConstraint *con;
1371
1372         for (con = conlist->first; con; con=con->next) {
1373                 /* patch for error introduced by changing constraints (dunno how) */
1374                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
1375                 if(con->data==NULL) {
1376                         con->type= CONSTRAINT_TYPE_NULL;
1377                 }
1378
1379                 switch (con->type) {
1380                 case CONSTRAINT_TYPE_ACTION:
1381                         {
1382                                 bActionConstraint *data;
1383                                 data= ((bActionConstraint*)con->data);
1384                                 data->tar = newlibadr(fd, id->lib, data->tar);
1385                                 data->act = newlibadr(fd, id->lib, data->act);
1386                         }
1387                         break;
1388                 case CONSTRAINT_TYPE_LOCLIKE:
1389                         {
1390                                 bLocateLikeConstraint *data;
1391                                 data= ((bLocateLikeConstraint*)con->data);
1392                                 data->tar = newlibadr(fd, id->lib, data->tar);
1393                         };
1394                         break;
1395                 case CONSTRAINT_TYPE_ROTLIKE:
1396                         {
1397                                 bRotateLikeConstraint *data;
1398                                 data= ((bRotateLikeConstraint*)con->data);
1399                                 data->tar = newlibadr(fd, id->lib, data->tar);
1400                         };
1401                         break;
1402                 case CONSTRAINT_TYPE_SIZELIKE:
1403                         {
1404                                 bSizeLikeConstraint *data;
1405                                 data= ((bSizeLikeConstraint*)con->data);
1406                                 data->tar = newlibadr(fd, id->lib, data->tar);
1407                         };
1408                         break;
1409                 case CONSTRAINT_TYPE_KINEMATIC:
1410                         {
1411                                 bKinematicConstraint *data;
1412                                 data = ((bKinematicConstraint*)con->data);
1413                                 data->tar = newlibadr(fd, id->lib, data->tar);
1414                         }
1415                         break;
1416                 case CONSTRAINT_TYPE_TRACKTO:
1417                         {
1418                                 bTrackToConstraint *data;
1419                                 data = ((bTrackToConstraint*)con->data);
1420                                 data->tar = newlibadr(fd, id->lib, data->tar);
1421                         }
1422                         break;
1423                 case CONSTRAINT_TYPE_MINMAX:
1424                         {
1425                                 bMinMaxConstraint *data;
1426                                 data = ((bMinMaxConstraint*)con->data);
1427                                 data->tar = newlibadr(fd, id->lib, data->tar);
1428                         }
1429                         break;
1430                 case CONSTRAINT_TYPE_LOCKTRACK:
1431                         {
1432                                 bLockTrackConstraint *data;
1433                                 data= ((bLockTrackConstraint*)con->data);
1434                                 data->tar = newlibadr(fd, id->lib, data->tar);
1435                         };
1436                         break;
1437                 case CONSTRAINT_TYPE_FOLLOWPATH:
1438                         {
1439                                 bFollowPathConstraint *data;
1440                                 data= ((bFollowPathConstraint*)con->data);
1441                                 data->tar = newlibadr(fd, id->lib, data->tar);
1442                         };
1443                         break;
1444                 case CONSTRAINT_TYPE_DISTANCELIMIT:
1445                         {
1446                                 bDistanceLimitConstraint *data;
1447                                 data= ((bDistanceLimitConstraint*)con->data);
1448                                 data->tar = newlibadr(fd, id->lib, data->tar);
1449                         };
1450                         break;
1451                 case CONSTRAINT_TYPE_STRETCHTO:
1452                         {
1453                                 bStretchToConstraint *data;
1454                                 data= ((bStretchToConstraint*)con->data);
1455                                 data->tar = newlibadr(fd, id->lib, data->tar);
1456                         };
1457                         break;
1458
1459                 case CONSTRAINT_TYPE_NULL:
1460                         break;
1461                 }
1462         }
1463 }
1464
1465 static void direct_link_constraints(FileData *fd, ListBase *lb)
1466 {
1467         bConstraint *cons;
1468
1469         link_list(fd, lb);
1470         for (cons=lb->first; cons; cons=cons->next) {
1471                 cons->data = newdataadr(fd, cons->data);
1472         }
1473 }
1474
1475 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1476 {
1477         bPoseChannel *pchan;
1478         bArmature *arm= ob->data;
1479         int rebuild= 0;
1480         if (!pose || !arm)
1481                 return;
1482
1483         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1484                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1485                 // hurms... loop in a loop, but yah... later... (ton)
1486                 pchan->bone= get_named_bone(arm, pchan->name);
1487                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
1488                 if(pchan->bone==NULL)
1489                         rebuild= 1;
1490         }
1491         if(rebuild) {
1492                 ob->recalc= OB_RECALC;
1493                 pose->flag |= POSE_RECALC;
1494         }
1495 }
1496
1497 static void lib_link_armature(FileData *fd, Main *main)
1498 {
1499         bArmature *arm;
1500
1501         arm= main->armature.first;
1502
1503         while(arm) {
1504                 if(arm->id.flag & LIB_NEEDLINK) {
1505                         arm->id.flag -= LIB_NEEDLINK;
1506                 }
1507                 arm= arm->id.next;
1508         }
1509 }
1510
1511 static void lib_link_action(FileData *fd, Main *main)
1512 {
1513         bAction *act;
1514         bActionChannel *chan;
1515
1516         act= main->action.first;
1517         while(act) {
1518                 if(act->id.flag & LIB_NEEDLINK) {
1519                         act->id.flag -= LIB_NEEDLINK;
1520
1521                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1522                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1523                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1524                         }
1525
1526                 }
1527                 act= act->id.next;
1528         }
1529 }
1530
1531 static void direct_link_bones(FileData *fd, Bone* bone)
1532 {
1533         Bone    *child;
1534
1535         bone->parent= newdataadr(fd, bone->parent);
1536
1537         link_list(fd, &bone->childbase);
1538
1539         for (child=bone->childbase.first; child; child=child->next) {
1540                 direct_link_bones(fd, child);
1541         }
1542 }
1543
1544
1545 static void direct_link_action(FileData *fd, bAction *act)
1546 {
1547         bActionChannel *achan;
1548
1549         link_list(fd, &act->chanbase);
1550
1551         for (achan = act->chanbase.first; achan; achan=achan->next)
1552                 link_list(fd, &achan->constraintChannels);
1553
1554 }
1555
1556 static void direct_link_armature(FileData *fd, bArmature *arm)
1557 {
1558         Bone    *bone;
1559
1560         link_list(fd, &arm->bonebase);
1561
1562         bone=arm->bonebase.first;
1563         while (bone) {
1564                 direct_link_bones(fd, bone);
1565                 bone=bone->next;
1566         }
1567 }
1568
1569 /* ************ READ CAMERA ***************** */
1570
1571 static void lib_link_camera(FileData *fd, Main *main)
1572 {
1573         Camera *ca;
1574
1575         ca= main->camera.first;
1576         while(ca) {
1577                 if(ca->id.flag & LIB_NEEDLINK) {
1578
1579                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1580
1581                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1582
1583                         ca->id.flag -= LIB_NEEDLINK;
1584                 }
1585                 ca= ca->id.next;
1586         }
1587 }
1588
1589 static void direct_link_camera(FileData *fd, Camera *ca)
1590 {
1591         direct_link_scriptlink(fd, &ca->scriptlink);
1592 }
1593
1594
1595 /* ************ READ LATTICE ***************** */
1596
1597 static void lib_link_latt(FileData *fd, Main *main)
1598 {
1599         Lattice *lt;
1600
1601         lt= main->latt.first;
1602         while(lt) {
1603                 if(lt->id.flag & LIB_NEEDLINK) {
1604
1605                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
1606                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
1607
1608                         lt->id.flag -= LIB_NEEDLINK;
1609                 }
1610                 lt= lt->id.next;
1611         }
1612 }
1613
1614 static void direct_link_latt(FileData *fd, Lattice *lt)
1615 {
1616         lt->def= newdataadr(fd, lt->def);
1617 }
1618
1619 /* ************ READ LAMP ***************** */
1620
1621 static void lib_link_lamp(FileData *fd, Main *main)
1622 {
1623         Lamp *la;
1624         MTex *mtex;
1625         int a;
1626
1627         la= main->lamp.first;
1628         while(la) {
1629                 if(la->id.flag & LIB_NEEDLINK) {
1630
1631                         for(a=0; a<MAX_MTEX; a++) {
1632                                 mtex= la->mtex[a];
1633                                 if(mtex) {
1634                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1635                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1636                                 }
1637                         }
1638
1639                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1640
1641                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1642
1643                         la->id.flag -= LIB_NEEDLINK;
1644                 }
1645                 la= la->id.next;
1646         }
1647 }
1648
1649 static void direct_link_lamp(FileData *fd, Lamp *la)
1650 {
1651         int a;
1652
1653         direct_link_scriptlink(fd, &la->scriptlink);
1654
1655         for(a=0; a<MAX_MTEX; a++) {
1656                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1657         }
1658 }
1659
1660 /* ************ READ keys ***************** */
1661
1662 static void lib_link_key(FileData *fd, Main *main)
1663 {
1664         Key *key;
1665
1666         key= main->key.first;
1667         while(key) {
1668                 if(key->id.flag & LIB_NEEDLINK) {
1669
1670                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1671                         key->from= newlibadr(fd, key->id.lib, key->from);
1672
1673                         key->id.flag -= LIB_NEEDLINK;
1674                 }
1675                 key= key->id.next;
1676         }
1677 }
1678
1679 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1680 {
1681         int elemsize, a, b;
1682         char *data, *poin, *cp;
1683
1684         elemsize= key->elemsize;
1685         data= kb->data;
1686
1687         for(a=0; a<kb->totelem; a++) {
1688
1689                 cp= key->elemstr;
1690                 poin= data;
1691
1692                 while( cp[0] ) {        /* cp[0]==amount */
1693
1694                         switch(cp[1]) {         /* cp[1]= type */
1695                         case IPO_FLOAT:
1696                         case IPO_BPOINT:
1697                         case IPO_BEZTRIPLE:
1698                                 b= cp[0];
1699                                 while(b--) {
1700                                         SWITCH_INT((*poin));
1701                                         poin+= 4;
1702                                 }
1703                                 break;
1704                         }
1705
1706                         cp+= 2;
1707
1708                 }
1709                 data+= elemsize;
1710         }
1711 }
1712
1713 static void direct_link_key(FileData *fd, Key *key)
1714 {
1715         KeyBlock *kb;
1716
1717         link_list(fd, &(key->block));
1718
1719         key->refkey= newdataadr(fd, key->refkey);
1720
1721         kb= key->block.first;
1722         while(kb) {
1723
1724                 kb->data= newdataadr(fd, kb->data);
1725
1726                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1727                         switch_endian_keyblock(key, kb);
1728
1729                 kb= kb->next;
1730         }
1731 }
1732
1733 /* ************ READ mball ***************** */
1734
1735 static void lib_link_mball(FileData *fd, Main *main)
1736 {
1737         MetaBall *mb;
1738         int a;
1739
1740         mb= main->mball.first;
1741         while(mb) {
1742                 if(mb->id.flag & LIB_NEEDLINK) {
1743
1744                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1745
1746                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1747
1748                         mb->id.flag -= LIB_NEEDLINK;
1749                 }
1750                 mb= mb->id.next;
1751         }
1752 }
1753
1754 static void direct_link_mball(FileData *fd, MetaBall *mb)
1755 {
1756         mb->mat= newdataadr(fd, mb->mat);
1757         test_pointer_array(fd, (void **)&mb->mat);
1758
1759         link_list(fd, &(mb->elems));
1760
1761         mb->disp.first= mb->disp.last= 0;
1762
1763         mb->bb= 0;
1764 }
1765
1766 /* ************ READ WORLD ***************** */
1767
1768 static void lib_link_world(FileData *fd, Main *main)
1769 {
1770         World *wrld;
1771         MTex *mtex;
1772         int a;
1773
1774         wrld= main->world.first;
1775         while(wrld) {
1776                 if(wrld->id.flag & LIB_NEEDLINK) {
1777
1778                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
1779
1780                         for(a=0; a<MAX_MTEX; a++) {
1781                                 mtex= wrld->mtex[a];
1782                                 if(mtex) {
1783                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
1784                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
1785                                 }
1786                         }
1787
1788                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
1789
1790                         wrld->id.flag -= LIB_NEEDLINK;
1791                 }
1792                 wrld= wrld->id.next;
1793         }
1794 }
1795
1796 static void direct_link_world(FileData *fd, World *wrld)
1797 {
1798         int a;
1799
1800         direct_link_scriptlink(fd, &wrld->scriptlink);
1801
1802         for(a=0; a<MAX_MTEX; a++) {
1803                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
1804         }
1805 }
1806
1807
1808 /* ************ READ IPO ***************** */
1809
1810 static void lib_link_ipo(FileData *fd, Main *main)
1811 {
1812         Ipo *ipo;
1813
1814         ipo= main->ipo.first;
1815         while(ipo) {
1816                 if(ipo->id.flag & LIB_NEEDLINK) {
1817                         IpoCurve *icu;
1818                         for(icu= ipo->curve.first; icu; icu= icu->next) {
1819                                 if(icu->driver)
1820                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
1821                         }
1822                         ipo->id.flag -= LIB_NEEDLINK;
1823                 }
1824                 ipo= ipo->id.next;
1825         }
1826 }
1827
1828 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1829 {
1830         IpoCurve *icu;
1831
1832         link_list(fd, &(ipo->curve));
1833         icu= ipo->curve.first;
1834         while(icu) {
1835                 icu->bezt= newdataadr(fd, icu->bezt);
1836                 icu->bp= newdataadr(fd, icu->bp);
1837                 icu->driver= newdataadr(fd, icu->driver);
1838                 icu= icu->next;
1839         }
1840 }
1841
1842 /* ************ READ VFONT ***************** */
1843
1844 static void lib_link_vfont(FileData *fd, Main *main)
1845 {
1846         VFont *vf;
1847
1848         vf= main->vfont.first;
1849         while(vf) {
1850                 if(vf->id.flag & LIB_NEEDLINK) {
1851                         vf->id.flag -= LIB_NEEDLINK;
1852                 }
1853                 vf= vf->id.next;
1854         }
1855 }
1856
1857 static void direct_link_vfont(FileData *fd, VFont *vf)
1858 {
1859         vf->data= NULL;
1860         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
1861 }
1862
1863 /* ************ READ TEXT ****************** */
1864
1865 static void lib_link_text(FileData *fd, Main *main)
1866 {
1867         Text *text;
1868
1869         text= main->text.first;
1870         while(text) {
1871                 if(text->id.flag & LIB_NEEDLINK) {
1872                         text->id.flag -= LIB_NEEDLINK;
1873                 }
1874                 text= text->id.next;
1875         }
1876 }
1877
1878 static void direct_link_text(FileData *fd, Text *text)
1879 {
1880         TextLine *ln;
1881
1882         text->name= newdataadr(fd, text->name);
1883
1884         text->undo_pos= -1;
1885         text->undo_len= TXT_INIT_UNDO;
1886         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
1887
1888         text->compiled= NULL;
1889
1890 /*
1891         if(text->flags & TXT_ISEXT) {
1892                 reopen_text(text);
1893         } else {
1894 */
1895
1896         link_list(fd, &text->lines);
1897
1898         text->curl= newdataadr(fd, text->curl);
1899         text->sell= newdataadr(fd, text->sell);
1900
1901         ln= text->lines.first;
1902         while(ln) {
1903                 ln->line= newdataadr(fd, ln->line);
1904                 ln->format= NULL;
1905                 
1906                 if (ln->len != (int) strlen(ln->line)) {
1907                         printf("Error loading text, line lengths differ\n");
1908                         ln->len = strlen(ln->line);
1909                 }
1910
1911                 ln= ln->next;
1912         }
1913
1914         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
1915
1916         text->id.us= 1;
1917 }
1918
1919 /* ************ READ IMAGE ***************** */
1920
1921 static void lib_link_image(FileData *fd, Main *main)
1922 {
1923         Image *ima;
1924
1925         ima= main->image.first;
1926         while (ima) {
1927                 if(ima->id.flag & LIB_NEEDLINK) {
1928
1929                         ima->id.flag -= LIB_NEEDLINK;
1930                 }
1931                 ima= ima->id.next;
1932         }
1933 }
1934
1935 static void direct_link_image(FileData *fd, Image *ima)
1936 {
1937         ima->ibuf= 0;
1938         ima->anim= 0;
1939         memset(ima->mipmap, 0, sizeof(ima->mipmap));
1940         ima->repbind= 0;
1941         ima->bindcode= 0;
1942
1943         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
1944
1945         ima->ok= 1;
1946 }
1947
1948
1949 /* ************ READ CURVE ***************** */
1950
1951 static void lib_link_curve(FileData *fd, Main *main)
1952 {
1953         Curve *cu;
1954         int a;
1955
1956         cu= main->curve.first;
1957         while(cu) {
1958                 if(cu->id.flag & LIB_NEEDLINK) {
1959
1960                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
1961
1962                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
1963                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
1964                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
1965                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
1966                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
1967                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
1968                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
1969
1970                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
1971                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
1972
1973                         cu->id.flag -= LIB_NEEDLINK;
1974                 }
1975                 cu= cu->id.next;
1976         }
1977 }
1978
1979
1980 static void switch_endian_knots(Nurb *nu)
1981 {
1982         int len;
1983
1984         if(nu->knotsu) {
1985                 len= KNOTSU(nu);
1986                 while(len--) {
1987                         SWITCH_INT(nu->knotsu[len]);
1988                 }
1989         }
1990         if(nu->knotsv) {
1991                 len= KNOTSV(nu);
1992                 while(len--) {
1993                         SWITCH_INT(nu->knotsv[len]);
1994                 }
1995         }
1996 }
1997
1998 static void direct_link_curve(FileData *fd, Curve *cu)
1999 {
2000         Nurb *nu;
2001         TextBox *tb;
2002
2003         cu->mat= newdataadr(fd, cu->mat);
2004         test_pointer_array(fd, (void **)&cu->mat);
2005         cu->str= newdataadr(fd, cu->str);
2006         cu->strinfo= newdataadr(fd, cu->strinfo);       
2007         cu->tb= newdataadr(fd, cu->tb);
2008
2009         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2010         else {
2011                 cu->nurb.first=cu->nurb.last= 0;
2012
2013                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2014                 if (cu->tb) {
2015                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2016                         MEM_freeN(cu->tb);
2017                         cu->tb= tb;                     
2018                 } else {
2019                         cu->totbox = 1;
2020                         cu->actbox = 1;
2021                         cu->tb = tb;
2022                         cu->tb[0].w = cu->linewidth;
2023                 }               
2024                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2025         }
2026
2027         cu->bev.first=cu->bev.last= 0;
2028         cu->disp.first=cu->disp.last= 0;
2029         cu->path= 0;
2030
2031         nu= cu->nurb.first;
2032         while(nu) {
2033                 nu->bezt= newdataadr(fd, nu->bezt);
2034                 nu->bp= newdataadr(fd, nu->bp);
2035                 nu->knotsu= newdataadr(fd, nu->knotsu);
2036                 nu->knotsv= newdataadr(fd, nu->knotsv);
2037                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2038
2039                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2040                         switch_endian_knots(nu);
2041                 }
2042
2043                 nu= nu->next;
2044         }
2045         cu->bb= NULL;
2046 }
2047
2048 /* ************ READ TEX ***************** */
2049
2050 static void lib_link_texture(FileData *fd, Main *main)
2051 {
2052         Tex *tex;
2053
2054         tex= main->tex.first;
2055         while(tex) {
2056                 if(tex->id.flag & LIB_NEEDLINK) {
2057
2058                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2059                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2060                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2061
2062                         tex->id.flag -= LIB_NEEDLINK;
2063                 }
2064                 tex= tex->id.next;
2065         }
2066 }
2067
2068 static void direct_link_texture(FileData *fd, Tex *tex)
2069 {
2070         tex->plugin= newdataadr(fd, tex->plugin);
2071         if(tex->plugin) {
2072                 tex->plugin->handle= 0;
2073                 open_plugin_tex(tex->plugin);
2074         }
2075         tex->coba= newdataadr(fd, tex->coba);
2076         tex->env= newdataadr(fd, tex->env);
2077         if(tex->env) {
2078                 tex->env->ima= 0;
2079                 memset(tex->env->cube, 0, 6*sizeof(void *));
2080                 tex->env->ok= 0;
2081         }
2082 }
2083
2084
2085
2086 /* ************ READ MATERIAL ***************** */
2087
2088 static void lib_link_material(FileData *fd, Main *main)
2089 {
2090         Material *ma;
2091         MTex *mtex;
2092         int a;
2093
2094         ma= main->mat.first;
2095         while(ma) {
2096                 if(ma->id.flag & LIB_NEEDLINK) {
2097
2098                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2099                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2100                         
2101                         for(a=0; a<MAX_MTEX; a++) {
2102                                 mtex= ma->mtex[a];
2103                                 if(mtex) {
2104                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2105                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2106                                 }
2107                         }
2108                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2109                         
2110                         if(ma->nodetree)
2111                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2112                         
2113                         ma->id.flag -= LIB_NEEDLINK;
2114                 }
2115                 ma= ma->id.next;
2116         }
2117 }
2118
2119 static void direct_link_material(FileData *fd, Material *ma)
2120 {
2121         int a;
2122
2123         for(a=0; a<MAX_MTEX; a++) {
2124                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2125         }
2126
2127         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2128         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2129         
2130         direct_link_scriptlink(fd, &ma->scriptlink);
2131         
2132         ma->nodetree= newdataadr(fd, ma->nodetree);
2133         if(ma->nodetree)
2134                 direct_link_nodetree(fd, ma->nodetree);
2135 }
2136
2137 /* ************ READ MESH ***************** */
2138
2139 static void lib_link_mesh(FileData *fd, Main *main)
2140 {
2141         Mesh *me;
2142
2143         me= main->mesh.first;
2144         while(me) {
2145                 if(me->id.flag & LIB_NEEDLINK) {
2146                         int i;
2147
2148                         /* this check added for python created meshes */
2149                         if(me->mat) {
2150                                 for(i=0; i<me->totcol; i++) {
2151                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2152                                 }
2153                         }
2154                         else me->totcol= 0;
2155
2156                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2157                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2158                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2159
2160                         if(me->tface) {
2161                                 TFace *tfaces= me->tface;
2162
2163                                 for (i=0; i<me->totface; i++) {
2164                                         TFace *tf= &tfaces[i];
2165
2166                                         tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2167                                         if(tf->tpage) {
2168                                                 Image *ima= tf->tpage;
2169                                                 if(ima->id.us==0)
2170                                                         ima->id.us= 1;
2171                                         }
2172                                 }
2173                         }
2174                         me->id.flag -= LIB_NEEDLINK;
2175                 }
2176                 me= me->id.next;
2177         }
2178 }
2179
2180 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2181 {
2182         int     i;
2183
2184         if (!mdverts)
2185                 return;
2186
2187         for (i=0; i<count; i++) {
2188                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2189                 if (!mdverts[i].dw)
2190                         mdverts[i].totweight=0;
2191         }
2192 }
2193
2194 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2195 {
2196         mesh->mat= newdataadr(fd, mesh->mat);
2197         test_pointer_array(fd, (void **)&mesh->mat);
2198
2199         mesh->mvert= newdataadr(fd, mesh->mvert);
2200         mesh->medge= newdataadr(fd, mesh->medge);
2201         mesh->mface= newdataadr(fd, mesh->mface);
2202         mesh->tface= newdataadr(fd, mesh->tface);
2203         mesh->mcol= newdataadr(fd, mesh->mcol);
2204         mesh->msticky= newdataadr(fd, mesh->msticky);
2205
2206         mesh->dvert= newdataadr(fd, mesh->dvert);
2207         direct_link_dverts(fd, mesh->totvert, mesh->dvert);
2208
2209         mesh->bb= NULL;
2210         mesh->oc= 0;
2211         mesh->dface= NULL;
2212         mesh->mselect= NULL;
2213         
2214         if (mesh->tface) {
2215                 TFace *tfaces= mesh->tface;
2216                 int i;
2217
2218                 for (i=0; i<mesh->totface; i++) {
2219                         TFace *tf= &tfaces[i];
2220
2221                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2222                                 SWITCH_INT(tf->col[0]);
2223                                 SWITCH_INT(tf->col[1]);
2224                                 SWITCH_INT(tf->col[2]);
2225                                 SWITCH_INT(tf->col[3]);
2226                         }
2227                 }
2228         }
2229 }
2230
2231 /* ************ READ OBJECT ***************** */
2232
2233 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob, Object **obpoin)
2234 {
2235         FileData *fd = userData;
2236
2237         *obpoin = newlibadr(fd, ob->id.lib, *obpoin);
2238 }
2239 static void lib_link_modifiers(FileData *fd, Object *ob)
2240 {
2241         modifiers_foreachObjectLink(ob, lib_link_modifiers__linkModifiers, fd);
2242 }
2243
2244 static void lib_link_object(FileData *fd, Main *main)
2245 {
2246         Object *ob;
2247         PartEff *paf;
2248         bSensor *sens;
2249         bController *cont;
2250         bActuator *act;
2251         void *poin;
2252         int warn=0, a;
2253
2254         ob= main->object.first;
2255         while(ob) {
2256                 if(ob->id.flag & LIB_NEEDLINK) {
2257
2258                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2259                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2260                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2261                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2262                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
2263                         
2264                         poin= ob->data;
2265                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2266                            
2267                         if(ob->data==NULL && poin!=NULL) {
2268                                 ob->type= OB_EMPTY;
2269                                 warn= 1;
2270                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2271                                 else printf("Object %s lost data. Lib:%x\n", ob->id.name+2, (unsigned int) ob->id.lib);
2272                         }
2273                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2274
2275                         ob->id.flag -= LIB_NEEDLINK;
2276                         /* if id.us==0 a new base will be created later on */
2277
2278                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2279                         lib_link_pose(fd, ob, ob->pose);
2280                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2281                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2282                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2283
2284                         for(paf= ob->effect.first; paf; paf= paf->next) {
2285                                 if(paf->type==EFF_PARTICLE) {
2286                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
2287                                 }
2288                         }                               
2289
2290                         sens= ob->sensors.first;
2291                         while(sens) {
2292                                 if(ob->id.lib==NULL) {  // done in expand_main
2293                                         for(a=0; a<sens->totlinks; a++) {
2294                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2295                                         }
2296                                 }
2297                                 if(sens->type==SENS_TOUCH) {
2298                                         bTouchSensor *ts= sens->data;
2299                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2300                                 }
2301                                 else if(sens->type==SENS_MESSAGE) {
2302                                         bMessageSensor *ms= sens->data;
2303                                         ms->fromObject=
2304                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2305                                 }
2306                                 sens= sens->next;
2307                         }
2308
2309                         cont= ob->controllers.first;
2310                         while(cont) {
2311                                 if(ob->id.lib==NULL) {  // done in expand_main
2312                                         for(a=0; a<cont->totlinks; a++) {
2313                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2314                                         }
2315                                 }
2316                                 if(cont->type==CONT_PYTHON) {
2317                                         bPythonCont *pc= cont->data;
2318                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2319                                 }
2320                                 cont->slinks= NULL;
2321                                 cont->totslinks= 0;
2322
2323                                 cont= cont->next;
2324                         }
2325
2326                         act= ob->actuators.first;
2327                         while(act) {
2328                                 if(act->type==ACT_SOUND) {
2329                                         bSoundActuator *sa= act->data;
2330                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2331                                 }
2332                                 else if(act->type==ACT_CD) {
2333                                         /* bCDActuator *cda= act->data; */
2334                                 }
2335                                 else if(act->type==ACT_GAME) {
2336                                         /* bGameActuator *ga= act->data; */
2337                                 }
2338                                 else if(act->type==ACT_CAMERA) {
2339                                         bCameraActuator *ca= act->data;
2340                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2341                                 }
2342                                         /* leave this one, it's obsolete but necessary to read for conversion */
2343                                 else if(act->type==ACT_ADD_OBJECT) {
2344                                         bAddObjectActuator *eoa= act->data;
2345                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2346                                 }
2347                                 else if(act->type==ACT_EDIT_OBJECT) {
2348                                         bEditObjectActuator *eoa= act->data;
2349                                         if(eoa==NULL) {
2350                                                 init_actuator(act);
2351                                         }
2352                                         eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2353                                         eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2354                                 }
2355                                 else if(act->type==ACT_SCENE) {
2356                                         bSceneActuator *sa= act->data;
2357                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2358                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2359                                 }
2360                                 else if(act->type==ACT_ACTION) {
2361                                         bActionActuator *aa= act->data;
2362                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2363                                 }
2364                                 else if(act->type==ACT_PROPERTY) {
2365                                         bPropertyActuator *pa= act->data;
2366                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2367                                 }
2368                                 else if(act->type==ACT_MESSAGE) {
2369                                         bMessageActuator *ma= act->data;
2370                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2371                                 }
2372                                 act= act->next;
2373                         }
2374
2375                         if(ob->fluidsimSettings) {
2376                                 ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
2377                         }
2378
2379                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2380                         lib_link_modifiers(fd, ob);
2381                 }
2382                 ob= ob->id.next;
2383         }
2384
2385         if(warn) error("WARNING IN CONSOLE");
2386 }
2387
2388
2389 static void direct_link_pose(FileData *fd, bPose *pose) {
2390
2391         bPoseChannel *pchan;
2392
2393         if (!pose)
2394                 return;
2395
2396         link_list(fd, &pose->chanbase);
2397
2398         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2399                 pchan->bone= NULL;
2400                 pchan->parent= newdataadr(fd, pchan->parent);
2401                 pchan->child= newdataadr(fd, pchan->child);
2402                 direct_link_constraints(fd, &pchan->constraints);
2403                 pchan->iktree.first= pchan->iktree.last= NULL;
2404                 pchan->path= NULL;
2405         }
2406
2407 }
2408
2409 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2410 {
2411         ModifierData *md;
2412
2413         link_list(fd, lb);
2414
2415         for (md=lb->first; md; md=md->next) {
2416                 md->error = NULL;
2417
2418                 if (md->type==eModifierType_Subsurf) {
2419                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2420
2421                         smd->emCache = smd->mCache = 0;
2422                 } else if (md->type==eModifierType_Hook) {
2423                         HookModifierData *hmd = (HookModifierData*) md;
2424
2425                         hmd->indexar= newdataadr(fd, hmd->indexar);
2426                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2427                                 int a;
2428                                 for(a=0; a<hmd->totindex; a++) {
2429                                         SWITCH_INT(hmd->indexar[a]);
2430                                 }
2431                         }
2432                 }
2433         }
2434 }
2435
2436 static void direct_link_object(FileData *fd, Object *ob)
2437 {
2438         PartEff *paf;
2439         bProperty *prop;
2440         bSensor *sens;
2441         bController *cont;
2442         bActuator *act;
2443         int a;
2444         
2445         ob->disp.first=ob->disp.last= NULL;
2446
2447         ob->pose= newdataadr(fd, ob->pose);
2448         direct_link_pose(fd, ob->pose);
2449
2450         link_list(fd, &ob->defbase);
2451         link_list(fd, &ob->nlastrips);
2452         link_list(fd, &ob->constraintChannels);
2453
2454         direct_link_scriptlink(fd, &ob->scriptlink);
2455
2456         ob->mat= newdataadr(fd, ob->mat);
2457         test_pointer_array(fd, (void **)&ob->mat);
2458         
2459         /* do it here, below old data gets converted */
2460         direct_link_modifiers(fd, &ob->modifiers);
2461         
2462         link_list(fd, &ob->effect);
2463         paf= ob->effect.first;
2464         while(paf) {
2465                 if(paf->type==EFF_PARTICLE) {
2466                         paf->keys= NULL;
2467                 }
2468                 if(paf->type==EFF_WAVE) {
2469                         WaveEff *wav = (WaveEff*) paf;
2470                         PartEff *next = paf->next;
2471                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
2472
2473                         wmd->damp = wav->damp;
2474                         wmd->flag = wav->flag;
2475                         wmd->height = wav->height;
2476                         wmd->lifetime = wav->lifetime;
2477                         wmd->narrow = wav->narrow;
2478                         wmd->speed = wav->speed;
2479                         wmd->startx = wav->startx;
2480                         wmd->starty = wav->startx;
2481                         wmd->timeoffs = wav->timeoffs;
2482                         wmd->width = wav->width;
2483
2484                         BLI_addtail(&ob->modifiers, wmd);
2485
2486                         BLI_remlink(&ob->effect, paf);
2487                         MEM_freeN(paf);
2488
2489                         paf = next;
2490                         continue;
2491                 }
2492                 if(paf->type==EFF_BUILD) {
2493                         BuildEff *baf = (BuildEff*) paf;
2494                         PartEff *next = paf->next;
2495                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
2496
2497                         bmd->start = baf->sfra;
2498                         bmd->length = baf->len;
2499                         bmd->randomize = 0;
2500                         bmd->seed = 1;
2501
2502                         BLI_addtail(&ob->modifiers, bmd);
2503
2504                         BLI_remlink(&ob->effect, paf);
2505                         MEM_freeN(paf);
2506
2507                         paf = next;
2508                         continue;
2509                 }
2510                 paf= paf->next;
2511         }
2512
2513         ob->pd= newdataadr(fd, ob->pd);
2514         ob->soft= newdataadr(fd, ob->soft);
2515         if(ob->soft) {
2516                 SoftBody *sb= ob->soft;         
2517                 
2518                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2519                 sb->bspring= NULL;
2520                 
2521                 sb->keys= newdataadr(fd, sb->keys);
2522                 test_pointer_array(fd, (void **)&sb->keys);
2523                 if(sb->keys) {
2524                         for(a=0; a<sb->totkey; a++) {
2525                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
2526                         }
2527                 }
2528         }
2529         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
2530         if(ob->fluidsimSettings) {
2531                 // reinit mesh pointers
2532                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
2533                 ob->fluidsimSettings->meshSurface = NULL;
2534                 ob->fluidsimSettings->meshBB = NULL;
2535                 ob->fluidsimSettings->meshSurfNormals = NULL;
2536         }
2537         
2538         link_list(fd, &ob->prop);
2539         prop= ob->prop.first;
2540         while(prop) {
2541                 prop->poin= newdataadr(fd, prop->poin);
2542                 if(prop->poin==0) prop->poin= &prop->data;
2543                 prop= prop->next;
2544         }
2545
2546         link_list(fd, &ob->sensors);
2547         sens= ob->sensors.first;
2548         while(sens) {
2549                 sens->data= newdataadr(fd, sens->data);
2550                 sens->links= newdataadr(fd, sens->links);
2551                 test_pointer_array(fd, (void **)&sens->links);
2552                 sens= sens->next;
2553         }
2554
2555         direct_link_constraints(fd, &ob->constraints);
2556
2557         link_glob_list(fd, &ob->controllers);
2558         cont= ob->controllers.first;
2559         while(cont) {
2560                 cont->data= newdataadr(fd, cont->data);
2561                 cont->links= newdataadr(fd, cont->links);
2562                 test_pointer_array(fd, (void **)&cont->links);
2563                 cont= cont->next;
2564         }
2565
2566         link_glob_list(fd, &ob->actuators);
2567         act= ob->actuators.first;
2568         while(act) {
2569                 act->data= newdataadr(fd, act->data);
2570                 act= act->next;
2571         }
2572
2573         link_list(fd, &ob->hooks);
2574         while (ob->hooks.first) {
2575                 ObHook *hook = ob->hooks.first;
2576                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
2577
2578                 hook->indexar= newdataadr(fd, hook->indexar);
2579                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2580                         int a;
2581                         for(a=0; a<hook->totindex; a++) {
2582                                 SWITCH_INT(hook->indexar[a]);
2583                         }
2584                 }
2585
2586                         /* Do conversion here because if we have loaded
2587                          * a hook we need to make sure it gets converted
2588                          * and free'd, regardless of version.
2589                          */
2590                 VECCOPY(hmd->cent, hook->cent);
2591                 hmd->falloff = hook->falloff;
2592                 hmd->force = hook->force;
2593                 hmd->indexar = hook->indexar;
2594                 hmd->object = hook->parent;
2595                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
2596                 hmd->totindex = hook->totindex;
2597
2598                 BLI_addhead(&ob->modifiers, hmd);
2599                 BLI_remlink(&ob->hooks, hook);
2600
2601                 MEM_freeN(hook);
2602         }
2603         
2604         ob->bb= NULL;
2605         ob->derivedDeform= NULL;
2606         ob->derivedFinal= NULL;
2607 }
2608
2609 /* ************ READ SCENE ***************** */
2610
2611 static void lib_link_scene(FileData *fd, Main *main)
2612 {
2613         Scene *sce;
2614         Base *base, *next;
2615         Editing *ed;
2616         Sequence *seq;
2617
2618         sce= main->scene.first;
2619         while(sce) {
2620                 if(sce->id.flag & LIB_NEEDLINK) {
2621                         
2622                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
2623                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
2624                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
2625                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
2626
2627                         base= sce->base.first;
2628                         while(base) {
2629                                 next= base->next;
2630
2631                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
2632                                 base->object= newlibadr_us(fd, sce->id.lib, base->object);
2633                                 
2634                                 /* when save during radiotool, needs cleared */
2635                                 base->flag &= ~OB_RADIO;
2636                                 
2637                                 if(base->object==NULL) {
2638                                         printf("LIB ERROR: base removed\n");
2639                                         BLI_remlink(&sce->base, base);
2640                                         if(base==sce->basact) sce->basact= 0;
2641                                         MEM_freeN(base);
2642                                 }
2643                                 base= next;
2644                         }
2645
2646                         ed= sce->ed;
2647                         if(ed) {
2648                                 WHILE_SEQ(&ed->seqbase) {
2649                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
2650                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
2651                                         if(seq->sound) {
2652                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
2653                                                 if (seq->sound) {
2654                                                         seq->sound->id.us++;
2655                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
2656                                                 }
2657                                         }
2658                                         seq->anim= 0;
2659                                         seq->hdaudio = 0;
2660                                 }
2661                                 END_SEQ
2662                         }
2663                         
2664                         lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
2665                         
2666                         if(sce->nodetree)
2667                                 lib_link_ntree(fd, &sce->id, sce->nodetree);
2668
2669                         sce->id.flag -= LIB_NEEDLINK;
2670                 }
2671
2672                 sce= sce->id.next;
2673         }
2674 }
2675
2676 static void link_recurs_seq(FileData *fd, ListBase *lb)
2677 {
2678         Sequence *seq;
2679
2680         link_list(fd, lb);
2681         seq= lb->first;
2682         while(seq) {
2683                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
2684                 seq= seq->next;
2685         }
2686 }
2687
2688 static void direct_link_scene(FileData *fd, Scene *sce)
2689 {
2690         Editing *ed;
2691         Sequence *seq;
2692         MetaStack *ms;
2693         StripElem *se;
2694         int a;
2695
2696         sce->theDag = NULL;
2697         sce->dagisvalid = 0;
2698         /* set users to one by default, not in lib-link, this will increase it for compo nodes */
2699         sce->id.us= 1;
2700         
2701         link_list(fd, &(sce->base));
2702
2703         sce->basact= newdataadr(fd, sce->basact);
2704
2705         sce->radio= newdataadr(fd, sce->radio);
2706         
2707         sce->toolsettings= newdataadr(fd, sce->toolsettings);
2708         
2709         if(sce->ed) {
2710                 ed= sce->ed= newdataadr(fd, sce->ed);
2711
2712                 /* recursive link sequences, lb will be correctly initialized */
2713                 link_recurs_seq(fd, &ed->seqbase);
2714
2715                 WHILE_SEQ(&ed->seqbase) {
2716                         seq->seq1= newdataadr(fd, seq->seq1);
2717                         seq->seq2= newdataadr(fd, seq->seq2);
2718                         seq->seq3= newdataadr(fd, seq->seq3);
2719                         /* a patch: after introduction of effects with 3 input strips */
2720                         if(seq->seq3==0) seq->seq3= seq->seq2;
2721
2722                         seq->curelem= 0;
2723
2724                         seq->plugin= newdataadr(fd, seq->plugin);
2725                         seq->effectdata= newdataadr(fd, seq->effectdata);
2726                         
2727                         if (seq->type & SEQ_EFFECT) {
2728                                 seq->flag |= SEQ_EFFECT_NOT_LOADED;
2729                         }
2730
2731                         seq->strip= newdataadr(fd, seq->strip);
2732                         if(seq->strip && seq->strip->done==0) {
2733                                 seq->strip->done= 1;
2734
2735                                 /* standard: strips from effects/metas are not written, but are mallocced */
2736
2737                                 if(seq->type==SEQ_IMAGE) {
2738                                         seq->strip->stripdata= newdataadr(fd, seq->strip->stripdata);
2739                                         se= seq->strip->stripdata;
2740                                         if(se) {
2741                                                 for(a=0; a<seq->strip->len; a++, se++) {
2742                                                         se->ok= 1;
2743                                                         se->ibuf= 0;
2744                                                 }
2745                                         }
2746                                 }
2747                                 else if(seq->type==SEQ_MOVIE) {
2748                                         /* only first stripelem is in file */
2749                                         se= newdataadr(fd, seq->strip->stripdata);
2750
2751                                         if(se) {
2752                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2753                                                 *seq->strip->stripdata= *se;
2754                                                 MEM_freeN(se);
2755
2756                                                 se= seq->strip->stripdata;
2757
2758                                                 for(a=0; a<seq->strip->len; a++, se++) {
2759                                                         se->ok= 1;
2760                                                         se->ibuf= 0;
2761                                                         se->nr= a + 1;
2762                                                 }
2763                                         }
2764                                 }
2765                                 else if(seq->type==SEQ_RAM_SOUND
2766                                         || seq->type == SEQ_HD_SOUND) {
2767                                         /* only first stripelem is in file */
2768                                         se= newdataadr(fd, seq->strip->stripdata);
2769
2770                                         if(se) {
2771                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2772                                                 *seq->strip->stripdata= *se;
2773                                                 MEM_freeN(se);
2774
2775                                                 se= seq->strip->stripdata;
2776
2777                                                 for(a=0; a<seq->strip->len; a++, se++) {
2778                                                         se->ok= 2; /* why? */
2779                                                         se->ibuf= 0;
2780                                                         se->nr= a + 1;
2781                                                 }
2782                                         }
2783                                 }
2784                                 else if(seq->len>0)
2785                                         seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2786
2787                         }
2788                 }
2789                 END_SEQ
2790                         
2791                 /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */
2792                 {
2793                         Sequence temp;
2794                         char *poin;
2795                         long offset;
2796                         /*int seted=0;*/ /*unused*/
2797                         
2798                         offset= ((long)&(temp.seqbase)) - ((long)&temp);
2799
2800                         /* root pointer */
2801                         poin= (char *)ed->seqbasep;
2802                         poin -= offset;
2803                         poin= newdataadr(fd, poin);
2804                         if(poin) ed->seqbasep= (ListBase *)(poin+offset);
2805                         else ed->seqbasep= &ed->seqbase;
2806                         
2807                         /* stack */
2808                         link_list(fd, &(ed->metastack));
2809                         
2810                         for(ms= ed->metastack.first; ms; ms= ms->next) {
2811                                 ms->parseq= newdataadr(fd, ms->parseq);
2812                                 
2813                                 poin= (char *)ms->oldbasep;
2814                                 poin -= offset;
2815                                 poin= newdataadr(fd, poin);
2816                                 if(poin) ms->oldbasep= (ListBase *)(poin+offset);
2817                                 else ms->oldbasep= &ed->seqbase;
2818                         }
2819                 }
2820         }
2821
2822         direct_link_scriptlink(fd, &sce->scriptlink);
2823         
2824         sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
2825         if (sce->r.avicodecdata) {
2826                 sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
2827                 sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
2828         }
2829         
2830         sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
2831         if (sce->r.qtcodecdata) {
2832                 sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
2833         }
2834         
2835         link_list(fd, &(sce->markers));
2836         link_list(fd, &(sce->r.layers));
2837         
2838         sce->nodetree= newdataadr(fd, sce->nodetree);
2839         if(sce->nodetree)
2840                 direct_link_nodetree(fd, sce->nodetree);
2841         
2842 }
2843
2844 /* ************ READ SCREEN ***************** */
2845
2846 /* note: file read without screens option G_FILE_NO_UI; 
2847    check lib pointers in call below */
2848 static void lib_link_screen(FileData *fd, Main *main)
2849 {
2850         bScreen *sc;
2851         ScrArea *sa;
2852
2853         sc= main->screen.first;
2854         while(sc) {
2855                 if(sc->id.flag & LIB_NEEDLINK) {
2856                         sc->id.us= 1;
2857                         sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
2858
2859                         sa= sc->areabase.first;
2860                         while(sa) {
2861                                 SpaceLink *sl;
2862
2863                                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
2864
2865                                 /* space handler scriptlinks */
2866                                 lib_link_scriptlink(fd, &sc->id, &sa->scriptlink);
2867
2868                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2869                                         if(sl->spacetype==SPACE_VIEW3D) {
2870                                                 View3D *v3d= (View3D*) sl;
2871
2872                                                 v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
2873
2874                                                 if(v3d->bgpic) {
2875                                                         v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
2876                                                         v3d->bgpic->tex= newlibadr_us(fd, sc->id.lib, v3d->bgpic->tex);
2877                                                         v3d->bgpic->rect= NULL;
2878                                                 }
2879                                                 if(v3d->localvd) {
2880                                                         v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
2881                                                 }
2882                                                 v3d->ri= NULL;
2883                                         }
2884                                         else if(sl->spacetype==SPACE_IPO) {
2885                                                 SpaceIpo *sipo= (SpaceIpo *)sl;
2886                                                 sipo->editipo= 0;
2887                                                 
2888                                                 if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
2889                                                 else sipo->from= newlibadr(fd, sc->id.lib, sipo->from);
2890                                                 
2891                                                 sipo->ipokey.first= sipo->ipokey.last= 0;
2892                                                 sipo->ipo= newlibadr(fd, sc->id.lib, sipo->ipo);
2893                                         }
2894                                         else if(sl->spacetype==SPACE_BUTS) {
2895                                                 SpaceButs *sbuts= (SpaceButs *)sl;
2896                                                 sbuts->lockpoin= NULL;
2897                                                 sbuts->ri= NULL;
2898                                                 if(main->versionfile<132) set_rects_butspace(sbuts);
2899                                         }
2900                                         else if(sl->spacetype==SPACE_FILE) {
2901                                                 SpaceFile *sfile= (SpaceFile *)sl;
2902
2903                                                 sfile->filelist= 0;
2904                                                 sfile->libfiledata= 0;
2905                                                 sfile->returnfunc= 0;
2906                                         }
2907                                         else if(sl->spacetype==SPACE_IMASEL) {
2908                                                 check_imasel_copy((SpaceImaSel *)sl);
2909                                         }
2910                                         else if(sl->spacetype==SPACE_ACTION) {
2911                                                 SpaceAction *saction= (SpaceAction *)sl;
2912                                                 saction->action = newlibadr(fd, sc->id.lib, saction->action);
2913                                         }
2914                                         else if(sl->spacetype==SPACE_IMAGE) {
2915                                                 SpaceImage *sima= (SpaceImage *)sl;
2916
2917                                                 sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
2918                                         }
2919                                         else if(sl->spacetype==SPACE_NLA){
2920                                                 /* SpaceNla *snla= (SpaceNla *)sl;      */
2921                                         }
2922                                         else if(sl->spacetype==SPACE_TEXT) {
2923                                                 SpaceText *st= (SpaceText *)sl;
2924
2925                                                 st->text= newlibadr(fd, sc->id.lib, st->text);
2926
2927                                         }
2928                                         else if(sl->spacetype==SPACE_SCRIPT) {
2929                                                 SpaceScript *sc= (SpaceScript *)sl;
2930
2931                                                 sc->script = NULL;
2932                                         }
2933                                         else if(sl->spacetype==SPACE_OOPS) {
2934                                                 SpaceOops *so= (SpaceOops *)sl;
2935                                                 Oops *oops;
2936                                                 TreeStoreElem *tselem;
2937                                                 int a;
2938
2939                                                 oops= so->oops.first;
2940                                                 while(oops) {
2941                                                         oops->id= newlibadr(fd, NULL, oops->id);
2942                                                         oops= oops->next;
2943                                                 }
2944                                                 so->lockpoin= NULL;
2945                                                 so->tree.first= so->tree.last= NULL;
2946                                                 
2947                                                 if(so->treestore) {
2948                                                         tselem= so->treestore->data;
2949                                                         for(a=0; a<so->treestore->usedelem; a++, tselem++) {
2950                                                                 tselem->id= newlibadr(fd, NULL, tselem->id);
2951                                                         }
2952                                                 }
2953                                         }
2954                                         else if(sl->spacetype==SPACE_SOUND) {
2955                                                 SpaceSound *ssound= (SpaceSound *)sl;
2956
2957                                                 ssound->sound= newlibadr_us(fd, sc->id.lib, ssound->sound);
2958                                         }
2959                                 }
2960                                 sa= sa->next;
2961                         }
2962                         sc->id.flag -= LIB_NEEDLINK;
2963                 }
2964                 sc= sc->id.next;
2965         }
2966 }
2967
2968 static void *restore_pointer_by_name(Main *mainp, ID *id, int user)
2969 {
2970         ListBase *lb;
2971         ID *idn=NULL;
2972                 
2973         if(id) {
2974                 lb= wich_libbase(mainp, GS(id->name));
2975                 
2976                 if(lb) {        // there's still risk of checking corrupt mem (freed Ids in oops)
2977                         idn= lb->first;
2978                         while(idn) {
2979                                 if( strcmp(idn->name, id->name)==0) {
2980                                         if(user && idn->us==0) idn->us++;
2981                                         break;
2982                                 }
2983                                 idn= idn->next;
2984                         }
2985                 }
2986         }
2987         return idn;
2988 }
2989
2990 /* called from kernel/blender.c */
2991 /* used to link a file (without UI) to the current UI */
2992 void lib_link_screen_restore(Main *newmain, Scene *curscene)
2993 {
2994         bScreen *sc;
2995         ScrArea *sa;
2996
2997         sc= newmain->screen.first;
2998         while(sc) {
2999                 
3000                 sc->scene= curscene;
3001
3002                 sa= sc->areabase.first;
3003                 while(sa) {
3004                         SpaceLink *sl;
3005
3006                         if (sa->scriptlink.totscript) {
3007                                 /* restore screen area script links */
3008                                 ScriptLink *slink = &sa->scriptlink;
3009                                 int script_idx;
3010                                 for (script_idx = 0; script_idx < slink->totscript; script_idx++) {
3011                                         slink->scripts[script_idx] = restore_pointer_by_name(newmain,
3012                                                 (ID *)slink->scripts[script_idx], 1);
3013                                 }
3014                         }
3015
3016                         for (sl= sa->spacedata.first; sl; sl= sl->next) {
3017                                 if(sl->spacetype==SPACE_VIEW3D) {
3018                                         View3D *v3d= (View3D*) sl;
3019                                         
3020                                         v3d->camera= sc->scene->camera;
3021                                         
3022                                         if(v3d->bgpic) {
3023                                                 v3d->bgpic->ima= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->ima, 1);
3024                                                 v3d->bgpic->tex= restore_pointer_by_name(newmain, (ID *)v3d->bgpic->tex, 1);
3025                                                 if(v3d->bgpic->rect) freeN(v3d->bgpic->rect);
3026                                                 v3d->bgpic->rect= NULL;
3027                                         }
3028                                         if(v3d->localvd) {
3029                                                 Base *base;
3030
3031                                                 v3d->localvd->camera= sc->scene->camera;
3032                                                 
3033                                                 /* localview can become invalid during undo/redo steps, so we exit it when no could be found */
3034                                                 for(base= sc->scene->base.first; base; base= base->next) {
3035                                                         if(base->lay & v3d->lay) break;
3036                                                 }
3037                                                 if(base==NULL) {
3038                                                         v3d->lay= v3d->localvd->lay;
3039                                                         v3d->layact= v3d->localvd->layact;
3040                                                         MEM_freeN(v3d->localvd);
3041                                                         v3d->localvd= NULL;
3042                                                         v3d->localview= 0;
3043                                                 }
3044                                         }
3045                                         else if(v3d->scenelock) v3d->lay= sc->scene->lay;
3046                                         
3047                                         /* not very nice, but could help */
3048                                         if((v3d->layact & v3d->lay)==0) v3d->layact= v3d->lay;
3049                                         
3050                                 }
3051                                 else if(sl->spacetype==SPACE_IPO) {
3052                                         SpaceIpo *sipo= (SpaceIpo *)sl;
3053                                         
3054                                         if(sipo->blocktype==ID_SEQ) sipo->from= NULL;   // no libdata
3055                                         else sipo->from= restore_pointer_by_name(newmain, (ID *)sipo->from, 0);
3056                                         
3057                                         // not free sipo->ipokey, creates dependency with src/
3058                                         sipo->ipo= restore_pointer_by_name(newmain, (ID *)sipo->ipo, 0);
3059                                         if(sipo->editipo) MEM_freeN(sipo->editipo);
3060                                         sipo->editipo= NULL;
3061                                 }
3062                                 else if(sl->spacetype==SPACE_BUTS) {
3063                                         SpaceButs *sbuts= (SpaceButs *)sl;
3064                                         sbuts->lockpoin= NULL;
3065                                         if (sbuts->ri) sbuts->ri->curtile = 0;
3066                                 }
3067                                 else if(sl->spacetype==SPACE_FILE) {
3068                                         SpaceFile *sfile= (SpaceFile *)sl;
3069                                         if(sfile->libfiledata)  
3070                                                 BLO_blendhandle_close(sfile->libfiledata);
3071                                         sfile->libfiledata= 0;
3072                                 }
3073                                 else if(sl->spacetype==SPACE_IMASEL) {
3074                                         ;
3075                                 }
3076                                 else if(sl->spacetype==SPACE_ACTION) {
3077                                         SpaceAction *saction= (SpaceAction *)sl;
3078                                         saction->action = restore_pointer_by_name(newmain, (ID *)saction->action, 1);
3079                                 }
3080                                 else if(sl->spacetype==SPACE_IMAGE) {
3081                                         SpaceImage *sima= (SpaceImage *)sl;
3082
3083                                         sima->image= restore_pointer_by_name(newmain, (ID *)sima->image, 1);
3084                                 }
3085                                 else if(sl->spacetype==SPACE_NLA){
3086                                         /* SpaceNla *snla= (SpaceNla *)sl;      */
3087                                 }
3088                                 else if(sl->spacetype==SPACE_TEXT) {
3089                                         SpaceText *st= (SpaceText *)sl;
3090
3091                                         st->text= restore_pointer_by_name(newmain, (ID *)st->text, 1);
3092                                         if(st->text==NULL) st->text= newmain->text.first;
3093                                 }
3094                                 else if(sl->spacetype==SPACE_SCRIPT) {
3095                                         SpaceScript *sc= (SpaceScript *)sl;
3096
3097                                         sc->script = NULL;
3098                                 }
3099                                 else if(sl->spacetype==SPACE_OOPS) {
3100                                         SpaceOops *so= (SpaceOops *)sl;
3101                                         Oops *oops;
3102                                         
3103                                         int a;
3104                                         oops= so->oops.first;
3105                                         while(oops) {
3106                                                 oops->id= restore_pointer_by_name(newmain, (ID *)oops->id, 0);
3107                                                 oops= oops->next;
3108                                         }
3109                                         so->lockpoin= NULL;
3110                                         
3111                                         if(so->treestore) {
3112                                                 TreeStore *ts= so->treestore;
3113                                                 TreeStoreElem *tselem=ts->data;
3114                                                 for(a=0; a<ts->usedelem; a++, tselem++) {
3115                                                         tselem->id= restore_pointer_by_name(newmain, tselem->id, 0);
3116                                                 }
3117                                         }
3118                                 }
3119                                 else if(sl->spacetype==SPACE_SOUND) {
3120                                         SpaceSound *ssound= (SpaceSound *)sl;
3121
3122                                         ssound->sound= restore_pointer_by_name(newmain, (ID *)ssound->sound, 1);
3123                                 }
3124                                 else if(sl->spacetype==SPACE_NODE) {
3125                                         SpaceNode *snode= (SpaceNode *)sl;
3126