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