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