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