Merging trunk up to r38932.
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  *
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  *
28  */
29
30 /** \file blender/blenloader/intern/readfile.c
31  *  \ingroup blenloader
32  */
33
34
35 #include "zlib.h"
36
37 #include <limits.h>
38 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
39 #include <stdlib.h> // for getenv atoi
40 #include <stddef.h> // for offsetof
41 #include <fcntl.h> // for open
42 #include <string.h> // for strrchr strncmp strstr
43 #include <math.h> // for fabs
44
45 #ifndef WIN32
46         #include <unistd.h> // for read close
47 #else
48         #include <io.h> // for open close read
49 #include "winsock2.h"
50 #include "BLI_winstuff.h"
51 #endif
52
53 #include "DNA_anim_types.h"
54 #include "DNA_armature_types.h"
55 #include "DNA_actuator_types.h"
56 #include "DNA_brush_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_cloth_types.h"
59 #include "DNA_controller_types.h"
60 #include "DNA_constraint_types.h"
61 #include "DNA_effect_types.h"
62 #include "DNA_fileglobal_types.h"
63 #include "DNA_genfile.h"
64 #include "DNA_group_types.h"
65 #include "DNA_gpencil_types.h"
66 #include "DNA_ipo_types.h"
67 #include "DNA_key_types.h"
68 #include "DNA_lattice_types.h"
69 #include "DNA_lamp_types.h"
70 #include "DNA_meta_types.h"
71 #include "DNA_material_types.h"
72 #include "DNA_mesh_types.h"
73 #include "DNA_meshdata_types.h"
74 #include "DNA_nla_types.h"
75 #include "DNA_node_types.h"
76 #include "DNA_object_fluidsim.h" // NT
77 #include "DNA_packedFile_types.h"
78 #include "DNA_particle_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_speaker_types.h"
89 #include "DNA_sound_types.h"
90 #include "DNA_space_types.h"
91 #include "DNA_vfont_types.h"
92 #include "DNA_world_types.h"
93
94 #include "MEM_guardedalloc.h"
95
96 #include "BLI_blenlib.h"
97 #include "BLI_math.h"
98 #include "BLI_utildefines.h"
99
100 #include "BKE_anim.h"
101 #include "BKE_action.h"
102 #include "BKE_armature.h"
103 #include "BKE_brush.h"
104 #include "BKE_colortools.h"
105 #include "BKE_constraint.h"
106 #include "BKE_context.h"
107 #include "BKE_curve.h"
108 #include "BKE_deform.h"
109 #include "BKE_effect.h" /* give_parteff */
110 #include "BKE_fcurve.h"
111 #include "BKE_global.h" // for G
112 #include "BKE_group.h"
113 #include "BKE_image.h"
114 #include "BKE_lattice.h"
115 #include "BKE_library.h" // for which_libbase
116 #include "BKE_idcode.h"
117 #include "BKE_material.h"
118 #include "BKE_main.h" // for Main
119 #include "BKE_mesh.h" // for ME_ defines (patching)
120 #include "BKE_modifier.h"
121 #include "BKE_multires.h"
122 #include "BKE_node.h" // for tree type defines
123 #include "BKE_object.h"
124 #include "BKE_paint.h"
125 #include "BKE_particle.h"
126 #include "BKE_pointcache.h"
127 #include "BKE_property.h" // for get_ob_property
128 #include "BKE_report.h"
129 #include "BKE_sca.h" // for init_actuator
130 #include "BKE_scene.h"
131 #include "BKE_screen.h"
132 #include "BKE_sequencer.h"
133 #include "BKE_texture.h" // for open_plugin_tex
134 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
135 #include "BKE_sound.h"
136
137 //XXX #include "BIF_butspace.h" // badlevel, for do_versions, patching event codes
138 //XXX #include "BIF_filelist.h" // badlevel too, where to move this? - elubie
139 //XXX #include "BIF_previewrender.h" // bedlelvel, for struct RenderInfo
140 #include "BLO_readfile.h"
141 #include "BLO_undofile.h"
142
143 #include "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 *filepath, const char *relabase)
493 {
494         Main *m;
495         Library *lib;
496         char name1[FILE_MAXDIR+FILE_MAXFILE];
497         
498         BLI_strncpy(name1, filepath, sizeof(name1));
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, filepath, 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", filepath);
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 *filepath, ReportList *reports)
950 {
951         gzFile gzfile;
952         errno= 0;
953         gzfile= gzopen(filepath, "rb");
954
955         if (gzfile == (gzFile)Z_NULL) {
956                 BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", filepath, 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, filepath, 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 (strcmp("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 < NUM_ICON_SIZES; ++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                                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1743                                         unsigned int a;
1744                                         for(a = 0; a < data->arraysize; a++)
1745                                                 SWITCH_INT(data->coefficients[a]);
1746                                 }
1747                         }
1748                                 break;
1749                         case FMODIFIER_TYPE_ENVELOPE:
1750                         {
1751                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
1752                                 
1753                                 data->data= newdataadr(fd, data->data);
1754                         }
1755                                 break;
1756                         case FMODIFIER_TYPE_PYTHON:
1757                         {
1758                                 FMod_Python *data= (FMod_Python *)fcm->data;
1759                                 
1760                                 data->prop = newdataadr(fd, data->prop);
1761                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1762                         }
1763                                 break;
1764                 }
1765         }
1766 }
1767
1768 /* NOTE: this assumes that link_list has already been called on the list */
1769 static void direct_link_fcurves(FileData *fd, ListBase *list)
1770 {
1771         FCurve *fcu;
1772         
1773         /* link F-Curve data to F-Curve again (non ID-libs) */
1774         for (fcu= list->first; fcu; fcu= fcu->next) {
1775                 /* curve data */
1776                 fcu->bezt= newdataadr(fd, fcu->bezt);
1777                 fcu->fpt= newdataadr(fd, fcu->fpt);
1778                 
1779                 /* rna path */
1780                 fcu->rna_path= newdataadr(fd, fcu->rna_path);
1781                 
1782                 /* group */
1783                 fcu->grp= newdataadr(fd, fcu->grp);
1784                 
1785                 /* driver */
1786                 fcu->driver= newdataadr(fd, fcu->driver);
1787                 if (fcu->driver) {
1788                         ChannelDriver *driver= fcu->driver;
1789                         DriverVar *dvar;
1790
1791                         driver->expr_comp= NULL;
1792                         
1793                         /* relink variables, targets and their paths */
1794                         link_list(fd, &driver->variables);
1795                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1796                                 DRIVER_TARGETS_LOOPER(dvar)
1797                                 {
1798                                         /* only relink the targets being used */
1799                                         if (tarIndex < dvar->num_targets)
1800                                                 dtar->rna_path= newdataadr(fd, dtar->rna_path);
1801                                         else
1802                                                 dtar->rna_path= NULL;
1803                                 }
1804                                 DRIVER_TARGETS_LOOPER_END
1805                         }
1806                 }
1807                 
1808                 /* modifiers */
1809                 link_list(fd, &fcu->modifiers);
1810                 direct_link_fmodifiers(fd, &fcu->modifiers);
1811         }
1812 }
1813
1814
1815 static void lib_link_action(FileData *fd, Main *main)
1816 {
1817         bAction *act;
1818         bActionChannel *chan;
1819
1820         for (act= main->action.first; act; act= act->id.next) {
1821                 if (act->id.flag & LIB_NEEDLINK) {
1822                         act->id.flag -= LIB_NEEDLINK;
1823                         
1824 // XXX depreceated - old animation system <<<
1825                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1826                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1827                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1828                         }
1829 // >>> XXX depreceated - old animation system
1830                         
1831                         lib_link_fcurves(fd, &act->id, &act->curves);
1832                 }
1833         }
1834 }
1835
1836 static void direct_link_action(FileData *fd, bAction *act)
1837 {
1838         bActionChannel *achan; // XXX depreceated - old animation system
1839         bActionGroup *agrp;
1840
1841         link_list(fd, &act->curves);
1842         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
1843         link_list(fd, &act->groups);
1844         link_list(fd, &act->markers);
1845
1846 // XXX depreceated - old animation system <<<
1847         for (achan = act->chanbase.first; achan; achan=achan->next) {
1848                 achan->grp= newdataadr(fd, achan->grp);
1849                 
1850                 link_list(fd, &achan->constraintChannels);
1851         }
1852 // >>> XXX depreceated - old animation system
1853
1854         direct_link_fcurves(fd, &act->curves);
1855         
1856         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1857                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
1858                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
1859         }
1860 }
1861
1862 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
1863 {
1864         NlaStrip *strip;
1865         
1866         for (strip= list->first; strip; strip= strip->next) {
1867                 /* check strip's children */
1868                 lib_link_nladata_strips(fd, id, &strip->strips);
1869                 
1870                 /* check strip's F-Curves */
1871                 lib_link_fcurves(fd, id, &strip->fcurves);
1872                 
1873                 /* reassign the counted-reference to action */
1874                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1875                 
1876                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
1877                 if ((strip->act) && (strip->act->idroot == 0))
1878                         strip->act->idroot = GS(id->name);
1879         }
1880 }
1881
1882 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
1883 {
1884         NlaTrack *nlt;
1885         
1886         /* we only care about the NLA strips inside the tracks */
1887         for (nlt= list->first; nlt; nlt= nlt->next) {
1888                 lib_link_nladata_strips(fd, id, &nlt->strips);
1889         }
1890 }
1891
1892 /* This handles Animato NLA-Strips linking 
1893  * NOTE: this assumes that link_list has already been called on the list 
1894  */
1895 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
1896 {
1897         NlaStrip *strip;
1898         
1899         for (strip= list->first; strip; strip= strip->next) {
1900                 /* strip's child strips */
1901                 link_list(fd, &strip->strips);
1902                 direct_link_nladata_strips(fd, &strip->strips);
1903                 
1904                 /* strip's F-Curves */
1905                 link_list(fd, &strip->fcurves);
1906                 direct_link_fcurves(fd, &strip->fcurves);
1907                 
1908                 /* strip's F-Modifiers */
1909                 link_list(fd, &strip->modifiers);
1910                 direct_link_modifiers(fd, &strip->modifiers);
1911         }
1912 }
1913
1914 /* NOTE: this assumes that link_list has already been called on the list */
1915 static void direct_link_nladata(FileData *fd, ListBase *list)
1916 {
1917         NlaTrack *nlt;
1918         
1919         for (nlt= list->first; nlt; nlt= nlt->next) {
1920                 /* relink list of strips */
1921                 link_list(fd, &nlt->strips);
1922                 
1923                 /* relink strip data */
1924                 direct_link_nladata_strips(fd, &nlt->strips);
1925         }
1926 }
1927
1928 /* ------- */
1929
1930 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
1931 {
1932         KeyingSet *ks;
1933         KS_Path *ksp;
1934         
1935         /* here, we're only interested in the ID pointer stored in some of the paths */
1936         for (ks= list->first; ks; ks= ks->next) {
1937                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1938                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
1939                 }
1940         }
1941 }
1942
1943 /* NOTE: this assumes that link_list has already been called on the list */
1944 static void direct_link_keyingsets(FileData *fd, ListBase *list)
1945 {
1946         KeyingSet *ks;
1947         KS_Path *ksp;
1948         
1949         /* link KeyingSet data to KeyingSet again (non ID-libs) */
1950         for (ks= list->first; ks; ks= ks->next) {
1951                 /* paths */
1952                 link_list(fd, &ks->paths);
1953                 
1954                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1955                         /* rna path */
1956                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
1957                 }
1958         }
1959 }
1960
1961 /* ------- */
1962
1963 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
1964 {
1965         if (adt == NULL)
1966                 return;
1967         
1968         /* link action data */
1969         adt->action= newlibadr_us(fd, id->lib, adt->action);
1970         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
1971         
1972         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
1973         if ((adt->action) && (adt->action->idroot == 0))
1974                 adt->action->idroot = GS(id->name);
1975         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
1976                 adt->tmpact->idroot = GS(id->name);
1977         
1978         /* link drivers */
1979         lib_link_fcurves(fd, id, &adt->drivers);
1980         
1981         /* overrides don't have lib-link for now, so no need to do anything */
1982         
1983         /* link NLA-data */
1984         lib_link_nladata(fd, id, &adt->nla_tracks);
1985 }
1986
1987 static void direct_link_animdata(FileData *fd, AnimData *adt)
1988 {
1989         /* NOTE: must have called newdataadr already before doing this... */
1990         if (adt == NULL)
1991                 return;
1992         
1993         /* link drivers */
1994         link_list(fd, &adt->drivers);
1995         direct_link_fcurves(fd, &adt->drivers);
1996         
1997         /* link overrides */
1998         // TODO...
1999         
2000         /* link NLA-data */
2001         link_list(fd, &adt->nla_tracks);
2002         direct_link_nladata(fd, &adt->nla_tracks);
2003         
2004         /* relink active strip - even though strictly speaking this should only be used
2005          * if we're in 'tweaking mode', we need to be able to have this loaded back for
2006          * undo, but also since users may not exit tweakmode before saving (#24535)
2007          */
2008         // TODO: it's not really nice that anyone should be able to save the file in this
2009         //              state, but it's going to be too hard to enforce this single case...
2010         adt->actstrip= newdataadr(fd, adt->actstrip);
2011 }       
2012
2013 /* ************ READ MOTION PATHS *************** */
2014
2015 /* direct data for cache */
2016 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2017 {
2018         /* sanity check */
2019         if (mpath == NULL)
2020                 return;
2021         
2022         /* relink points cache */
2023         mpath->points= newdataadr(fd, mpath->points);
2024 }
2025
2026 /* ************ READ NODE TREE *************** */
2027
2028 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2029 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2030 {
2031         bNode *node;
2032         
2033         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
2034         
2035         ntree->gpd= newlibadr_us(fd, id->lib, ntree->gpd);
2036         
2037         for(node= ntree->nodes.first; node; node= node->next)
2038                 node->id= newlibadr_us(fd, id->lib, node->id);
2039 }
2040
2041 /* library ntree linking after fileread */
2042 static void lib_link_nodetree(FileData *fd, Main *main)
2043 {
2044         bNodeTree *ntree;
2045         
2046         /* only link ID pointers */
2047         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2048                 if(ntree->id.flag & LIB_NEEDLINK) {
2049                         ntree->id.flag -= LIB_NEEDLINK;
2050                         lib_link_ntree(fd, &ntree->id, ntree);
2051                 }
2052         }
2053 }
2054
2055 /* updates group node socket own_index so that
2056  * external links to/from the group node are preserved.
2057  */
2058 static void lib_node_do_versions_group(bNode *gnode)
2059 {
2060         bNodeTree *ngroup= (bNodeTree*)gnode->id;
2061         bNode *intnode;
2062         bNodeSocket *sock, *gsock, *intsock;
2063         int found;
2064         
2065         for (sock=gnode->outputs.first; sock; sock=sock->next) {
2066                 int old_index = sock->to_index;
2067                 for (gsock=ngroup->outputs.first; gsock; gsock=gsock->next) {
2068                         if (gsock->link && gsock->link->fromsock->own_index == old_index) {
2069                                 sock->own_index = gsock->own_index;
2070                                 break;
2071                         }
2072                 }
2073         }
2074         for (sock=gnode->inputs.first; sock; sock=sock->next) {
2075                 int old_index = sock->to_index;
2076                 /* can't use break in double loop */
2077                 found = 0;
2078                 for (intnode=ngroup->nodes.first; intnode && !found; intnode=intnode->next) {
2079                         for (intsock=intnode->inputs.first; intsock; intsock=intsock->next) {
2080                                 if (intsock->own_index == old_index && intsock->link) {
2081                                         sock->own_index = intsock->link->fromsock->own_index;
2082                                         found = 1;
2083                                         break;
2084                                 }
2085                         }
2086                 }
2087         }
2088 }
2089
2090 /* updates external links for all group nodes in a tree */
2091 static void lib_nodetree_do_versions_group(bNodeTree *ntree)
2092 {
2093         bNode *node;
2094         
2095         for (node=ntree->nodes.first; node; node=node->next) {
2096                 if (node->type==NODE_GROUP) {
2097                         bNodeTree *ngroup= (bNodeTree*)node->id;
2098                         if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS))
2099                                 lib_node_do_versions_group(node);
2100                 }
2101         }
2102 }
2103
2104 /* verify types for nodes and groups, all data has to be read */
2105 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2106 * typedefs*/
2107 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2108 {
2109         Scene *sce;
2110         Material *ma;
2111         Tex *tx;
2112         bNodeTree *ntree;
2113         
2114         /* this crashes blender on undo/redo
2115                 if(open==1) {
2116                         reinit_nodesystem();
2117                 }*/
2118         
2119         /* now create the own typeinfo structs an verify nodes */
2120         /* here we still assume no groups in groups */
2121         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2122                 ntreeVerifyTypes(ntree);                /* internal nodes, no groups! */
2123         }
2124         
2125         {
2126                 /*int has_old_groups=0;*/ /*UNUSED*/
2127                 /* XXX this should actually be part of do_versions, but since we need
2128                  * finished library linking, it is not possible there. Instead in do_versions
2129                  * we have set the NTREE_DO_VERSIONS flag, so at this point we can do the
2130                  * actual group node updates.
2131                  */
2132                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2133                         if (ntree->flag & NTREE_DO_VERSIONS) {
2134                                 /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */
2135                                 nodeGroupExposeAllSockets(ntree);
2136                                 /*has_old_groups = 1;*/ /*UNUSED*/
2137                         }
2138                 }
2139                 /* now verify all types in material trees, groups are set OK now */
2140                 for(ma= main->mat.first; ma; ma= ma->id.next) {
2141                         if(ma->nodetree)
2142                                 lib_nodetree_do_versions_group(ma->nodetree);
2143                 }
2144                 /* and scene trees */
2145                 for(sce= main->scene.first; sce; sce= sce->id.next) {
2146                         if(sce->nodetree)
2147                                 lib_nodetree_do_versions_group(sce->nodetree);
2148                 }
2149                 /* and texture trees */
2150                 for(tx= main->tex.first; tx; tx= tx->id.next) {
2151                         if(tx->nodetree)
2152                                 lib_nodetree_do_versions_group(tx->nodetree);
2153                 }
2154                 
2155                 for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
2156                         ntree->flag &= ~NTREE_DO_VERSIONS;
2157         }
2158
2159         /* now verify all types in material trees, groups are set OK now */
2160         for(ma= main->mat.first; ma; ma= ma->id.next) {
2161                 if(ma->nodetree)
2162                         ntreeVerifyTypes(ma->nodetree);
2163         }
2164         /* and scene trees */
2165         for(sce= main->scene.first; sce; sce= sce->id.next) {
2166                 if(sce->nodetree)
2167                         ntreeVerifyTypes(sce->nodetree);
2168         }
2169         /* and texture trees */
2170         for(tx= main->tex.first; tx; tx= tx->id.next) {
2171                 if(tx->nodetree)
2172                         ntreeVerifyTypes(tx->nodetree);
2173         }
2174 }
2175
2176
2177
2178 /* ntree itself has been read! */
2179 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2180 {
2181         /* note: writing and reading goes in sync, for speed */
2182         bNode *node;
2183         bNodeSocket *sock;
2184         bNodeLink *link;
2185         
2186         ntree->init= 0;         /* to set callbacks and force setting types */
2187         ntree->progress= NULL;
2188         
2189         ntree->adt= newdataadr(fd, ntree->adt);
2190         direct_link_animdata(fd, ntree->adt);
2191         
2192         link_list(fd, &ntree->nodes);
2193         for(node= ntree->nodes.first; node; node= node->next) {
2194                 if(node->type == NODE_DYNAMIC) {
2195                         node->custom1= 0;
2196                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
2197                         node->typeinfo= NULL;
2198                 }
2199                 
2200                 node->storage= newdataadr(fd, node->storage);
2201                 if(node->storage) {
2202                         
2203                         /* could be handlerized at some point */
2204                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2205                                 direct_link_curvemapping(fd, node->storage);
2206                         else if(ntree->type==NTREE_COMPOSIT) {
2207                                 if( ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
2208                                         direct_link_curvemapping(fd, node->storage);
2209                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2210                                         ((ImageUser *)node->storage)->ok= 1;
2211                         }
2212                         else if( ntree->type==NTREE_TEXTURE) {
2213                                 if(node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
2214                                         direct_link_curvemapping(fd, node->storage);
2215                                 else if(node->type==TEX_NODE_IMAGE)
2216                                         ((ImageUser *)node->storage)->ok= 1;
2217                         }
2218                 }
2219                 link_list(fd, &node->inputs);
2220                 link_list(fd, &node->outputs);
2221         }
2222         link_list(fd, &ntree->links);
2223         
2224         /* external sockets */
2225         link_list(fd, &ntree->inputs);
2226         link_list(fd, &ntree->outputs);
2227         
2228         /* and we connect the rest */
2229         for(node= ntree->nodes.first; node; node= node->next) {
2230                 node->preview= newimaadr(fd, node->preview);
2231                 node->lasty= 0;
2232                 for(sock= node->inputs.first; sock; sock= sock->next)
2233                         sock->link= newdataadr(fd, sock->link);
2234                 for(sock= node->outputs.first; sock; sock= sock->next)
2235                         sock->ns.data= NULL;
2236         }
2237         for(sock= ntree->outputs.first; sock; sock= sock->next)
2238                 sock->link= newdataadr(fd, sock->link);
2239         
2240         for(link= ntree->links.first; link; link= link->next) {
2241                 link->fromnode= newdataadr(fd, link->fromnode);
2242                 link->tonode= newdataadr(fd, link->tonode);
2243                 link->fromsock= newdataadr(fd, link->fromsock);
2244                 link->tosock= newdataadr(fd, link->tosock);
2245         }
2246         
2247         /* type verification is in lib-link */
2248 }
2249
2250 /* ************ READ ARMATURE ***************** */
2251
2252 /* temp struct used to transport needed info to lib_link_constraint_cb() */
2253 typedef struct tConstraintLinkData {
2254         FileData *fd;
2255         ID *id;
2256 } tConstraintLinkData;
2257 /* callback function used to relink constraint ID-links */
2258 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
2259 {
2260         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
2261         *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
2262 }
2263
2264 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2265 {
2266         tConstraintLinkData cld;
2267         bConstraint *con;
2268         
2269         /* legacy fixes */
2270         for (con = conlist->first; con; con=con->next) {
2271                 /* patch for error introduced by changing constraints (dunno how) */
2272                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2273                 if(con->data==NULL) {
2274                         con->type= CONSTRAINT_TYPE_NULL;
2275                 }
2276                 /* own ipo, all constraints have it */
2277                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2278         }
2279         
2280         /* relink all ID-blocks used by the constraints */
2281         cld.fd= fd;
2282         cld.id= id;
2283         
2284         id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
2285 }
2286
2287 static void direct_link_constraints(FileData *fd, ListBase *lb)
2288 {
2289         bConstraint *con;
2290
2291         link_list(fd, lb);
2292         for (con=lb->first; con; con=con->next) {
2293                 con->data = newdataadr(fd, con->data);
2294                 
2295                 switch (con->type) {
2296                         case CONSTRAINT_TYPE_PYTHON:
2297                         {
2298                                 bPythonConstraint *data= con->data;
2299                                 
2300                                 link_list(fd, &data->targets);
2301                                 
2302                                 data->prop = newdataadr(fd, data->prop);
2303                                 if (data->prop)
2304                                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2305                         }
2306                                 break;
2307                         case CONSTRAINT_TYPE_SPLINEIK:
2308                         {
2309                                 bSplineIKConstraint *data= con->data;
2310                                 
2311                                 data->points= newdataadr(fd, data->points);
2312                         }
2313                                 break;
2314                         case CONSTRAINT_TYPE_KINEMATIC:
2315                         {
2316                                 con->lin_error = 0.f;
2317                                 con->rot_error = 0.f;
2318                         }
2319                         case CONSTRAINT_TYPE_CHILDOF:
2320                         {
2321                                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
2322                                 if(con->ownspace == CONSTRAINT_SPACE_POSE)
2323                                         con->flag |= CONSTRAINT_SPACEONCE;
2324                         }
2325                                 break;
2326                 }
2327         }
2328 }
2329
2330 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2331 {
2332         bPoseChannel *pchan;
2333         bArmature *arm= ob->data;
2334         int rebuild;
2335         
2336         if (!pose || !arm)
2337                 return;
2338         
2339
2340         /* always rebuild to match proxy or lib changes */
2341         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2342
2343         if(ob->proxy) {
2344                 /* sync proxy layer */
2345                 if(pose->proxy_layer)
2346                         arm->layer = pose->proxy_layer;
2347                 
2348                 /* sync proxy active bone */
2349                 if(pose->proxy_act_bone[0]) {
2350                         Bone *bone = get_named_bone(arm, pose->proxy_act_bone);
2351                         if (bone)
2352                                 arm->act_bone = bone;
2353                 }
2354         }
2355
2356         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2357                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2358                 
2359                 /* hurms... loop in a loop, but yah... later... (ton) */
2360                 pchan->bone= get_named_bone(arm, pchan->name);
2361                 
2362                 pchan->custom= newlibadr_us(fd, arm->id.lib, pchan->custom);
2363                 if(pchan->bone==NULL)
2364                         rebuild= 1;
2365                 else if(ob->id.lib==NULL && arm->id.lib) {
2366                         /* local pose selection copied to armature, bit hackish */
2367                         pchan->bone->flag &= ~BONE_SELECTED;
2368                         pchan->bone->flag |= pchan->selectflag;
2369                 }
2370         }
2371         
2372         if(rebuild) {
2373                 ob->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
2374                 pose->flag |= POSE_RECALC;
2375         }
2376 }
2377
2378 static void lib_link_armature(FileData *fd, Main *main)
2379 {
2380         bArmature *arm;
2381
2382         arm= main->armature.first;
2383
2384         while(arm) {
2385                 if(arm->id.flag & LIB_NEEDLINK) {
2386                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2387                         arm->id.flag -= LIB_NEEDLINK;
2388                 }
2389                 arm= arm->id.next;
2390         }
2391 }
2392
2393 static void direct_link_bones(FileData *fd, Bone* bone)
2394 {
2395         Bone    *child;
2396
2397         bone->parent= newdataadr(fd, bone->parent);
2398         bone->prop= newdataadr(fd, bone->prop);
2399         if(bone->prop)
2400                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2401                 
2402         bone->flag &= ~BONE_DRAW_ACTIVE;
2403
2404         link_list(fd, &bone->childbase);
2405
2406         for(child=bone->childbase.first; child; child=child->next)
2407                 direct_link_bones(fd, child);
2408 }
2409
2410 static void direct_link_armature(FileData *fd, bArmature *arm)
2411 {
2412         Bone    *bone;
2413
2414         link_list(fd, &arm->bonebase);
2415         arm->edbo= NULL;
2416         arm->sketch = NULL;
2417         
2418         arm->adt= newdataadr(fd, arm->adt);
2419         direct_link_animdata(fd, arm->adt);
2420         
2421         bone=arm->bonebase.first;
2422         while (bone) {
2423                 direct_link_bones(fd, bone);
2424                 bone=bone->next;
2425         }
2426
2427         arm->act_bone= newdataadr(fd, arm->act_bone);
2428         arm->act_edbone= NULL;
2429 }
2430
2431 /* ************ READ CAMERA ***************** */
2432
2433 static void lib_link_camera(FileData *fd, Main *main)
2434 {
2435         Camera *ca;
2436
2437         ca= main->camera.first;
2438         while(ca) {
2439                 if(ca->id.flag & LIB_NEEDLINK) {
2440                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2441                         
2442                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2443                         
2444                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2445                         
2446                         ca->id.flag -= LIB_NEEDLINK;
2447                 }
2448                 ca= ca->id.next;
2449         }
2450 }
2451
2452 static void direct_link_camera(FileData *fd, Camera *ca)
2453 {
2454         ca->adt= newdataadr(fd, ca->adt);
2455         direct_link_animdata(fd, ca->adt);
2456 }
2457
2458
2459 /* ************ READ LAMP ***************** */
2460
2461 static void lib_link_lamp(FileData *fd, Main *main)
2462 {
2463         Lamp *la;
2464         MTex *mtex;
2465         int a;
2466
2467         la= main->lamp.first;
2468         while(la) {
2469                 if(la->id.flag & LIB_NEEDLINK) {
2470                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2471                         
2472                         for(a=0; a<MAX_MTEX; a++) {
2473                                 mtex= la->mtex[a];
2474                                 if(mtex) {
2475                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2476                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2477                                 }
2478                         }
2479                         
2480                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2481                         
2482                         la->id.flag -= LIB_NEEDLINK;
2483                 }
2484                 la= la->id.next;
2485         }
2486 }
2487
2488 static void direct_link_lamp(FileData *fd, Lamp *la)
2489 {
2490         int a;
2491         
2492         la->adt= newdataadr(fd, la->adt);
2493         direct_link_animdata(fd, la->adt);
2494
2495         for(a=0; a<MAX_MTEX; a++) {
2496                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2497         }
2498         
2499         la->curfalloff= newdataadr(fd, la->curfalloff);
2500         if(la->curfalloff)
2501                 direct_link_curvemapping(fd, la->curfalloff);
2502         
2503         la->preview = direct_link_preview_image(fd, la->preview);
2504 }
2505
2506 /* ************ READ keys ***************** */
2507
2508 static void lib_link_key(FileData *fd, Main *main)
2509 {
2510         Key *key;
2511
2512         key= main->key.first;
2513         while(key) {
2514                 if(key->id.flag & LIB_NEEDLINK) {
2515                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2516                         
2517                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2518                         key->from= newlibadr(fd, key->id.lib, key->from);
2519
2520                         key->id.flag -= LIB_NEEDLINK;
2521                 }
2522                 key= key->id.next;
2523         }
2524 }
2525
2526 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2527 {
2528         int elemsize, a, b;
2529         char *data, *poin, *cp;
2530
2531         elemsize= key->elemsize;
2532         data= kb->data;
2533
2534         for(a=0; a<kb->totelem; a++) {
2535
2536                 cp= key->elemstr;
2537                 poin= data;
2538
2539                 while( cp[0] ) {        /* cp[0]==amount */
2540
2541                         switch(cp[1]) {         /* cp[1]= type */
2542                         case IPO_FLOAT:
2543                         case IPO_BPOINT:
2544                         case IPO_BEZTRIPLE:
2545                                 b= cp[0];
2546                                 while(b--) {
2547                                         SWITCH_INT((*poin));
2548                                         poin+= 4;
2549                                 }
2550                                 break;
2551                         }
2552
2553                         cp+= 2;
2554
2555                 }
2556                 data+= elemsize;
2557         }
2558 }
2559
2560 static void direct_link_key(FileData *fd, Key *key)
2561 {
2562         KeyBlock *kb;
2563
2564         link_list(fd, &(key->block));
2565
2566         key->adt= newdataadr(fd, key->adt);
2567         direct_link_animdata(fd, key->adt);
2568         
2569         key->refkey= newdataadr(fd, key->refkey);
2570
2571         kb= key->block.first;
2572         while(kb) {
2573
2574                 kb->data= newdataadr(fd, kb->data);
2575                 
2576                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2577                         switch_endian_keyblock(key, kb);
2578
2579                 kb= kb->next;
2580         }
2581 }
2582
2583 /* ************ READ mball ***************** */
2584
2585 static void lib_link_mball(FileData *fd, Main *main)
2586 {
2587         MetaBall *mb;
2588         int a;
2589
2590         mb= main->mball.first;
2591         while(mb) {
2592                 if(mb->id.flag & LIB_NEEDLINK) {
2593                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2594                         
2595                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2596
2597                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2598
2599                         mb->id.flag -= LIB_NEEDLINK;
2600                 }
2601                 mb= mb->id.next;
2602         }
2603 }
2604
2605 static void direct_link_mball(FileData *fd, MetaBall *mb)
2606 {
2607         mb->adt= newdataadr(fd, mb->adt);
2608         direct_link_animdata(fd, mb->adt);
2609         
2610         mb->mat= newdataadr(fd, mb->mat);
2611         test_pointer_array(fd, (void **)&mb->mat);
2612
2613         link_list(fd, &(mb->elems));
2614
2615         mb->disp.first= mb->disp.last= NULL;
2616         mb->editelems= NULL;
2617         mb->bb= NULL;
2618 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
2619         mb->lastelem= NULL;
2620 }
2621
2622 /* ************ READ WORLD ***************** */
2623
2624 static void lib_link_world(FileData *fd, Main *main)
2625 {
2626         World *wrld;
2627         MTex *mtex;
2628         int a;
2629
2630         wrld= main->world.first;
2631         while(wrld) {
2632                 if(wrld->id.flag & LIB_NEEDLINK) {
2633                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2634                         
2635                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2636                         
2637                         for(a=0; a<MAX_MTEX; a++) {
2638                                 mtex= wrld->mtex[a];
2639                                 if(mtex) {
2640                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2641                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2642                                 }
2643                         }
2644                         
2645                         wrld->id.flag -= LIB_NEEDLINK;
2646                 }
2647                 wrld= wrld->id.next;
2648         }
2649 }
2650
2651 static void direct_link_world(FileData *fd, World *wrld)
2652 {
2653         int a;
2654
2655         wrld->adt= newdataadr(fd, wrld->adt);
2656         direct_link_animdata(fd, wrld->adt);
2657
2658         for(a=0; a<MAX_MTEX; a++) {
2659                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2660         }
2661         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2662 }
2663
2664
2665 /* ************ READ VFONT ***************** */
2666
2667 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
2668 {
2669         VFont *vf;
2670
2671         vf= main->vfont.first;
2672         while(vf) {
2673                 if(vf->id.flag & LIB_NEEDLINK) {
2674                         vf->id.flag -= LIB_NEEDLINK;
2675                 }
2676                 vf= vf->id.next;
2677         }
2678 }
2679
2680 static void direct_link_vfont(FileData *fd, VFont *vf)
2681 {
2682         vf->data= NULL;
2683         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2684 }
2685
2686 /* ************ READ TEXT ****************** */
2687
2688 static void lib_link_text(FileData *UNUSED(fd), Main *main)
2689 {
2690         Text *text;
2691
2692         text= main->text.first;
2693         while(text) {
2694                 if(text->id.flag & LIB_NEEDLINK) {
2695                         text->id.flag -= LIB_NEEDLINK;
2696                 }
2697                 text= text->id.next;
2698         }
2699 }
2700
2701 static void direct_link_text(FileData *fd, Text *text)
2702 {
2703         TextLine *ln;
2704
2705         text->name= newdataadr(fd, text->name);
2706
2707         text->undo_pos= -1;
2708         text->undo_len= TXT_INIT_UNDO;
2709         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2710
2711         text->compiled= NULL;
2712
2713 /*
2714         if(text->flags & TXT_ISEXT) {
2715                 reopen_text(text);
2716         } else {
2717 */
2718
2719         link_list(fd, &text->lines);
2720         link_list(fd, &text->markers);
2721
2722         text->curl= newdataadr(fd, text->curl);
2723         text->sell= newdataadr(fd, text->sell);
2724
2725         ln= text->lines.first;
2726         while(ln) {
2727                 ln->line= newdataadr(fd, ln->line);
2728                 ln->format= NULL;
2729                 
2730                 if (ln->len != (int) strlen(ln->line)) {
2731                         printf("Error loading text, line lengths differ\n");
2732                         ln->len = strlen(ln->line);
2733                 }
2734
2735                 ln= ln->next;
2736         }
2737
2738         text->flags = (text->flags) & ~TXT_ISEXT;
2739
2740         text->id.us= 1;
2741 }
2742
2743 /* ************ READ IMAGE ***************** */
2744
2745 static void lib_link_image(FileData *fd, Main *main)
2746 {
2747         Image *ima;
2748
2749         ima= main->image.first;
2750         while (ima) {
2751                 if(ima->id.flag & LIB_NEEDLINK) {
2752                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2753
2754                         ima->id.flag -= LIB_NEEDLINK;
2755                 }
2756                 ima= ima->id.next;
2757         }
2758 }
2759
2760 static void link_ibuf_list(FileData *fd, ListBase *lb)
2761 {
2762         Link *ln, *prev;
2763         
2764         if(lb->first==NULL) return;
2765         
2766         lb->first= newimaadr(fd, lb->first);
2767         ln= lb->first;
2768         prev= NULL;
2769         while(ln) {
2770                 ln->next= newimaadr(fd, ln->next);
2771                 ln->prev= prev;
2772                 prev= ln;
2773                 ln= ln->next;
2774         }
2775         lb->last= prev;
2776 }
2777
2778 static void direct_link_image(FileData *fd, Image *ima)
2779 {
2780         /* for undo system, pointers could be restored */
2781         if(fd->imamap)
2782                 link_ibuf_list(fd, &ima->ibufs);
2783         else
2784                 ima->ibufs.first= ima->ibufs.last= NULL;
2785         
2786         /* if not restored, we keep the binded opengl index */
2787         if(ima->ibufs.first==NULL) {
2788                 ima->bindcode= 0;
2789                 ima->gputexture= NULL;
2790         }
2791         
2792         ima->anim= NULL;
2793         ima->rr= NULL;
2794         ima->repbind= NULL;
2795         
2796         /* undo system, try to restore render buffers */
2797         if(fd->imamap) {
2798                 int a;
2799                 
2800                 for(a=0; a<IMA_MAX_RENDER_SLOT; a++)
2801                         ima->renders[a]= newimaadr(fd, ima->renders[a]);
2802         }
2803         else {
2804                 memset(ima->renders, 0, sizeof(ima->renders));
2805                 ima->last_render_slot= ima->render_slot;
2806         }
2807         
2808         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2809         ima->preview = direct_link_preview_image(fd, ima->preview);
2810         ima->ok= 1;
2811 }
2812
2813
2814 /* ************ READ CURVE ***************** */
2815
2816 static void lib_link_curve(FileData *fd, Main *main)
2817 {
2818         Curve *cu;
2819         int a;
2820
2821         cu= main->curve.first;
2822         while(cu) {
2823                 if(cu->id.flag & LIB_NEEDLINK) {
2824                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2825
2826                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2827
2828                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2829                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2830                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2831                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2832                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2833                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2834                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2835
2836                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2837                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2838
2839                         cu->id.flag -= LIB_NEEDLINK;
2840                 }
2841                 cu= cu->id.next;
2842         }
2843 }
2844
2845
2846 static void switch_endian_knots(Nurb *nu)
2847 {
2848         int len;
2849
2850         if(nu->knotsu) {
2851                 len= KNOTSU(nu);
2852                 while(len--) {
2853                         SWITCH_INT(nu->knotsu[len]);
2854                 }
2855         }
2856         if(nu->knotsv) {
2857                 len= KNOTSV(nu);
2858                 while(len--) {
2859                         SWITCH_INT(nu->knotsv[len]);
2860                 }
2861         }
2862 }
2863
2864 static void direct_link_curve(FileData *fd, Curve *cu)
2865 {
2866         Nurb *nu;
2867         TextBox *tb;
2868         
2869         cu->adt= newdataadr(fd, cu->adt);
2870         direct_link_animdata(fd, cu->adt);
2871         
2872         cu->mat= newdataadr(fd, cu->mat);
2873         test_pointer_array(fd, (void **)&cu->mat);
2874         cu->str= newdataadr(fd, cu->str);
2875         cu->strinfo= newdataadr(fd, cu->strinfo);       
2876         cu->tb= newdataadr(fd, cu->tb);
2877
2878         if(cu->vfont == NULL) link_list(fd, &(cu->nurb));
2879         else {
2880                 cu->nurb.first=cu->nurb.last= NULL;
2881
2882                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2883                 if (cu->tb) {
2884                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2885                         MEM_freeN(cu->tb);
2886                         cu->tb= tb;                     
2887                 } else {
2888                         cu->totbox = 1;
2889                         cu->actbox = 1;
2890                         cu->tb = tb;
2891                         cu->tb[0].w = cu->linewidth;
2892                 }               
2893                 if (cu->wordspace == 0.0f) cu->wordspace = 1.0f;
2894         }
2895
2896         cu->bev.first=cu->bev.last= NULL;
2897         cu->disp.first=cu->disp.last= NULL;
2898         cu->editnurb= NULL;
2899         cu->lastsel= NULL;
2900         cu->path= NULL;
2901         cu->editfont= NULL;
2902         
2903         nu= cu->nurb.first;
2904         while(nu) {
2905                 nu->bezt= newdataadr(fd, nu->bezt);
2906                 nu->bp= newdataadr(fd, nu->bp);
2907                 nu->knotsu= newdataadr(fd, nu->knotsu);
2908                 nu->knotsv= newdataadr(fd, nu->knotsv);
2909                 if (cu->vfont == NULL) nu->charidx= nu->mat_nr;
2910
2911                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2912                         switch_endian_knots(nu);
2913                 }
2914
2915                 nu= nu->next;
2916         }
2917         cu->bb= NULL;
2918 }
2919
2920 /* ************ READ TEX ***************** */
2921
2922 static void lib_link_texture(FileData *fd, Main *main)
2923 {
2924         Tex *tex;
2925
2926         tex= main->tex.first;
2927         while(tex) {
2928                 if(tex->id.flag & LIB_NEEDLINK) {
2929                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2930
2931                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2932                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2933                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2934                         if(tex->pd)
2935                                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
2936                         if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
2937
2938                         if(tex->nodetree)
2939                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2940                         
2941                         tex->id.flag -= LIB_NEEDLINK;
2942                 }
2943                 tex= tex->id.next;
2944         }
2945 }
2946
2947 static void direct_link_texture(FileData *fd, Tex *tex)
2948 {
2949         tex->adt= newdataadr(fd, tex->adt);
2950         direct_link_animdata(fd, tex->adt);
2951         
2952         tex->plugin= newdataadr(fd, tex->plugin);
2953         if(tex->plugin) {
2954                 tex->plugin->handle= NULL;
2955                 open_plugin_tex(tex->plugin);
2956                 /* initialize data for this instance, if an initialization
2957                  * function exists.
2958                  */
2959                 if (tex->plugin->instance_init)
2960                         tex->plugin->instance_init((void *) tex->plugin->data);
2961         }
2962         tex->coba= newdataadr(fd, tex->coba);
2963         tex->env= newdataadr(fd, tex->env);
2964         if(tex->env) {
2965                 tex->env->ima= NULL;
2966                 memset(tex->env->cube, 0, 6*sizeof(void *));
2967                 tex->env->ok= 0;
2968         }
2969         tex->pd= newdataadr(fd, tex->pd);
2970         if(tex->pd) {
2971                 tex->pd->point_tree = NULL;
2972                 tex->pd->coba= newdataadr(fd, tex->pd->coba);
2973                 tex->pd->falloff_curve= newdataadr(fd, tex->pd->falloff_curve);
2974                 if(tex->pd->falloff_curve) {
2975                         direct_link_curvemapping(fd, tex->pd->falloff_curve);
2976                 }
2977         }
2978         
2979         tex->vd= newdataadr(fd, tex->vd);
2980         if(tex->vd) {
2981                 tex->vd->dataset = NULL;
2982                 tex->vd->ok = 0;
2983         }
2984         
2985         tex->nodetree= newdataadr(fd, tex->nodetree);
2986         if(tex->nodetree)
2987                 direct_link_nodetree(fd, tex->nodetree);
2988         
2989         tex->preview = direct_link_preview_image(fd, tex->preview);
2990
2991         tex->iuser.ok= 1;
2992 }
2993
2994
2995
2996 /* ************ READ MATERIAL ***************** */
2997
2998 static void lib_link_material(FileData *fd, Main *main)
2999 {
3000         Material *ma;
3001         MTex *mtex;
3002         int a;
3003
3004         ma= main->mat.first;
3005         while(ma) {
3006                 if(ma->id.flag & LIB_NEEDLINK) {
3007                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
3008
3009                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3010                         of library blocks that implement this.*/
3011                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3012
3013                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
3014                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
3015                         
3016                         for(a=0; a<MAX_MTEX; a++) {
3017                                 mtex= ma->mtex[a];
3018                                 if(mtex) {
3019                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
3020                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
3021                                 }
3022                         }
3023                         
3024                         if(ma->nodetree)
3025                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
3026                         
3027                         ma->id.flag -= LIB_NEEDLINK;
3028                 }
3029                 ma= ma->id.next;
3030         }
3031 }
3032
3033 static void direct_link_material(FileData *fd, Material *ma)
3034 {
3035         int a;
3036
3037         ma->adt= newdataadr(fd, ma->adt);
3038         direct_link_animdata(fd, ma->adt);
3039         
3040         for(a=0; a<MAX_MTEX; a++) {
3041                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
3042         }
3043
3044         ma->ramp_col= newdataadr(fd, ma->ramp_col);
3045         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
3046         
3047         ma->nodetree= newdataadr(fd, ma->nodetree);
3048         if(ma->nodetree)
3049                 direct_link_nodetree(fd, ma->nodetree);
3050
3051         ma->preview = direct_link_preview_image(fd, ma->preview);
3052         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
3053 }
3054
3055 /* ************ READ PARTICLE SETTINGS ***************** */
3056 /* update this also to writefile.c */
3057 static const char *ptcache_data_struct[] = {
3058         "", // BPHYS_DATA_INDEX
3059         "", // BPHYS_DATA_LOCATION
3060         "", // BPHYS_DATA_VELOCITY
3061         "", // BPHYS_DATA_ROTATION
3062         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
3063         "", // BPHYS_DATA_SIZE:
3064         "", // BPHYS_DATA_TIMES:        
3065         "BoidData" // case BPHYS_DATA_BOIDS:
3066 };
3067 static void direct_link_pointcache(FileData *fd, PointCache *cache)
3068 {
3069         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
3070                 PTCacheMem *pm;
3071                 PTCacheExtra *extra;
3072                 int i;
3073
3074                 link_list(fd, &cache->mem_cache);
3075
3076                 pm = cache->mem_cache.first;
3077
3078                 for(; pm; pm=pm->next) {
3079                         for(i=0; i<BPHYS_TOT_DATA; i++) {
3080                                 pm->data[i] = newdataadr(fd, pm->data[i]);
3081                                 
3082                                 /* the cache saves non-struct data without DNA */
3083                                 if(pm->data[i] && strcmp(ptcache_data_struct[i], "")==0 && (fd->flags & FD_FLAGS_SWITCH_ENDIAN)) {
3084                                         int j, tot= (BKE_ptcache_data_size (i) * pm->totpoint)/4; /* data_size returns bytes */
3085                                         int *poin= pm->data[i];
3086                                         
3087                                         for(j= 0; j<tot; j++)
3088                                                 SWITCH_INT(poin[j]);
3089                                 }
3090                         }
3091                         
3092                         link_list(fd, &pm->extradata);
3093
3094                         for(extra=pm->extradata.first; extra; extra=extra->next)
3095                                 extra->data = newdataadr(fd, extra->data);
3096                 }
3097         }
3098         else
3099                 cache->mem_cache.first = cache->mem_cache.last = NULL;
3100
3101         cache->flag &= ~PTCACHE_SIMULATION_VALID;
3102         cache->simframe= 0;
3103         cache->edit= NULL;
3104         cache->free_edit= NULL;
3105         cache->cached_frames= NULL;
3106 }
3107
3108 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache, int force_disk)
3109 {
3110         if(ptcaches->first) {
3111                 PointCache *cache= NULL;
3112                 link_list(fd, ptcaches);
3113                 for(cache=ptcaches->first; cache; cache=cache->next) {
3114                         direct_link_pointcache(fd, cache);
3115                         if(force_disk) {
3116                                 cache->flag |= PTCACHE_DISK_CACHE;
3117                                 cache->step = 1;
3118                         }
3119                 }
3120
3121                 *ocache = newdataadr(fd, *ocache);
3122         }
3123         else if(*ocache) {
3124                 /* old "single" caches need to be linked too */
3125                 *ocache = newdataadr(fd, *ocache);
3126                 direct_link_pointcache(fd, *ocache);
3127                 if(force_disk) {
3128                         (*ocache)->flag |= PTCACHE_DISK_CACHE;
3129                         (*ocache)->step = 1;
3130                 }
3131
3132                 ptcaches->first = ptcaches->last = *ocache;
3133         }
3134 }
3135
3136 static void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
3137 {
3138         if(pd && pd->tex)
3139                 pd->tex=newlibadr_us(fd, id->lib, pd->tex);
3140 }
3141
3142 static void lib_link_particlesettings(FileData *fd, Main *main)
3143 {
3144         ParticleSettings *part;
3145         ParticleDupliWeight *dw;
3146         MTex *mtex;
3147         int a;
3148
3149         part= main->particle.first;
3150         while(part) {
3151                 if(part->id.flag & LIB_NEEDLINK) {
3152                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
3153                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
3154                         
3155                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
3156                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
3157                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
3158                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
3159
3160                         lib_link_partdeflect(fd, &part->id, part->pd);
3161                         lib_link_partdeflect(fd, &part->id, part->pd2);
3162
3163                         if(part->effector_weights)
3164                                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
3165
3166                         if(part->dupliweights.first && part->dup_group) {
3167                                 int index_ok = 0;
3168                                 /* check for old files without indices (all indexes 0) */
3169                                 dw = part->dupliweights.first;
3170                                 if(part->dupliweights.first == part->dupliweights.last) {
3171                                         /* special case for only one object in the group */
3172                                         index_ok = 1;
3173                                 }
3174                                 else { 
3175                                         for(; dw; dw=dw->next) {
3176                                                 if(dw->index > 0) {
3177                                                         index_ok = 1;
3178                                                         break;
3179                                                 }
3180                                         }
3181                                 }
3182
3183                                 if(index_ok) {
3184                                         /* if we have indexes, let's use them */
3185                                         dw = part->dupliweights.first;
3186                                         for(; dw; dw=dw->next) {
3187                                                 GroupObject *go = (GroupObject *)BLI_findlink(&part->dup_group->gobject, dw->index);
3188                                                 dw->ob = go ? go->ob : NULL;
3189                                         }
3190                                 }
3191                                 else {
3192                                         /* otherwise try to get objects from own library (won't work on library linked groups) */
3193                                         for(; dw; dw=dw->next)
3194                                                 dw->ob = newlibadr(fd, part->id.lib, dw->ob);
3195                                 }
3196                         }
3197                         else {
3198                                 part->dupliweights.first = part->dupliweights.last = NULL;
3199                         }
3200
3201                         if(part->boids) {
3202                                 BoidState *state = part->boids->states.first;
3203                                 BoidRule *rule;
3204                                 for(; state; state=state->next) {
3205                                         rule = state->rules.first;
3206                                 for(; rule; rule=rule->next)
3207                                         switch(rule->type) {
3208                                                 case eBoidRuleType_Goal:
3209                                                 case eBoidRuleType_Avoid:
3210                                                 {
3211                                                         BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
3212                                                         brga->ob = newlibadr(fd, part->id.lib, brga->ob);
3213                                                         break;
3214                                                 }
3215                                                 case eBoidRuleType_FollowLeader:
3216                                                 {
3217                                                         BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
3218                                                         brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
3219                                                         break;
3220                                                 }
3221                                         }
3222                                 }
3223                         }
3224                         
3225                         for(a=0; a<MAX_MTEX; a++) {
3226                                 mtex= part->mtex[a];
3227                                 if(mtex) {
3228                                         mtex->tex = newlibadr_us(fd, part->id.lib, mtex->tex);
3229                                         mtex->object = newlibadr(fd, part->id.lib, mtex->object);
3230                                 }
3231                         }
3232
3233                         part->id.flag -= LIB_NEEDLINK;
3234                 }
3235                 part= part->id.next;
3236         }
3237 }
3238
3239 static void direct_link_partdeflect(PartDeflect *pd)
3240 {
3241         if(pd) pd->rng=NULL;
3242 }
3243
3244 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
3245 {
3246         int a;
3247         part->adt= newdataadr(fd, part->adt);
3248         part->pd= newdataadr(fd, part->pd);
3249         part->pd2= newdataadr(fd, part->pd2);
3250
3251         direct_link_animdata(fd, part->adt);
3252         direct_link_partdeflect(part->pd);
3253         direct_link_partdeflect(part->pd2);
3254
3255         part->effector_weights = newdataadr(fd, part->effector_weights);
3256         if(!part->effector_weights)
3257                 part->effector_weights = BKE_add_effector_weights(part->eff_group);
3258