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