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