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