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