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