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