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