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