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