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