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