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