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