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