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