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