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