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