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