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