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