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