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