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