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