Sequencer drawing cleanup (Part 1)
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  *
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  *
28  */
29
30 #include "zlib.h"
31
32 #include <limits.h>
33 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
34 #include <stdlib.h> // for getenv atoi
35 #include <fcntl.h> // for open
36 #include <string.h> // for strrchr strncmp strstr
37 #include <math.h> // for fabs
38
39 #ifndef WIN32
40     #include <unistd.h> // for read close
41     #include <sys/param.h> // for MAXPATHLEN
42 #else
43     #include <io.h> // for open close read
44 #include "winsock2.h"
45 #include "BLI_winstuff.h"
46 #endif
47
48 #include "DNA_anim_types.h"
49 #include "DNA_action_types.h"
50 #include "DNA_armature_types.h"
51 #include "DNA_ID.h"
52 #include "DNA_actuator_types.h"
53 #include "DNA_boid_types.h"
54 #include "DNA_brush_types.h"
55 #include "DNA_camera_types.h"
56 #include "DNA_cloth_types.h"
57 #include "DNA_color_types.h"
58 #include "DNA_controller_types.h"
59 #include "DNA_constraint_types.h"
60 #include "DNA_curve_types.h"
61 #include "DNA_customdata_types.h"
62 #include "DNA_effect_types.h"
63 #include "DNA_fileglobal_types.h"
64 #include "DNA_genfile.h"
65 #include "DNA_group_types.h"
66 #include "DNA_gpencil_types.h"
67 #include "DNA_ipo_types.h"
68 #include "DNA_image_types.h"
69 #include "DNA_key_types.h"
70 #include "DNA_lattice_types.h"
71 #include "DNA_lamp_types.h"
72 #include "DNA_meta_types.h"
73 #include "DNA_material_types.h"
74 #include "DNA_mesh_types.h"
75 #include "DNA_meshdata_types.h"
76 #include "DNA_modifier_types.h"
77 #include "DNA_nla_types.h"
78 #include "DNA_node_types.h"
79 #include "DNA_object_types.h"
80 #include "DNA_object_force.h"
81 #include "DNA_object_fluidsim.h" // NT
82 #include "DNA_outliner_types.h"
83 #include "DNA_object_force.h"
84 #include "DNA_packedFile_types.h"
85 #include "DNA_particle_types.h"
86 #include "DNA_property_types.h"
87 #include "DNA_text_types.h"
88 #include "DNA_view3d_types.h"
89 #include "DNA_screen_types.h"
90 #include "DNA_sensor_types.h"
91 #include "DNA_sdna_types.h"
92 #include "DNA_scene_types.h"
93 #include "DNA_sequence_types.h"
94 #include "DNA_smoke_types.h"
95 #include "DNA_sound_types.h"
96 #include "DNA_space_types.h"
97 #include "DNA_texture_types.h"
98 #include "DNA_userdef_types.h"
99 #include "DNA_vfont_types.h"
100 #include "DNA_world_types.h"
101 #include "DNA_windowmanager_types.h"
102
103 #include "MEM_guardedalloc.h"
104 #include "BLI_blenlib.h"
105 #include "BLI_math.h"
106 #include "BLI_storage_types.h" // for relname flags
107
108 #include "BKE_animsys.h"
109 #include "BKE_action.h"
110 #include "BKE_armature.h"
111 #include "BKE_brush.h"
112 #include "BKE_cdderivedmesh.h"
113 #include "BKE_cloth.h"
114 #include "BKE_colortools.h"
115 #include "BKE_constraint.h"
116 #include "BKE_context.h"
117 #include "BKE_curve.h"
118 #include "BKE_customdata.h"
119 #include "BKE_deform.h"
120 #include "BKE_depsgraph.h"
121 #include "BKE_effect.h" /* give_parteff */
122 #include "BKE_fcurve.h"
123 #include "BKE_global.h" // for G
124 #include "BKE_group.h"
125 #include "BKE_image.h"
126 #include "BKE_ipo.h" 
127 #include "BKE_lattice.h"
128 #include "BKE_library.h" // for wich_libbase
129 #include "BKE_main.h" // for Main
130 #include "BKE_mesh.h" // for ME_ defines (patching)
131 #include "BKE_modifier.h"
132 #include "BKE_multires.h"
133 #include "BKE_node.h" // for tree type defines
134 #include "BKE_object.h"
135 #include "BKE_paint.h"
136 #include "BKE_particle.h"
137 #include "BKE_pointcache.h"
138 #include "BKE_property.h" // for get_ob_property
139 #include "BKE_report.h"
140 #include "BKE_sca.h" // for init_actuator
141 #include "BKE_scene.h"
142 #include "BKE_softbody.h"       // sbNew()
143 #include "BKE_bullet.h"         // bsbNew()
144 #include "BKE_sequencer.h"
145 #include "BKE_texture.h" // for open_plugin_tex
146 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
147 #include "BKE_idprop.h"
148
149 #include "BKE_sound.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->relabase, name, sizeof(fd->relabase));
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 int BLO_is_a_library(char *path, char *dir, char *group)
1070 {
1071         /* return ok when a blenderfile, in dir is the filename,
1072          * in group the type of libdata
1073          */
1074         int len;
1075         char *fd;
1076         
1077         strcpy(dir, path);
1078         len= strlen(dir);
1079         if(len<7) return 0;
1080         if( dir[len-1] != '/' && dir[len-1] != '\\') return 0;
1081         
1082         group[0]= 0;
1083         dir[len-1]= 0;
1084
1085         /* Find the last slash */
1086         fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
1087
1088         if(fd==0) return 0;
1089         *fd= 0;
1090         if(BLO_has_bfile_extension(fd+1)) {
1091                 /* the last part of the dir is a .blend file, no group follows */
1092                 *fd= '/'; /* put back the removed slash separating the dir and the .blend file name */
1093         }
1094         else {          
1095                 char *gp = fd+1; // in case we have a .blend file, gp points to the group
1096
1097                 /* Find the last slash */
1098                 fd= (strrchr(dir, '/')>strrchr(dir, '\\'))?strrchr(dir, '/'):strrchr(dir, '\\');
1099                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
1100
1101                 /* now we know that we are in a blend file and it is safe to 
1102                    assume that gp actually points to a group */
1103                 if (BLI_streq("Screen", gp)==0)
1104                         BLI_strncpy(group, gp, GROUP_MAX);
1105         }
1106         return 1;
1107 }
1108
1109 /* ************** OLD POINTERS ******************* */
1110
1111 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
1112 {
1113         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1114 }
1115
1116 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
1117 {
1118         return oldnewmap_lookup_and_inc(fd->globmap, adr);
1119 }
1120
1121 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
1122 {
1123         if(fd->imamap && adr)
1124                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
1125         return NULL;
1126 }
1127
1128
1129 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
1130 {
1131         return oldnewmap_liblookup(fd->libmap, adr, lib);
1132 }
1133
1134 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1135 {
1136         ID *id= newlibadr(fd, lib, adr);
1137
1138         if(id)
1139                 id->us++;
1140
1141         return id;
1142 }
1143
1144 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
1145 {
1146         int i;
1147         
1148         for (i=0; i<fd->libmap->nentries; i++) {
1149                 OldNew *entry= &fd->libmap->entries[i];
1150                 
1151                 if (old==entry->newp && entry->nr==ID_ID) {
1152                         entry->newp= new;
1153                         if(new) entry->nr= GS( ((ID *)new)->name );
1154                         break;
1155                 }
1156         }
1157 }
1158
1159 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1160 {
1161         Main *mainptr;
1162         
1163         for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
1164                 FileData *fd;
1165                 
1166                 if(mainptr->curlib) fd= mainptr->curlib->filedata;
1167                 else fd= basefd;
1168                 
1169                 if(fd) {
1170                         change_idid_adr_fd(fd, old, new);
1171                 }
1172         }
1173 }
1174
1175 /* lib linked proxy objects point to our local data, we need
1176  * to clear that pointer before reading the undo memfile since
1177  * the object might be removed, it is set again in reading
1178  * if the local object still exists */
1179 void blo_clear_proxy_pointers_from_lib(FileData *fd, Main *oldmain)
1180 {
1181         Object *ob= oldmain->object.first;
1182         
1183         for(;ob; ob= ob->id.next)
1184                 if(ob->id.lib)
1185                         ob->proxy_from= NULL;
1186 }
1187
1188 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1189 {
1190         Image *ima= oldmain->image.first;
1191         Scene *sce= oldmain->scene.first;
1192         
1193         fd->imamap= oldnewmap_new();
1194         
1195         for(;ima; ima= ima->id.next) {
1196                 Link *ibuf= ima->ibufs.first;
1197                 for(; ibuf; ibuf= ibuf->next) 
1198                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
1199                 if(ima->gputexture)
1200                         oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
1201         }
1202         for(; sce; sce= sce->id.next) {
1203                 if(sce->nodetree) {
1204                         bNode *node;
1205                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1206                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
1207                 }
1208         }
1209 }
1210
1211 /* set old main image ibufs to zero if it has been restored */
1212 /* this works because freeing old main only happens after this call */
1213 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1214 {
1215         OldNew *entry= fd->imamap->entries;
1216         Image *ima= oldmain->image.first;
1217         Scene *sce= oldmain->scene.first;
1218         int i;
1219         
1220         /* used entries were restored, so we put them to zero */
1221         for (i=0; i<fd->imamap->nentries; i++, entry++) {
1222                 if (entry->nr>0)
1223                         entry->newp= NULL;
1224         }
1225         
1226         for(;ima; ima= ima->id.next) {
1227                 Link *ibuf, *next;
1228                 
1229                 /* this mirrors direct_link_image */
1230                 for(ibuf= ima->ibufs.first; ibuf; ibuf= next) {
1231                         next= ibuf->next;
1232                         if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
1233                                 BLI_remlink(&ima->ibufs, ibuf);
1234                                 ima->bindcode= 0;
1235                                 ima->gputexture= NULL;
1236                         }
1237                 }
1238
1239                 ima->gputexture= newimaadr(fd, ima->gputexture);
1240         }
1241         for(; sce; sce= sce->id.next) {
1242                 if(sce->nodetree) {
1243                         bNode *node;
1244                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1245                                 node->preview= newimaadr(fd, node->preview);
1246                 }
1247         }
1248 }
1249
1250 /* undo file support: add all library pointers in lookup */
1251 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
1252 {
1253         Main *ptr= mainlist->first;
1254         ListBase *lbarray[MAX_LIBARRAY];
1255         
1256         for(ptr= ptr->next; ptr; ptr= ptr->next) {
1257                 int i= set_listbasepointers(ptr, lbarray);
1258                 while(i--) {
1259                         ID *id;
1260                         for(id= lbarray[i]->first; id; id= id->next)
1261                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1262                 }
1263         }
1264 }
1265                 
1266
1267 /* ********** END OLD POINTERS ****************** */
1268 /* ********** READ FILE ****************** */
1269
1270 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1271 {
1272         int blocksize, nblocks;
1273         char *data;
1274
1275         data= (char *)(bhead+1);
1276         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1277
1278         nblocks= bhead->nr;
1279         while(nblocks--) {
1280                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1281
1282                 data+= blocksize;
1283         }
1284 }
1285
1286 static void *read_struct(FileData *fd, BHead *bh, char *blockname)
1287 {
1288         void *temp= NULL;
1289
1290         if (bh->len) {
1291                 /* switch is based on file dna */
1292                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1293                         switch_endian_structs(fd->filesdna, bh);
1294
1295                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1296                         if(fd->compflags[bh->SDNAnr]==2) {
1297                                 temp= DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1298                         } else {
1299                                 temp= MEM_mallocN(bh->len, blockname);
1300                                 memcpy(temp, (bh+1), bh->len);
1301                         }
1302                 }
1303         }
1304
1305         return temp;
1306 }
1307
1308 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1309 {
1310         Link *ln, *prev;
1311
1312         if(lb->first==NULL) return;
1313
1314         lb->first= newdataadr(fd, lb->first);
1315         ln= lb->first;
1316         prev= NULL;
1317         while(ln) {
1318                 ln->next= newdataadr(fd, ln->next);
1319                 ln->prev= prev;
1320                 prev= ln;
1321                 ln= ln->next;
1322         }
1323         lb->last= prev;
1324 }
1325
1326 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1327 {
1328         Link *ln, *prev;
1329         void *poin;
1330
1331         if(lb->first==0) return;
1332         poin= newdataadr(fd, lb->first);
1333         if(lb->first) {
1334                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1335         }
1336         lb->first= poin;
1337
1338         ln= lb->first;
1339         prev= 0;
1340         while(ln) {
1341                 poin= newdataadr(fd, ln->next);
1342                 if(ln->next) {
1343                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1344                 }
1345                 ln->next= poin;
1346                 ln->prev= prev;
1347                 prev= ln;
1348                 ln= ln->next;
1349         }
1350         lb->last= prev;
1351 }
1352
1353 static void test_pointer_array(FileData *fd, void **mat)
1354 {
1355 #if defined(WIN32) && !defined(FREE_WINDOWS)
1356         __int64 *lpoin, *lmat;
1357 #else
1358         long long *lpoin, *lmat;
1359 #endif
1360         int len, *ipoin, *imat;
1361
1362                 /* manually convert the pointer array in
1363                  * the old dna format to a pointer array in
1364                  * the new dna format.
1365                  */
1366         if(*mat) {
1367                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1368
1369                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1370                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
1371                         lpoin= *mat;
1372
1373                         while(len-- > 0) {
1374                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1375                                         SWITCH_LONGINT(*lpoin);
1376                                 *ipoin= (int) ((*lpoin) >> 3);
1377                                 ipoin++;
1378                                 lpoin++;
1379                         }
1380                         MEM_freeN(*mat);
1381                         *mat= imat;
1382                 }
1383
1384                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1385                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
1386                         ipoin= *mat;
1387
1388                         while(len-- > 0) {
1389                                 *lpoin= *ipoin;
1390                                 ipoin++;
1391                                 lpoin++;
1392                         }
1393                         MEM_freeN(*mat);
1394                         *mat= lmat;
1395                 }
1396         }
1397 }
1398
1399 /* ************ READ ID Properties *************** */
1400
1401 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1402 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1403
1404 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1405 {
1406         IDProperty *array;
1407         int i;
1408
1409         /*since we didn't save the extra buffer, set totallen to len.*/
1410         prop->totallen = prop->len;
1411         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1412
1413         array= (IDProperty*) prop->data.pointer;
1414
1415         for(i=0; i<prop->len; i++)
1416                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
1417 }
1418
1419 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
1420 {
1421         IDProperty **array;
1422         int i;
1423
1424         /*since we didn't save the extra buffer, set totallen to len.*/
1425         prop->totallen = prop->len;
1426         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1427
1428         if(prop->subtype == IDP_GROUP) {
1429                 test_pointer_array(fd, prop->data.pointer);
1430                 array= prop->data.pointer;
1431
1432                 for(i=0; i<prop->len; i++)
1433                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
1434         }
1435         else if(prop->subtype == IDP_DOUBLE) {
1436                 if (switch_endian) {
1437                         for (i=0; i<prop->len; i++) {
1438                                 SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
1439                         }
1440                 }
1441         }
1442         else {
1443                 if (switch_endian) {
1444                         for (i=0; i<prop->len; i++) {
1445                                 SWITCH_INT(((int*)prop->data.pointer)[i]);
1446                         }
1447                 }
1448         }
1449 }
1450
1451 static void IDP_DirectLinkString(IDProperty *prop, int switch_endian, FileData *fd)
1452 {
1453         /*since we didn't save the extra string buffer, set totallen to len.*/
1454         prop->totallen = prop->len;
1455         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1456 }
1457
1458 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
1459 {
1460         ListBase *lb = &prop->data.group;
1461         IDProperty *loop;
1462
1463         link_list(fd, lb);
1464
1465         /*Link child id properties now*/
1466         for (loop=prop->data.group.first; loop; loop=loop->next) {
1467                 IDP_DirectLinkProperty(loop, switch_endian, fd);
1468         }
1469 }
1470
1471 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
1472 {
1473         switch (prop->type) {
1474                 case IDP_GROUP:
1475                         IDP_DirectLinkGroup(prop, switch_endian, fd);
1476                         break;
1477                 case IDP_STRING:
1478                         IDP_DirectLinkString(prop, switch_endian, fd);
1479                         break;
1480                 case IDP_ARRAY:
1481                         IDP_DirectLinkArray(prop, switch_endian, fd);
1482                         break;
1483                 case IDP_IDPARRAY:
1484                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
1485                         break;
1486                 case IDP_DOUBLE:
1487                         /*erg, stupid doubles.  since I'm storing them
1488                          in the same field as int val; val2 in the
1489                          IDPropertyData struct, they have to deal with
1490                          endianness specifically
1491                          
1492                          in theory, val and val2 would've already been swapped
1493                          if switch_endian is true, so we have to first unswap
1494                          them then reswap them as a single 64-bit entity.
1495                          */
1496                         
1497                         if (switch_endian) {
1498                                 SWITCH_INT(prop->data.val);
1499                                 SWITCH_INT(prop->data.val2);
1500                                 SWITCH_LONGINT(prop->data.val);
1501                         }
1502                         
1503                         break;
1504         }
1505 }
1506
1507 /*stub function*/
1508 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
1509 {
1510 }
1511
1512 /* ************ READ CurveMapping *************** */
1513
1514 /* cuma itself has been read! */
1515 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
1516 {
1517         int a;
1518         
1519         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
1520         cumap->flag &= ~CUMA_PREMULLED;
1521         
1522         for(a=0; a<CM_TOT; a++) {
1523                 cumap->cm[a].curve= newdataadr(fd, cumap->cm[a].curve);
1524                 cumap->cm[a].table= NULL;
1525         }
1526 }
1527
1528 /* ************ READ Brush *************** */
1529 /* library brush linking after fileread */
1530 static void lib_link_brush(FileData *fd, Main *main)
1531 {
1532         Brush *brush;
1533         MTex *mtex;
1534         int a;
1535         
1536         /* only link ID pointers */
1537         for(brush= main->brush.first; brush; brush= brush->id.next) {
1538                 if(brush->id.flag & LIB_NEEDLINK) {
1539                         brush->id.flag -= LIB_NEEDLINK;
1540
1541                         brush->clone.image= newlibadr_us(fd, brush->id.lib, brush->clone.image);
1542                         
1543                         for(a=0; a<MAX_MTEX; a++) {
1544                                 mtex= brush->mtex[a];
1545                                 if(mtex)
1546                                         mtex->tex= newlibadr_us(fd, brush->id.lib, mtex->tex);
1547                         }
1548
1549                         brush->clone.image= newlibadr_us(fd, brush->id.lib, brush->clone.image);
1550                 }
1551         }
1552 }
1553
1554 static void direct_link_brush(FileData *fd, Brush *brush)
1555 {
1556         /* brush itself has been read */
1557         int a;
1558
1559         for(a=0; a<MAX_MTEX; a++)
1560                 brush->mtex[a]= newdataadr(fd, brush->mtex[a]);
1561
1562         /* fallof curve */
1563         brush->curve= newdataadr(fd, brush->curve);
1564         if(brush->curve)
1565                 direct_link_curvemapping(fd, brush->curve);
1566         else
1567                 brush_curve_preset(brush, BRUSH_PRESET_SHARP);
1568 }
1569
1570 static void direct_link_script(FileData *fd, Script *script)
1571 {
1572         script->id.us = 1;
1573         SCRIPT_SET_NULL(script)
1574 }
1575
1576
1577 /* ************ READ PACKEDFILE *************** */
1578
1579 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1580 {
1581         PackedFile *pf= newdataadr(fd, oldpf);
1582
1583         if (pf) {
1584                 pf->data= newdataadr(fd, pf->data);
1585         }
1586
1587         return pf;
1588 }
1589
1590 /* ************ READ IMAGE PREVIEW *************** */
1591
1592 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
1593 {
1594         PreviewImage *prv= newdataadr(fd, old_prv);
1595
1596         if (prv) {
1597                 int i;
1598                 for (i=0; i < PREVIEW_MIPMAPS; ++i) {
1599                         if (prv->rect[i]) {
1600                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
1601                         }
1602                 }
1603         }
1604
1605         return prv;
1606 }
1607
1608 /* ************ READ ANIMATION STUFF ***************** */
1609
1610 /* Legacy Data Support (for Version Patching) ----------------------------- */
1611
1612 // XXX depreceated - old animation system
1613 static void lib_link_ipo(FileData *fd, Main *main)
1614 {
1615         Ipo *ipo;
1616
1617         ipo= main->ipo.first;
1618         while(ipo) {
1619                 if(ipo->id.flag & LIB_NEEDLINK) {
1620                         IpoCurve *icu;
1621                         for(icu= ipo->curve.first; icu; icu= icu->next) {
1622                                 if(icu->driver)
1623                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
1624                         }
1625                         ipo->id.flag -= LIB_NEEDLINK;
1626                 }
1627                 ipo= ipo->id.next;
1628         }
1629 }
1630
1631 // XXX depreceated - old animation system
1632 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1633 {
1634         IpoCurve *icu;
1635
1636         link_list(fd, &(ipo->curve));
1637         icu= ipo->curve.first;
1638         while(icu) {
1639                 icu->bezt= newdataadr(fd, icu->bezt);
1640                 icu->bp= newdataadr(fd, icu->bp);
1641                 icu->driver= newdataadr(fd, icu->driver);
1642                 icu= icu->next;
1643         }
1644 }
1645
1646 // XXX depreceated - old animation system
1647 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1648 {
1649         bActionStrip *strip;
1650         bActionModifier *amod;
1651         
1652         for (strip=striplist->first; strip; strip=strip->next){
1653                 strip->object = newlibadr(fd, id->lib, strip->object);
1654                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1655                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1656                 for(amod= strip->modifiers.first; amod; amod= amod->next)
1657                         amod->ob= newlibadr(fd, id->lib, amod->ob);
1658         }
1659 }
1660
1661 // XXX depreceated - old animation system
1662 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
1663 {
1664         bActionStrip *strip;
1665         
1666         link_list(fd, strips);
1667         
1668         for(strip= strips->first; strip; strip= strip->next)
1669                 link_list(fd, &strip->modifiers);
1670 }
1671
1672 // XXX depreceated - old animation system
1673 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1674 {
1675         bConstraintChannel *chan;
1676
1677         for (chan=chanbase->first; chan; chan=chan->next){
1678                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1679         }
1680 }
1681
1682 /* Data Linking ----------------------------- */
1683
1684 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
1685 {
1686         FModifier *fcm;
1687         
1688         for (fcm= list->first; fcm; fcm= fcm->next) {
1689                 /* data for specific modifiers */
1690                 switch (fcm->type) {
1691                         case FMODIFIER_TYPE_PYTHON:
1692                         {
1693                                 FMod_Python *data= (FMod_Python *)fcm->data;
1694                                 data->script = newlibadr(fd, id->lib, data->script);
1695                         }
1696                                 break;
1697                         case FMODIFIER_TYPE_SOUND:
1698                         {
1699                                 FMod_Sound *data= (FMod_Sound *)fcm->data;
1700                                 data->sound = newlibadr(fd, id->lib, data->sound);
1701                         }
1702                                 break;
1703                 }
1704         }
1705 }
1706
1707 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
1708 {
1709         FCurve *fcu;
1710         
1711         if (list == NULL)
1712                 return;
1713         
1714         /* relink ID-block references... */
1715         for (fcu= list->first; fcu; fcu= fcu->next) {
1716                 /* driver data */
1717                 if (fcu->driver) {
1718                         ChannelDriver *driver= fcu->driver;
1719                         DriverTarget *dtar;
1720                         
1721                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1722                                 dtar->id= newlibadr(fd, id->lib, dtar->id); 
1723                 }
1724                 
1725                 /* modifiers */
1726                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
1727         }
1728 }
1729
1730
1731 /* NOTE: this assumes that link_list has already been called on the list */
1732 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
1733 {
1734         FModifier *fcm;
1735         
1736         for (fcm= list->first; fcm; fcm= fcm->next) {
1737                 /* relink general data */
1738                 fcm->data = newdataadr(fd, fcm->data);
1739                 fcm->edata= NULL;
1740                 
1741                 /* do relinking of data for specific types */
1742                 switch (fcm->type) {
1743                         case FMODIFIER_TYPE_GENERATOR:
1744                         {
1745                                 FMod_Generator *data= (FMod_Generator *)fcm->data;
1746                                 
1747                                 data->coefficients= newdataadr(fd, data->coefficients);
1748                         }
1749                                 break;
1750                         case FMODIFIER_TYPE_ENVELOPE:
1751                         {
1752                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
1753                                 
1754                                 data->data= newdataadr(fd, data->data);
1755                         }
1756                                 break;
1757                         case FMODIFIER_TYPE_PYTHON:
1758                         {
1759                                 FMod_Python *data= (FMod_Python *)fcm->data;
1760                                 
1761                                 data->prop = newdataadr(fd, data->prop);
1762                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1763                         }
1764                                 break;
1765                 }
1766         }
1767 }
1768
1769 /* NOTE: this assumes that link_list has already been called on the list */
1770 static void direct_link_fcurves(FileData *fd, ListBase *list)
1771 {
1772         FCurve *fcu;
1773         
1774         /* link F-Curve data to F-Curve again (non ID-libs) */
1775         for (fcu= list->first; fcu; fcu= fcu->next) {
1776                 /* curve data */
1777                 fcu->bezt= newdataadr(fd, fcu->bezt);
1778                 fcu->fpt= newdataadr(fd, fcu->fpt);
1779                 
1780                 /* rna path */
1781                 fcu->rna_path= newdataadr(fd, fcu->rna_path);
1782                 
1783                 /* group */
1784                 fcu->grp= newdataadr(fd, fcu->grp);
1785                 
1786                 /* driver */
1787                 fcu->driver= newdataadr(fd, fcu->driver);
1788                 if (fcu->driver) {
1789                         ChannelDriver *driver= fcu->driver;
1790                         DriverTarget *dtar;
1791                         
1792                         /* relink targets and their paths */
1793                         link_list(fd, &driver->targets);
1794                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1795                                 dtar->rna_path= newdataadr(fd, dtar->rna_path);
1796                 }
1797                 
1798                 /* modifiers */
1799                 link_list(fd, &fcu->modifiers);
1800                 direct_link_fmodifiers(fd, &fcu->modifiers);
1801         }
1802 }
1803
1804
1805 static void lib_link_action(FileData *fd, Main *main)
1806 {
1807         bAction *act;
1808         bActionChannel *chan;
1809
1810         for (act= main->action.first; act; act= act->id.next) {
1811                 if (act->id.flag & LIB_NEEDLINK) {
1812                         act->id.flag -= LIB_NEEDLINK;
1813                         
1814 // XXX depreceated - old animation system <<<
1815                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1816                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1817                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1818                         }
1819 // >>> XXX depreceated - old animation system
1820                         
1821                         lib_link_fcurves(fd, &act->id, &act->curves);
1822                 }
1823         }
1824 }
1825
1826 static void direct_link_action(FileData *fd, bAction *act)
1827 {
1828         bActionChannel *achan; // XXX depreceated - old animation system
1829         bActionGroup *agrp;
1830
1831         link_list(fd, &act->curves);
1832         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
1833         link_list(fd, &act->groups);
1834         link_list(fd, &act->markers);
1835
1836 // XXX depreceated - old animation system <<<
1837         for (achan = act->chanbase.first; achan; achan=achan->next) {
1838                 achan->grp= newdataadr(fd, achan->grp);
1839                 
1840                 link_list(fd, &achan->constraintChannels);
1841         }
1842 // >>> XXX depreceated - old animation system
1843
1844         direct_link_fcurves(fd, &act->curves);
1845         
1846         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1847                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
1848                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
1849         }
1850 }
1851
1852 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
1853 {
1854         NlaStrip *strip;
1855         
1856         for (strip= list->first; strip; strip= strip->next) {
1857                 /* check strip's children */
1858                 lib_link_nladata_strips(fd, id, &strip->strips);
1859                 
1860                 /* check strip's F-Curves */
1861                 lib_link_fcurves(fd, id, &strip->fcurves);
1862                 
1863                 /* reassign the counted-reference to action */
1864                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1865         }
1866 }
1867
1868 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
1869 {
1870         NlaTrack *nlt;
1871         
1872         /* we only care about the NLA strips inside the tracks */
1873         for (nlt= list->first; nlt; nlt= nlt->next) {
1874                 lib_link_nladata_strips(fd, id, &nlt->strips);
1875         }
1876 }
1877
1878 /* This handles Animato NLA-Strips linking 
1879  * NOTE: this assumes that link_list has already been called on the list 
1880  */
1881 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
1882 {
1883         NlaStrip *strip;
1884         
1885         for (strip= list->first; strip; strip= strip->next) {
1886                 /* strip's child strips */
1887                 link_list(fd, &strip->strips);
1888                 direct_link_nladata_strips(fd, &strip->strips);
1889                 
1890                 /* strip's F-Curves */
1891                 link_list(fd, &strip->fcurves);
1892                 direct_link_fcurves(fd, &strip->fcurves);
1893                 
1894                 /* strip's F-Modifiers */
1895                 link_list(fd, &strip->modifiers);
1896                 direct_link_fcurves(fd, &strip->modifiers);
1897         }
1898 }
1899
1900 /* NOTE: this assumes that link_list has already been called on the list */
1901 static void direct_link_nladata(FileData *fd, ListBase *list)
1902 {
1903         NlaTrack *nlt;
1904         
1905         for (nlt= list->first; nlt; nlt= nlt->next) {
1906                 /* relink list of strips */
1907                 link_list(fd, &nlt->strips);
1908                 
1909                 /* relink strip data */
1910                 direct_link_nladata_strips(fd, &nlt->strips);
1911         }
1912 }
1913
1914 /* ------- */
1915
1916 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
1917 {
1918         KeyingSet *ks;
1919         KS_Path *ksp;
1920         
1921         /* here, we're only interested in the ID pointer stored in some of the paths */
1922         for (ks= list->first; ks; ks= ks->next) {
1923                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1924                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
1925                 }
1926         }
1927 }
1928
1929 /* NOTE: this assumes that link_list has already been called on the list */
1930 static void direct_link_keyingsets(FileData *fd, ListBase *list)
1931 {
1932         KeyingSet *ks;
1933         KS_Path *ksp;
1934         
1935         /* link KeyingSet data to KeyingSet again (non ID-libs) */
1936         for (ks= list->first; ks; ks= ks->next) {
1937                 /* paths */
1938                 link_list(fd, &ks->paths);
1939                 
1940                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1941                         /* rna path */
1942                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
1943                 }
1944         }
1945 }
1946
1947 /* ------- */
1948
1949 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
1950 {
1951         if (adt == NULL)
1952                 return;
1953         
1954         /* link action data */
1955         adt->action= newlibadr_us(fd, id->lib, adt->action);
1956         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
1957         
1958         /* link drivers */
1959         lib_link_fcurves(fd, id, &adt->drivers);
1960         
1961         /* overrides don't have lib-link for now, so no need to do anything */
1962         
1963         /* link NLA-data */
1964         lib_link_nladata(fd, id, &adt->nla_tracks);
1965 }
1966
1967 static void direct_link_animdata(FileData *fd, AnimData *adt)
1968 {
1969         /* NOTE: must have called newdataadr already before doing this... */
1970         if (adt == NULL)
1971                 return;
1972         
1973         /* link drivers */
1974         link_list(fd, &adt->drivers);
1975         direct_link_fcurves(fd, &adt->drivers);
1976         
1977         /* link overrides */
1978         // TODO...
1979         
1980         /* link NLA-data */
1981         link_list(fd, &adt->nla_tracks);
1982         direct_link_nladata(fd, &adt->nla_tracks);
1983         
1984         /* clear temp pointers that may have been set... */
1985         // TODO: it's probably only a small cost to reload this anyway...
1986         adt->actstrip= NULL;
1987 }       
1988
1989 /* ************ READ NODE TREE *************** */
1990
1991 /* singe node tree (also used for material/scene trees), ntree is not NULL */
1992 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
1993 {
1994         bNode *node;
1995         
1996         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
1997         
1998         ntree->gpd= newlibadr_us(fd, id->lib, ntree->gpd);
1999         
2000         for(node= ntree->nodes.first; node; node= node->next)
2001                 node->id= newlibadr_us(fd, id->lib, node->id);
2002 }
2003
2004 /* library ntree linking after fileread */
2005 static void lib_link_nodetree(FileData *fd, Main *main)
2006 {
2007         bNodeTree *ntree;
2008         
2009         /* only link ID pointers */
2010         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2011                 if(ntree->id.flag & LIB_NEEDLINK) {
2012                         ntree->id.flag -= LIB_NEEDLINK;
2013                         lib_link_ntree(fd, &ntree->id, ntree);
2014                 }
2015         }
2016 }
2017
2018 /* verify types for nodes and groups, all data has to be read */
2019 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2020 * typedefs*/
2021 static void lib_verify_nodetree(Main *main, int open)
2022 {
2023         Scene *sce;
2024         Material *ma;
2025         Tex *tx;
2026         bNodeTree *ntree;
2027         
2028         /* this crashes blender on undo/redo
2029                 if(open==1) {
2030                         reinit_nodesystem();
2031                 }*/
2032         
2033         /* now create the own typeinfo structs an verify nodes */
2034         /* here we still assume no groups in groups */
2035         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2036                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
2037                 ntreeMakeOwnType(ntree);        /* for group usage */
2038         }
2039         
2040         /* now verify all types in material trees, groups are set OK now */
2041         for(ma= main->mat.first; ma; ma= ma->id.next) {
2042                 if(ma->nodetree)
2043                         ntreeVerifyTypes(ma->nodetree);
2044         }
2045         /* and scene trees */
2046         for(sce= main->scene.first; sce; sce= sce->id.next) {
2047                 if(sce->nodetree)
2048                         ntreeVerifyTypes(sce->nodetree);
2049         }
2050         /* and texture trees */
2051         for(tx= main->tex.first; tx; tx= tx->id.next) {
2052                 if(tx->nodetree)
2053                         ntreeVerifyTypes(tx->nodetree);
2054         }
2055 }
2056
2057
2058
2059 /* ntree itself has been read! */
2060 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2061 {
2062         /* note: writing and reading goes in sync, for speed */
2063         bNode *node;
2064         bNodeSocket *sock;
2065         bNodeLink *link;
2066         
2067         ntree->init= 0;         /* to set callbacks and force setting types */
2068         ntree->owntype= NULL;
2069         ntree->timecursor= NULL;
2070         
2071         ntree->adt= newdataadr(fd, ntree->adt);
2072         direct_link_animdata(fd, ntree->adt);
2073         
2074         link_list(fd, &ntree->nodes);
2075         for(node= ntree->nodes.first; node; node= node->next) {
2076                 if(node->type == NODE_DYNAMIC) {
2077                         node->custom1= 0;
2078                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
2079                         node->typeinfo= NULL;
2080                 }
2081                 
2082                 node->storage= newdataadr(fd, node->storage);
2083                 if(node->storage) {
2084                         
2085                         /* could be handlerized at some point */
2086                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2087                                 direct_link_curvemapping(fd, node->storage);
2088                         else if(ntree->type==NTREE_COMPOSIT) {
2089                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
2090                                         direct_link_curvemapping(fd, node->storage);
2091                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2092                                         ((ImageUser *)node->storage)->ok= 1;
2093                         }
2094                         else if( ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) ) {
2095                                 direct_link_curvemapping(fd, node->storage);
2096                         }
2097                 }
2098                 link_list(fd, &node->inputs);
2099                 link_list(fd, &node->outputs);
2100         }
2101         link_list(fd, &ntree->links);
2102         
2103         /* and we connect the rest */
2104         for(node= ntree->nodes.first; node; node= node->next) {
2105                 node->preview= newimaadr(fd, node->preview);
2106                 node->lasty= 0;
2107                 for(sock= node->inputs.first; sock; sock= sock->next)
2108                         sock->link= newdataadr(fd, sock->link);
2109                 for(sock= node->outputs.first; sock; sock= sock->next)
2110                         sock->ns.data= NULL;
2111         }
2112         for(link= ntree->links.first; link; link= link->next) {
2113                 link->fromnode= newdataadr(fd, link->fromnode);
2114                 link->tonode= newdataadr(fd, link->tonode);
2115                 link->fromsock= newdataadr(fd, link->fromsock);
2116                 link->tosock= newdataadr(fd, link->tosock);
2117         }
2118         
2119         /* set selin and selout */
2120         for(node= ntree->nodes.first; node; node= node->next) {
2121                 for(sock= node->inputs.first; sock; sock= sock->next) {
2122                         if(sock->flag & SOCK_SEL) {
2123                                 ntree->selin= sock;
2124                                 break;
2125                         }
2126                 }
2127                 for(sock= node->outputs.first; sock; sock= sock->next) {
2128                         if(sock->flag & SOCK_SEL) {
2129                                 ntree->selout= sock;
2130                                 break;
2131                         }
2132                 }
2133         }
2134         
2135         /* type verification is in lib-link */
2136 }
2137
2138 /* ************ READ ARMATURE ***************** */
2139
2140 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2141 {
2142         bConstraint *con;
2143
2144         for (con = conlist->first; con; con=con->next) {
2145                 /* patch for error introduced by changing constraints (dunno how) */
2146                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2147                 if(con->data==NULL) {
2148                         con->type= CONSTRAINT_TYPE_NULL;
2149                 }
2150                 /* own ipo, all constraints have it */
2151                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2152                 
2153                 switch (con->type) {
2154                 case CONSTRAINT_TYPE_PYTHON:
2155                         {
2156                                 bPythonConstraint *data= (bPythonConstraint*)con->data;
2157                                 bConstraintTarget *ct;
2158                                 
2159                                 for (ct= data->targets.first; ct; ct= ct->next)
2160                                         ct->tar = newlibadr(fd, id->lib, ct->tar);
2161                                         
2162                                 data->text = newlibadr(fd, id->lib, data->text);
2163                                 //IDP_LibLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2164                         }
2165                         break;
2166                 case CONSTRAINT_TYPE_ACTION:
2167                         {
2168                                 bActionConstraint *data;
2169                                 data= ((bActionConstraint*)con->data);
2170                                 data->tar = newlibadr(fd, id->lib, data->tar);
2171                                 data->act = newlibadr(fd, id->lib, data->act);
2172                         }
2173                         break;
2174                 case CONSTRAINT_TYPE_LOCLIKE:
2175                         {
2176                                 bLocateLikeConstraint *data;
2177                                 data= ((bLocateLikeConstraint*)con->data);
2178                                 data->tar = newlibadr(fd, id->lib, data->tar);
2179                         }
2180                         break;
2181                 case CONSTRAINT_TYPE_ROTLIKE:
2182                         {
2183                                 bRotateLikeConstraint *data;
2184                                 data= ((bRotateLikeConstraint*)con->data);
2185                                 data->tar = newlibadr(fd, id->lib, data->tar);
2186                         }
2187                         break;
2188                 case CONSTRAINT_TYPE_SIZELIKE:
2189                         {
2190                                 bSizeLikeConstraint *data;
2191                                 data= ((bSizeLikeConstraint*)con->data);
2192                                 data->tar = newlibadr(fd, id->lib, data->tar);
2193                         }
2194                         break;
2195                 case CONSTRAINT_TYPE_KINEMATIC:
2196                         {
2197                                 bKinematicConstraint *data;
2198                                 data = ((bKinematicConstraint*)con->data);
2199                                 data->tar = newlibadr(fd, id->lib, data->tar);
2200                                 data->poletar = newlibadr(fd, id->lib, data->poletar);
2201                                 con->lin_error = 0.f;
2202                                 con->rot_error = 0.f;
2203                         }
2204                         break;
2205                 case CONSTRAINT_TYPE_TRACKTO:
2206                         {
2207                                 bTrackToConstraint *data;
2208                                 data = ((bTrackToConstraint*)con->data);
2209                                 data->tar = newlibadr(fd, id->lib, data->tar);
2210                         }
2211                         break;
2212                 case CONSTRAINT_TYPE_MINMAX:
2213                         {
2214                                 bMinMaxConstraint *data;
2215                                 data = ((bMinMaxConstraint*)con->data);
2216                                 data->tar = newlibadr(fd, id->lib, data->tar);
2217                         }
2218                         break;
2219                 case CONSTRAINT_TYPE_LOCKTRACK:
2220                         {
2221                                 bLockTrackConstraint *data;
2222                                 data= ((bLockTrackConstraint*)con->data);
2223                                 data->tar = newlibadr(fd, id->lib, data->tar);
2224                         }
2225                         break;
2226                 case CONSTRAINT_TYPE_FOLLOWPATH:
2227                         {
2228                                 bFollowPathConstraint *data;
2229                                 data= ((bFollowPathConstraint*)con->data);
2230                                 data->tar = newlibadr(fd, id->lib, data->tar);
2231                         }
2232                         break;
2233                 case CONSTRAINT_TYPE_STRETCHTO:
2234                         {
2235                                 bStretchToConstraint *data;
2236                                 data= ((bStretchToConstraint*)con->data);
2237                                 data->tar = newlibadr(fd, id->lib, data->tar);
2238                         }
2239                         break;
2240                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
2241                         {
2242                                 bRigidBodyJointConstraint *data;
2243                                 data= ((bRigidBodyJointConstraint*)con->data);
2244                                 data->tar = newlibadr(fd, id->lib, data->tar);
2245                         }
2246                         break;
2247                 case CONSTRAINT_TYPE_CLAMPTO:
2248                         {
2249                                 bClampToConstraint *data;
2250                                 data= ((bClampToConstraint*)con->data);
2251                                 data->tar = newlibadr(fd, id->lib, data->tar);
2252                         }
2253                         break;
2254                 case CONSTRAINT_TYPE_CHILDOF:
2255                         {
2256                                 bChildOfConstraint *data;
2257                                 data= ((bChildOfConstraint*)con->data);
2258                                 data->tar = newlibadr(fd, id->lib, data->tar);
2259                         }
2260                         break;
2261                 case CONSTRAINT_TYPE_TRANSFORM:
2262                         {
2263                                 bTransformConstraint *data;
2264                                 data= ((bTransformConstraint*)con->data);
2265                                 data->tar = newlibadr(fd, id->lib, data->tar);
2266                         }
2267                         break;
2268                 case CONSTRAINT_TYPE_DISTLIMIT:
2269                         {
2270                                 bDistLimitConstraint *data;
2271                                 data= ((bDistLimitConstraint*)con->data);
2272                                 data->tar = newlibadr(fd, id->lib, data->tar);
2273                         }
2274                         break;
2275                 case CONSTRAINT_TYPE_SHRINKWRAP:
2276                         {
2277                                 bShrinkwrapConstraint *data;
2278                                 data= ((bShrinkwrapConstraint*)con->data);
2279                                 data->target = newlibadr(fd, id->lib, data->target);
2280                         }
2281                         break;
2282                 case CONSTRAINT_TYPE_DAMPTRACK:
2283                         {
2284                                 bDampTrackConstraint *data;
2285                                 data= ((bDampTrackConstraint*)con->data);
2286                                 data->tar = newlibadr(fd, id->lib, data->tar);
2287                         }
2288                         break;
2289                 case CONSTRAINT_TYPE_SPLINEIK:
2290                         {
2291                                 bSplineIKConstraint *data;
2292                                 data= ((bSplineIKConstraint*)con->data);
2293                                 data->tar = newlibadr(fd, id->lib, data->tar);
2294                         }
2295                         break;
2296                 case CONSTRAINT_TYPE_NULL:
2297                         break;
2298                 }
2299         }
2300 }
2301
2302 static void direct_link_constraints(FileData *fd, ListBase *lb)
2303 {
2304         bConstraint *cons;
2305
2306         link_list(fd, lb);
2307         for (cons=lb->first; cons; cons=cons->next) {
2308                 cons->data = newdataadr(fd, cons->data);
2309                 
2310                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
2311                         bPythonConstraint *data= cons->data;
2312                         
2313                         link_list(fd, &data->targets);
2314                         
2315                         data->prop = newdataadr(fd, data->prop);
2316                         if (data->prop)
2317                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2318                 }
2319                 else if (cons->type == CONSTRAINT_TYPE_SPLINEIK) {
2320                         bSplineIKConstraint *data= cons->data;
2321                         
2322                         data->points= newdataadr(fd, data->points);
2323                 }
2324         }
2325 }
2326
2327 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2328 {
2329         bPoseChannel *pchan;
2330         bArmature *arm= ob->data;
2331         int rebuild;
2332         
2333         if (!pose || !arm)
2334                 return;
2335         
2336         /* always rebuild to match proxy or lib changes */
2337         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2338
2339         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2340                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2341                 
2342                 /* hurms... loop in a loop, but yah... later... (ton) */
2343                 pchan->bone= get_named_bone(arm, pchan->name);
2344                 
2345                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
2346                 if(pchan->bone==NULL)
2347                         rebuild= 1;
2348                 else if(ob->id.lib==NULL && arm->id.lib) {
2349                         /* local pose selection copied to armature, bit hackish */
2350                         pchan->bone->flag &= ~BONE_SELECTED;
2351                         pchan->bone->flag |= pchan->selectflag;
2352                 }
2353         }
2354         
2355         if(rebuild) {
2356                 ob->recalc= OB_RECALC;
2357                 pose->flag |= POSE_RECALC;
2358         }
2359 }
2360
2361 static void lib_link_armature(FileData *fd, Main *main)
2362 {
2363         bArmature *arm;
2364
2365         arm= main->armature.first;
2366
2367         while(arm) {
2368                 if(arm->id.flag & LIB_NEEDLINK) {
2369                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2370                         arm->id.flag -= LIB_NEEDLINK;
2371                 }
2372                 arm= arm->id.next;
2373         }
2374 }
2375
2376 static void direct_link_bones(FileData *fd, Bone* bone)
2377 {
2378         Bone    *child;
2379
2380         bone->parent= newdataadr(fd, bone->parent);
2381         bone->prop= newdataadr(fd, bone->prop);
2382         if(bone->prop)
2383                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2384                 
2385         bone->flag &= ~BONE_DRAW_ACTIVE;
2386
2387         link_list(fd, &bone->childbase);
2388
2389         for(child=bone->childbase.first; child; child=child->next)
2390                 direct_link_bones(fd, child);
2391 }
2392
2393 static void direct_link_armature(FileData *fd, bArmature *arm)
2394 {
2395         Bone    *bone;
2396
2397         link_list(fd, &arm->bonebase);
2398         arm->edbo= NULL;
2399         arm->sketch = NULL;
2400         
2401         arm->adt= newdataadr(fd, arm->adt);
2402         direct_link_animdata(fd, arm->adt);
2403         
2404         bone=arm->bonebase.first;
2405         while (bone) {
2406                 direct_link_bones(fd, bone);
2407                 bone=bone->next;
2408         }
2409
2410         arm->act_bone= newdataadr(fd, arm->act_bone);
2411         arm->act_edbone= NULL;
2412 }
2413
2414 /* ************ READ CAMERA ***************** */
2415
2416 static void lib_link_camera(FileData *fd, Main *main)
2417 {
2418         Camera *ca;
2419
2420         ca= main->camera.first;
2421         while(ca) {
2422                 if(ca->id.flag & LIB_NEEDLINK) {
2423                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2424                         
2425                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2426                         
2427                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2428                         
2429                         ca->id.flag -= LIB_NEEDLINK;
2430                 }
2431                 ca= ca->id.next;
2432         }
2433 }
2434
2435 static void direct_link_camera(FileData *fd, Camera *ca)
2436 {
2437         ca->adt= newdataadr(fd, ca->adt);
2438         direct_link_animdata(fd, ca->adt);
2439 }
2440
2441
2442 /* ************ READ LAMP ***************** */
2443
2444 static void lib_link_lamp(FileData *fd, Main *main)
2445 {
2446         Lamp *la;
2447         MTex *mtex;
2448         int a;
2449
2450         la= main->lamp.first;
2451         while(la) {
2452                 if(la->id.flag & LIB_NEEDLINK) {
2453                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2454                         
2455                         for(a=0; a<MAX_MTEX; a++) {
2456                                 mtex= la->mtex[a];
2457                                 if(mtex) {
2458                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2459                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2460                                 }
2461                         }
2462                         
2463                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2464                         
2465                         la->id.flag -= LIB_NEEDLINK;
2466                 }
2467                 la= la->id.next;
2468         }
2469 }
2470
2471 static void direct_link_lamp(FileData *fd, Lamp *la)
2472 {
2473         int a;
2474         
2475         la->adt= newdataadr(fd, la->adt);
2476         direct_link_animdata(fd, la->adt);
2477
2478         for(a=0; a<MAX_MTEX; a++) {
2479                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2480         }
2481         
2482         la->curfalloff= newdataadr(fd, la->curfalloff);
2483         if(la->curfalloff)
2484                 direct_link_curvemapping(fd, la->curfalloff);
2485         
2486         la->preview = direct_link_preview_image(fd, la->preview);
2487 }
2488
2489 /* ************ READ keys ***************** */
2490
2491 static void lib_link_key(FileData *fd, Main *main)
2492 {
2493         Key *key;
2494
2495         key= main->key.first;
2496         while(key) {
2497                 if(key->id.flag & LIB_NEEDLINK) {
2498                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2499                         
2500                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2501                         key->from= newlibadr(fd, key->id.lib, key->from);
2502
2503                         key->id.flag -= LIB_NEEDLINK;
2504                 }
2505                 key= key->id.next;
2506         }
2507 }
2508
2509 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2510 {
2511         int elemsize, a, b;
2512         char *data, *poin, *cp;
2513
2514         elemsize= key->elemsize;
2515         data= kb->data;
2516
2517         for(a=0; a<kb->totelem; a++) {
2518
2519                 cp= key->elemstr;
2520                 poin= data;
2521
2522                 while( cp[0] ) {        /* cp[0]==amount */
2523
2524                         switch(cp[1]) {         /* cp[1]= type */
2525                         case IPO_FLOAT:
2526                         case IPO_BPOINT:
2527                         case IPO_BEZTRIPLE:
2528                                 b= cp[0];
2529                                 while(b--) {
2530                                         SWITCH_INT((*poin));
2531                                         poin+= 4;
2532                                 }
2533                                 break;
2534                         }
2535
2536                         cp+= 2;
2537
2538                 }
2539                 data+= elemsize;
2540         }
2541 }
2542
2543 static void direct_link_key(FileData *fd, Key *key)
2544 {
2545         KeyBlock *kb;
2546
2547         link_list(fd, &(key->block));
2548
2549         key->adt= newdataadr(fd, key->adt);
2550         direct_link_animdata(fd, key->adt);
2551         
2552         key->refkey= newdataadr(fd, key->refkey);
2553
2554         kb= key->block.first;
2555         while(kb) {
2556
2557                 kb->data= newdataadr(fd, kb->data);
2558
2559                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2560                         switch_endian_keyblock(key, kb);
2561
2562                 kb= kb->next;
2563         }
2564 }
2565
2566 /* ************ READ mball ***************** */
2567
2568 static void lib_link_mball(FileData *fd, Main *main)
2569 {
2570         MetaBall *mb;
2571         int a;
2572
2573         mb= main->mball.first;
2574         while(mb) {
2575                 if(mb->id.flag & LIB_NEEDLINK) {
2576                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2577                         
2578                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2579
2580                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2581
2582                         mb->id.flag -= LIB_NEEDLINK;
2583                 }
2584                 mb= mb->id.next;
2585         }
2586 }
2587
2588 static void direct_link_mball(FileData *fd, MetaBall *mb)
2589 {
2590         mb->adt= newdataadr(fd, mb->adt);
2591         direct_link_animdata(fd, mb->adt);
2592         
2593         mb->mat= newdataadr(fd, mb->mat);
2594         test_pointer_array(fd, (void **)&mb->mat);
2595
2596         link_list(fd, &(mb->elems));
2597
2598         mb->disp.first= mb->disp.last= NULL;
2599         mb->editelems= NULL;
2600         mb->bb= NULL;
2601 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
2602         mb->lastelem= NULL;
2603 }
2604
2605 /* ************ READ WORLD ***************** */
2606
2607 static void lib_link_world(FileData *fd, Main *main)
2608 {
2609         World *wrld;
2610         MTex *mtex;
2611         int a;
2612
2613         wrld= main->world.first;
2614         while(wrld) {
2615                 if(wrld->id.flag & LIB_NEEDLINK) {
2616                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2617                         
2618                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2619                         
2620                         for(a=0; a<MAX_MTEX; a++) {
2621                                 mtex= wrld->mtex[a];
2622                                 if(mtex) {
2623                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2624                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2625                                 }
2626                         }
2627                         
2628                         wrld->id.flag -= LIB_NEEDLINK;
2629                 }
2630                 wrld= wrld->id.next;
2631         }
2632 }
2633
2634 static void direct_link_world(FileData *fd, World *wrld)
2635 {
2636         int a;
2637
2638         wrld->adt= newdataadr(fd, wrld->adt);
2639         direct_link_animdata(fd, wrld->adt);
2640
2641         for(a=0; a<MAX_MTEX; a++) {
2642                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2643         }
2644         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2645 }
2646
2647
2648 /* ************ READ VFONT ***************** */
2649
2650 static void lib_link_vfont(FileData *fd, Main *main)
2651 {
2652         VFont *vf;
2653
2654         vf= main->vfont.first;
2655         while(vf) {
2656                 if(vf->id.flag & LIB_NEEDLINK) {
2657                         vf->id.flag -= LIB_NEEDLINK;
2658                 }
2659                 vf= vf->id.next;
2660         }
2661 }
2662
2663 static void direct_link_vfont(FileData *fd, VFont *vf)
2664 {
2665         vf->data= NULL;
2666         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2667 }
2668
2669 /* ************ READ TEXT ****************** */
2670
2671 static void lib_link_text(FileData *fd, Main *main)
2672 {
2673         Text *text;
2674
2675         text= main->text.first;
2676         while(text) {
2677                 if(text->id.flag & LIB_NEEDLINK) {
2678                         text->id.flag -= LIB_NEEDLINK;
2679                 }
2680                 text= text->id.next;
2681         }
2682 }
2683
2684 static void direct_link_text(FileData *fd, Text *text)
2685 {
2686         TextLine *ln;
2687
2688         text->name= newdataadr(fd, text->name);
2689
2690         text->undo_pos= -1;
2691         text->undo_len= TXT_INIT_UNDO;
2692         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2693
2694         text->compiled= NULL;
2695
2696 /*
2697         if(text->flags & TXT_ISEXT) {
2698                 reopen_text(text);
2699         } else {
2700 */
2701
2702         link_list(fd, &text->lines);
2703         link_list(fd, &text->markers);
2704
2705         text->curl= newdataadr(fd, text->curl);
2706         text->sell= newdataadr(fd, text->sell);
2707
2708         ln= text->lines.first;
2709         while(ln) {
2710                 ln->line= newdataadr(fd, ln->line);
2711                 ln->format= NULL;
2712                 
2713                 if (ln->len != (int) strlen(ln->line)) {
2714                         printf("Error loading text, line lengths differ\n");
2715                         ln->len = strlen(ln->line);
2716                 }
2717
2718                 ln= ln->next;
2719         }
2720
2721         text->flags = (text->flags) & ~TXT_ISEXT;
2722
2723         text->id.us= 1;
2724 }
2725
2726 /* ************ READ IMAGE ***************** */
2727
2728 static void lib_link_image(FileData *fd, Main *main)
2729 {
2730         Image *ima;
2731
2732         ima= main->image.first;
2733         while (ima) {
2734                 if(ima->id.flag & LIB_NEEDLINK) {
2735                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2736
2737                         ima->id.flag -= LIB_NEEDLINK;
2738                 }
2739                 ima= ima->id.next;
2740         }
2741 }
2742
2743 static void link_ibuf_list(FileData *fd, ListBase *lb)
2744 {
2745         Link *ln, *prev;
2746         
2747         if(lb->first==NULL) return;
2748         
2749         lb->first= newimaadr(fd, lb->first);
2750         ln= lb->first;
2751         prev= NULL;
2752         while(ln) {
2753                 ln->next= newimaadr(fd, ln->next);
2754                 ln->prev= prev;
2755                 prev= ln;
2756                 ln= ln->next;
2757         }
2758         lb->last= prev;
2759 }
2760
2761 static void direct_link_image(FileData *fd, Image *ima)
2762 {
2763         /* for undo system, pointers could be restored */
2764         if(fd->imamap)
2765                 link_ibuf_list(fd, &ima->ibufs);
2766         else
2767                 ima->ibufs.first= ima->ibufs.last= NULL;
2768         
2769         /* if not restored, we keep the binded opengl index */
2770         if(ima->ibufs.first==NULL) {
2771                 ima->bindcode= 0;
2772                 ima->gputexture= NULL;
2773         }
2774         
2775         ima->anim= NULL;
2776         ima->rr= NULL;
2777         ima->repbind= NULL;
2778         ima->render_text= newdataadr(fd, ima->render_text);
2779         
2780         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2781         ima->preview = direct_link_preview_image(fd, ima->preview);
2782         ima->ok= 1;
2783 }
2784
2785
2786 /* ************ READ CURVE ***************** */
2787
2788 static void lib_link_curve(FileData *fd, Main *main)
2789 {
2790         Curve *cu;
2791         int a;
2792
2793         cu= main->curve.first;
2794         while(cu) {
2795                 if(cu->id.flag & LIB_NEEDLINK) {
2796                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2797
2798                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2799
2800                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2801                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2802                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2803                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2804                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2805                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2806                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2807
2808                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2809                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2810
2811                         cu->id.flag -= LIB_NEEDLINK;
2812                 }
2813                 cu= cu->id.next;
2814         }
2815 }
2816
2817
2818 static void switch_endian_knots(Nurb *nu)
2819 {
2820         int len;
2821
2822         if(nu->knotsu) {
2823                 len= KNOTSU(nu);
2824                 while(len--) {
2825                         SWITCH_INT(nu->knotsu[len]);
2826                 }
2827         }
2828         if(nu->knotsv) {
2829                 len= KNOTSV(nu);
2830                 while(len--) {
2831                         SWITCH_INT(nu->knotsv[len]);
2832                 }
2833         }
2834 }
2835
2836 static void direct_link_curve(FileData *fd, Curve *cu)
2837 {
2838         Nurb *nu;
2839         TextBox *tb;
2840         
2841         cu->adt= newdataadr(fd, cu->adt);
2842         direct_link_animdata(fd, cu->adt);
2843         
2844         cu->mat= newdataadr(fd, cu->mat);
2845         test_pointer_array(fd, (void **)&cu->mat);
2846         cu->str= newdataadr(fd, cu->str);
2847         cu->strinfo= newdataadr(fd, cu->strinfo);       
2848         cu->tb= newdataadr(fd, cu->tb);
2849
2850         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2851         else {
2852                 cu->nurb.first=cu->nurb.last= 0;
2853
2854                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2855                 if (cu->tb) {
2856                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2857                         MEM_freeN(cu->tb);
2858                         cu->tb= tb;                     
2859                 } else {
2860                         cu->totbox = 1;
2861                         cu->actbox = 1;
2862                         cu->tb = tb;
2863                         cu->tb[0].w = cu->linewidth;
2864                 }               
2865                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2866         }
2867
2868         cu->bev.first=cu->bev.last= NULL;
2869         cu->disp.first=cu->disp.last= NULL;
2870         cu->editnurb= NULL;
2871         cu->lastselbp= NULL;
2872         cu->path= NULL;
2873         cu->editfont= NULL;
2874         
2875         nu= cu->nurb.first;
2876         while(nu) {
2877                 nu->bezt= newdataadr(fd, nu->bezt);
2878                 nu->bp= newdataadr(fd, nu->bp);
2879                 nu->knotsu= newdataadr(fd, nu->knotsu);
2880                 nu->knotsv= newdataadr(fd, nu->knotsv);
2881                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2882
2883                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2884                         switch_endian_knots(nu);
2885                 }
2886
2887                 nu= nu->next;
2888         }
2889         cu->bb= NULL;
2890 }
2891
2892 /* ************ READ TEX ***************** */
2893
2894 static void lib_link_texture(FileData *fd, Main *main)
2895 {
2896         Tex *tex;
2897
2898         tex= main->tex.first;
2899         while(tex) {
2900                 if(tex->id.flag & LIB_NEEDLINK) {
2901                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2902
2903                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2904                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2905                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2906                         if(tex->pd)
2907                                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
2908                         if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
2909
2910                         if(tex->nodetree)
2911                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2912                         
2913                         tex->id.flag -= LIB_NEEDLINK;
2914                 }
2915                 tex= tex->id.next;
2916         }
2917 }
2918
2919 static void direct_link_texture(FileData *fd, Tex *tex)
2920 {
2921         tex->adt= newdataadr(fd, tex->adt);
2922         direct_link_animdata(fd, tex->adt);
2923         
2924         tex->plugin= newdataadr(fd, tex->plugin);
2925         if(tex->plugin) {
2926                 tex->plugin->handle= 0;
2927                 open_plugin_tex(tex->plugin);
2928                 /* initialize data for this instance, if an initialization
2929                  * function exists.
2930                  */
2931                 if (tex->plugin->instance_init)
2932                         tex->plugin->instance_init((void *) tex->plugin->data);
2933         }
2934         tex->coba= newdataadr(fd, tex->coba);
2935         tex->env= newdataadr(fd, tex->env);
2936         if(tex->env) {
2937                 tex->env->ima= NULL;
2938                 memset(tex->env->cube, 0, 6*sizeof(void *));
2939                 tex->env->ok= 0;
2940         }
2941         tex->pd= newdataadr(fd, tex->pd);
2942         if(tex->pd) {
2943                 tex->pd->point_tree = NULL;
2944                 tex->pd->coba= newdataadr(fd, tex->pd->coba);
2945         }
2946         
2947         tex->vd= newdataadr(fd, tex->vd);
2948         if(tex->vd) {
2949                 tex->vd->dataset = NULL;
2950         }
2951         
2952         tex->nodetree= newdataadr(fd, tex->nodetree);
2953         if(tex->nodetree)
2954                 direct_link_nodetree(fd, tex->nodetree);
2955         
2956         tex->preview = direct_link_preview_image(fd, tex->preview);
2957
2958         tex->iuser.ok= 1;
2959 }
2960
2961
2962
2963 /* ************ READ MATERIAL ***************** */
2964
2965 static void lib_link_material(FileData *fd, Main *main)
2966 {
2967         Material *ma;
2968         MTex *mtex;
2969         int a;
2970
2971         ma= main->mat.first;
2972         while(ma) {
2973                 if(ma->id.flag & LIB_NEEDLINK) {
2974                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2975
2976                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2977                         of library blocks that implement this.*/
2978                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2979
2980                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2981                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2982                         
2983                         for(a=0; a<MAX_MTEX; a++) {
2984                                 mtex= ma->mtex[a];
2985                                 if(mtex) {
2986                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2987                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2988                                 }
2989                         }
2990                         
2991                         if(ma->nodetree)
2992                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2993                         
2994                         ma->id.flag -= LIB_NEEDLINK;
2995                 }
2996                 ma= ma->id.next;
2997         }
2998 }
2999
3000 static void direct_link_material(FileData *fd, Material *ma)
3001 {
3002         int a;
3003
3004         ma->adt= newdataadr(fd, ma->adt);
3005         direct_link_animdata(fd, ma->adt);
3006         
3007         for(a=0; a<MAX_MTEX; a++) {
3008                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
3009         }
3010
3011         ma->ramp_col= newdataadr(fd, ma->ramp_col);
3012         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
3013         
3014         ma->nodetree= newdataadr(fd, ma->nodetree);
3015         if(ma->nodetree)
3016                 direct_link_nodetree(fd, ma->nodetree);
3017
3018         ma->preview = direct_link_preview_image(fd, ma->preview);
3019         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
3020 }
3021
3022 /* ************ READ PARTICLE SETTINGS ***************** */
3023
3024 static void direct_link_pointcache(FileData *fd, PointCache *cache)
3025 {
3026         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
3027                 PTCacheMem *pm;
3028                 int i;
3029
3030                 link_list(fd, &cache->mem_cache);
3031
3032                 pm = cache->mem_cache.first;
3033
3034                 for(; pm; pm=pm->next) {
3035                         if(pm->index_array)
3036                                 pm->index_array = newdataadr(fd, pm->index_array);
3037                         
3038                         for(i=0; i<BPHYS_TOT_DATA; i++) {
3039                                 if(pm->data[i] && pm->data_types & (1<<i))
3040                                         pm->data[i] = newdataadr(fd, pm->data[i]);
3041                         }
3042                 }
3043         }
3044         else
3045                 cache->mem_cache.first = cache->mem_cache.last = NULL;
3046
3047         cache->flag &= ~PTCACHE_SIMULATION_VALID;
3048         cache->simframe= 0;
3049         cache->edit= NULL;
3050         cache->free_edit= NULL;
3051 }
3052
3053 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache)
3054 {
3055         PointCache *cache;
3056
3057         if(ptcaches->first) {
3058                 link_list(fd, ptcaches);
3059                 for(cache=ptcaches->first; cache; cache=cache->next)
3060                         direct_link_pointcache(fd, cache);
3061
3062                 *ocache = newdataadr(fd, *ocache);
3063         }
3064         else if(*ocache) {
3065                 /* old "single" caches need to be linked too */
3066                 *ocache = newdataadr(fd, *ocache);
3067                 direct_link_pointcache(fd, *ocache);
3068
3069                 ptcaches->first = ptcaches->last = *ocache;
3070         }
3071 }
3072
3073 static void lib_link_particlesettings(FileData *fd, Main *main)
3074 {
3075         ParticleSettings *part;
3076         ParticleDupliWeight *dw;
3077
3078         part= main->particle.first;
3079         while(part) {
3080                 if(part->id.flag & LIB_NEEDLINK) {
3081                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
3082                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
3083                         
3084                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
3085                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
3086                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
3087                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
3088
3089                         if(part->effector_weights)
3090                                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
3091
3092                         dw = part->dupliweights.first;
3093                         for(; dw; dw=dw->next)
3094                                 dw->ob = newlibadr(fd, part->id.lib, dw->ob);
3095
3096                         if(part->boids) {
3097                                 BoidState *state = part->boids->states.first;
3098                                 BoidRule *rule;
3099                                 for(; state; state=state->next) {
3100                                         rule = state->rules.first;
3101                                 for(; rule; rule=rule->next)
3102                                         switch(rule->type) {
3103                                                 case eBoidRuleType_Goal:
3104                                                 case eBoidRuleType_Avoid:
3105                                                 {
3106                                                         BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
3107                                                         brga->ob = newlibadr(fd, part->id.lib, brga->ob);
3108                                                         break;
3109                                                 }
3110                                                 case eBoidRuleType_FollowLeader:
3111                                                 {
3112                                                         BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
3113                                                         brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
3114                                                         break;
3115                                                 }
3116                                         }
3117                                 }
3118                         }
3119                         part->id.flag -= LIB_NEEDLINK;
3120                 }
3121                 part= part->id.next;
3122         }
3123 }
3124
3125 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
3126 {
3127         part->adt= newdataadr(fd, part->adt);
3128         part->pd= newdataadr(fd, part->pd);
3129         part->pd2= newdataadr(fd, part->pd2);
3130
3131         part->effector_weights = newdataadr(fd, part->effector_weights);
3132         if(!part->effector_weights)
3133                 part->effector_weights = BKE_add_effector_weights(part->eff_group);
3134
3135         link_list(fd, &part->dupliweights);
3136
3137         part->boids= newdataadr(fd, part->boids);
3138
3139         if(part->boids) {
3140                 BoidState *state;
3141                 link_list(fd, &part->boids->states);
3142                 
3143                 for(state=part->boids->states.first; state; state=state->next) {
3144                         link_list(fd, &state->rules);
3145                         link_list(fd, &state->conditions);
3146                         link_list(fd, &state->actions);
3147                 }
3148         }
3149 }
3150
3151 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
3152 {
3153         ParticleSystem *psys, *psysnext;
3154
3155         for(psys=particles->first; psys; psys=psysnext){
3156                 psysnext= psys->next;
3157                 
3158                 psys->part = newlibadr_us(fd, id->lib, psys->part);
3159                 if(psys->part) {
3160                         ParticleTarget *pt = psys->targets.first;
3161
3162                         for(; pt; pt=pt->next)
3163                                 pt->ob=newlibadr(fd, id->lib, pt->ob);
3164
3165                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
3166                 }
3167                 else {
3168                         /* particle modifier must be removed before particle system */
3169                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3170                         BLI_remlink(&ob->modifiers, psmd);
3171                         modifier_free((ModifierData *)psmd);
3172
3173                         BLI_remlink(particles, psys);
3174                         MEM_freeN(psys);
3175                 }
3176         }
3177 }
3178 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
3179 {
3180         ParticleSystem *psys;
3181         ParticleData *pa;
3182         int a;
3183
3184         for(psys=particles->first; psys; psys=psys->next) {
3185                 psys->particles=newdataadr(fd,psys->particles);
3186                 
3187                 if(psys->particles && psys->particles->hair){
3188                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3189                                 pa->hair=newdataadr(fd,pa->hair);
3190                 }
3191                 
3192                 if(psys->particles && psys->particles->keys){
3193                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++) {
3194                                 pa->keys= NULL;
3195                                 pa->totkey= 0;
3196                         }
3197
3198                         psys->flag &= ~PSYS_KEYED;
3199                 }
3200
3201                 if(psys->particles && psys->particles->boid) {
3202                         pa = psys->particles;
3203                         pa->boid = newdataadr(fd, pa->boid);
3204                         for(a=1,pa++; a<psys->totpart; a++, pa++)
3205                                 pa->boid = (pa-1)->boid + 1;
3206                 }
3207                 else {
3208                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3209                                 pa->boid = NULL;
3210                 }
3211
3212
3213                 psys->child = newdataadr(fd,psys->child);
3214                 psys->effectors = NULL;
3215
3216                 link_list(fd, &psys->targets);
3217
3218                 psys->edit = NULL;
3219                 psys->free_edit = NULL;
3220                 psys->pathcache = NULL;
3221                 psys->childcache = NULL;
3222                 psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
3223                 psys->childcachebufs.first = psys->childcachebufs.last = NULL;
3224                 psys->frand = NULL;
3225                 psys->pdd = NULL;
3226
3227                 direct_link_pointcache_list(fd, &psys->ptcaches, &psys->pointcache);
3228
3229                 if(psys->clmd) {
3230                         psys->clmd = newdataadr(fd, psys->clmd);
3231                         psys->clmd->clothObject = NULL;
3232                         
3233                         psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
3234                         psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
3235                         
3236                         if(psys->clmd->sim_parms) {
3237                                 if(psys->clmd->sim_parms->presets > 10)
3238                                         psys->clmd->sim_parms->presets = 0;
3239                         }
3240
3241                         psys->hair_in_dm = psys->hair_out_dm = NULL;
3242
3243                         psys->clmd->point_cache = psys->pointcache;
3244                 }
3245
3246                 psys->tree = NULL;
3247         }
3248         return;
3249 }
3250
3251 /* ************ READ MESH ***************** */
3252
3253 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
3254 {
3255         MTFace *tf= mtface;
3256         int i;
3257
3258         for (i=0; i<totface; i++, tf++) {
3259                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
3260                 if(tf->tpage && tf->tpage->id.us==0)
3261                         tf->tpage->id.us= 1;
3262         }
3263 }
3264
3265 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
3266 {