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