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