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