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