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