2.5 Material:
[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                         
2180                         link_list(fd, &data->targets);
2181                         
2182                         data->prop = newdataadr(fd, data->prop);
2183                         if (data->prop)
2184                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2185                 }
2186         }
2187 }
2188
2189 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2190 {
2191         bPoseChannel *pchan;
2192         bArmature *arm= ob->data;
2193         int rebuild;
2194         
2195         if (!pose || !arm)
2196                 return;
2197         
2198         /* always rebuild to match proxy or lib changes */
2199         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2200
2201         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2202                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2203                 
2204                 /* hurms... loop in a loop, but yah... later... (ton) */
2205                 pchan->bone= get_named_bone(arm, pchan->name);
2206                 
2207                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
2208                 if(pchan->bone==NULL)
2209                         rebuild= 1;
2210                 else if(ob->id.lib==NULL && arm->id.lib) {
2211                         /* local pose selection copied to armature, bit hackish */
2212                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
2213                         pchan->bone->flag |= pchan->selectflag;
2214                 }
2215         }
2216         
2217         if(rebuild) {
2218                 ob->recalc= OB_RECALC;
2219                 pose->flag |= POSE_RECALC;
2220         }
2221 }
2222
2223 static void lib_link_armature(FileData *fd, Main *main)
2224 {
2225         bArmature *arm;
2226
2227         arm= main->armature.first;
2228
2229         while(arm) {
2230                 if(arm->id.flag & LIB_NEEDLINK) {
2231                         arm->id.flag -= LIB_NEEDLINK;
2232                 }
2233                 arm= arm->id.next;
2234         }
2235 }
2236
2237 static void direct_link_bones(FileData *fd, Bone* bone)
2238 {
2239         Bone    *child;
2240
2241         bone->parent= newdataadr(fd, bone->parent);
2242
2243         link_list(fd, &bone->childbase);
2244
2245         for (child=bone->childbase.first; child; child=child->next) {
2246                 direct_link_bones(fd, child);
2247         }
2248 }
2249
2250 static void direct_link_armature(FileData *fd, bArmature *arm)
2251 {
2252         Bone    *bone;
2253
2254         link_list(fd, &arm->bonebase);
2255         arm->edbo= NULL;
2256         
2257         bone=arm->bonebase.first;
2258         while (bone) {
2259                 direct_link_bones(fd, bone);
2260                 bone=bone->next;
2261         }
2262 }
2263
2264 /* ************ READ CAMERA ***************** */
2265
2266 static void lib_link_camera(FileData *fd, Main *main)
2267 {
2268         Camera *ca;
2269
2270         ca= main->camera.first;
2271         while(ca) {
2272                 if(ca->id.flag & LIB_NEEDLINK) {
2273                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2274                         
2275                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2276                         
2277                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2278                         
2279                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
2280                         
2281                         ca->id.flag -= LIB_NEEDLINK;
2282                 }
2283                 ca= ca->id.next;
2284         }
2285 }
2286
2287 static void direct_link_camera(FileData *fd, Camera *ca)
2288 {
2289         ca->adt= newdataadr(fd, ca->adt);
2290         direct_link_animdata(fd, ca->adt);
2291         
2292         direct_link_scriptlink(fd, &ca->scriptlink);
2293 }
2294
2295
2296 /* ************ READ LAMP ***************** */
2297
2298 static void lib_link_lamp(FileData *fd, Main *main)
2299 {
2300         Lamp *la;
2301         MTex *mtex;
2302         int a;
2303
2304         la= main->lamp.first;
2305         while(la) {
2306                 if(la->id.flag & LIB_NEEDLINK) {
2307                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2308                         
2309                         for(a=0; a<MAX_MTEX; a++) {
2310                                 mtex= la->mtex[a];
2311                                 if(mtex) {
2312                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2313                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2314                                 }
2315                         }
2316                         
2317                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2318                         
2319                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
2320                         
2321                         la->id.flag -= LIB_NEEDLINK;
2322                 }
2323                 la= la->id.next;
2324         }
2325 }
2326
2327 static void direct_link_lamp(FileData *fd, Lamp *la)
2328 {
2329         int a;
2330         
2331         la->adt= newdataadr(fd, la->adt);
2332         direct_link_animdata(fd, la->adt);
2333         
2334         direct_link_scriptlink(fd, &la->scriptlink);
2335
2336         for(a=0; a<MAX_MTEX; a++) {
2337                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2338         }
2339         
2340         la->curfalloff= newdataadr(fd, la->curfalloff);
2341         if(la->curfalloff)
2342                 direct_link_curvemapping(fd, la->curfalloff);
2343         
2344         la->preview = direct_link_preview_image(fd, la->preview);
2345 }
2346
2347 /* ************ READ keys ***************** */
2348
2349 static void lib_link_key(FileData *fd, Main *main)
2350 {
2351         Key *key;
2352
2353         key= main->key.first;
2354         while(key) {
2355                 if(key->id.flag & LIB_NEEDLINK) {
2356                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2357                         
2358                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2359                         key->from= newlibadr(fd, key->id.lib, key->from);
2360
2361                         key->id.flag -= LIB_NEEDLINK;
2362                 }
2363                 key= key->id.next;
2364         }
2365 }
2366
2367 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2368 {
2369         int elemsize, a, b;
2370         char *data, *poin, *cp;
2371
2372         elemsize= key->elemsize;
2373         data= kb->data;
2374
2375         for(a=0; a<kb->totelem; a++) {
2376
2377                 cp= key->elemstr;
2378                 poin= data;
2379
2380                 while( cp[0] ) {        /* cp[0]==amount */
2381
2382                         switch(cp[1]) {         /* cp[1]= type */
2383                         case IPO_FLOAT:
2384                         case IPO_BPOINT:
2385                         case IPO_BEZTRIPLE:
2386                                 b= cp[0];
2387                                 while(b--) {
2388                                         SWITCH_INT((*poin));
2389                                         poin+= 4;
2390                                 }
2391                                 break;
2392                         }
2393
2394                         cp+= 2;
2395
2396                 }
2397                 data+= elemsize;
2398         }
2399 }
2400
2401 static void direct_link_key(FileData *fd, Key *key)
2402 {
2403         KeyBlock *kb;
2404
2405         link_list(fd, &(key->block));
2406
2407         key->adt= newdataadr(fd, key->adt);
2408         direct_link_animdata(fd, key->adt);
2409         
2410         key->refkey= newdataadr(fd, key->refkey);
2411
2412         kb= key->block.first;
2413         while(kb) {
2414
2415                 kb->data= newdataadr(fd, kb->data);
2416
2417                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2418                         switch_endian_keyblock(key, kb);
2419
2420                 kb= kb->next;
2421         }
2422 }
2423
2424 /* ************ READ mball ***************** */
2425
2426 static void lib_link_mball(FileData *fd, Main *main)
2427 {
2428         MetaBall *mb;
2429         int a;
2430
2431         mb= main->mball.first;
2432         while(mb) {
2433                 if(mb->id.flag & LIB_NEEDLINK) {
2434
2435                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2436
2437                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2438
2439                         mb->id.flag -= LIB_NEEDLINK;
2440                 }
2441                 mb= mb->id.next;
2442         }
2443 }
2444
2445 static void direct_link_mball(FileData *fd, MetaBall *mb)
2446 {
2447         mb->mat= newdataadr(fd, mb->mat);
2448         test_pointer_array(fd, (void **)&mb->mat);
2449
2450         link_list(fd, &(mb->elems));
2451
2452         mb->disp.first= mb->disp.last= NULL;
2453         mb->editelems= NULL;
2454         mb->bb= NULL;
2455 }
2456
2457 /* ************ READ WORLD ***************** */
2458
2459 static void lib_link_world(FileData *fd, Main *main)
2460 {
2461         World *wrld;
2462         MTex *mtex;
2463         int a;
2464
2465         wrld= main->world.first;
2466         while(wrld) {
2467                 if(wrld->id.flag & LIB_NEEDLINK) {
2468                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2469                         
2470                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2471                         
2472                         for(a=0; a<MAX_MTEX; a++) {
2473                                 mtex= wrld->mtex[a];
2474                                 if(mtex) {
2475                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2476                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2477                                 }
2478                         }
2479                         
2480                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2481                         
2482                         wrld->id.flag -= LIB_NEEDLINK;
2483                 }
2484                 wrld= wrld->id.next;
2485         }
2486 }
2487
2488 static void direct_link_world(FileData *fd, World *wrld)
2489 {
2490         int a;
2491
2492         wrld->adt= newdataadr(fd, wrld->adt);
2493         direct_link_animdata(fd, wrld->adt);
2494         
2495         direct_link_scriptlink(fd, &wrld->scriptlink);
2496
2497         for(a=0; a<MAX_MTEX; a++) {
2498                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2499         }
2500         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2501 }
2502
2503
2504 /* ************ READ VFONT ***************** */
2505
2506 static void lib_link_vfont(FileData *fd, Main *main)
2507 {
2508         VFont *vf;
2509
2510         vf= main->vfont.first;
2511         while(vf) {
2512                 if(vf->id.flag & LIB_NEEDLINK) {
2513                         vf->id.flag -= LIB_NEEDLINK;
2514                 }
2515                 vf= vf->id.next;
2516         }
2517 }
2518
2519 static void direct_link_vfont(FileData *fd, VFont *vf)
2520 {
2521         vf->data= NULL;
2522         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2523 }
2524
2525 /* ************ READ TEXT ****************** */
2526
2527 static void lib_link_text(FileData *fd, Main *main)
2528 {
2529         Text *text;
2530
2531         text= main->text.first;
2532         while(text) {
2533                 if(text->id.flag & LIB_NEEDLINK) {
2534                         text->id.flag -= LIB_NEEDLINK;
2535                 }
2536                 text= text->id.next;
2537         }
2538 }
2539
2540 static void direct_link_text(FileData *fd, Text *text)
2541 {
2542         TextLine *ln;
2543
2544         text->name= newdataadr(fd, text->name);
2545
2546         text->undo_pos= -1;
2547         text->undo_len= TXT_INIT_UNDO;
2548         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2549
2550         text->compiled= NULL;
2551
2552 /*
2553         if(text->flags & TXT_ISEXT) {
2554                 reopen_text(text);
2555         } else {
2556 */
2557
2558         link_list(fd, &text->lines);
2559         link_list(fd, &text->markers);
2560
2561         text->curl= newdataadr(fd, text->curl);
2562         text->sell= newdataadr(fd, text->sell);
2563
2564         ln= text->lines.first;
2565         while(ln) {
2566                 ln->line= newdataadr(fd, ln->line);
2567                 ln->format= NULL;
2568                 
2569                 if (ln->len != (int) strlen(ln->line)) {
2570                         printf("Error loading text, line lengths differ\n");
2571                         ln->len = strlen(ln->line);
2572                 }
2573
2574                 ln= ln->next;
2575         }
2576
2577         text->flags = (text->flags) & ~TXT_ISEXT;
2578
2579         text->id.us= 1;
2580 }
2581
2582 /* ************ READ IMAGE ***************** */
2583
2584 static void lib_link_image(FileData *fd, Main *main)
2585 {
2586         Image *ima;
2587
2588         ima= main->image.first;
2589         while (ima) {
2590                 if(ima->id.flag & LIB_NEEDLINK) {
2591                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2592
2593                         ima->id.flag -= LIB_NEEDLINK;
2594                 }
2595                 ima= ima->id.next;
2596         }
2597 }
2598
2599 static void link_ibuf_list(FileData *fd, ListBase *lb)
2600 {
2601         Link *ln, *prev;
2602         
2603         if(lb->first==NULL) return;
2604         
2605         lb->first= newimaadr(fd, lb->first);
2606         ln= lb->first;
2607         prev= NULL;
2608         while(ln) {
2609                 ln->next= newimaadr(fd, ln->next);
2610                 ln->prev= prev;
2611                 prev= ln;
2612                 ln= ln->next;
2613         }
2614         lb->last= prev;
2615 }
2616
2617 static void direct_link_image(FileData *fd, Image *ima)
2618 {
2619         /* for undo system, pointers could be restored */
2620         if(fd->imamap)
2621                 link_ibuf_list(fd, &ima->ibufs);
2622         else
2623                 ima->ibufs.first= ima->ibufs.last= NULL;
2624         
2625         /* if not restored, we keep the binded opengl index */
2626         if(ima->ibufs.first==NULL) {
2627                 ima->bindcode= 0;
2628                 ima->gputexture= NULL;
2629         }
2630         
2631         ima->anim= NULL;
2632         ima->rr= NULL;
2633         ima->repbind= NULL;
2634         
2635         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2636         ima->preview = direct_link_preview_image(fd, ima->preview);
2637         ima->ok= 1;
2638 }
2639
2640
2641 /* ************ READ CURVE ***************** */
2642
2643 static void lib_link_curve(FileData *fd, Main *main)
2644 {
2645         Curve *cu;
2646         int a;
2647
2648         cu= main->curve.first;
2649         while(cu) {
2650                 if(cu->id.flag & LIB_NEEDLINK) {
2651                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2652
2653                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2654
2655                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2656                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2657                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2658                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2659                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2660                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2661                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2662
2663                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2664                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2665
2666                         cu->id.flag -= LIB_NEEDLINK;
2667                 }
2668                 cu= cu->id.next;
2669         }
2670 }
2671
2672
2673 static void switch_endian_knots(Nurb *nu)
2674 {
2675         int len;
2676
2677         if(nu->knotsu) {
2678                 len= KNOTSU(nu);
2679                 while(len--) {
2680                         SWITCH_INT(nu->knotsu[len]);
2681                 }
2682         }
2683         if(nu->knotsv) {
2684                 len= KNOTSV(nu);
2685                 while(len--) {
2686                         SWITCH_INT(nu->knotsv[len]);
2687                 }
2688         }
2689 }
2690
2691 static void direct_link_curve(FileData *fd, Curve *cu)
2692 {
2693         Nurb *nu;
2694         TextBox *tb;
2695         
2696         cu->adt= newdataadr(fd, cu->adt);
2697         direct_link_animdata(fd, cu->adt);
2698         
2699         cu->mat= newdataadr(fd, cu->mat);
2700         test_pointer_array(fd, (void **)&cu->mat);
2701         cu->str= newdataadr(fd, cu->str);
2702         cu->strinfo= newdataadr(fd, cu->strinfo);       
2703         cu->tb= newdataadr(fd, cu->tb);
2704
2705         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2706         else {
2707                 cu->nurb.first=cu->nurb.last= 0;
2708
2709                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2710                 if (cu->tb) {
2711                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2712                         MEM_freeN(cu->tb);
2713                         cu->tb= tb;                     
2714                 } else {
2715                         cu->totbox = 1;
2716                         cu->actbox = 1;
2717                         cu->tb = tb;
2718                         cu->tb[0].w = cu->linewidth;
2719                 }               
2720                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2721         }
2722
2723         cu->bev.first=cu->bev.last= NULL;
2724         cu->disp.first=cu->disp.last= NULL;
2725         cu->editnurb= NULL;
2726         cu->lastselbp= NULL;
2727         cu->path= NULL;
2728         cu->editfont= NULL;
2729         
2730         nu= cu->nurb.first;
2731         while(nu) {
2732                 nu->bezt= newdataadr(fd, nu->bezt);
2733                 nu->bp= newdataadr(fd, nu->bp);
2734                 nu->knotsu= newdataadr(fd, nu->knotsu);
2735                 nu->knotsv= newdataadr(fd, nu->knotsv);
2736                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2737
2738                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2739                         switch_endian_knots(nu);
2740                 }
2741
2742                 nu= nu->next;
2743         }
2744         cu->bb= NULL;
2745 }
2746
2747 /* ************ READ TEX ***************** */
2748
2749 static void lib_link_texture(FileData *fd, Main *main)
2750 {
2751         Tex *tex;
2752
2753         tex= main->tex.first;
2754         while(tex) {
2755                 if(tex->id.flag & LIB_NEEDLINK) {
2756                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2757
2758                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2759                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2760                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2761
2762                         if(tex->nodetree)
2763                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2764                         
2765                         tex->id.flag -= LIB_NEEDLINK;
2766                 }
2767                 tex= tex->id.next;
2768         }
2769 }
2770
2771 static void direct_link_texture(FileData *fd, Tex *tex)
2772 {
2773         tex->adt= newdataadr(fd, tex->adt);
2774         direct_link_animdata(fd, tex->adt);
2775         
2776         tex->plugin= newdataadr(fd, tex->plugin);
2777         if(tex->plugin) {
2778                 tex->plugin->handle= 0;
2779                 open_plugin_tex(tex->plugin);
2780                 /* initialize data for this instance, if an initialization
2781                  * function exists.
2782                  */
2783                 if (tex->plugin->instance_init)
2784                         tex->plugin->instance_init((void *) tex->plugin->data);
2785         }
2786         tex->coba= newdataadr(fd, tex->coba);
2787         tex->env= newdataadr(fd, tex->env);
2788         if(tex->env) {
2789                 tex->env->ima= NULL;
2790                 memset(tex->env->cube, 0, 6*sizeof(void *));
2791                 tex->env->ok= 0;
2792         }
2793         
2794         tex->nodetree= newdataadr(fd, tex->nodetree);
2795         if(tex->nodetree)
2796                 direct_link_nodetree(fd, tex->nodetree);
2797         
2798         tex->preview = direct_link_preview_image(fd, tex->preview);
2799
2800         tex->iuser.ok= 1;
2801 }
2802
2803
2804
2805 /* ************ READ MATERIAL ***************** */
2806
2807 static void lib_link_material(FileData *fd, Main *main)
2808 {
2809         Material *ma;
2810         MTex *mtex;
2811         int a;
2812
2813         ma= main->mat.first;
2814         while(ma) {
2815                 if(ma->id.flag & LIB_NEEDLINK) {
2816                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2817
2818                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2819                         of library blocks that implement this.*/
2820                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2821
2822                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2823                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2824                         
2825                         for(a=0; a<MAX_MTEX; a++) {
2826                                 mtex= ma->mtex[a];
2827                                 if(mtex) {
2828                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2829                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2830                                 }
2831                         }
2832                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2833                         
2834                         if(ma->nodetree)
2835                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2836                         
2837                         ma->id.flag -= LIB_NEEDLINK;
2838                 }
2839                 ma= ma->id.next;
2840         }
2841 }
2842
2843 static void direct_link_material(FileData *fd, Material *ma)
2844 {
2845         int a;
2846
2847         ma->adt= newdataadr(fd, ma->adt);
2848         direct_link_animdata(fd, ma->adt);
2849         
2850         for(a=0; a<MAX_MTEX; a++) {
2851                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2852         }
2853
2854         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2855         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2856         
2857         direct_link_scriptlink(fd, &ma->scriptlink);
2858         
2859         ma->nodetree= newdataadr(fd, ma->nodetree);
2860         if(ma->nodetree)
2861                 direct_link_nodetree(fd, ma->nodetree);
2862
2863         ma->preview = direct_link_preview_image(fd, ma->preview);
2864         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
2865 }
2866
2867 /* ************ READ PARTICLE SETTINGS ***************** */
2868
2869 static void direct_link_pointcache(FileData *fd, PointCache *cache)
2870 {
2871         cache->flag &= ~(PTCACHE_SIMULATION_VALID|PTCACHE_BAKE_EDIT_ACTIVE);
2872         cache->simframe= 0;
2873 }
2874
2875 static void lib_link_particlesettings(FileData *fd, Main *main)
2876 {
2877         ParticleSettings *part;
2878
2879         part= main->particle.first;
2880         while(part) {
2881                 if(part->id.flag & LIB_NEEDLINK) {
2882                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
2883                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
2884                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
2885                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
2886                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
2887                         part->id.flag -= LIB_NEEDLINK;
2888                 }
2889                 part= part->id.next;
2890         }
2891 }
2892
2893 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
2894 {
2895         part->pd= newdataadr(fd, part->pd);
2896         part->pd2= newdataadr(fd, part->pd2);
2897 }
2898
2899 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
2900 {
2901         ParticleSystem *psys, *psysnext;
2902         int a;
2903
2904         for(psys=particles->first; psys; psys=psysnext){
2905                 ParticleData *pa;
2906                 
2907                 psysnext= psys->next;
2908                 
2909                 psys->part = newlibadr_us(fd, id->lib, psys->part);
2910                 if(psys->part) {
2911                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
2912                         psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
2913
2914                         for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
2915                                 pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
2916                         }
2917                 }
2918                 else {
2919                         /* particle modifier must be removed before particle system */
2920                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
2921                         BLI_remlink(&ob->modifiers, psmd);
2922                         modifier_free((ModifierData *)psmd);
2923
2924                         BLI_remlink(particles, psys);
2925                         MEM_freeN(psys);
2926                 }
2927         }
2928 }
2929 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
2930 {
2931         ParticleSystem *psys;
2932         int a;
2933
2934         for(psys=particles->first; psys; psys=psys->next) {
2935                 psys->particles=newdataadr(fd,psys->particles);
2936                 if(psys->particles && psys->particles->hair){
2937                         ParticleData *pa = psys->particles;
2938                         for(a=0; a<psys->totpart; a++, pa++)
2939                                 pa->hair=newdataadr(fd,pa->hair);
2940                 }
2941                 if(psys->particles && psys->particles->keys){
2942                         ParticleData *pa = psys->particles;
2943                         for(a=0; a<psys->totpart; a++, pa++) {
2944                                 pa->keys= NULL;
2945                                 pa->totkey= 0;
2946                         }
2947
2948                         psys->flag &= ~PSYS_KEYED;
2949                 }
2950                 psys->child=newdataadr(fd,psys->child);
2951                 psys->effectors.first=psys->effectors.last=0;
2952
2953                 psys->soft= newdataadr(fd, psys->soft);
2954                 if(psys->soft) {
2955                         SoftBody *sb = psys->soft;
2956                         sb->particles = psys;
2957                         sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2958                         sb->bspring= NULL;
2959                         sb->scratch= NULL;
2960
2961                         sb->pointcache= newdataadr(fd, sb->pointcache);
2962                         if(sb->pointcache)
2963                                 direct_link_pointcache(fd, sb->pointcache);
2964                 }
2965
2966                 psys->edit = 0;
2967                 psys->free_edit = NULL;
2968                 psys->pathcache = 0;
2969                 psys->childcache = 0;
2970                 psys->pathcachebufs.first = psys->pathcachebufs.last = 0;
2971                 psys->childcachebufs.first = psys->childcachebufs.last = 0;
2972                 psys->reactevents.first = psys->reactevents.last = 0;
2973
2974                 psys->pointcache= newdataadr(fd, psys->pointcache);
2975                 if(psys->pointcache)
2976                         direct_link_pointcache(fd, psys->pointcache);
2977         }
2978         return;
2979 }
2980
2981 /* ************ READ MESH ***************** */
2982
2983 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
2984 {
2985         MTFace *tf= mtface;
2986         int i;
2987
2988         for (i=0; i<totface; i++, tf++) {
2989                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2990                 if(tf->tpage && tf->tpage->id.us==0)
2991                         tf->tpage->id.us= 1;
2992         }
2993 }
2994
2995 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
2996 {
2997         int i;  
2998         for(i=0; i<fdata->totlayer; i++) {
2999                 CustomDataLayer *layer = &fdata->layers[i];
3000                 
3001                 if(layer->type == CD_MTFACE)
3002                         lib_link_mtface(fd, me, layer->data, totface);
3003         }
3004
3005 }
3006
3007 static void lib_link_mesh(FileData *fd, Main *main)
3008 {
3009         Mesh *me;
3010
3011         me= main->mesh.first;
3012         while(me) {
3013                 if(me->id.flag & LIB_NEEDLINK) {
3014                         int i;
3015
3016                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3017                         of library blocks that implement this.*/
3018                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3019
3020                         /* this check added for python created meshes */
3021                         if(me->mat) {
3022                                 for(i=0; i<me->totcol; i++) {
3023                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
3024                                 }
3025                         }
3026                         else me->totcol= 0;
3027
3028                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
3029                         me->key= newlibadr_us(fd, me->id.lib, me->key);
3030                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
3031
3032                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
3033                         if(me->mr && me->mr->levels.first)
3034                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
3035                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
3036
3037                         me->id.flag -= LIB_NEEDLINK;
3038                 }
3039                 me= me->id.next;
3040         }
3041 }
3042
3043 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
3044 {
3045         int     i;
3046
3047         if (!mdverts)
3048                 return;
3049
3050         for (i=0; i<count; i++) {
3051                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
3052                 if (!mdverts[i].dw)
3053                         mdverts[i].totweight=0;
3054         }
3055 }
3056
3057 static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps)
3058 {
3059         if(mdisps) {
3060                 int i;
3061
3062                 for(i = 0; i < count; ++i) {
3063                         mdisps[i].disps = newdataadr(fd, mdisps[i].disps);
3064                         if(!mdisps[i].disps)
3065                                 mdisps[i].totdisp = 0;
3066                 }
3067         }       
3068 }
3069
3070 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
3071 {
3072         int i = 0;
3073
3074         data->layers= newdataadr(fd, data->layers);
3075
3076         while (i < data->totlayer) {
3077                 CustomDataLayer *layer = &data->layers[i];
3078
3079                 if (CustomData_verify_versions(data, i)) {
3080                         layer->data = newdataadr(fd, layer->data);
3081                         if(layer->type == CD_MDISPS)
3082                                 direct_link_mdisps(fd, count, layer->data);
3083                         i++;
3084                 }
3085         }
3086 }
3087
3088 static void direct_link_mesh(FileData *fd, Mesh *mesh)
3089 {
3090         mesh->mat= newdataadr(fd, mesh->mat);
3091         test_pointer_array(fd, (void **)&mesh->mat);
3092
3093         mesh->mvert= newdataadr(fd, mesh->mvert);
3094         mesh->medge= newdataadr(fd, mesh->medge);
3095         mesh->mface= newdataadr(fd, mesh->mface);
3096         mesh->tface= newdataadr(fd, mesh->tface);
3097         mesh->mtface= newdataadr(fd, mesh->mtface);
3098         mesh->mcol= newdataadr(fd, mesh->mcol);
3099         mesh->msticky= newdataadr(fd, mesh->msticky);
3100         mesh->dvert= newdataadr(fd, mesh->dvert);
3101         
3102         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
3103         mesh->pv= newdataadr(fd, mesh->pv);
3104         if(mesh->pv) {
3105                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
3106                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
3107                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
3108                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
3109         }
3110
3111         /* normally direct_link_dverts should be called in direct_link_customdata,
3112            but for backwards compat in do_versions to work we do it here */
3113         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
3114
3115         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
3116         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
3117         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
3118
3119         mesh->bb= NULL;
3120         mesh->mselect = NULL;
3121         mesh->edit_mesh= NULL;
3122         
3123         /* Multires data */
3124         mesh->mr= newdataadr(fd, mesh->mr);
3125         if(mesh->mr) {
3126                 MultiresLevel *lvl;
3127                 
3128                 link_list(fd, &mesh->mr->levels);
3129                 lvl= mesh->mr->levels.first;
3130                 
3131                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
3132                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
3133                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
3134                 
3135                 if(!mesh->mr->edge_flags)
3136                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
3137                 if(!mesh->mr->edge_creases)
3138                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
3139
3140                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
3141                         
3142                 for(; lvl; lvl= lvl->next) {
3143                         lvl->verts= newdataadr(fd, lvl->verts);
3144                         lvl->faces= newdataadr(fd, lvl->faces);
3145                         lvl->edges= newdataadr(fd, lvl->edges);
3146                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
3147                 }
3148         }
3149         
3150         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
3151                 TFace *tf= mesh->tface;
3152                 unsigned int i;
3153
3154                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
3155                         SWITCH_INT(tf->col[0]);
3156                         SWITCH_INT(tf->col[1]);
3157                         SWITCH_INT(tf->col[2]);
3158                         SWITCH_INT(tf->col[3]);
3159                 }
3160         }
3161 }
3162
3163 /* ************ READ LATTICE ***************** */
3164
3165 static void lib_link_latt(FileData *fd, Main *main)
3166 {
3167         Lattice *lt;
3168         
3169         lt= main->latt.first;
3170         while(lt) {
3171                 if(lt->id.flag & LIB_NEEDLINK) {
3172                         
3173                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX depreceated - old animation system
3174                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
3175                         
3176                         lt->id.flag -= LIB_NEEDLINK;
3177                 }
3178                 lt= lt->id.next;
3179         }
3180 }
3181
3182 static void direct_link_latt(FileData *fd, Lattice *lt)
3183 {
3184         lt->def= newdataadr(fd, lt->def);
3185         
3186         lt->dvert= newdataadr(fd, lt->dvert);
3187         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
3188         
3189         lt->editlatt= NULL;
3190 }
3191
3192
3193 /* ************ READ OBJECT ***************** */
3194
3195 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
3196                                               ID **idpoin)
3197 {
3198         FileData *fd = userData;
3199
3200         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
3201         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
3202         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
3203                 (*idpoin)->us++;
3204 }
3205 static void lib_link_modifiers(FileData *fd, Object *ob)
3206 {
3207         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
3208 }
3209
3210 static void lib_link_object(FileData *fd, Main *main)
3211 {
3212         Object *ob;
3213         PartEff *paf;
3214         bSensor *sens;
3215         bController *cont;
3216         bActuator *act;
3217         void *poin;
3218         int warn=0, a;
3219
3220         ob= main->object.first;
3221         while(ob) {
3222                 if(ob->id.flag & LIB_NEEDLINK) {
3223                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3224                         if (ob->adt) lib_link_animdata(fd, &ob->id, ob->adt);
3225                         
3226 // XXX depreceated - old animation system <<<                   
3227                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
3228                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
3229 // >>> XXX depreceated - old animation system
3230
3231                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
3232                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
3233                         ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
3234                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
3235                         
3236                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
3237                         if(ob->proxy) {
3238                                 /* paranoia check, actually a proxy_from pointer should never be written... */
3239                                 if(ob->proxy->id.lib==NULL) {
3240                                         ob->proxy->proxy_from= NULL;
3241                                         ob->proxy= NULL;
3242                                 }
3243                                 else {
3244                                         /* this triggers object_update to always use a copy */
3245                                         ob->proxy->proxy_from= ob;
3246                                         /* force proxy updates after load/undo, a bit weak */
3247                                         ob->recalc= ob->proxy->recalc= OB_RECALC;
3248                                 }
3249                         }
3250                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
3251                         
3252                         poin= ob->data;
3253                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
3254                            
3255                         if(ob->data==NULL && poin!=NULL) {
3256                                 ob->type= OB_EMPTY;
3257                                 warn= 1;
3258                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
3259                                 else printf("Object %s lost data.", ob->id.name+2);
3260                                 
3261                                 if(ob->pose) {
3262                                         free_pose(ob->pose);
3263                                         ob->pose= NULL;
3264                                         ob->flag &= ~OB_POSEMODE;
3265                                 }
3266   &nb