778c1df7cd2f8e87bb09abe1a2e053061d90eb4e
[blender-staging.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include "zlib.h"
36
37 #ifdef WIN32
38 #include "winsock2.h"
39 #include "BLI_winstuff.h"
40 #endif
41
42 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
43 #include <stdlib.h> // for getenv atoi
44 #include <fcntl.h> // for open
45 #include <string.h> // for strrchr strncmp strstr
46 #include <math.h> // for fabs
47
48 #ifndef WIN32
49     #include <unistd.h> // for read close
50     #include <sys/param.h> // for MAXPATHLEN
51 #else
52     #include <io.h> // for open close read
53 #endif
54
55 #include "nla.h"
56
57 #include "DNA_action_types.h"
58 #include "DNA_armature_types.h"
59 #include "DNA_ID.h"
60 #include "DNA_actuator_types.h"
61 #include "DNA_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_DISTANCELIMIT:
1688                         {
1689                                 bDistanceLimitConstraint *data;
1690                                 data= ((bDistanceLimitConstraint*)con->data);
1691                                 data->tar = newlibadr(fd, id->lib, data->tar);
1692                         };
1693                         break;
1694                 case CONSTRAINT_TYPE_STRETCHTO:
1695                         {
1696                                 bStretchToConstraint *data;
1697                                 data= ((bStretchToConstraint*)con->data);
1698                                 data->tar = newlibadr(fd, id->lib, data->tar);
1699                         };
1700                         break;
1701                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1702                         {
1703                                 bRigidBodyJointConstraint *data;
1704                                 data= ((bRigidBodyJointConstraint*)con->data);
1705                                 data->tar = newlibadr(fd, id->lib, data->tar);
1706                         };
1707                         break;
1708                 case CONSTRAINT_TYPE_CLAMPTO:
1709                         {
1710                                 bClampToConstraint *data;
1711                                 data= ((bClampToConstraint*)con->data);
1712                                 data->tar = newlibadr(fd, id->lib, data->tar);
1713                         };
1714                         break;
1715
1716                 case CONSTRAINT_TYPE_NULL:
1717                         break;
1718                 }
1719         }
1720 }
1721
1722 static void direct_link_constraints(FileData *fd, ListBase *lb)
1723 {
1724         bConstraint *cons;
1725
1726         link_list(fd, lb);
1727         for (cons=lb->first; cons; cons=cons->next) {
1728                 cons->data = newdataadr(fd, cons->data);
1729                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
1730                         bPythonConstraint *data= cons->data;
1731                         data->prop = newdataadr(fd, data->prop);
1732                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1733                 }
1734         }
1735 }
1736
1737 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1738 {
1739         bPoseChannel *pchan;
1740         bArmature *arm= ob->data;
1741         int rebuild;
1742         
1743         if (!pose || !arm)
1744                 return;
1745         
1746         /* always rebuild to match proxy or lib changes */
1747         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
1748
1749         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1750                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1751                 
1752                 /* hurms... loop in a loop, but yah... later... (ton) */
1753                 pchan->bone= get_named_bone(arm, pchan->name);
1754                 
1755                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
1756                 if(pchan->bone==NULL)
1757                         rebuild= 1;
1758                 else if(ob->id.lib==NULL && arm->id.lib) {
1759                         /* local pose selection copied to armature, bit hackish */
1760                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
1761                         pchan->bone->flag |= pchan->selectflag;
1762                 }
1763         }
1764         
1765         if(rebuild) {
1766                 ob->recalc= OB_RECALC;
1767                 pose->flag |= POSE_RECALC;
1768         }
1769 }
1770
1771 static void lib_link_armature(FileData *fd, Main *main)
1772 {
1773         bArmature *arm;
1774
1775         arm= main->armature.first;
1776
1777         while(arm) {
1778                 if(arm->id.flag & LIB_NEEDLINK) {
1779                         arm->id.flag -= LIB_NEEDLINK;
1780                 }
1781                 arm= arm->id.next;
1782         }
1783 }
1784
1785 static void lib_link_action(FileData *fd, Main *main)
1786 {
1787         bAction *act;
1788         bActionChannel *chan;
1789
1790         act= main->action.first;
1791         while(act) {
1792                 if(act->id.flag & LIB_NEEDLINK) {
1793                         act->id.flag -= LIB_NEEDLINK;
1794
1795                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1796                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1797                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1798                         }
1799
1800                 }
1801                 act= act->id.next;
1802         }
1803 }
1804
1805 static void direct_link_bones(FileData *fd, Bone* bone)
1806 {
1807         Bone    *child;
1808
1809         bone->parent= newdataadr(fd, bone->parent);
1810
1811         link_list(fd, &bone->childbase);
1812
1813         for (child=bone->childbase.first; child; child=child->next) {
1814                 direct_link_bones(fd, child);
1815         }
1816 }
1817
1818
1819 static void direct_link_action(FileData *fd, bAction *act)
1820 {
1821         bActionChannel *achan;
1822
1823         link_list(fd, &act->chanbase);
1824
1825         for (achan = act->chanbase.first; achan; achan=achan->next)
1826                 link_list(fd, &achan->constraintChannels);
1827
1828 }
1829
1830 static void direct_link_armature(FileData *fd, bArmature *arm)
1831 {
1832         Bone    *bone;
1833
1834         link_list(fd, &arm->bonebase);
1835
1836         bone=arm->bonebase.first;
1837         while (bone) {
1838                 direct_link_bones(fd, bone);
1839                 bone=bone->next;
1840         }
1841 }
1842
1843 /* ************ READ CAMERA ***************** */
1844
1845 static void lib_link_camera(FileData *fd, Main *main)
1846 {
1847         Camera *ca;
1848
1849         ca= main->camera.first;
1850         while(ca) {
1851                 if(ca->id.flag & LIB_NEEDLINK) {
1852
1853                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1854
1855                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1856
1857                         ca->id.flag -= LIB_NEEDLINK;
1858                 }
1859                 ca= ca->id.next;
1860         }
1861 }
1862
1863 static void direct_link_camera(FileData *fd, Camera *ca)
1864 {
1865         direct_link_scriptlink(fd, &ca->scriptlink);
1866 }
1867
1868
1869 /* ************ READ LAMP ***************** */
1870
1871 static void lib_link_lamp(FileData *fd, Main *main)
1872 {
1873         Lamp *la;
1874         MTex *mtex;
1875         int a;
1876
1877         la= main->lamp.first;
1878         while(la) {
1879                 if(la->id.flag & LIB_NEEDLINK) {
1880
1881                         for(a=0; a<MAX_MTEX; a++) {
1882                                 mtex= la->mtex[a];
1883                                 if(mtex) {
1884                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1885                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1886                                 }
1887                         }
1888
1889                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1890
1891                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1892
1893                         la->id.flag -= LIB_NEEDLINK;
1894                 }
1895                 la= la->id.next;
1896         }
1897 }
1898
1899 static void direct_link_lamp(FileData *fd, Lamp *la)
1900 {
1901         int a;
1902
1903         direct_link_scriptlink(fd, &la->scriptlink);
1904
1905         for(a=0; a<MAX_MTEX; a++) {
1906                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1907         }
1908 }
1909
1910 /* ************ READ keys ***************** */
1911
1912 static void lib_link_key(FileData *fd, Main *main)
1913 {
1914         Key *key;
1915
1916         key= main->key.first;
1917         while(key) {
1918                 if(key->id.flag & LIB_NEEDLINK) {
1919
1920                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1921                         key->from= newlibadr(fd, key->id.lib, key->from);
1922
1923                         key->id.flag -= LIB_NEEDLINK;
1924                 }
1925                 key= key->id.next;
1926         }
1927 }
1928
1929 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1930 {
1931         int elemsize, a, b;
1932         char *data, *poin, *cp;
1933
1934         elemsize= key->elemsize;
1935         data= kb->data;
1936
1937         for(a=0; a<kb->totelem; a++) {
1938
1939                 cp= key->elemstr;
1940                 poin= data;
1941
1942                 while( cp[0] ) {        /* cp[0]==amount */
1943
1944                         switch(cp[1]) {         /* cp[1]= type */
1945                         case IPO_FLOAT:
1946                         case IPO_BPOINT:
1947                         case IPO_BEZTRIPLE:
1948                                 b= cp[0];
1949                                 while(b--) {
1950                                         SWITCH_INT((*poin));
1951                                         poin+= 4;
1952                                 }
1953                                 break;
1954                         }
1955
1956                         cp+= 2;
1957
1958                 }
1959                 data+= elemsize;
1960         }
1961 }
1962
1963 static void direct_link_key(FileData *fd, Key *key)
1964 {
1965         KeyBlock *kb;
1966
1967         link_list(fd, &(key->block));
1968
1969         key->refkey= newdataadr(fd, key->refkey);
1970
1971         kb= key->block.first;
1972         while(kb) {
1973
1974                 kb->data= newdataadr(fd, kb->data);
1975
1976                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1977                         switch_endian_keyblock(key, kb);
1978
1979                 kb= kb->next;
1980         }
1981 }
1982
1983 /* ************ READ mball ***************** */
1984
1985 static void lib_link_mball(FileData *fd, Main *main)
1986 {
1987         MetaBall *mb;
1988         int a;
1989
1990         mb= main->mball.first;
1991         while(mb) {
1992                 if(mb->id.flag & LIB_NEEDLINK) {
1993
1994                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1995
1996                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1997
1998                         mb->id.flag -= LIB_NEEDLINK;
1999                 }
2000                 mb= mb->id.next;
2001         }
2002 }
2003
2004 static void direct_link_mball(FileData *fd, MetaBall *mb)
2005 {
2006         mb->mat= newdataadr(fd, mb->mat);
2007         test_pointer_array(fd, (void **)&mb->mat);
2008
2009         link_list(fd, &(mb->elems));
2010
2011         mb->disp.first= mb->disp.last= 0;
2012
2013         mb->bb= 0;
2014 }
2015
2016 /* ************ READ WORLD ***************** */
2017
2018 static void lib_link_world(FileData *fd, Main *main)
2019 {
2020         World *wrld;
2021         MTex *mtex;
2022         int a;
2023
2024         wrld= main->world.first;
2025         while(wrld) {
2026                 if(wrld->id.flag & LIB_NEEDLINK) {
2027
2028                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
2029
2030                         for(a=0; a<MAX_MTEX; a++) {
2031                                 mtex= wrld->mtex[a];
2032                                 if(mtex) {
2033                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2034                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2035                                 }
2036                         }
2037
2038                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2039
2040                         wrld->id.flag -= LIB_NEEDLINK;
2041                 }
2042                 wrld= wrld->id.next;
2043         }
2044 }
2045
2046 static void direct_link_world(FileData *fd, World *wrld)
2047 {
2048         int a;
2049
2050         direct_link_scriptlink(fd, &wrld->scriptlink);
2051
2052         for(a=0; a<MAX_MTEX; a++) {
2053                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2054         }
2055 }
2056
2057
2058 /* ************ READ IPO ***************** */
2059
2060 static void lib_link_ipo(FileData *fd, Main *main)
2061 {
2062         Ipo *ipo;
2063
2064         ipo= main->ipo.first;
2065         while(ipo) {
2066                 if(ipo->id.flag & LIB_NEEDLINK) {
2067                         IpoCurve *icu;
2068                         for(icu= ipo->curve.first; icu; icu= icu->next) {
2069                                 if(icu->driver)
2070                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
2071                         }
2072                         ipo->id.flag -= LIB_NEEDLINK;
2073                 }
2074                 ipo= ipo->id.next;
2075         }
2076 }
2077
2078 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2079 {
2080         IpoCurve *icu;
2081
2082         link_list(fd, &(ipo->curve));
2083         icu= ipo->curve.first;
2084         while(icu) {
2085                 icu->bezt= newdataadr(fd, icu->bezt);
2086                 icu->bp= newdataadr(fd, icu->bp);
2087                 icu->driver= newdataadr(fd, icu->driver);
2088                 icu= icu->next;
2089         }
2090 }
2091
2092 /* ************ READ VFONT ***************** */
2093
2094 static void lib_link_vfont(FileData *fd, Main *main)
2095 {
2096         VFont *vf;
2097
2098         vf= main->vfont.first;
2099         while(vf) {
2100                 if(vf->id.flag & LIB_NEEDLINK) {
2101                         vf->id.flag -= LIB_NEEDLINK;
2102                 }
2103                 vf= vf->id.next;
2104         }
2105 }
2106
2107 static void direct_link_vfont(FileData *fd, VFont *vf)
2108 {
2109         vf->data= NULL;
2110         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2111 }
2112
2113 /* ************ READ TEXT ****************** */
2114
2115 static void lib_link_text(FileData *fd, Main *main)
2116 {
2117         Text *text;
2118
2119         text= main->text.first;
2120         while(text) {
2121                 if(text->id.flag & LIB_NEEDLINK) {
2122                         text->id.flag -= LIB_NEEDLINK;
2123                 }
2124                 text= text->id.next;
2125         }
2126 }
2127
2128 static void direct_link_text(FileData *fd, Text *text)
2129 {
2130         TextLine *ln;
2131
2132         text->name= newdataadr(fd, text->name);
2133
2134         text->undo_pos= -1;
2135         text->undo_len= TXT_INIT_UNDO;
2136         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2137
2138         text->compiled= NULL;
2139
2140 /*
2141         if(text->flags & TXT_ISEXT) {
2142                 reopen_text(text);
2143         } else {
2144 */
2145
2146         link_list(fd, &text->lines);
2147
2148         text->curl= newdataadr(fd, text->curl);
2149         text->sell= newdataadr(fd, text->sell);
2150
2151         ln= text->lines.first;
2152         while(ln) {
2153                 ln->line= newdataadr(fd, ln->line);
2154                 ln->format= NULL;
2155                 
2156                 if (ln->len != (int) strlen(ln->line)) {
2157                         printf("Error loading text, line lengths differ\n");
2158                         ln->len = strlen(ln->line);
2159                 }
2160
2161                 ln= ln->next;
2162         }
2163
2164         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
2165
2166         text->id.us= 1;
2167 }
2168
2169 /* ************ READ IMAGE ***************** */
2170
2171 static void lib_link_image(FileData *fd, Main *main)
2172 {
2173         Image *ima;
2174
2175         ima= main->image.first;
2176         while (ima) {
2177                 if(ima->id.flag & LIB_NEEDLINK) {
2178                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2179
2180                         ima->id.flag -= LIB_NEEDLINK;
2181                 }
2182                 ima= ima->id.next;
2183         }
2184 }
2185
2186 static void link_ibuf_list(FileData *fd, ListBase *lb)
2187 {
2188         Link *ln, *prev;
2189         
2190         if(lb->first==NULL) return;
2191         
2192         lb->first= newimaadr(fd, lb->first);
2193         ln= lb->first;
2194         prev= NULL;
2195         while(ln) {
2196                 ln->next= newimaadr(fd, ln->next);
2197                 ln->prev= prev;
2198                 prev= ln;
2199                 ln= ln->next;
2200         }
2201         lb->last= prev;
2202 }
2203
2204 static void direct_link_image(FileData *fd, Image *ima)
2205 {
2206         /* for undo system, pointers could be restored */
2207         if(fd->imamap)
2208                 link_ibuf_list(fd, &ima->ibufs);
2209         else
2210                 ima->ibufs.first= ima->ibufs.last= NULL;
2211         
2212         /* if not restored, we keep the binded opengl index */
2213         if(ima->ibufs.first==NULL)
2214                 ima->bindcode= 0;
2215         
2216         ima->anim= NULL;
2217         ima->rr= NULL;
2218         ima->repbind= NULL;
2219         
2220         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2221         ima->preview = direct_link_preview_image(fd, ima->preview);
2222         ima->ok= 1;
2223 }
2224
2225
2226 /* ************ READ CURVE ***************** */
2227
2228 static void lib_link_curve(FileData *fd, Main *main)
2229 {
2230         Curve *cu;
2231         int a;
2232
2233         cu= main->curve.first;
2234         while(cu) {
2235                 if(cu->id.flag & LIB_NEEDLINK) {
2236
2237                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2238
2239                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2240                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2241                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2242                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2243                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2244                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2245                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2246
2247                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
2248                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2249
2250                         cu->id.flag -= LIB_NEEDLINK;
2251                 }
2252                 cu= cu->id.next;
2253         }
2254 }
2255
2256
2257 static void switch_endian_knots(Nurb *nu)
2258 {
2259         int len;
2260
2261         if(nu->knotsu) {
2262                 len= KNOTSU(nu);
2263                 while(len--) {
2264                         SWITCH_INT(nu->knotsu[len]);
2265                 }
2266         }
2267         if(nu->knotsv) {
2268                 len= KNOTSV(nu);
2269                 while(len--) {
2270                         SWITCH_INT(nu->knotsv[len]);
2271                 }
2272         }
2273 }
2274
2275 static void direct_link_curve(FileData *fd, Curve *cu)
2276 {
2277         Nurb *nu;
2278         TextBox *tb;
2279
2280         cu->mat= newdataadr(fd, cu->mat);
2281         test_pointer_array(fd, (void **)&cu->mat);
2282         cu->str= newdataadr(fd, cu->str);
2283         cu->strinfo= newdataadr(fd, cu->strinfo);       
2284         cu->tb= newdataadr(fd, cu->tb);
2285
2286         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2287         else {
2288                 cu->nurb.first=cu->nurb.last= 0;
2289
2290                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2291                 if (cu->tb) {
2292                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2293                         MEM_freeN(cu->tb);
2294                         cu->tb= tb;                     
2295                 } else {
2296                         cu->totbox = 1;
2297                         cu->actbox = 1;
2298                         cu->tb = tb;
2299                         cu->tb[0].w = cu->linewidth;
2300                 }               
2301                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2302         }
2303
2304         cu->bev.first=cu->bev.last= 0;
2305         cu->disp.first=cu->disp.last= 0;
2306         cu->path= 0;
2307
2308         nu= cu->nurb.first;
2309         while(nu) {
2310                 nu->bezt= newdataadr(fd, nu->bezt);
2311                 nu->bp= newdataadr(fd, nu->bp);
2312                 nu->knotsu= newdataadr(fd, nu->knotsu);
2313                 nu->knotsv= newdataadr(fd, nu->knotsv);
2314                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2315
2316                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2317                         switch_endian_knots(nu);
2318                 }
2319
2320                 nu= nu->next;
2321         }
2322         cu->bb= NULL;
2323 }
2324
2325 /* ************ READ TEX ***************** */
2326
2327 static void lib_link_texture(FileData *fd, Main *main)
2328 {
2329         Tex *tex;
2330
2331         tex= main->tex.first;
2332         while(tex) {
2333                 if(tex->id.flag & LIB_NEEDLINK) {
2334
2335                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2336                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2337                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2338
2339                         tex->id.flag -= LIB_NEEDLINK;
2340                 }
2341                 tex= tex->id.next;
2342         }
2343 }
2344
2345 static void direct_link_texture(FileData *fd, Tex *tex)
2346 {
2347         tex->plugin= newdataadr(fd, tex->plugin);
2348         if(tex->plugin) {
2349                 tex->plugin->handle= 0;
2350                 open_plugin_tex(tex->plugin);
2351                 /* initialize data for this instance, if an initialization
2352                  * function exists.
2353                  */
2354                 if (tex->plugin->instance_init)
2355                         tex->plugin->instance_init((void *) tex->plugin->data);
2356         }
2357         tex->coba= newdataadr(fd, tex->coba);
2358         tex->env= newdataadr(fd, tex->env);
2359         if(tex->env) {
2360                 tex->env->ima= NULL;
2361                 memset(tex->env->cube, 0, 6*sizeof(void *));
2362                 tex->env->ok= 0;
2363         }
2364         tex->iuser.ok= 1;
2365 }
2366
2367
2368
2369 /* ************ READ MATERIAL ***************** */
2370
2371 static void lib_link_material(FileData *fd, Main *main)
2372 {
2373         Material *ma;
2374         MTex *mtex;
2375         int a;
2376
2377         ma= main->mat.first;
2378         while(ma) {
2379                 if(ma->id.flag & LIB_NEEDLINK) {
2380                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2381                         of library blocks that implement this.*/
2382                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2383
2384                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2385                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2386                         
2387                         for(a=0; a<MAX_MTEX; a++) {
2388                                 mtex= ma->mtex[a];
2389                                 if(mtex) {
2390                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2391                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2392                                 }
2393                         }
2394                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2395                         
2396                         if(ma->nodetree)
2397                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2398                         
2399                         ma->id.flag -= LIB_NEEDLINK;
2400                 }
2401                 ma= ma->id.next;
2402         }
2403 }
2404
2405 static void direct_link_material(FileData *fd, Material *ma)
2406 {
2407         int a;
2408
2409         for(a=0; a<MAX_MTEX; a++) {
2410                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2411         }
2412
2413         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2414         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2415         
2416         direct_link_scriptlink(fd, &ma->scriptlink);
2417         
2418         ma->nodetree= newdataadr(fd, ma->nodetree);
2419         if(ma->nodetree)
2420                 direct_link_nodetree(fd, ma->nodetree);
2421 }
2422
2423 /* ************ READ MESH ***************** */
2424
2425 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
2426 {
2427         MTFace *tf= mtface;
2428         int i;
2429
2430         for (i=0; i<totface; i++, tf++) {
2431                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2432                 if(tf->tpage && tf->tpage->id.us==0)
2433                         tf->tpage->id.us= 1;
2434         }
2435 }
2436
2437 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
2438 {
2439         int i;  
2440         for(i=0; i<fdata->totlayer; i++) {
2441                 CustomDataLayer *layer = &fdata->layers[i];
2442                 
2443                 if(layer->type == CD_MTFACE)
2444                         lib_link_mtface(fd, me, layer->data, totface);
2445         }
2446
2447 }
2448
2449 static void lib_link_mesh(FileData *fd, Main *main)
2450 {
2451         Mesh *me;
2452
2453         me= main->mesh.first;
2454         while(me) {
2455                 if(me->id.flag & LIB_NEEDLINK) {
2456                         int i;
2457
2458                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2459                         of library blocks that implement this.*/
2460                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2461
2462                         /* this check added for python created meshes */
2463                         if(me->mat) {
2464                                 for(i=0; i<me->totcol; i++) {
2465                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2466                                 }
2467                         }
2468                         else me->totcol= 0;
2469
2470                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2471                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2472                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2473
2474                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
2475                         if(me->mr && me->mr->levels.first)
2476                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
2477                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
2478
2479                         me->id.flag -= LIB_NEEDLINK;
2480                 }
2481                 me= me->id.next;
2482         }
2483 }
2484
2485 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2486 {
2487         int     i;
2488
2489         if (!mdverts)
2490                 return;
2491
2492         for (i=0; i<count; i++) {
2493                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2494                 if (!mdverts[i].dw)
2495                         mdverts[i].totweight=0;
2496         }
2497 }
2498
2499 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
2500 {
2501         int i = 0;
2502
2503         data->layers= newdataadr(fd, data->layers);
2504
2505         while (i < data->totlayer) {
2506                 CustomDataLayer *layer = &data->layers[i];
2507
2508                 if (CustomData_verify_versions(data, i)) {
2509                         layer->data = newdataadr(fd, layer->data);
2510                         i++;
2511                 }
2512         }
2513 }
2514
2515 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2516 {
2517         mesh->mat= newdataadr(fd, mesh->mat);
2518         test_pointer_array(fd, (void **)&mesh->mat);
2519
2520         mesh->mvert= newdataadr(fd, mesh->mvert);
2521         mesh->medge= newdataadr(fd, mesh->medge);
2522         mesh->mface= newdataadr(fd, mesh->mface);
2523         mesh->tface= newdataadr(fd, mesh->tface);
2524         mesh->mtface= newdataadr(fd, mesh->mtface);
2525         mesh->mcol= newdataadr(fd, mesh->mcol);
2526         mesh->msticky= newdataadr(fd, mesh->msticky);
2527         mesh->dvert= newdataadr(fd, mesh->dvert);
2528         
2529         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
2530         mesh->pv= newdataadr(fd, mesh->pv);
2531         if(mesh->pv) {
2532                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
2533                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
2534                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
2535                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
2536         }
2537
2538         /* normally direct_link_dverts should be called in direct_link_customdata,
2539            but for backwards compat in do_versions to work we do it here */
2540         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
2541
2542         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
2543         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
2544         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
2545
2546         mesh->bb= NULL;
2547         mesh->oc= 0;
2548         mesh->mselect= NULL;
2549
2550         /* Multires data */
2551         mesh->mr= newdataadr(fd, mesh->mr);
2552         if(mesh->mr) {
2553                 MultiresLevel *lvl;
2554                 
2555                 link_list(fd, &mesh->mr->levels);
2556                 lvl= mesh->mr->levels.first;
2557                 
2558                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
2559                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
2560                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
2561                 
2562                 if(mesh->mr->edge_flags)
2563                         mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
2564                 if(mesh->mr->edge_creases)
2565                         mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
2566                 
2567                 if(!mesh->mr->edge_flags)
2568                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
2569                 if(!mesh->mr->edge_creases)
2570                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
2571
2572                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
2573                         
2574                 for(; lvl; lvl= lvl->next) {
2575                         lvl->verts= newdataadr(fd, lvl->verts);
2576                         lvl->faces= newdataadr(fd, lvl->faces);
2577                         lvl->edges= newdataadr(fd, lvl->edges);
2578                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
2579                         lvl->edge_boundary_states= NULL;
2580                         lvl->vert_face_map = lvl->vert_edge_map = NULL;
2581                         lvl->map_mem= NULL;
2582                 }
2583         }
2584         
2585         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
2586                 TFace *tf= mesh->tface;
2587                 int i;
2588
2589                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
2590                         SWITCH_INT(tf->col[0]);
2591                         SWITCH_INT(tf->col[1]);
2592                         SWITCH_INT(tf->col[2]);
2593                         SWITCH_INT(tf->col[3]);
2594                 }
2595         }
2596 }
2597
2598 /* ************ READ LATTICE ***************** */
2599
2600 static void lib_link_latt(FileData *fd, Main *main)
2601 {
2602         Lattice *lt;
2603         
2604         lt= main->latt.first;
2605         while(lt) {
2606                 if(lt->id.flag & LIB_NEEDLINK) {
2607                         
2608                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
2609                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
2610                         
2611                         lt->id.flag -= LIB_NEEDLINK;
2612                 }
2613                 lt= lt->id.next;
2614         }
2615 }
2616
2617 static void direct_link_latt(FileData *fd, Lattice *lt)
2618 {
2619         lt->def= newdataadr(fd, lt->def);
2620         
2621         lt->dvert= newdataadr(fd, lt->dvert);
2622         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
2623 }
2624
2625
2626 /* ************ READ OBJECT ***************** */
2627
2628 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
2629                                               ID **idpoin)
2630 {
2631         FileData *fd = userData;
2632
2633         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
2634         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
2635         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
2636                 (*idpoin)->us++;
2637 }
2638 static void lib_link_modifiers(FileData *fd, Object *ob)
2639 {
2640         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
2641 }
2642
2643 static void lib_link_object(FileData *fd, Main *main)
2644 {
2645         Object *ob;
2646         PartEff *paf;
2647         bSensor *sens;
2648         bController *cont;
2649         bActuator *act;
2650         void *poin;
2651         int warn=0, a;
2652
2653         ob= main->object.first;
2654         while(ob) {
2655                 if(ob->id.flag & LIB_NEEDLINK) {
2656                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2657
2658                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2659                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2660                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2661                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2662                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
2663                         
2664                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
2665                         if(ob->proxy) {
2666                                 /* paranoia check, actually a proxy_from pointer should never be written... */
2667                                 if(ob->proxy->id.lib==NULL) {
2668                                         ob->proxy->proxy_from= NULL;
2669                                         ob->proxy= NULL;
2670                                 }
2671                                 else {
2672                                         /* this triggers object_update to always use a copy */
2673                                         ob->proxy->proxy_from= ob;
2674                                         /* force proxy updates after load/undo, a bit weak */
2675                                         ob->recalc= ob->proxy->recalc= OB_RECALC;
2676                                 }
2677                         }
2678                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
2679
2680                         poin= ob->data;
2681                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2682                            
2683                         if(ob->data==NULL && poin!=NULL) {
2684                                 ob->type= OB_EMPTY;
2685                                 warn= 1;
2686                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2687                                 else printf("Object %s lost data.", ob->id.name+2);
2688                                 
2689                                 if(ob->pose) {
2690                                         free_pose_channels(ob->pose);
2691                                         MEM_freeN(ob->pose);
2692                                         ob->pose= NULL;
2693                                         ob->flag &= ~OB_POSEMODE;
2694                                 }
2695                         }
2696                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2697
2698                         ob->id.flag -= LIB_NEEDLINK;
2699                         /* if id.us==0 a new base will be created later on */
2700
2701                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2702                         lib_link_pose(fd, ob, ob->pose);
2703                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2704                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2705                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2706
2707                         for(paf= ob->effect.first; paf; paf= paf->next) {
2708                                 if(paf->type==EFF_PARTICLE) {
2709                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
2710                                 }
2711                         }                               
2712
2713                         sens= ob->sensors.first;
2714                         while(sens) {
2715                                 if(ob->id.lib==NULL) {  // done in expand_main
2716                                         for(a=0; a<sens->totlinks; a++) {
2717                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2718                                         }
2719                                 }
2720                                 if(sens->type==SENS_TOUCH) {
2721                                         bTouchSensor *ts= sens->data;
2722                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2723                                 }
2724                                 else if(sens->type==SENS_MESSAGE) {
2725                                         bMessageSensor *ms= sens->data;
2726                                         ms->fromObject=
2727                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2728                                 }
2729                                 sens= sens->next;
2730                         }
2731
2732                         cont= ob->controllers.first;
2733                         while(cont) {
2734                                 if(ob->id.lib==NULL) {  // done in expand_main
2735                                         for(a=0; a<cont->totlinks; a++) {
2736                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2737                                         }
2738                                 }
2739                                 if(cont->type==CONT_PYTHON) {
2740                                         bPythonCont *pc= cont->data;
2741                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2742                                 }
2743                                 cont->slinks= NULL;
2744                                 cont->totslinks= 0;
2745
2746                                 cont= cont->next;
2747                         }
2748
2749                         act= ob->actuators.first;
2750                         while(act) {
2751                                 if(act->type==ACT_SOUND) {
2752                                         bSoundActuator *sa= act->data;
2753                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2754                                 }
2755                                 else if(act->type==ACT_CD) {
2756                                         /* bCDActuator *cda= act->data; */
2757                                 }
2758                                 else if(act->type==ACT_GAME) {
2759                                         /* bGameActuator *ga= act->data; */
2760                                 }
2761                                 else if(act->type==ACT_CAMERA) {
2762                                         bCameraActuator *ca= act->data;
2763                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2764                                 }
2765                                         /* leave this one, it's obsolete but necessary to read for conversion */
2766                                 else if(act->type==ACT_ADD_OBJECT) {
2767                                         bAddObjectActuator *eoa= act->data;
2768                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2769                                 }
2770                                 else if(act->type==ACT_EDIT_OBJECT) {
2771                                         bEditObjectActuator *eoa= act->data;
2772                                         if(eoa==NULL) {
2773                                                 init_actuator(act);
2774                                         }
2775                                         else {
2776                                                 eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2777                                                 eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2778                                         }
2779                                 }
2780                                 else if(act->type==ACT_SCENE) {
2781                                         bSceneActuator *sa= act->data;
2782                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2783                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2784                                 }
2785                                 else if(act->type==ACT_ACTION) {
2786                                         bActionActuator *aa= act->data;
2787                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2788                                 }
2789                                 else if(act->type==ACT_PROPERTY) {
2790                                         bPropertyActuator *pa= act->data;
2791                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2792                                 }
2793                                 else if(act->type==ACT_MESSAGE) {
2794                                         bMessageActuator *ma= act->data;
2795                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2796                                 }
2797                                 act= act->next;
2798                         }
2799
2800                         if(ob->fluidsimSettings) {
2801                                 ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
2802                         }
2803
2804                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2805                         lib_link_modifiers(fd, ob);
2806                 }
2807                 ob= ob->id.next;
2808         }
2809
2810         if(warn) error("WARNING IN CONSOLE");
2811 }
2812
2813
2814 static void direct_link_pose(FileData *fd, bPose *pose) {
2815
2816         bPoseChannel *pchan;
2817
2818         if (!pose)
2819                 return;
2820
2821         link_list(fd, &pose->chanbase);
2822
2823         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2824                 pchan->bone= NULL;
2825                 pchan->parent= newdataadr(fd, pchan->parent);
2826                 pchan->child= newdataadr(fd, pchan->child);
2827                 direct_link_constraints(fd, &pchan->constraints);
2828                 pchan->iktree.first= pchan->iktree.last= NULL;
2829                 pchan->path= NULL;
2830         }
2831
2832 }
2833
2834 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2835 {
2836         ModifierData *md;
2837
2838         link_list(fd, lb);
2839
2840         for (md=lb->first; md; md=md->next) {
2841                 md->error = NULL;
2842                 
2843                 /* if modifiers disappear, or for upward compatibility */
2844                 if(NULL==modifierType_getInfo(md->type))
2845                         md->type= eModifierType_None;
2846                         
2847                 if (md->type==eModifierType_Subsurf) {
2848                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2849
2850                         smd->emCache = smd->mCache = 0;
2851                 } else if (md->type==eModifierType_Hook) {
2852                         HookModifierData *hmd = (HookModifierData*) md;
2853
2854                         hmd->indexar= newdataadr(fd, hmd->indexar);
2855                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2856                                 int a;
2857                                 for(a=0; a<hmd->totindex; a++) {
2858                                         SWITCH_INT(hmd->indexar[a]);
2859                                 }
2860                         }
2861                 }
2862         }
2863 }
2864
2865 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
2866 {
2867         bActionStrip *strip;
2868         
2869         link_list(fd, strips);
2870         
2871         for(strip= strips->first; strip; strip= strip->next)
2872                 link_list(fd, &strip->modifiers);
2873 }
2874
2875 static void direct_link_object(FileData *fd, Object *ob)
2876 {
2877         PartEff *paf;
2878         bProperty *prop;
2879         bSensor *sens;
2880         bController *cont;
2881         bActuator *act;
2882         int a;
2883         
2884         /* weak weak... this was only meant as draw flag, now is used in give_base too */
2885         ob->flag &= ~OB_FROMGROUP;
2886
2887         ob->disp.first=ob->disp.last= NULL;
2888
2889         ob->pose= newdataadr(fd, ob->pose);
2890         direct_link_pose(fd, ob->pose);
2891
2892         link_list(fd, &ob->defbase);
2893         direct_link_nlastrips(fd, &ob->nlastrips);
2894         link_list(fd, &ob->constraintChannels);
2895
2896         direct_link_scriptlink(fd, &ob->scriptlink);
2897
2898         ob->mat= newdataadr(fd, ob->mat);
2899         test_pointer_array(fd, (void **)&ob->mat);
2900         
2901         /* do it here, below old data gets converted */
2902         direct_link_modifiers(fd, &ob->modifiers);
2903         
2904         link_list(fd, &ob->effect);
2905         paf= ob->effect.first;
2906         while(paf) {
2907                 if(paf->type==EFF_PARTICLE) {
2908                         paf->keys= NULL;
2909                 }
2910                 if(paf->type==EFF_WAVE) {
2911                         WaveEff *wav = (WaveEff*) paf;
2912                         PartEff *next = paf->next;
2913                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
2914
2915                         wmd->damp = wav->damp;
2916                         wmd->flag = wav->flag;
2917                         wmd->height = wav->height;
2918                         wmd->lifetime = wav->lifetime;
2919                         wmd->narrow = wav->narrow;
2920                         wmd->speed = wav->speed;
2921                         wmd->startx = wav->startx;
2922                         wmd->starty = wav->startx;
2923                         wmd->timeoffs = wav->timeoffs;
2924                         wmd->width = wav->width;
2925
2926                         BLI_addtail(&ob->modifiers, wmd);
2927
2928                         BLI_remlink(&ob->effect, paf);
2929                         MEM_freeN(paf);
2930
2931                         paf = next;
2932                         continue;
2933                 }
2934                 if(paf->type==EFF_BUILD) {
2935                         BuildEff *baf = (BuildEff*) paf;
2936                         PartEff *next = paf->next;
2937                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
2938
2939                         bmd->start = baf->sfra;
2940                         bmd->length = baf->len;
2941                         bmd->randomize = 0;
2942                         bmd->seed = 1;
2943
2944                         BLI_addtail(&ob->modifiers, bmd);
2945
2946                         BLI_remlink(&ob->effect, paf);
2947                         MEM_freeN(paf);
2948
2949                         paf = next;
2950                         continue;
2951                 }
2952                 paf= paf->next;
2953         }
2954
2955         ob->pd= newdataadr(fd, ob->pd);
2956         ob->soft= newdataadr(fd, ob->soft);
2957         if(ob->soft) {
2958                 SoftBody *sb= ob->soft;         
2959                 
2960                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2961                 sb->bspring= NULL;
2962                 sb->scratch= NULL;
2963
2964                 
2965                 sb->keys= newdataadr(fd, sb->keys);
2966                 test_pointer_array(fd, (void **)&sb->keys);
2967                 if(sb->keys) {
2968                         for(a=0; a<sb->totkey; a++) {
2969                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
2970                         }
2971                 }
2972         }
2973         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
2974         if(ob->fluidsimSettings) {
2975                 // reinit mesh pointers
2976                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
2977                 ob->fluidsimSettings->meshSurface = NULL;
2978                 ob->fluidsimSettings->meshBB = NULL;
2979                 ob->fluidsimSettings->meshSurfNormals = NULL;
2980         }
2981         
2982         link_list(fd, &ob->prop);
2983         prop= ob->prop.first;
2984         while(prop) {
2985                 prop->poin= newdataadr(fd, prop->poin);
2986                 if(prop->poin==0) prop->poin= &prop->data;
2987                 prop= prop->next;
2988         }
2989
2990         link_list(fd, &ob->sensors);
2991         sens= ob->sensors.first;
2992         while(sens) {
2993                 sens->data= newdataadr(fd, sens->data);
2994                 sens->links= newdataadr(fd, sens->links);
2995                 test_pointer_array(fd, (void **)&sens->links);
2996                 sens= sens->next;
2997         }
2998
2999         direct_link_constraints(fd, &ob->constraints);
3000
3001         link_glob_list(fd, &ob->controllers);
3002         cont= ob->controllers.first;
3003         while(cont) {
3004                 cont->data= newdataadr(fd, cont->data);
3005                 cont->links= newdataadr(fd, cont->links);
3006                 test_pointer_array(fd, (void **)&cont->links);
3007                 cont= cont->next;
3008         }
3009
3010         link_glob_list(fd, &ob->actuators);
3011         act= ob->actuators.first;
3012         while(act) {
3013                 act->data= newdataadr(fd, act->data);
3014                 act= act->next;
3015         }
3016
3017         link_list(fd, &ob->hooks);
3018         while (ob->hooks.first) {
3019                 ObHook *hook = ob->hooks.first;
3020                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
3021
3022                 hook->indexar= newdataadr(fd, hook->indexar);
3023                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3024                         int a;
3025                         for(a=0; a<hook->totindex; a++) {
3026                                 SWITCH_INT(hook->indexar[a]);
3027                         }
3028                 }
3029
3030                         /* Do conversion here because if we have loaded
3031                          * a hook we need to make sure it gets converted
3032                          * and free'd, regardless of version.
3033                          */
3034                 VECCOPY(hmd->cent, hook->cent);
3035                 hmd->falloff = hook->falloff;
3036                 hmd->force = hook->force;
3037                 hmd->indexar = hook->indexar;
3038                 hmd->object = hook->parent;
3039                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
3040                 hmd->totindex = hook->totindex;
3041
3042                 BLI_addhead(&ob->modifiers, hmd);
3043                 BLI_remlink(&ob->hooks, hook);
3044
3045                 MEM_freeN(hook);
3046         }
3047         
3048         ob->bb= NULL;
3049         ob->derivedDeform= NULL;
3050         ob->derivedFinal= NULL;
3051 }
3052
3053 /* ************ READ SCENE ***************** */
3054
3055 static void lib_link_scene(FileData *fd, Main *main)
3056 {
3057         Scene *sce;
3058         Base *base, *next;
3059         Editing *ed;
3060         Sequence *seq;
3061         SceneRenderLayer *srl;
3062         int a;
3063         
3064         sce= main->scene.first;
3065         while(sce) {
3066                 if(sce->id.flag & LIB_NEEDLINK) {
3067                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3068                         of library blocks that implement this.*/
3069                         if (sce->id.properties) IDP_LibLinkProperty(sce->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3070
3071                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
3072                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
3073                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
3074                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
3075                         sce->toolsettings->imapaint.brush=
3076                                 newlibadr_us(fd, sce->id.lib, sce->toolsettings->imapaint.brush);
3077
3078                         /* Sculptdata textures */
3079                         for(a=0; a<MAX_MTEX; ++a) {
3080                                 MTex *mtex= sce->sculptdata.mtex[a];
3081                                 if(mtex)
3082                                         mtex->tex= newlibadr_us(fd, sce->id.lib, mtex->tex);
3083                         }
3084
3085                         for(base= sce->base.first; base; base= next) {
3086                                 next= base->next;
3087
3088                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
3089                                 base->object= newlibadr_us(fd, sce->id.lib, base->object);
3090                                 
3091                                 /* when save during radiotool, needs cleared */
3092                                 base->flag &= ~OB_RADIO;
3093                                 
3094                                 if(base->object==NULL) {
3095                                         printf("LIB ERROR: base removed\n");
3096                                         BLI_remlink(&sce->base, base);
3097                                         if(base==sce->basact) sce->basact= 0;
3098                                         MEM_freeN(base);
3099                                 }
3100                         }
3101
3102                         ed= sce->ed;
3103                         if(ed) {
3104                                 WHILE_SEQ(&ed->seqbase) {
3105                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
3106                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
3107                                         if(seq->sound) {
3108                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
3109                                                 if (seq->sound) {
3110                                                         seq->sound->id.us++;
3111                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
3112                                                 }
3113                                         }
3114                                         seq->anim= 0;
3115                                         seq->hdaudio = 0;
3116                                 }
3117                                 END_SEQ
3118                         }
3119                         
3120                         lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
3121                         
3122                         if(sce->nodetree)
3123                                 lib_link_ntree(fd, &sce->id, sce->nodetree);
3124                         
3125                         for(srl= sce->r.layers.first; srl; srl= srl->next) {
3126                                 srl->mat_override= newlibadr_us(fd, sce->id.lib, srl->mat_override);
3127                                 srl->light_override= newlibadr_us(fd, sce->id.lib, srl->light_override);
3128                         }
3129                         
3130                         sce->id.flag -= LIB_NEEDLINK;
3131                 }
3132
3133                 sce= sce->id.next;
3134         }
3135 }
3136
3137 static void link_recurs_seq(FileData *fd, ListBase *lb)
3138 {
3139         Sequence *seq;
3140
3141         link_list(fd, lb);
3142         seq= lb->first;
3143         while(seq) {
3144                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
3145                 seq= seq->next;
3146         }
3147 }
3148
3149 static void direct_link_scene(FileData *fd, Scene *sce)
3150 {
3151         Editing *ed;
3152         Sequence *seq;
3153         MetaStack *ms;
3154         StripElem *se;
3155         int a;
3156
3157         sce->theDag = NULL;
3158         sce->dagisvalid = 0;
3159         /* set users to one by default, not in lib-link, this will increase it for compo nodes */
3160         sce->id.us= 1;
3161
3162         link_list(fd, &(sce->base));
3163
3164         sce->basact= newdataadr(fd, sce->basact);
3165
3166         sce->radio= newdataadr(fd, sce->radio);
3167         
3168         sce->toolsettings= newdataadr(fd, sce->toolsettings);
3169
3170         sce->sculptdata.session= NULL;
3171         /* SculptData textures */
3172         for(a=0; a<MAX_MTEX; ++a)