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