untested fixes for vgroups
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include "zlib.h"
36
37 #ifdef WIN32
38 #include "winsock2.h"
39 #include "BLI_winstuff.h"
40 #endif
41
42 #include <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 = 0;
731         BHead *bhead = 0;
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
1037                 MEM_freeN(fd);
1038         }
1039 }
1040
1041 /* ************ DIV ****************** */
1042
1043 int BLO_has_bfile_extension(char *str)
1044 {
1045         return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend")||BLI_testextensie(str, ".blend.gz"));
1046 }
1047
1048 /* ************** OLD POINTERS ******************* */
1049
1050 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
1051 {
1052         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1053 }
1054
1055 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
1056 {
1057         return oldnewmap_lookup_and_inc(fd->globmap, adr);
1058 }
1059
1060 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
1061 {
1062         if(fd->imamap && adr)
1063                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
1064         return NULL;
1065 }
1066
1067
1068 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
1069 {
1070         return oldnewmap_liblookup(fd->libmap, adr, lib);
1071 }
1072
1073 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1074 {
1075         ID *id= newlibadr(fd, lib, adr);
1076
1077         if(id)
1078                 id->us++;
1079
1080         return id;
1081 }
1082
1083 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
1084 {
1085         int i;
1086         
1087         for (i=0; i<fd->libmap->nentries; i++) {
1088                 OldNew *entry= &fd->libmap->entries[i];
1089                 
1090                 if (old==entry->newp && entry->nr==ID_ID) {
1091                         entry->newp= new;
1092                         if(new) entry->nr= GS( ((ID *)new)->name );
1093                         break;
1094                 }
1095         }
1096 }
1097
1098 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1099 {
1100         Main *mainptr;
1101         
1102         for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
1103                 FileData *fd;
1104                 
1105                 if(mainptr->curlib) fd= mainptr->curlib->filedata;
1106                 else fd= basefd;
1107                 
1108                 if(fd) {
1109                         change_idid_adr_fd(fd, old, new);
1110                 }
1111         }
1112 }
1113
1114 /* assumed; G.main still exists */
1115 void blo_make_image_pointer_map(FileData *fd)
1116 {
1117         Image *ima= G.main->image.first;
1118         Scene *sce= G.main->scene.first;
1119         
1120         fd->imamap= oldnewmap_new();
1121         
1122         for(;ima; ima= ima->id.next) {
1123                 Link *ibuf= ima->ibufs.first;
1124                 for(; ibuf; ibuf= ibuf->next) 
1125                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
1126         }
1127         for(; sce; sce= sce->id.next) {
1128                 if(sce->nodetree) {
1129                         bNode *node;
1130                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1131                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
1132                 }
1133         }
1134 }
1135
1136 /* set G.main image ibufs to zero if it has been restored */
1137 /* this works because freeing G.main only happens after this call */
1138 void blo_end_image_pointer_map(FileData *fd)
1139 {
1140         OldNew *entry= fd->imamap->entries;
1141         Image *ima= G.main->image.first;
1142         Scene *sce= G.main->scene.first;
1143         int i;
1144         
1145         /* used entries were restored, so we put them to zero */
1146         for (i=0; i<fd->imamap->nentries; i++, entry++) {
1147                 if (entry->nr>0)
1148                         entry->newp= NULL;
1149         }
1150         
1151         for(;ima; ima= ima->id.next) {
1152                 Link *ibuf, *next;
1153                 
1154                 /* this mirrors direct_link_image */
1155                 for(ibuf= ima->ibufs.first; ibuf; ibuf= next) {
1156                         next= ibuf->next;
1157                         if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
1158                                 BLI_remlink(&ima->ibufs, ibuf);
1159                                 ima->bindcode= 0;
1160                         }
1161                 }
1162         }
1163         for(; sce; sce= sce->id.next) {
1164                 if(sce->nodetree) {
1165                         bNode *node;
1166                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1167                                 node->preview= newimaadr(fd, node->preview);
1168                 }
1169         }
1170 }
1171
1172 /* undo file support: add all library pointers in lookup */
1173 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
1174 {
1175         Main *ptr= mainlist->first;
1176         ListBase *lbarray[MAX_LIBARRAY];
1177         
1178         for(ptr= ptr->next; ptr; ptr= ptr->next) {
1179                 int i= set_listbasepointers(ptr, lbarray);
1180                 while(i--) {
1181                         ID *id;
1182                         for(id= lbarray[i]->first; id; id= id->next)
1183                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1184                 }
1185         }
1186 }
1187                 
1188
1189 /* ********** END OLD POINTERS ****************** */
1190 /* ********** READ FILE ****************** */
1191
1192 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1193 {
1194         int blocksize, nblocks;
1195         char *data;
1196
1197         data= (char *)(bhead+1);
1198         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1199
1200         nblocks= bhead->nr;
1201         while(nblocks--) {
1202                 dna_switch_endian_struct(filesdna, bhead->SDNAnr, data);
1203
1204                 data+= blocksize;
1205         }
1206 }
1207
1208 static void *read_struct(FileData *fd, BHead *bh, char *blockname)
1209 {
1210         void *temp= NULL;
1211
1212         if (bh->len) {
1213                 /* switch is based on file dna */
1214                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1215                         switch_endian_structs(fd->filesdna, bh);
1216
1217                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1218                         if(fd->compflags[bh->SDNAnr]==2) {
1219                                 temp= dna_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1220                         } else {
1221                                 temp= MEM_mallocN(bh->len, blockname);
1222                                 memcpy(temp, (bh+1), bh->len);
1223                         }
1224                 }
1225         }
1226
1227         return temp;
1228 }
1229
1230 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1231 {
1232         Link *ln, *prev;
1233
1234         if(lb->first==NULL) return;
1235
1236         lb->first= newdataadr(fd, lb->first);
1237         ln= lb->first;
1238         prev= NULL;
1239         while(ln) {
1240                 ln->next= newdataadr(fd, ln->next);
1241                 ln->prev= prev;
1242                 prev= ln;
1243                 ln= ln->next;
1244         }
1245         lb->last= prev;
1246 }
1247
1248 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1249 {
1250         Link *ln, *prev;
1251         void *poin;
1252
1253         if(lb->first==0) return;
1254         poin= newdataadr(fd, lb->first);
1255         if(lb->first) {
1256                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1257         }
1258         lb->first= poin;
1259
1260         ln= lb->first;
1261         prev= 0;
1262         while(ln) {
1263                 poin= newdataadr(fd, ln->next);
1264                 if(ln->next) {
1265                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1266                 }
1267                 ln->next= poin;
1268                 ln->prev= prev;
1269                 prev= ln;
1270                 ln= ln->next;
1271         }
1272         lb->last= prev;
1273 }
1274
1275 static void test_pointer_array(FileData *fd, void **mat)
1276 {
1277 #if defined(WIN32) && !defined(FREE_WINDOWS)
1278         __int64 *lpoin, *lmat;
1279 #else
1280         long long *lpoin, *lmat;
1281 #endif
1282         int len, *ipoin, *imat;
1283
1284                 /* manually convert the pointer array in
1285                  * the old dna format to a pointer array in
1286                  * the new dna format.
1287                  */
1288         if(*mat) {
1289                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1290
1291                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1292                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
1293                         lpoin= *mat;
1294
1295                         while(len-- > 0) {
1296                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1297                                         SWITCH_LONGINT(*lpoin);
1298                                 *ipoin= (int) ((*lpoin) >> 3);
1299                                 ipoin++;
1300                                 lpoin++;
1301                         }
1302                         MEM_freeN(*mat);
1303                         *mat= imat;
1304                 }
1305
1306                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1307                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
1308                         ipoin= *mat;
1309
1310                         while(len-- > 0) {
1311                                 *lpoin= *ipoin;
1312                                 ipoin++;
1313                                 lpoin++;
1314                         }
1315                         MEM_freeN(*mat);
1316                         *mat= lmat;
1317                 }
1318         }
1319 }
1320
1321 /* ************ READ ID Properties *************** */
1322
1323 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd);
1324 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd);
1325
1326 void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
1327 {
1328         int i;
1329
1330         /*since we didn't save the extra buffer, set totallen to len.*/
1331         prop->totallen = prop->len;
1332         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1333
1334         if (switch_endian) {
1335                 for (i=0; i<prop->len; i++) {
1336                         SWITCH_INT(((int*)prop->data.pointer)[i]);
1337                 }
1338         }
1339 }
1340
1341 void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
1342 {
1343         /*since we didn't save the extra string buffer, set totallen to len.*/
1344         prop->totallen = prop->len;
1345         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1346 }
1347
1348 void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
1349 {
1350         ListBase *lb = &prop->data.group;
1351         IDProperty *loop;
1352
1353         link_list(fd, lb);
1354
1355         /*Link child id properties now*/
1356         for (loop=prop->data.group.first; loop; loop=loop->next) {
1357                 IDP_DirectLinkProperty(loop, switch_endian, fd);
1358         }
1359 }
1360
1361 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd)
1362 {
1363         switch (prop->type) {
1364                 case IDP_GROUP:
1365                         IDP_DirectLinkGroup(prop, switch_endian, fd);
1366                         break;
1367                 case IDP_STRING:
1368                         IDP_DirectLinkString(prop, switch_endian, fd);
1369                         break;
1370                 case IDP_ARRAY:
1371                         IDP_DirectLinkArray(prop, switch_endian, fd);
1372                         break;
1373         }
1374 }
1375
1376 /*stub function*/
1377 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd)
1378 {
1379 }
1380
1381 /* ************ READ Brush *************** */
1382 /* library brush linking after fileread */
1383 static void lib_link_brush(FileData *fd, Main *main)
1384 {
1385         Brush *brush;
1386         MTex *mtex;
1387         int a;
1388         
1389         /* only link ID pointers */
1390         for(brush= main->brush.first; brush; brush= brush->id.next) {
1391                 if(brush->id.flag & LIB_NEEDLINK) {
1392                         brush->id.flag -= LIB_NEEDLINK;
1393
1394                         for(a=0; a<MAX_MTEX; a++) {
1395                                 mtex= brush->mtex[a];
1396                                 if(mtex)
1397                                         mtex->tex= newlibadr_us(fd, brush->id.lib, mtex->tex);
1398                         }
1399                 }
1400         }
1401 }
1402
1403 static void direct_link_brush(FileData *fd, Brush *brush)
1404 {
1405         /* brush itself has been read */
1406         int a;
1407
1408         for(a=0; a<MAX_MTEX; a++)
1409                 brush->mtex[a]= newdataadr(fd, brush->mtex[a]);
1410 }
1411
1412 /* ************ READ CurveMapping *************** */
1413
1414 /* cuma itself has been read! */
1415 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
1416 {
1417         int a;
1418         
1419         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
1420         cumap->flag &= ~CUMA_PREMULLED;
1421         
1422         for(a=0; a<CM_TOT; a++) {
1423                 cumap->cm[a].curve= newdataadr(fd, cumap->cm[a].curve);
1424                 cumap->cm[a].table= NULL;
1425         }
1426 }
1427
1428 /* ************ READ NODE TREE *************** */
1429
1430 /* singe node tree (also used for material/scene trees), ntree is not NULL */
1431 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
1432 {
1433         bNode *node;
1434         
1435         for(node= ntree->nodes.first; node; node= node->next)
1436                 node->id= newlibadr_us(fd, id->lib, node->id);
1437 }
1438
1439 /* library ntree linking after fileread */
1440 static void lib_link_nodetree(FileData *fd, Main *main)
1441 {
1442         bNodeTree *ntree;
1443         
1444         /* only link ID pointers */
1445         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1446                 if(ntree->id.flag & LIB_NEEDLINK) {
1447                         ntree->id.flag -= LIB_NEEDLINK;
1448                         lib_link_ntree(fd, &ntree->id, ntree);
1449                 }
1450         }
1451 }
1452
1453 /* verify types for nodes and groups, all data has to be read */
1454 static void lib_verify_nodetree(Main *main)
1455 {
1456         Scene *sce;
1457         Material *ma;
1458         bNodeTree *ntree;
1459         
1460         /* now create the own typeinfo structs an verify nodes */
1461         /* here we still assume no groups in groups */
1462         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1463                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
1464                 ntreeMakeOwnType(ntree);        /* for group usage */
1465         }
1466         
1467         /* now verify all types in material trees, groups are set OK now */
1468         for(ma= main->mat.first; ma; ma= ma->id.next) {
1469                 if(ma->nodetree)
1470                         ntreeVerifyTypes(ma->nodetree);
1471         }
1472         /* and scene trees */
1473         for(sce= main->scene.first; sce; sce= sce->id.next) {
1474                 if(sce->nodetree)
1475                         ntreeVerifyTypes(sce->nodetree);
1476         }
1477 }
1478
1479
1480
1481 /* ntree itself has been read! */
1482 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
1483 {
1484         /* note: writing and reading goes in sync, for speed */
1485         bNode *node;
1486         bNodeSocket *sock;
1487         bNodeLink *link;
1488         
1489         ntree->init= 0;         /* to set callbacks and force setting types */
1490         ntree->owntype= NULL;
1491         ntree->timecursor= NULL;
1492         
1493         link_list(fd, &ntree->nodes);
1494         for(node= ntree->nodes.first; node; node= node->next) {
1495                 node->storage= newdataadr(fd, node->storage);
1496                 if(node->storage) {
1497                         
1498                         /* could be handlerized at some point */
1499                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
1500                                 direct_link_curvemapping(fd, node->storage);
1501                         else if(ntree->type==NTREE_COMPOSIT) {
1502                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
1503                                         direct_link_curvemapping(fd, node->storage);
1504                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
1505                                         ((ImageUser *)node->storage)->ok= 1;
1506                         }
1507                 }
1508                 link_list(fd, &node->inputs);
1509                 link_list(fd, &node->outputs);
1510         }
1511         link_list(fd, &ntree->links);
1512         
1513         /* and we connect the rest */
1514         for(node= ntree->nodes.first; node; node= node->next) {
1515                 node->preview= newimaadr(fd, node->preview);
1516                 node->lasty= 0;
1517                 for(sock= node->inputs.first; sock; sock= sock->next)
1518                         sock->link= newdataadr(fd, sock->link);
1519                 for(sock= node->outputs.first; sock; sock= sock->next)
1520                         sock->ns.data= NULL;
1521         }
1522         for(link= ntree->links.first; link; link= link->next) {
1523                 link->fromnode= newdataadr(fd, link->fromnode);
1524                 link->tonode= newdataadr(fd, link->tonode);
1525                 link->fromsock= newdataadr(fd, link->fromsock);
1526                 link->tosock= newdataadr(fd, link->tosock);
1527         }
1528         
1529         /* set selin and selout */
1530         for(node= ntree->nodes.first; node; node= node->next) {
1531                 for(sock= node->inputs.first; sock; sock= sock->next) {
1532                         if(sock->flag & SOCK_SEL) {
1533                                 ntree->selin= sock;
1534                                 break;
1535                         }
1536                 }
1537                 for(sock= node->outputs.first; sock; sock= sock->next) {
1538                         if(sock->flag & SOCK_SEL) {
1539                                 ntree->selout= sock;
1540                                 break;
1541                         }
1542                 }
1543         }
1544         
1545         /* type verification is in lib-link */
1546 }
1547
1548 /* ************ READ PACKEDFILE *************** */
1549
1550 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1551 {
1552         PackedFile *pf= newdataadr(fd, oldpf);
1553
1554         if (pf) {
1555                 pf->data= newdataadr(fd, pf->data);
1556         }
1557
1558         return pf;
1559 }
1560
1561 /* ************ READ IMAGE PREVIEW *************** */
1562
1563 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
1564 {
1565         PreviewImage *prv= newdataadr(fd, old_prv);
1566
1567         if (prv) {
1568                 int i;
1569                 for (i=0; i < PREVIEW_MIPMAPS; ++i) {
1570                         if (prv->rect[i]) {
1571                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
1572                         }
1573                 }
1574         }
1575
1576         return prv;
1577 }
1578
1579 /* ************ READ SCRIPTLINK *************** */
1580
1581 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1582 {
1583         int i;
1584
1585         for(i=0; i<slink->totscript; i++) {
1586                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1587         }
1588 }
1589
1590 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1591 {
1592         slink->scripts= newdataadr(fd, slink->scripts);
1593         test_pointer_array(fd, (void **)&slink->scripts);
1594         
1595         slink->flag= newdataadr(fd, slink->flag);
1596
1597         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1598                 int a;
1599
1600                 for(a=0; a<slink->totscript; a++) {
1601                         SWITCH_SHORT(slink->flag[a]);
1602                 }
1603         }
1604 }
1605
1606 /* ************ READ ARMATURE ***************** */
1607
1608 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1609 {
1610         bActionStrip *strip;
1611         bActionModifier *amod;
1612         
1613         for (strip=striplist->first; strip; strip=strip->next){
1614                 strip->object = newlibadr(fd, id->lib, strip->object);
1615                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1616                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1617                 for(amod= strip->modifiers.first; amod; amod= amod->next)
1618                         amod->ob= newlibadr(fd, id->lib, amod->ob);
1619         }
1620 }
1621
1622 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1623 {
1624         bConstraintChannel *chan;
1625
1626         for (chan=chanbase->first; chan; chan=chan->next){
1627                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1628         }
1629 }
1630
1631 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1632 {
1633         bConstraint *con;
1634
1635         for (con = conlist->first; con; con=con->next) {
1636                 /* patch for error introduced by changing constraints (dunno how) */
1637                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
1638                 if(con->data==NULL) {
1639                         con->type= CONSTRAINT_TYPE_NULL;
1640                 }
1641                 /* own ipo, all constraints have it */
1642                 con->ipo= newlibadr_us(fd, id->lib, con->ipo);
1643                 
1644                 switch (con->type) {
1645                 case CONSTRAINT_TYPE_PYTHON:
1646                         {
1647                                 bPythonConstraint *data= (bPythonConstraint*)con->data;
1648                                 bConstraintTarget *ct;
1649                                 
1650                                 for (ct= data->targets.first; ct; ct= ct->next)
1651                                         ct->tar = newlibadr(fd, id->lib, ct->tar);
1652                                         
1653                                 data->text = newlibadr(fd, id->lib, data->text);
1654                                 //IDP_LibLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1655                         }
1656                         break;
1657                 case CONSTRAINT_TYPE_ACTION:
1658                         {
1659                                 bActionConstraint *data;
1660                                 data= ((bActionConstraint*)con->data);
1661                                 data->tar = newlibadr(fd, id->lib, data->tar);
1662                                 data->act = newlibadr(fd, id->lib, data->act);
1663                         }
1664                         break;
1665                 case CONSTRAINT_TYPE_LOCLIKE:
1666                         {
1667                                 bLocateLikeConstraint *data;
1668                                 data= ((bLocateLikeConstraint*)con->data);
1669                                 data->tar = newlibadr(fd, id->lib, data->tar);
1670                         }
1671                         break;
1672                 case CONSTRAINT_TYPE_ROTLIKE:
1673                         {
1674                                 bRotateLikeConstraint *data;
1675                                 data= ((bRotateLikeConstraint*)con->data);
1676                                 data->tar = newlibadr(fd, id->lib, data->tar);
1677                         }
1678                         break;
1679                 case CONSTRAINT_TYPE_SIZELIKE:
1680                         {
1681                                 bSizeLikeConstraint *data;
1682                                 data= ((bSizeLikeConstraint*)con->data);
1683                                 data->tar = newlibadr(fd, id->lib, data->tar);
1684                         }
1685                         break;
1686                 case CONSTRAINT_TYPE_KINEMATIC:
1687                         {
1688                                 bKinematicConstraint *data;
1689                                 data = ((bKinematicConstraint*)con->data);
1690                                 data->tar = newlibadr(fd, id->lib, data->tar);
1691                                 data->poletar = newlibadr(fd, id->lib, data->poletar);
1692                         }
1693                         break;
1694                 case CONSTRAINT_TYPE_TRACKTO:
1695                         {
1696                                 bTrackToConstraint *data;
1697                                 data = ((bTrackToConstraint*)con->data);
1698                                 data->tar = newlibadr(fd, id->lib, data->tar);
1699                         }
1700                         break;
1701                 case CONSTRAINT_TYPE_MINMAX:
1702                         {
1703                                 bMinMaxConstraint *data;
1704                                 data = ((bMinMaxConstraint*)con->data);
1705                                 data->tar = newlibadr(fd, id->lib, data->tar);
1706                         }
1707                         break;
1708                 case CONSTRAINT_TYPE_LOCKTRACK:
1709                         {
1710                                 bLockTrackConstraint *data;
1711                                 data= ((bLockTrackConstraint*)con->data);
1712                                 data->tar = newlibadr(fd, id->lib, data->tar);
1713                         }
1714                         break;
1715                 case CONSTRAINT_TYPE_FOLLOWPATH:
1716                         {
1717                                 bFollowPathConstraint *data;
1718                                 data= ((bFollowPathConstraint*)con->data);
1719                                 data->tar = newlibadr(fd, id->lib, data->tar);
1720                         }
1721                         break;
1722                 case CONSTRAINT_TYPE_STRETCHTO:
1723                         {
1724                                 bStretchToConstraint *data;
1725                                 data= ((bStretchToConstraint*)con->data);
1726                                 data->tar = newlibadr(fd, id->lib, data->tar);
1727                         }
1728                         break;
1729                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1730                         {
1731                                 bRigidBodyJointConstraint *data;
1732                                 data= ((bRigidBodyJointConstraint*)con->data);
1733                                 data->tar = newlibadr(fd, id->lib, data->tar);
1734                         }
1735                         break;
1736                 case CONSTRAINT_TYPE_CLAMPTO:
1737                         {
1738                                 bClampToConstraint *data;
1739                                 data= ((bClampToConstraint*)con->data);
1740                                 data->tar = newlibadr(fd, id->lib, data->tar);
1741                         }
1742                         break;
1743                 case CONSTRAINT_TYPE_CHILDOF:
1744                         {
1745                                 bChildOfConstraint *data;
1746                                 data= ((bChildOfConstraint*)con->data);
1747                                 data->tar = newlibadr(fd, id->lib, data->tar);
1748                         }
1749                         break;
1750                 case CONSTRAINT_TYPE_TRANSFORM:
1751                         {
1752                                 bTransformConstraint *data;
1753                                 data= ((bTransformConstraint*)con->data);
1754                                 data->tar = newlibadr(fd, id->lib, data->tar);
1755                         }
1756                         break;
1757                 case CONSTRAINT_TYPE_NULL:
1758                         break;
1759                 }
1760         }
1761 }
1762
1763 static void direct_link_constraints(FileData *fd, ListBase *lb)
1764 {
1765         bConstraint *cons;
1766
1767         link_list(fd, lb);
1768         for (cons=lb->first; cons; cons=cons->next) {
1769                 cons->data = newdataadr(fd, cons->data);
1770                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
1771                         bPythonConstraint *data= cons->data;
1772                         link_list(fd, &data->targets);
1773                         data->prop = newdataadr(fd, data->prop);
1774                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1775                 }
1776         }
1777 }
1778
1779 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1780 {
1781         bPoseChannel *pchan;
1782         bArmature *arm= ob->data;
1783         int rebuild;
1784         
1785         if (!pose || !arm)
1786                 return;
1787         
1788         /* always rebuild to match proxy or lib changes */
1789         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
1790
1791         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1792                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1793                 
1794                 /* hurms... loop in a loop, but yah... later... (ton) */
1795                 pchan->bone= get_named_bone(arm, pchan->name);
1796                 
1797                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
1798                 if(pchan->bone==NULL)
1799                         rebuild= 1;
1800                 else if(ob->id.lib==NULL && arm->id.lib) {
1801                         /* local pose selection copied to armature, bit hackish */
1802                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
1803                         pchan->bone->flag |= pchan->selectflag;
1804                 }
1805         }
1806         
1807         if(rebuild) {
1808                 ob->recalc= OB_RECALC;
1809                 pose->flag |= POSE_RECALC;
1810         }
1811 }
1812
1813 static void lib_link_armature(FileData *fd, Main *main)
1814 {
1815         bArmature *arm;
1816
1817         arm= main->armature.first;
1818
1819         while(arm) {
1820                 if(arm->id.flag & LIB_NEEDLINK) {
1821                         arm->id.flag -= LIB_NEEDLINK;
1822                 }
1823                 arm= arm->id.next;
1824         }
1825 }
1826
1827 static void lib_link_action(FileData *fd, Main *main)
1828 {
1829         bAction *act;
1830         bActionChannel *chan;
1831
1832         act= main->action.first;
1833         while(act) {
1834                 if(act->id.flag & LIB_NEEDLINK) {
1835                         act->id.flag -= LIB_NEEDLINK;
1836                         
1837                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1838                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1839                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1840                         }
1841                         
1842                 }
1843                 act= act->id.next;
1844         }
1845 }
1846
1847 static void direct_link_bones(FileData *fd, Bone* bone)
1848 {
1849         Bone    *child;
1850
1851         bone->parent= newdataadr(fd, bone->parent);
1852
1853         link_list(fd, &bone->childbase);
1854
1855         for (child=bone->childbase.first; child; child=child->next) {
1856                 direct_link_bones(fd, child);
1857         }
1858 }
1859
1860
1861 static void direct_link_action(FileData *fd, bAction *act)
1862 {
1863         bActionChannel *achan;
1864         bActionGroup *agrp;
1865
1866         link_list(fd, &act->chanbase);
1867         link_list(fd, &act->groups);
1868         link_list(fd, &act->markers);
1869
1870         for (achan = act->chanbase.first; achan; achan=achan->next) {
1871                 achan->grp= newdataadr(fd, achan->grp);
1872                 
1873                 link_list(fd, &achan->constraintChannels);
1874         }
1875                 
1876         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1877                 if (agrp->channels.first) {
1878                         agrp->channels.first= newdataadr(fd, agrp->channels.first);
1879                         agrp->channels.last= newdataadr(fd, agrp->channels.last);
1880                 }
1881         }
1882 }
1883
1884 static void direct_link_armature(FileData *fd, bArmature *arm)
1885 {
1886         Bone    *bone;
1887
1888         link_list(fd, &arm->bonebase);
1889
1890         bone=arm->bonebase.first;
1891         while (bone) {
1892                 direct_link_bones(fd, bone);
1893                 bone=bone->next;
1894         }
1895 }
1896
1897 /* ************ READ CAMERA ***************** */
1898
1899 static void lib_link_camera(FileData *fd, Main *main)
1900 {
1901         Camera *ca;
1902
1903         ca= main->camera.first;
1904         while(ca) {
1905                 if(ca->id.flag & LIB_NEEDLINK) {
1906
1907                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1908                         
1909                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
1910                         
1911                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1912
1913                         ca->id.flag -= LIB_NEEDLINK;
1914                 }
1915                 ca= ca->id.next;
1916         }
1917 }
1918
1919 static void direct_link_camera(FileData *fd, Camera *ca)
1920 {
1921         direct_link_scriptlink(fd, &ca->scriptlink);
1922 }
1923
1924
1925 /* ************ READ LAMP ***************** */
1926
1927 static void lib_link_lamp(FileData *fd, Main *main)
1928 {
1929         Lamp *la;
1930         MTex *mtex;
1931         int a;
1932
1933         la= main->lamp.first;
1934         while(la) {
1935                 if(la->id.flag & LIB_NEEDLINK) {
1936
1937                         for(a=0; a<MAX_MTEX; a++) {
1938                                 mtex= la->mtex[a];
1939                                 if(mtex) {
1940                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1941                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1942                                 }
1943                         }
1944
1945                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1946
1947                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1948
1949                         la->id.flag -= LIB_NEEDLINK;
1950                 }
1951                 la= la->id.next;
1952         }
1953 }
1954
1955 static void direct_link_lamp(FileData *fd, Lamp *la)
1956 {
1957         int a;
1958
1959         direct_link_scriptlink(fd, &la->scriptlink);
1960
1961         for(a=0; a<MAX_MTEX; a++) {
1962                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1963         }
1964         
1965         la->curfalloff= newdataadr(fd, la->curfalloff);
1966         if(la->curfalloff)
1967                 direct_link_curvemapping(fd, la->curfalloff);
1968         
1969         la->preview = direct_link_preview_image(fd, la->preview);
1970 }
1971
1972 /* ************ READ keys ***************** */
1973
1974 static void lib_link_key(FileData *fd, Main *main)
1975 {
1976         Key *key;
1977
1978         key= main->key.first;
1979         while(key) {
1980                 if(key->id.flag & LIB_NEEDLINK) {
1981
1982                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1983                         key->from= newlibadr(fd, key->id.lib, key->from);
1984
1985                         key->id.flag -= LIB_NEEDLINK;
1986                 }
1987                 key= key->id.next;
1988         }
1989 }
1990
1991 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1992 {
1993         int elemsize, a, b;
1994         char *data, *poin, *cp;
1995
1996         elemsize= key->elemsize;
1997         data= kb->data;
1998
1999         for(a=0; a<kb->totelem; a++) {
2000
2001                 cp= key->elemstr;
2002                 poin= data;
2003
2004                 while( cp[0] ) {        /* cp[0]==amount */
2005
2006                         switch(cp[1]) {         /* cp[1]= type */
2007                         case IPO_FLOAT:
2008                         case IPO_BPOINT:
2009                         case IPO_BEZTRIPLE:
2010                                 b= cp[0];
2011                                 while(b--) {
2012                                         SWITCH_INT((*poin));
2013                                         poin+= 4;
2014                                 }
2015                                 break;
2016                         }
2017
2018                         cp+= 2;
2019
2020                 }
2021                 data+= elemsize;
2022         }
2023 }
2024
2025 static void direct_link_key(FileData *fd, Key *key)
2026 {
2027         KeyBlock *kb;
2028
2029         link_list(fd, &(key->block));
2030
2031         key->refkey= newdataadr(fd, key->refkey);
2032
2033         kb= key->block.first;
2034         while(kb) {
2035
2036                 kb->data= newdataadr(fd, kb->data);
2037
2038                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2039                         switch_endian_keyblock(key, kb);
2040
2041                 kb= kb->next;
2042         }
2043 }
2044
2045 /* ************ READ mball ***************** */
2046
2047 static void lib_link_mball(FileData *fd, Main *main)
2048 {
2049         MetaBall *mb;
2050         int a;
2051
2052         mb= main->mball.first;
2053         while(mb) {
2054                 if(mb->id.flag & LIB_NEEDLINK) {
2055
2056                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2057
2058                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
2059
2060                         mb->id.flag -= LIB_NEEDLINK;
2061                 }
2062                 mb= mb->id.next;
2063         }
2064 }
2065
2066 static void direct_link_mball(FileData *fd, MetaBall *mb)
2067 {
2068         mb->mat= newdataadr(fd, mb->mat);
2069         test_pointer_array(fd, (void **)&mb->mat);
2070
2071         link_list(fd, &(mb->elems));
2072
2073         mb->disp.first= mb->disp.last= 0;
2074
2075         mb->bb= 0;
2076 }
2077
2078 /* ************ READ WORLD ***************** */
2079
2080 static void lib_link_world(FileData *fd, Main *main)
2081 {
2082         World *wrld;
2083         MTex *mtex;
2084         int a;
2085
2086         wrld= main->world.first;
2087         while(wrld) {
2088                 if(wrld->id.flag & LIB_NEEDLINK) {
2089
2090                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
2091
2092                         for(a=0; a<MAX_MTEX; a++) {
2093                                 mtex= wrld->mtex[a];
2094                                 if(mtex) {
2095                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2096                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2097                                 }
2098                         }
2099
2100                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2101
2102                         wrld->id.flag -= LIB_NEEDLINK;
2103                 }
2104                 wrld= wrld->id.next;
2105         }
2106 }
2107
2108 static void direct_link_world(FileData *fd, World *wrld)
2109 {
2110         int a;
2111
2112         direct_link_scriptlink(fd, &wrld->scriptlink);
2113
2114         for(a=0; a<MAX_MTEX; a++) {
2115                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2116         }
2117         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2118 }
2119
2120
2121 /* ************ READ IPO ***************** */
2122
2123 static void lib_link_ipo(FileData *fd, Main *main)
2124 {
2125         Ipo *ipo;
2126
2127         ipo= main->ipo.first;
2128         while(ipo) {
2129                 if(ipo->id.flag & LIB_NEEDLINK) {
2130                         IpoCurve *icu;
2131                         for(icu= ipo->curve.first; icu; icu= icu->next) {
2132                                 if(icu->driver)
2133                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
2134                         }
2135                         ipo->id.flag -= LIB_NEEDLINK;
2136                 }
2137                 ipo= ipo->id.next;
2138         }
2139 }
2140
2141 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2142 {
2143         IpoCurve *icu;
2144
2145         link_list(fd, &(ipo->curve));
2146         icu= ipo->curve.first;
2147         while(icu) {
2148                 icu->bezt= newdataadr(fd, icu->bezt);
2149                 icu->bp= newdataadr(fd, icu->bp);
2150                 icu->driver= newdataadr(fd, icu->driver);
2151                 icu= icu->next;
2152         }
2153 }
2154
2155 /* ************ READ VFONT ***************** */
2156
2157 static void lib_link_vfont(FileData *fd, Main *main)
2158 {
2159         VFont *vf;
2160
2161         vf= main->vfont.first;
2162         while(vf) {
2163                 if(vf->id.flag & LIB_NEEDLINK) {
2164                         vf->id.flag -= LIB_NEEDLINK;
2165                 }
2166                 vf= vf->id.next;
2167         }
2168 }
2169
2170 static void direct_link_vfont(FileData *fd, VFont *vf)
2171 {
2172         vf->data= NULL;
2173         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2174 }
2175
2176 /* ************ READ TEXT ****************** */
2177
2178 static void lib_link_text(FileData *fd, Main *main)
2179 {
2180         Text *text;
2181
2182         text= main->text.first;
2183         while(text) {
2184                 if(text->id.flag & LIB_NEEDLINK) {
2185                         text->id.flag -= LIB_NEEDLINK;
2186                 }
2187                 text= text->id.next;
2188         }
2189 }
2190
2191 static void direct_link_text(FileData *fd, Text *text)
2192 {
2193         TextLine *ln;
2194
2195         text->name= newdataadr(fd, text->name);
2196
2197         text->undo_pos= -1;
2198         text->undo_len= TXT_INIT_UNDO;
2199         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2200
2201         text->compiled= NULL;
2202
2203 /*
2204         if(text->flags & TXT_ISEXT) {
2205                 reopen_text(text);
2206         } else {
2207 */
2208
2209         link_list(fd, &text->lines);
2210
2211         text->curl= newdataadr(fd, text->curl);
2212         text->sell= newdataadr(fd, text->sell);
2213
2214         ln= text->lines.first;
2215         while(ln) {
2216                 ln->line= newdataadr(fd, ln->line);
2217                 ln->format= NULL;
2218                 
2219                 if (ln->len != (int) strlen(ln->line)) {
2220                         printf("Error loading text, line lengths differ\n");
2221                         ln->len = strlen(ln->line);
2222                 }
2223
2224                 ln= ln->next;
2225         }
2226
2227         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
2228
2229         text->id.us= 1;
2230 }
2231
2232 /* ************ READ IMAGE ***************** */
2233
2234 static void lib_link_image(FileData *fd, Main *main)
2235 {
2236         Image *ima;
2237
2238         ima= main->image.first;
2239         while (ima) {
2240                 if(ima->id.flag & LIB_NEEDLINK) {
2241                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2242
2243                         ima->id.flag -= LIB_NEEDLINK;
2244                 }
2245                 ima= ima->id.next;
2246         }
2247 }
2248
2249 static void link_ibuf_list(FileData *fd, ListBase *lb)
2250 {
2251         Link *ln, *prev;
2252         
2253         if(lb->first==NULL) return;
2254         
2255         lb->first= newimaadr(fd, lb->first);
2256         ln= lb->first;
2257         prev= NULL;
2258         while(ln) {
2259                 ln->next= newimaadr(fd, ln->next);
2260                 ln->prev= prev;
2261                 prev= ln;
2262                 ln= ln->next;
2263         }
2264         lb->last= prev;
2265 }
2266
2267 static void direct_link_image(FileData *fd, Image *ima)
2268 {
2269         /* for undo system, pointers could be restored */
2270         if(fd->imamap)
2271                 link_ibuf_list(fd, &ima->ibufs);
2272         else
2273                 ima->ibufs.first= ima->ibufs.last= NULL;
2274         
2275         /* if not restored, we keep the binded opengl index */
2276         if(ima->ibufs.first==NULL)
2277                 ima->bindcode= 0;
2278         
2279         ima->anim= NULL;
2280         ima->rr= NULL;
2281         ima->repbind= NULL;
2282         
2283         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2284         ima->preview = direct_link_preview_image(fd, ima->preview);
2285         ima->ok= 1;
2286 }
2287
2288
2289 /* ************ READ CURVE ***************** */
2290
2291 static void lib_link_curve(FileData *fd, Main *main)
2292 {
2293         Curve *cu;
2294         int a;
2295
2296         cu= main->curve.first;
2297         while(cu) {
2298                 if(cu->id.flag & LIB_NEEDLINK) {
2299
2300                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2301
2302                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2303                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2304                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2305                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2306                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2307                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2308                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2309
2310                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
2311                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2312
2313                         cu->id.flag -= LIB_NEEDLINK;
2314                 }
2315                 cu= cu->id.next;
2316         }
2317 }
2318
2319
2320 static void switch_endian_knots(Nurb *nu)
2321 {
2322         int len;
2323
2324         if(nu->knotsu) {
2325                 len= KNOTSU(nu);
2326                 while(len--) {
2327                         SWITCH_INT(nu->knotsu[len]);
2328                 }
2329         }
2330         if(nu->knotsv) {
2331                 len= KNOTSV(nu);
2332                 while(len--) {
2333                         SWITCH_INT(nu->knotsv[len]);
2334                 }
2335         }
2336 }
2337
2338 static void direct_link_curve(FileData *fd, Curve *cu)
2339 {
2340         Nurb *nu;
2341         TextBox *tb;
2342
2343         cu->mat= newdataadr(fd, cu->mat);
2344         test_pointer_array(fd, (void **)&cu->mat);
2345         cu->str= newdataadr(fd, cu->str);
2346         cu->strinfo= newdataadr(fd, cu->strinfo);       
2347         cu->tb= newdataadr(fd, cu->tb);
2348
2349         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2350         else {
2351                 cu->nurb.first=cu->nurb.last= 0;
2352
2353                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2354                 if (cu->tb) {
2355                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2356                         MEM_freeN(cu->tb);
2357                         cu->tb= tb;                     
2358                 } else {
2359                         cu->totbox = 1;
2360                         cu->actbox = 1;
2361                         cu->tb = tb;
2362                         cu->tb[0].w = cu->linewidth;
2363                 }               
2364                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2365         }
2366
2367         cu->bev.first=cu->bev.last= 0;
2368         cu->disp.first=cu->disp.last= 0;
2369         cu->path= 0;
2370
2371         nu= cu->nurb.first;
2372         while(nu) {
2373                 nu->bezt= newdataadr(fd, nu->bezt);
2374                 nu->bp= newdataadr(fd, nu->bp);
2375                 nu->knotsu= newdataadr(fd, nu->knotsu);
2376                 nu->knotsv= newdataadr(fd, nu->knotsv);
2377                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2378
2379                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2380                         switch_endian_knots(nu);
2381                 }
2382
2383                 nu= nu->next;
2384         }
2385         cu->bb= NULL;
2386 }
2387
2388 /* ************ READ TEX ***************** */
2389
2390 static void lib_link_texture(FileData *fd, Main *main)
2391 {
2392         Tex *tex;
2393
2394         tex= main->tex.first;
2395         while(tex) {
2396                 if(tex->id.flag & LIB_NEEDLINK) {
2397
2398                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2399                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2400                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2401
2402                         tex->id.flag -= LIB_NEEDLINK;
2403                 }
2404                 tex= tex->id.next;
2405         }
2406 }
2407
2408 static void direct_link_texture(FileData *fd, Tex *tex)
2409 {
2410         tex->plugin= newdataadr(fd, tex->plugin);
2411         if(tex->plugin) {
2412                 tex->plugin->handle= 0;
2413                 open_plugin_tex(tex->plugin);
2414                 /* initialize data for this instance, if an initialization
2415                  * function exists.
2416                  */
2417                 if (tex->plugin->instance_init)
2418                         tex->plugin->instance_init((void *) tex->plugin->data);
2419         }
2420         tex->coba= newdataadr(fd, tex->coba);
2421         tex->env= newdataadr(fd, tex->env);
2422         if(tex->env) {
2423                 tex->env->ima= NULL;
2424                 memset(tex->env->cube, 0, 6*sizeof(void *));
2425                 tex->env->ok= 0;
2426         }
2427         tex->preview = direct_link_preview_image(fd, tex->preview);
2428
2429         tex->iuser.ok= 1;
2430 }
2431
2432
2433
2434 /* ************ READ MATERIAL ***************** */
2435
2436 static void lib_link_material(FileData *fd, Main *main)
2437 {
2438         Material *ma;
2439         MTex *mtex;
2440         int a;
2441
2442         ma= main->mat.first;
2443         while(ma) {
2444                 if(ma->id.flag & LIB_NEEDLINK) {
2445                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2446                         of library blocks that implement this.*/
2447                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2448
2449                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2450                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2451                         
2452                         for(a=0; a<MAX_MTEX; a++) {
2453                                 mtex= ma->mtex[a];
2454                                 if(mtex) {
2455                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2456                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2457                                 }
2458                         }
2459                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2460                         
2461                         if(ma->nodetree)
2462                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2463                         
2464                         ma->id.flag -= LIB_NEEDLINK;
2465                 }
2466                 ma= ma->id.next;
2467         }
2468 }
2469
2470 static void direct_link_material(FileData *fd, Material *ma)
2471 {
2472         int a;
2473
2474         for(a=0; a<MAX_MTEX; a++) {
2475                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2476         }
2477
2478         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2479         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2480         
2481         direct_link_scriptlink(fd, &ma->scriptlink);
2482         
2483         ma->nodetree= newdataadr(fd, ma->nodetree);
2484         if(ma->nodetree)
2485                 direct_link_nodetree(fd, ma->nodetree);
2486
2487         ma->preview = direct_link_preview_image(fd, ma->preview);
2488 }
2489
2490 /* ************ READ PARTICLE SETTINGS ***************** */
2491
2492 static void lib_link_particlesettings(FileData *fd, Main *main)
2493 {
2494         ParticleSettings *part;
2495
2496         part= main->particle.first;
2497         while(part) {
2498                 if(part->id.flag & LIB_NEEDLINK) {
2499                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo);
2500                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
2501                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
2502                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
2503                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
2504                         part->id.flag -= LIB_NEEDLINK;
2505                 }
2506                 part= part->id.next;
2507         }
2508 }
2509
2510 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
2511 {
2512         part->pd= newdataadr(fd, part->pd);
2513 }
2514
2515 static void lib_link_particlesystems(FileData *fd, ID *id, ListBase *particles)
2516 {
2517         ParticleSystem *psys;
2518         int a;
2519
2520         for(psys=particles->first; psys; psys=psys->next){
2521                 ParticleData *pa;
2522                 psys->part = newlibadr_us(fd, id->lib, psys->part);
2523                 psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
2524                 psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
2525
2526                 for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
2527                         pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
2528                 }
2529         }
2530 }
2531 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
2532 {
2533         ParticleSystem *psys;
2534         int a;
2535
2536         for(psys=particles->first; psys; psys=psys->next) {
2537                 psys->particles=newdataadr(fd,psys->particles);
2538                 if(psys->particles && psys->particles->hair){
2539                         ParticleData *pa = psys->particles;
2540                         for(a=0; a<psys->totpart; a++, pa++)
2541                                 pa->hair=newdataadr(fd,pa->hair);
2542                 }
2543                 if(psys->particles && psys->particles->keys){
2544                         ParticleData *pa = psys->particles;
2545                         for(a=0; a<psys->totpart; a++, pa++)
2546                                 pa->keys=newdataadr(fd,pa->keys);
2547                 }
2548                 psys->child=newdataadr(fd,psys->child);
2549                 psys->effectors.first=psys->effectors.last=0;
2550
2551                 psys->soft= newdataadr(fd, psys->soft);
2552                 if(psys->soft) {
2553                         SoftBody *sb = psys->soft;
2554                         sb->particles = psys;
2555                         sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2556                         sb->bspring= NULL;
2557                         sb->scratch= NULL;
2558                 }
2559
2560                 psys->edit = 0;
2561                 psys->pathcache = 0;
2562                 psys->childcache = 0;
2563                 psys->reactevents.first = psys->reactevents.last = 0;
2564         }
2565         return;
2566 }
2567
2568 /* ************ READ MESH ***************** */
2569
2570 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
2571 {
2572         MTFace *tf= mtface;
2573         int i;
2574
2575         for (i=0; i<totface; i++, tf++) {
2576                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2577                 if(tf->tpage && tf->tpage->id.us==0)
2578                         tf->tpage->id.us= 1;
2579         }
2580 }
2581
2582 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
2583 {
2584         int i;  
2585         for(i=0; i<fdata->totlayer; i++) {
2586                 CustomDataLayer *layer = &fdata->layers[i];
2587                 
2588                 if(layer->type == CD_MTFACE)
2589                         lib_link_mtface(fd, me, layer->data, totface);
2590         }
2591
2592 }
2593
2594 static void lib_link_mesh(FileData *fd, Main *main)
2595 {
2596         Mesh *me;
2597
2598         me= main->mesh.first;
2599         while(me) {
2600                 if(me->id.flag & LIB_NEEDLINK) {
2601                         int i;
2602
2603                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2604                         of library blocks that implement this.*/
2605                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2606
2607                         /* this check added for python created meshes */
2608                         if(me->mat) {
2609                                 for(i=0; i<me->totcol; i++) {
2610                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2611                                 }
2612                         }
2613                         else me->totcol= 0;
2614
2615                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2616                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2617                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2618
2619                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
2620                         if(me->mr && me->mr->levels.first)
2621                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
2622                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
2623
2624                         me->id.flag -= LIB_NEEDLINK;
2625                 }
2626                 me= me->id.next;
2627         }
2628 }
2629
2630 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2631 {
2632         int     i;
2633
2634         if (!mdverts)
2635                 return;
2636
2637         for (i=0; i<count; i++) {
2638                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2639                 if (!mdverts[i].dw)
2640                         mdverts[i].totweight=0;
2641         }
2642 }
2643
2644 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
2645 {
2646         int i = 0;
2647
2648         data->layers= newdataadr(fd, data->layers);
2649
2650         while (i < data->totlayer) {
2651                 CustomDataLayer *layer = &data->layers[i];
2652
2653                 if (CustomData_verify_versions(data, i)) {
2654                         layer->data = newdataadr(fd, layer->data);
2655                         i++;
2656                 }
2657         }
2658 }
2659
2660 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2661 {
2662         mesh->mat= newdataadr(fd, mesh->mat);
2663         test_pointer_array(fd, (void **)&mesh->mat);
2664
2665         mesh->mvert= newdataadr(fd, mesh->mvert);
2666         mesh->medge= newdataadr(fd, mesh->medge);
2667         mesh->mface= newdataadr(fd, mesh->mface);
2668         mesh->tface= newdataadr(fd, mesh->tface);
2669         mesh->mtface= newdataadr(fd, mesh->mtface);
2670         mesh->mcol= newdataadr(fd, mesh->mcol);
2671         mesh->msticky= newdataadr(fd, mesh->msticky);
2672         mesh->dvert= newdataadr(fd, mesh->dvert);
2673         
2674         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
2675         mesh->pv= newdataadr(fd, mesh->pv);
2676         if(mesh->pv) {
2677                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
2678                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
2679                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
2680                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
2681         }
2682
2683         /* normally direct_link_dverts should be called in direct_link_customdata,
2684            but for backwards compat in do_versions to work we do it here */
2685         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
2686
2687         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
2688         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
2689         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
2690
2691         mesh->bb= NULL;
2692         mesh->mselect = NULL;
2693
2694         /* Multires data */
2695         mesh->mr= newdataadr(fd, mesh->mr);
2696         if(mesh->mr) {
2697                 MultiresLevel *lvl;
2698                 
2699                 link_list(fd, &mesh->mr->levels);
2700                 lvl= mesh->mr->levels.first;
2701                 
2702                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
2703                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
2704                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
2705                 
2706                 if(mesh->mr->edge_flags)
2707                         mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
2708                 if(mesh->mr->edge_creases)
2709                         mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
2710                 
2711                 if(!mesh->mr->edge_flags)
2712                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
2713                 if(!mesh->mr->edge_creases)
2714                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
2715
2716                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
2717                         
2718                 for(; lvl; lvl= lvl->next) {
2719                         lvl->verts= newdataadr(fd, lvl->verts);
2720                         lvl->faces= newdataadr(fd, lvl->faces);
2721                         lvl->edges= newdataadr(fd, lvl->edges);
2722                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
2723                         lvl->edge_boundary_states= NULL;
2724                         lvl->vert_face_map = lvl->vert_edge_map = NULL;
2725                         lvl->map_mem= NULL;
2726                 }
2727         }
2728         
2729         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
2730                 TFace *tf= mesh->tface;
2731                 int i;
2732
2733                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
2734                         SWITCH_INT(tf->col[0]);
2735                         SWITCH_INT(tf->col[1]);
2736                         SWITCH_INT(tf->col[2]);
2737                         SWITCH_INT(tf->col[3]);
2738                 }
2739         }
2740 }
2741
2742 /* ************ READ LATTICE ***************** */
2743
2744 static void lib_link_latt(FileData *fd, Main *main)
2745 {
2746         Lattice *lt;
2747         
2748         lt= main->latt.first;
2749         while(lt) {
2750                 if(lt->id.flag & LIB_NEEDLINK) {
2751                         
2752                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
2753                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
2754                         
2755                         lt->id.flag -= LIB_NEEDLINK;
2756                 }
2757                 lt= lt->id.next;
2758         }
2759 }
2760
2761 static void direct_link_latt(FileData *fd, Lattice *lt)
2762 {
2763         lt->def= newdataadr(fd, lt->def);
2764         
2765         lt->dvert= newdataadr(fd, lt->dvert);
2766         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
2767 }
2768
2769
2770 /* ************ READ OBJECT ***************** */
2771
2772 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
2773                                               ID **idpoin)
2774 {
2775         FileData *fd = userData;
2776
2777         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
2778         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
2779         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
2780                 (*idpoin)->us++;
2781 }
2782 static void lib_link_modifiers(FileData *fd, Object *ob)
2783 {
2784         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
2785 }
2786
2787 static void lib_link_object(FileData *fd, Main *main)
2788 {
2789         Object *ob;
2790         PartEff *paf;
2791         bSensor *sens;
2792         bController *cont;
2793         bActuator *act;
2794         void *poin;
2795         int warn=0, a;
2796
2797         ob= main->object.first;
2798         while(ob) {
2799                 if(ob->id.flag & LIB_NEEDLINK) {
2800                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2801
2802                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2803                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2804                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2805                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2806                         ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
2807                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
2808                         
2809                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
2810                         if(ob->proxy) {
2811                                 /* paranoia check, actually a proxy_from pointer should never be written... */
2812                                 if(ob->proxy->id.lib==NULL) {
2813                                         ob->proxy->proxy_from= NULL;
2814                                         ob->proxy= NULL;
2815                                 }
2816                                 else {
2817                                         /* this triggers object_update to always use a copy */
2818                                         ob->proxy->proxy_from= ob;
2819                                         /* force proxy updates after load/undo, a bit weak */
2820                                         ob->recalc= ob->proxy->recalc= OB_RECALC;
2821                                 }
2822                         }
2823                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
2824
2825                         poin= ob->data;
2826                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2827                            
2828                         if(ob->data==NULL && poin!=NULL) {
2829                                 ob->type= OB_EMPTY;
2830                                 warn= 1;
2831                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2832                                 else printf("Object %s lost data.", ob->id.name+2);
2833                                 
2834                                 if(ob->pose) {
2835                                         free_pose(ob->pose);
2836                                         ob->pose= NULL;
2837                                         ob->flag &= ~OB_POSEMODE;
2838                                 }
2839                         }
2840                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2841
2842                         ob->id.flag -= LIB_NEEDLINK;
2843                         /* if id.us==0 a new base will be created later on */
2844
2845                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2846                         lib_link_pose(fd, ob, ob->pose);
2847                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2848                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2849                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2850
2851                         for(paf= ob->effect.first; paf; paf= paf->next) {
2852                                 if(paf->type==EFF_PARTICLE) {
2853                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
2854                                 }
2855                         }                               
2856
2857                         sens= ob->sensors.first;
2858                         while(sens) {
2859                                 if(ob->id.lib==NULL) {  // done in expand_main
2860                                         for(a=0; a<sens->totlinks; a++) {
2861                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2862                                         }
2863                                 }
2864                                 if(sens->type==SENS_TOUCH) {
2865                                         bTouchSensor *ts= sens->data;
2866                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2867                                 }
2868                                 else if(sens->type==SENS_MESSAGE) {
2869                                         bMessageSensor *ms= sens->data;
2870                                         ms->fromObject=
2871                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2872                                 }
2873                                 sens= sens->next;
2874                         }
2875
2876                         cont= ob->controllers.first;
2877                         while(cont) {
2878                                 if(ob->id.lib==NULL) {  // done in expand_main
2879                                         for(a=0; a<cont->totlinks; a++) {
2880                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2881                                         }
2882                                 }
2883                                 if(cont->type==CONT_PYTHON) {
2884                                         bPythonCont *pc= cont->data;
2885                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2886                                 }
2887                                 cont->slinks= NULL;
2888                                 cont->totslinks= 0;
2889
2890                                 cont= cont->next;
2891                         }
2892
2893                         act= ob->actuators.first;
2894                         while(act) {
2895                                 if(act->type==ACT_SOUND) {
2896                                         bSoundActuator *sa= act->data;
2897                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2898                                 }
2899                                 else if(act->type==ACT_CD) {
2900                                         /* bCDActuator *cda= act->data; */
2901                                 }
2902                                 else if(act->type==ACT_GAME) {
2903                                         /* bGameActuator *ga= act->data; */
2904                                 }
2905                                 else if(act->type==ACT_CAMERA) {
2906                                         bCameraActuator *ca= act->data;
2907                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2908                                 }
2909                                         /* leave this one, it's obsolete but necessary to read for conversion */
2910                                 else if(act->type==ACT_ADD_OBJECT) {
2911                                         bAddObjectActuator *eoa= act->data;
2912                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2913                                 }
2914                                 else if(act->type==ACT_EDIT_OBJECT) {
2915                                         bEditObjectActuator *eoa= act->data;
2916                                         if(eoa==NULL) {
2917                                                 init_actuator(act);
2918                                         }
2919                                         else {
2920                                                 eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2921                                                 eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2922                                         }
2923                                 }
2924                                 else if(act->type==ACT_SCENE) {
2925                                         bSceneActuator *sa= act->data;
2926                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2927                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2928                                 }
2929                                 else if(act->type==ACT_ACTION) {
2930                                         bActionActuator *aa= act->data;
2931                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2932                                 }
2933                                 else if(act->type==ACT_PROPERTY) {
2934                                         bPropertyActuator *pa= act->data;
2935                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2936                                 }
2937                                 else if(act->type==ACT_MESSAGE) {
2938                                         bMessageActuator *ma= act->data;
2939                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2940                                 }
2941                                 act= act->next;
2942                         }
2943
2944                         if(ob->fluidsimSettings) {
2945                                 ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
2946                         }
2947                         
2948                         /* texture field */
2949                         if(ob->pd)
2950                                 if(ob->pd->tex)
2951                                         ob->pd->tex=newlibadr_us(fd, ob->id.lib, ob->pd->tex);
2952
2953                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2954                         lib_link_particlesystems(fd, &ob->id, &ob->particlesystem);
2955                         lib_link_modifiers(fd, ob);
2956                 }
2957                 ob= ob->id.next;
2958         }
2959
2960         if(warn) error("WARNING IN CONSOLE");
2961 }
2962
2963
2964 static void direct_link_pose(FileData *fd, bPose *pose) {
2965
2966         bPoseChannel *pchan;
2967
2968         if (!pose)
2969                 return;
2970
2971         link_list(fd, &pose->chanbase);
2972         link_list(fd, &pose->agroups);
2973
2974         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2975                 pchan->bone= NULL;
2976                 pchan->parent= newdataadr(fd, pchan->parent);
2977                 pchan->child= newdataadr(fd, pchan->child);
2978                 direct_link_constraints(fd, &pchan->constraints);
2979                 pchan->iktree.first= pchan->iktree.last= NULL;
2980                 pchan->path= NULL;
2981         }
2982 }
2983
2984 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2985 {
2986         ModifierData *md;
2987
2988         link_list(fd, lb);
2989
2990         for (md=lb->first; md; md=md->next) {
2991                 md->error = NULL;
2992                 
2993                 /* if modifiers disappear, or for upward compatibility */
2994                 if(NULL==modifierType_getInfo(md->type))
2995                         md->type= eModifierType_None;
2996                         
2997                 if (md->type==eModifierType_Subsurf) {
2998                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2999
3000                         smd->emCache = smd->mCache = 0;
3001                 }
3002                 else if (md->type==eModifierType_Cloth) {
3003                         ClothModifierData *clmd = (ClothModifierData*) md;
3004                         
3005                         clmd->clothObject = NULL;
3006                         
3007                         clmd->sim_parms= newdataadr(fd, clmd->sim_parms);
3008                         clmd->coll_parms= newdataadr(fd, clmd->coll_parms);
3009                         
3010                 }
3011                 else if (md->type==eModifierType_Collision) {
3012                         
3013                         CollisionModifierData *collmd = (CollisionModifierData*) md;
3014                         /*
3015                         // TODO: CollisionModifier should use pointcache 
3016                         // + have proper reset events before enabling this
3017                         collmd->x = newdataadr(fd, collmd->x);
3018                         collmd->xnew = newdataadr(fd, collmd->xnew);
3019                         collmd->mfaces = newdataadr(fd, collmd->mfaces);
3020                         
3021                         collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_x");
3022                         collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_xnew");
3023                         collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_v");
3024                         */
3025                         
3026                         collmd->x = NULL;
3027                         collmd->xnew = NULL;
3028                         collmd->current_x = NULL;
3029                         collmd->current_xnew = NULL;
3030                         collmd->current_v = NULL;
3031                         collmd->time = -1;
3032                         collmd->numverts = 0;
3033                         collmd->tree = NULL;
3034                         collmd->mfaces = NULL;
3035                         
3036                 }
3037                 else if (md->type==eModifierType_Hook) {
3038                         HookModifierData *hmd = (HookModifierData*) md;
3039
3040                         hmd->indexar= newdataadr(fd, hmd->indexar);
3041                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3042                                 int a;
3043                                 for(a=0; a<hmd->totindex; a++) {
3044                                         SWITCH_INT(hmd->indexar[a]);
3045                                 }
3046                         }
3047                 } else if (md->type==eModifierType_ParticleSystem) {
3048                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData*) md;
3049
3050                         psmd->dm=0;
3051                         psmd->psys=newdataadr(fd, psmd->psys);
3052                         psmd->flag &= ~eParticleSystemFlag_psys_updated;
3053                 } else if (md->type==eModifierType_Explode) {
3054                         ExplodeModifierData *psmd = (ExplodeModifierData*) md;
3055
3056                         psmd->facepa=0;
3057                 }
3058                 else if (md->type==eModifierType_MeshDeform) {
3059                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
3060
3061                         mmd->bindweights= newdataadr(fd, mmd->bindweights);
3062                         mmd->bindcos= newdataadr(fd, mmd->bindcos);
3063                         mmd->dyngrid= newdataadr(fd, mmd->dyngrid);
3064                         mmd->dyninfluences= newdataadr(fd, mmd->dyninfluences);
3065                         mmd->dynverts= newdataadr(fd, mmd->dynverts);
3066
3067                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3068                                 int a;
3069
3070                                 if(mmd->bindweights)
3071                                         for(a=0; a<mmd->totcagevert*mmd->totvert; a++)
3072                                                 SWITCH_INT(mmd->bindweights[a])
3073                                 if(mmd->bindcos)
3074                                         for(a=0; a<mmd->totcagevert*3; a++)
3075                                                 SWITCH_INT(mmd->bindcos[a])
3076                                 if(mmd->dynverts)
3077                                         for(a=0; a<mmd->totvert; a++)
3078                                                 SWITCH_INT(mmd->dynverts[a])
3079                         }
3080                 }
3081         }
3082 }
3083
3084 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
3085 {
3086         bActionStrip *strip;
3087         
3088         link_list(fd, strips);
3089         
3090         for(strip= strips->first; strip; strip= strip->next)
3091                 link_list(fd, &strip->modifiers);
3092 }
3093
3094 static void direct_link_object(FileData *fd, Object *ob)
3095 {
3096         PartEff *paf;
3097         bProperty *prop;
3098         bSensor *sens;
3099         bController *cont;
3100         bActuator *act;
3101         int a;
3102         
3103         /* weak weak... this was only meant as draw flag, now is used in give_base too */
3104         ob->flag &= ~OB_FROMGROUP;
3105
3106         ob->disp.first=ob->disp.last= NULL;
3107
3108         ob->pose= newdataadr(fd, ob->pose);
3109         direct_link_pose(fd, ob->pose);
3110
3111         link_list(fd, &ob->defbase);
3112         direct_link_nlastrips(fd, &ob->nlastrips);
3113         link_list(fd, &ob->constraintChannels);
3114
3115         direct_link_scriptlink(fd, &ob->scriptlink);
3116
3117         ob->mat= newdataadr(fd, ob->mat);
3118         test_pointer_array(fd, (void **)&ob->mat);
3119         
3120         /* do it here, below old data gets converted */
3121         direct_link_modifiers(fd, &ob->modifiers);
3122         
3123         link_list(fd, &ob->effect);
3124         paf= ob->effect.first;
3125         while(paf) {
3126                 if(paf->type==EFF_PARTICLE) {
3127                         paf->keys= NULL;
3128                 }
3129                 if(paf->type==EFF_WAVE) {
3130                         WaveEff *wav = (WaveEff*) paf;
3131                         PartEff *next = paf->next;
3132                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
3133
3134                         wmd->damp = wav->damp;
3135                         wmd->flag = wav->flag;
3136                         wmd->height = wav->height;
3137                         wmd->lifetime = wav->lifetime;
3138                         wmd->narrow = wav->narrow;
3139                         wmd->speed = wav->speed;
3140                         wmd->startx = wav->startx;
3141                         wmd->starty = wav->startx;
3142                         wmd->timeoffs = wav->timeoffs;
3143                         wmd->width = wav->width;
3144
3145                         BLI_addtail(&ob->modifiers, wmd);
3146
3147                         BLI_remlink(&ob->effect, paf);
3148                         MEM_freeN(paf);
3149
3150                         paf = next;
3151                         continue;
3152                 }
3153                 if(paf->type==EFF_BUILD) {
3154                         BuildEff *baf = (BuildEff*) paf;
3155                         PartEff *next = paf->next;
3156                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
3157
3158                         bmd->start = baf->sfra;
3159                         bmd->length = baf->len;
3160                         bmd->randomize = 0;
3161                         bmd->seed = 1;
3162
3163                         BLI_addtail(&ob->modifiers, bmd);
3164
3165                         BLI_remlink(&ob->effect, paf);
3166                         MEM_freeN(paf);
3167
3168                         paf = next;
3169                         continue;
3170                 }
3171                 paf= paf->next;
3172         }
3173
3174         ob->pd= newdataadr(fd, ob->pd);
3175         ob->soft= newdataadr(fd, ob->soft);
3176         if(ob->soft) {
3177                 SoftBody *sb= ob->soft;         
3178                 
3179                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
3180                 sb->bspring= NULL;
3181                 sb->scratch= NULL;
3182                 /* although not used anymore */
3183                 /* still have to be loaded to be compatible with old files */
3184                 sb->keys= newdataadr(fd, sb->keys);
3185                 test_pointer_array(fd, (void **)&sb->keys);
3186                 if(sb->keys) {
3187                         for(a=0; a<sb->totkey; a++) {
3188                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
3189                         }
3190                 }
3191         }
3192         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
3193         if(ob->fluidsimSettings) {
3194                 // reinit mesh pointers
3195                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
3196                 ob->fluidsimSettings->meshSurface = NULL;
3197                 ob->fluidsimSettings->meshBB = NULL;
3198                 ob->fluidsimSettings->meshSurfNormals = NULL;
3199         }
3200
3201         link_list(fd, &ob->particlesystem);
3202         direct_link_particlesystems(fd,&ob->particlesystem);
3203         
3204         link_list(fd, &ob->prop);
3205         prop= ob->prop.first;
3206         while(prop) {
3207                 prop->poin= newdataadr(fd, prop->poin);
3208                 if(prop->poin==0) prop->poin= &prop->data;
3209                 prop= prop->next;
3210         }
3211
3212         link_list(fd, &ob->sensors);
3213         sens= ob->sensors.first;
3214         while(sens) {
3215                 sens->data= newdataadr(fd, sens->data);
3216                 sens->links= newdataadr(fd, sens->links);
3217                 test_pointer_array(fd, (void **)&sens->links);
3218                 sens= sens->next;
3219         }
3220
3221         direct_link_constraints(fd, &ob->constraints);
3222
3223         link_glob_list(fd, &ob->controllers);
3224         cont= ob->controllers.first;
3225         while(cont) {
3226                 cont->data= newdataadr(fd, cont->data);
3227                 cont->links= newdataadr(fd, cont->links);
3228                 test_pointer_array(fd, (void **)&cont->links);
3229                 cont= cont->next;
3230         }
3231
3232         link_glob_list(fd, &ob->actuators);
3233         act= ob->actuators.first;
3234         while(act) {
3235                 act->data= newdataadr(fd, act->data);
3236                 act= act->next;
3237         }
3238
3239         link_list(fd, &ob->hooks);
3240         while (ob->hooks.first) {
3241                 ObHook *hook = ob->hooks.first;
3242                 Hoo