701d621bafc01b9bc3b66c30bd5f0c27c8ed0f31
[blender.git] / source / blender / blenloader / intern / readfile.c
1 /*
2  * readfile.c
3  *
4  * .blend file reading
5  *
6  * $Id$
7  *
8  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version. The Blender
14  * Foundation also sells licenses for use in proprietary software under
15  * the Blender License.  See http://www.blender.org/BL/ for information
16  * about this.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  *
27  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
28  * All rights reserved.
29  *
30  * The Original Code is: all of this file.
31  *
32  * Contributor(s): none yet.
33  *
34  * ***** END GPL/BL DUAL LICENSE BLOCK *****
35  * 
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #ifdef WIN32
43 #include "winsock2.h"
44 #include "BLI_winstuff.h"
45 #endif
46
47 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
48 #include <stdlib.h> // for getenv atoi
49 #include <fcntl.h> // for open
50 #include <string.h> // for strcasecmp strrchr strncmp strstr
51
52 #ifndef WIN32 
53     #include <unistd.h> // for read close
54     #include <sys/param.h> // for MAXPATHLEN
55 #else
56     #include <io.h> // for open close read
57 #endif
58
59 #include "nla.h"
60
61 #include "DNA_ID.h"
62 #include "DNA_packedFile_types.h"
63 #include "DNA_property_types.h"
64 #include "DNA_actuator_types.h"
65 #include "DNA_controller_types.h"
66 #include "DNA_sensor_types.h"
67 #include "DNA_sdna_types.h"
68 #include "DNA_scene_types.h"
69 #include "DNA_sequence_types.h"
70 #include "DNA_ika_types.h"
71 #include "DNA_camera_types.h"
72 #include "DNA_lattice_types.h"
73 #include "DNA_texture_types.h"
74 #include "DNA_key_types.h"
75 #include "DNA_meta_types.h"
76 #include "DNA_lamp_types.h"
77 #include "DNA_object_types.h"
78 #include "DNA_world_types.h"
79 #include "DNA_ipo_types.h"
80 #include "DNA_mesh_types.h"
81 #include "DNA_image_types.h"
82 #include "DNA_material_types.h"
83 #include "DNA_curve_types.h"
84 #include "DNA_vfont_types.h"
85 #include "DNA_effect_types.h"
86 #include "DNA_text_types.h"
87 #include "DNA_view3d_types.h"
88 #include "DNA_screen_types.h"
89 #include "DNA_sound_types.h"
90 #include "DNA_space_types.h"
91 #include "DNA_oops_types.h"
92 #include "DNA_group_types.h"
93 #include "DNA_userdef_types.h"
94 #include "DNA_fileglobal_types.h"
95 #include "DNA_constraint_types.h"
96 #include "DNA_action_types.h"
97 #include "DNA_armature_types.h"
98 #include "DNA_nla_types.h"
99
100 #include "MEM_guardedalloc.h"
101 #include "BLI_blenlib.h"
102 #include "BLI_storage_types.h" // for relname flags
103
104 #include "BKE_bad_level_calls.h" // for reopen_text build_seqar (from WHILE_SEQ) open_plugin_seq set_rects_butspace check_imasel_copy
105
106 #include "BKE_constraint.h"
107 #include "BKE_utildefines.h" // SWITCH_INT WHILE_SEQ END_SEQ DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
108 #include "BKE_main.h" // for Main
109 #include "BKE_global.h" // for G
110 #include "BKE_property.h" // for get_property
111 #include "BKE_library.h" // for wich_libbase 
112 #include "BKE_texture.h" // for open_plugin_tex
113 #include "BKE_effect.h" // for give_parteff 
114 #include "BKE_sca.h" // for init_actuator
115 #include "BKE_mesh.h" // for ME_ defines (patching)
116 #include "BKE_armature.h"       //      for precalc_bonelist_irestmats
117 #include "BKE_action.h"
118
119 #include "BIF_butspace.h" // for do_versions, patching event codes
120
121 #include "BLO_readfile.h"
122 #include "readfile.h"
123
124 #include "genfile.h"
125
126 #include "BLO_readblenfile.h" // streaming read pipe, for BLO_readblenfile BLO_readblenfilememory
127
128 #include "mydevice.h"
129
130
131
132
133 /*
134  Remark: still a weak point is the newadress() function, that doesnt solve reading from
135  multiple files at the same time
136
137  (added remark: oh, i thought that was solved? will look at that... (ton)
138     
139 READ
140 - Existing Library (Main) push or free
141 - allocate new Main
142 - load file
143 - read SDNA
144 - for each LibBlock
145         - read LibBlock
146         - if a Library
147                 - make a new Main
148                 - attach ID's to it
149         - else 
150                 - read associated 'direct data'
151                 - link direct data (internal and to LibBlock)
152 - read FileGlobal
153 - read USER data, only when indicated (file is ~/.B.blend)
154 - free file
155 - per Library (per Main)
156         - read file
157         - read SDNA
158         - find LibBlocks and attach IDs to Main
159                 - if external LibBlock
160                         - search all Main's 
161                                 - or it's already read,
162                                 - or not read yet
163                                 - or make new Main
164         - per LibBlock
165                 - read recursive
166                 - read associated direct data
167                 - link direct data (internal and to LibBlock)
168         - free file
169 - per Library with unread LibBlocks
170         - read file
171         - read SDNA
172         - per LibBlock
173                - read recursive
174                - read associated direct data
175                - link direct data (internal and to LibBlock)
176         - free file
177 - join all Mains
178 - link all LibBlocks and indirect pointers to libblocks
179 - initialize FileGlobal and copy pointers to Global
180 */
181
182 /* also occurs in library.c */
183 /* GS reads the memory pointed at in a specific ordering. There are,
184  * however two definitions for it. I have jotted them down here, both,
185  * but I think the first one is actually used. The thing is that
186  * big-endian systems might read this the wrong way round. OTOH, we
187  * constructed the IDs that are read out with this macro explicitly as
188  * well. I expect we'll sort it out soon... */
189
190 /* from blendef: */
191 #define GS(a)   (*((short *)(a)))
192
193 /* from misc_util: flip the bytes from x  */
194 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
195
196 // only used here in readfile.c
197 #define SWITCH_LONGINT(a) { \
198     char s_i, *p_i; \
199     p_i= (char *)&(a);  \
200     s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
201     s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
202     s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
203     s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
204 // only used here in readfile.c
205 #define SWITCH_SHORT(a) { \
206     char s_i, *p_i; \
207     p_i= (char *)&(a); \
208     s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
209
210
211 /***/
212
213 typedef struct OldNew {
214         void *old, *newp;
215         int nr;
216 } OldNew;
217
218 typedef struct OldNewMap {
219         OldNew *entries;
220         int nentries, entriessize;
221         
222         int lasthit;
223 } OldNewMap;
224
225 static OldNewMap *oldnewmap_new(void) {
226         OldNewMap *onm= MEM_mallocN(sizeof(*onm), "OldNewMap");
227         onm->lasthit= 0;
228         onm->nentries= 0;
229         onm->entriessize= 1024;
230         onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
231         
232         return onm;
233 }
234
235 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) {
236         OldNew *entry;
237         
238         if (onm->nentries==onm->entriessize) {
239                 int osize= onm->entriessize;
240                 OldNew *oentries= onm->entries;
241                 
242                 onm->entriessize*= 2;
243                 onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
244                 
245                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
246                 MEM_freeN(oentries);
247         }
248         
249         entry= &onm->entries[onm->nentries++];
250         entry->old= oldaddr;
251         entry->newp= newaddr;
252         entry->nr= nr;
253 }
254
255 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) {
256         int i;
257         
258         if (onm->lasthit<onm->nentries-1) {
259                 OldNew *entry= &onm->entries[++onm->lasthit];
260                 
261                 if (entry->old==addr) {
262                         entry->nr++;
263                         return entry->newp;
264                 }
265         }
266         
267         for (i=0; i<onm->nentries; i++) {
268                 OldNew *entry= &onm->entries[i];
269                 
270                 if (entry->old==addr) {
271                         onm->lasthit= i;
272                         
273                         entry->nr++;
274                         return entry->newp;
275                 }
276         }
277
278         return NULL;
279 }
280
281 static void *oldnewmap_liblookup_and_inc(OldNewMap *onm, void *addr, void *lib) {
282         int i;
283         
284         if (onm->lasthit<onm->nentries-1) {
285                 OldNew *entry= &onm->entries[++onm->lasthit];
286                 
287                 if (entry->old==addr) {
288                         ID *id= entry->newp;
289                         
290                         if (id && (!lib || id->lib)) {
291                                 entry->nr++;
292                         
293                                 return entry->newp;
294                         }
295                 }
296         }
297         
298         for (i=0; i<onm->nentries; i++) {
299                 OldNew *entry= &onm->entries[i];
300                 
301                 if (entry->old==addr) {
302                         ID *id= entry->newp;
303                         
304                         if (id && (!lib || id->lib)) {
305                                 entry->nr++;
306                         
307                                 return entry->newp;
308                         }
309                 }
310         }
311
312         return NULL;
313 }
314
315 static void *oldnewmap_typelookup_and_inc(OldNewMap *onm, void *addr, short type) {
316         int i;
317         
318         if (onm->lasthit<onm->nentries-1) {
319                 OldNew *entry= &onm->entries[++onm->lasthit];
320                 
321                 if (entry->old==addr) {
322                         ID *id= entry->newp;
323                         
324                         if (id && (GS(id->name) == type)) {
325                                 entry->nr++;
326                         
327                                 return entry->newp;
328                         }
329                 }
330         }
331         
332         for (i=0; i<onm->nentries; i++) {
333                 OldNew *entry= &onm->entries[i];
334                 
335                 if (entry->old==addr) {
336                         ID *id= entry->newp;
337                         
338                         if (id && (GS(id->name) == type)) {
339                                 entry->nr++;
340                         
341                                 return entry->newp;
342                         }
343                 }
344         }
345
346         return NULL;
347 }
348
349 static void oldnewmap_free_unused(OldNewMap *onm) {
350         int i;
351         
352         for (i=0; i<onm->nentries; i++) {
353                 OldNew *entry= &onm->entries[i];
354                 if (entry->nr==0) {
355                         MEM_freeN(entry->newp);
356                         entry->newp= NULL;
357                 }
358         }
359 }
360
361 static void oldnewmap_clear(OldNewMap *onm) {
362         onm->nentries= 0;
363         onm->lasthit= 0;
364 }
365
366 static void oldnewmap_free(OldNewMap *onm) {
367         MEM_freeN(onm->entries);
368         MEM_freeN(onm);
369 }
370
371 /***/
372
373 static void read_libraries(FileData *basefd, ListBase *mainlist);
374
375 /* ************ help functions ***************** */
376
377 static void add_main_to_main(Main *mainvar, Main *from)
378 {
379         ListBase *lbarray[30], *fromarray[30];
380         int a;
381         
382         a= set_listbasepointers(mainvar, lbarray);
383         a= set_listbasepointers(from, fromarray);
384         while(a--) {
385                 addlisttolist(lbarray[a], fromarray[a]);
386         }
387 }
388
389 void blo_join_main(ListBase *mainlist)
390 {
391         Main *tojoin, *mainl= mainlist->first;
392
393         while (tojoin= mainl->next) {
394                 add_main_to_main(mainl, tojoin);
395                 BLI_remlink(mainlist, tojoin);
396                 MEM_freeN(tojoin);
397         }       
398 }
399
400 static void split_libdata(ListBase *lb, Main *first)
401 {
402         ListBase *lbn;
403         ID *id, *idnext;
404         Main *mainvar;
405         
406         id= lb->first;
407         while(id) {
408                 idnext= id->next;
409                 if(id->lib) {
410                         mainvar= first;
411                         while(mainvar) {
412                                 if(mainvar->curlib==id->lib) {
413                                         lbn= wich_libbase(mainvar, GS(id->name));
414                                         BLI_remlink(lb, id);
415                                         BLI_addtail(lbn, id);
416                                         break;
417                                 }
418                                 mainvar= mainvar->next;
419                         }
420                         if(mainvar==0) printf("error split_libdata\n");
421                 }
422                 id= idnext;
423         }
424 }
425
426 void blo_split_main(ListBase *mainlist)
427 {
428         Main *mainl= mainlist->first;
429         ListBase *lbarray[30];
430         Library *lib;
431         int i;
432         
433         for (lib= mainl->library.first; lib; lib= lib->id.next) {
434                 Main *libmain= MEM_callocN(sizeof(*libmain), "libmain");
435                 libmain->curlib= lib;
436
437                 BLI_addtail(mainlist, libmain);
438         }
439         
440         i= set_listbasepointers(mainl, lbarray);
441         while(i--)
442                 split_libdata(lbarray[i], mainl->next);
443 }
444
445 static Main *blo_find_main(ListBase *mainlist, char *name)
446 {
447         Main *m;
448         Library *lib;
449         
450         for (m= mainlist->first; m; m= m->next) {
451                 char *libname= (m->curlib)?m->curlib->name:m->name;
452
453                 if (BLI_streq(name, libname))
454                         return m;
455         }
456
457         m= MEM_callocN(sizeof(*m), "find_main");
458         BLI_addtail(mainlist, m);
459         
460         lib= alloc_libblock(&m->library, ID_LI, "lib");
461         strcpy(lib->name, name);
462         m->curlib= lib;
463         
464         return m;
465 }
466
467
468 /* ************ FILE PARSING ****************** */
469
470 static void switch_endian_bh4(BHead4 *bhead)
471 {
472         /* the ID_.. codes */
473         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
474
475         if (bhead->code != ENDB) {
476                 SWITCH_INT(bhead->len);
477                 SWITCH_INT(bhead->SDNAnr);
478                 SWITCH_INT(bhead->nr);
479         }
480 }
481
482 static void switch_endian_bh8(BHead8 *bhead)
483 {
484         /* the ID_.. codes */
485         if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
486
487         if (bhead->code != ENDB) {
488                 SWITCH_INT(bhead->len);
489                 SWITCH_INT(bhead->SDNAnr);
490                 SWITCH_INT(bhead->nr);
491         }
492 }
493
494 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
495 {
496         BHead4 *bhead4 = (BHead4 *) bhead;
497 #if defined(WIN32) && !defined(FREE_WINDOWS)
498         __int64 old;
499 #else
500         long long old;
501 #endif
502
503         bhead4->code= bhead8->code;
504         bhead4->len= bhead8->len;
505
506         if (bhead4->code != ENDB) {
507         
508                 // why is this here ??
509                 if (do_endian_swap) {
510                         SWITCH_LONGINT(bhead8->old);
511                 }
512                 
513                 /* this patch is to avoid a long long being read from not-eight aligned positions
514                    is necessary on SGI with -n32 compiling (no, is necessary on
515                    any modern 64bit architecture) */
516                 memcpy(&old, &bhead8->old, 8);
517                 bhead4->old = (int) (old >> 3);
518                 
519                 bhead4->SDNAnr= bhead8->SDNAnr;
520                 bhead4->nr= bhead8->nr;
521         }
522 }
523
524 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
525 {
526         BHead8 *bhead8 = (BHead8 *) bhead;
527
528         bhead8->code= bhead4->code;
529         bhead8->len= bhead4->len;
530
531         if (bhead8->code != ENDB) {     
532                 bhead8->old= bhead4->old;
533                 bhead8->SDNAnr= bhead4->SDNAnr;
534                 bhead8->nr= bhead4->nr;
535         }
536 }
537
538 static BHeadN *get_bhead(FileData *fd)
539 {
540         BHead8 bhead8;
541         BHead4 bhead4;
542         BHead  bhead;
543         BHeadN *new_bhead = 0;
544         int readsize;
545
546         if (fd) {
547                 if ( ! fd->eof) {
548
549                         // First read the bhead structure.
550                         // Depending on the platform the file was written on this can
551                         // be a big or little endian BHead4 or BHead8 structure.
552
553                         // As usual 'ENDB' (the last *partial* bhead of the file)
554                         // needs some special handling. We don't want to EOF just yet.
555                         
556                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
557                                 bhead4.code = DATA;
558                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
559                                 
560                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {                                        
561                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
562                                                 switch_endian_bh4(&bhead4);
563                                         }
564                                         
565                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
566                                                 bh8_from_bh4(&bhead, &bhead4);
567                                         } else {
568                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
569                                         }
570                                 } else {
571                                         fd->eof = 1;
572                                 }
573                         } else {
574                                 bhead8.code = DATA;
575                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
576                                 
577                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
578                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
579                                                 switch_endian_bh8(&bhead8);
580                                         }
581                                         
582                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
583                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
584                                         } else {
585                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
586                                         }
587                                 } else {
588                                         fd->eof = 1;
589                                 }
590                         }
591                         
592                         // bhead now contains the (converted) bhead structure. Now read
593                         // the associated data and put everything in a BHeadN (creative naming !)
594
595                         if ( ! fd->eof) {
596                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
597                                 if (new_bhead) {
598                                         new_bhead->next = new_bhead->prev = 0;
599                                         new_bhead->bhead = bhead;
600                                         
601                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
602                                         
603                                         if (readsize != bhead.len) {
604                                                 fd->eof = 1;
605                                                 MEM_freeN(new_bhead);
606                                         }
607                                 } else {
608                                         fd->eof = 1;
609                                 }
610                         }
611                 }
612         }
613         
614         // We've read a new block. Now add it to the list 
615         // of blocks.
616
617         if (new_bhead) {
618                 BLI_addtail(&fd->listbase, new_bhead);
619         }
620         
621         return(new_bhead);
622 }
623
624 BHead *blo_firstbhead(FileData *fd)
625 {
626         BHeadN *new_bhead;
627         BHead *bhead = 0;
628         
629         // Rewind the file
630         // Read in a new block if necessary
631         
632         new_bhead = fd->listbase.first;
633         if (new_bhead == 0) {
634                 new_bhead = get_bhead(fd);
635         }
636         
637         if (new_bhead) {
638                 bhead = &new_bhead->bhead;
639         }
640         
641         return(bhead);
642 }
643
644 BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
645 {
646         BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
647         BHeadN *prev= bheadn->prev;
648         
649         return prev?&prev->bhead:NULL;
650 }
651
652 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
653 {
654         BHeadN *new_bhead = 0;
655         BHead *bhead = 0;
656
657         if (thisblock) {
658                 // bhead is actually a sub part of BHeadN
659                 // We calculate the BHeadN pointer from the BHead pointer below
660                 new_bhead = (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
661
662                 // get the next BHeadN. If it doesn't exist we read in the next one
663                 new_bhead = new_bhead->next;
664                 if (new_bhead == 0) {
665                         new_bhead = get_bhead(fd);
666                 }
667         }
668
669         if (new_bhead) {
670                 // here we do the reverse:
671                 // go from the BHeadN pointer to the BHead pointer
672                 bhead = &new_bhead->bhead;
673         }
674
675         return(bhead);
676 }
677
678 static void decode_blender_header(FileData *fd)
679 {
680         char header[SIZEOFBLENDERHEADER], num[4];
681         int readsize;
682         
683         // read in the header data
684         readsize = fd->read(fd, header, sizeof(header));
685
686         if (readsize == sizeof(header)) {
687                 if(strncmp(header, "BLENDER", 7) == 0) {
688                         int remove_this_endian_test= 1;
689                         
690                         fd->flags |= FD_FLAGS_FILE_OK;
691                 
692                         // what size are pointers in the file ?
693                         if(header[7]=='_') {
694                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
695                                 if (sizeof(void *) != 4) {
696                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
697                                 }
698                         } else {
699                                 if (sizeof(void *) != 8) {
700                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
701                                 }
702                         }
703                         
704                         // is the file saved in a different endian
705                         // than we need ?
706                         if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
707                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
708                         }
709                         
710                         // get the version number
711
712                         memcpy(num, header+9, 3);
713                         num[3] = 0;
714                         fd->fileversion = atoi(num);
715                 }
716         }
717 }
718
719 static int read_file_dna(FileData *fd)
720 {
721         BHead *bhead;
722         
723         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
724                 if (bhead->code==DNA1) {
725                         int do_endian_swap= (fd->flags&FD_FLAGS_SWITCH_ENDIAN)?1:0;
726         
727                         fd->filesdna= dna_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
728                         if (fd->filesdna)
729                                 fd->compflags= dna_get_structDNA_compareflags(fd->filesdna, fd->memsdna);
730                                 
731                         return 1;
732                 } else if (bhead->code==ENDB)
733                         break;
734         }
735         
736         return 0;
737 }
738 static int fd_read_from_file(FileData *filedata, void *buffer, int size)
739 {
740         int readsize = read(filedata->filedes, buffer, size);
741         
742         if (readsize < 0) {
743                 readsize = EOF;
744         } else {
745                 filedata->seek += readsize;
746         }
747
748         return (readsize);      
749 }
750
751 static int fd_read_from_memory(FileData *filedata, void *buffer, int size)
752 {
753                 // don't read more bytes then there are available in the buffer
754         int readsize = MIN2(size, filedata->buffersize - filedata->seek);
755
756         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
757         filedata->seek += readsize;
758
759         return (readsize);
760 }
761
762 static FileData *filedata_new(void)
763 {
764         extern char DNAstr[];   /* DNA.c */
765         extern int DNAlen;
766         FileData *fd = MEM_callocN(sizeof(*fd), "FileData");
767         
768         fd->filedes = -1;       
769         
770                 /* XXX, this doesn't need to be done all the time,
771                  * but it keeps us reentrant,  remove once we have
772                  * a lib that provides a nice lock. - zr
773                  */
774         fd->memsdna = dna_sdna_from_data(DNAstr,  DNAlen,  0);
775         
776         fd->datamap = oldnewmap_new();
777         fd->globmap = oldnewmap_new();
778         fd->libmap = oldnewmap_new();
779
780         return fd;
781 }
782
783 FileData *blo_openblenderfile(char *name)
784 {
785         int file= open(name, O_BINARY|O_RDONLY);
786         
787         if (file == -1) {
788                 return NULL;
789         } else {
790                 FileData *fd = filedata_new();
791                 fd->filedes = file;
792                 fd->buffersize = BLI_filesize(file);
793                 fd->read = fd_read_from_file;
794         
795                 decode_blender_header(fd);
796                 
797                 if (fd->flags & FD_FLAGS_FILE_OK) {
798                         if (!read_file_dna(fd)) {
799                                 blo_freefiledata(fd);
800                                 fd= NULL;
801                         }
802                 } else {
803                         blo_freefiledata(fd);
804                         fd= NULL;
805                 }
806
807                 return fd;
808         }
809 }
810
811 FileData *blo_openblendermemory(void *mem, int memsize)
812 {
813         if (!mem || memsize<SIZEOFBLENDERHEADER) {
814                 return NULL;
815         } else {
816                 FileData *fd= filedata_new();
817                 fd->buffer= mem;
818                 fd->buffersize= memsize;
819                 fd->read= fd_read_from_memory;
820                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
821                 
822                 decode_blender_header(fd);
823                 
824                 if (fd->flags & FD_FLAGS_FILE_OK) {
825                         if (!read_file_dna(fd)) {
826                                 blo_freefiledata(fd);
827                                 fd= NULL;
828                         }
829                 } else {
830                         blo_freefiledata(fd);
831                         fd= NULL;
832                 }
833                 
834                 return fd;
835         }
836 }
837
838 void blo_freefiledata(FileData *fd)
839 {
840         if (fd) {
841                 if (fd->filedes != -1) {
842                         close(fd->filedes);
843                 }
844
845                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
846                         MEM_freeN(fd->buffer);
847                         fd->buffer = 0;
848                 }
849                 
850                 // Free all BHeadN data blocks
851                 BLI_freelistN(&fd->listbase);
852
853                 if (fd->memsdna)
854                         dna_freestructDNA(fd->memsdna);
855                 if (fd->filesdna)
856                         dna_freestructDNA(fd->filesdna);
857                 if (fd->compflags)
858                         MEM_freeN(fd->compflags);
859
860                 if (fd->datamap)
861                         oldnewmap_free(fd->datamap);
862                 if (fd->globmap)
863                         oldnewmap_free(fd->globmap);
864                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
865                         oldnewmap_free(fd->libmap);
866                 
867                 MEM_freeN(fd);
868         }
869 }
870
871 /* ************ DIV ****************** */
872
873 int BLO_has_bfile_extension(char *str)
874 {
875         return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend"));
876 }
877
878 /* ************** OLD POINTERS ******************* */
879
880 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
881 {
882         return oldnewmap_lookup_and_inc(fd->datamap, adr);
883 }
884
885 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
886 {
887         return oldnewmap_lookup_and_inc(fd->globmap, adr);
888 }
889
890 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
891 {
892         return oldnewmap_liblookup_and_inc(fd->libmap, adr, lib);
893 }
894
895 static void *newlibadr_us_type(FileData *fd, short type, void *adr)     /* only Lib data */
896 {
897         ID *id= oldnewmap_typelookup_and_inc(fd->libmap, adr, type);
898         
899         if (id) {
900                 id->us++;
901         }
902         
903         return id;
904 }
905
906 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
907 {
908         ID *id= newlibadr(fd, lib, adr);
909
910         if(id) {
911                 id->us++;
912         }
913         
914         return id;
915 }
916
917 static void change_libadr(FileData *fd, void *old, void *new)
918 {
919         int i;
920         
921                 /* changed one thing here, the old change_libadr
922                  * only remapped addresses that had an id->lib, 
923                  * but that doesn't make sense to me... its an
924                  * old pointer, period, it needs to be remapped. - zr
925                  */
926
927                 /*
928                  * Ton seemed to think it was necessary to look
929                  * through all entries, and not return after finding
930                  * a match, leaving this cryptic comment, 
931                  * // no return, maybe there can be more?
932                  * 
933                  * That doesn't make sense to me either but I am
934                  * too scared to remove it... it only would make
935                  * sense if two distinct old address map to the
936                  * same new address - obviously that shouldn't happen
937                  * because memory addresses are unique.
938                  * 
939                  * The only case it might happen is when two distinct
940                  * libraries are mapped using the same table... this
941                  * won't work to start with... At some point this 
942                  * all needs to be made sense of and made understandable, 
943                  * but I'm afraid I don't have time now. -zr
944                  * 
945                  */
946     /* the code is nasty, and needs a lot of energy to get into full understanding
947        again... i now translate dutch comments, maybe that gives me more insight!
948        But i guess it has to do with the assumption that 2 addresses can be allocated
949        in different sessions, and therefore be the same... like the remark in the top
950        of this c file (ton) */
951      
952         for (i=0; i<fd->libmap->nentries; i++) {
953                 OldNew *entry= &fd->libmap->entries[i];
954                 
955                 if (old==entry->newp) {
956                         entry->newp= new;
957                         break;
958                 }
959         }
960 }
961
962
963 /* ********** END OLD POINTERS ****************** */
964 /* ********** READ FILE ****************** */
965
966 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
967 {
968         int blocksize, nblocks;
969         char *data;
970         
971         data= (char *)(bhead+1); /*  BHEAD+DATA dependancy */
972         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
973
974         nblocks= bhead->nr;
975         while(nblocks--) {
976                 dna_switch_endian_struct(filesdna, bhead->SDNAnr, data);
977                 
978                 data+= blocksize;
979         }
980 }
981
982 static void *read_struct(FileData *fd, BHead *bh)
983 {
984         void *temp= NULL;
985         
986         if (bh->len) {
987                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
988                         switch_endian_structs(fd->filesdna, bh);
989                 
990                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
991                         if(fd->compflags[bh->SDNAnr]==2) {
992                                 temp= dna_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
993                         } else {
994                                 temp= MEM_mallocN(bh->len, "read_struct");
995                                 memcpy(temp, (bh+1), bh->len); /*  BHEAD+DATA dependancy */
996                         }
997                 }
998         }
999         
1000         return temp;    
1001 }
1002
1003 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1004 {
1005         Link *ln, *prev;
1006         
1007         if(lb->first==0) return;
1008
1009         lb->first= newdataadr(fd, lb->first);
1010         ln= lb->first;
1011         prev= 0;
1012         while(ln) {
1013                 ln->next= newdataadr(fd, ln->next);
1014                 ln->prev= prev;
1015                 prev= ln;
1016                 ln= ln->next;
1017         }
1018         lb->last= prev;
1019 }
1020
1021 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1022 {
1023         Link *ln, *prev;
1024         void *poin;
1025     
1026         if(lb->first==0) return;
1027         
1028         poin= newdataadr(fd, lb->first);
1029         if(lb->first) {
1030                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1031         }
1032         lb->first= poin;
1033         
1034         ln= lb->first;
1035         prev= 0;
1036         while(ln) {
1037                 poin= newdataadr(fd, ln->next);
1038                 if(ln->next) {
1039                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1040                 }
1041                 ln->next= poin;
1042                 ln->prev= prev;
1043                 prev= ln;
1044                 ln= ln->next;
1045         }
1046         lb->last= prev;
1047 }
1048
1049 static void test_pointer_array(FileData *fd, void **mat)
1050 {
1051 #if defined(WIN32) && !defined(FREE_WINDOWS)
1052         __int64 *lpoin, *lmat;
1053 #else
1054         long long *lpoin, *lmat;
1055 #endif
1056         int len, *ipoin, *imat;
1057
1058                 /* manually convert the pointer array in
1059                  * the old dna format to a pointer array in
1060                  * the new dna format.
1061                  */
1062         if(*mat) {
1063                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1064                 
1065                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1066                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
1067                         lpoin= *mat;
1068
1069                         while(len-- > 0) {
1070                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))        
1071                                         SWITCH_LONGINT(*lpoin);
1072                                 *ipoin= (int) ((*lpoin) >> 3);
1073                                 ipoin++;
1074                                 lpoin++;
1075                         }
1076                         MEM_freeN(*mat);
1077                         *mat= imat;
1078                 }
1079                 
1080                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1081                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
1082                         ipoin= *mat;
1083
1084                         while(len-- > 0) {
1085                                 *lpoin= *ipoin;
1086                                 ipoin++;
1087                                 lpoin++;
1088                         }
1089                         MEM_freeN(*mat);
1090                         *mat= lmat;
1091                 }
1092         }
1093 }
1094
1095 /* ************ READ PACKEDFILE *************** */
1096
1097 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1098 {
1099         PackedFile *pf= newdataadr(fd, oldpf);
1100         
1101         if (pf) {
1102                 pf->data= newdataadr(fd, pf->data);
1103         }
1104         
1105         return pf;
1106 }
1107
1108 /* ************ READ SCRIPTLINK *************** */
1109
1110 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1111 {
1112         int i;
1113
1114         for(i=0; i<slink->totscript; i++) {
1115                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1116         }
1117 }               
1118
1119 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1120 {
1121         slink->scripts= newdataadr(fd, slink->scripts); 
1122         slink->flag= newdataadr(fd, slink->flag);       
1123
1124         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1125                 int a;
1126                 
1127                 for(a=0; a<slink->totscript; a++) {
1128                         SWITCH_SHORT(slink->flag[a]);
1129                 }
1130         }
1131 }
1132
1133 /* ************ READ IKA ***************** */
1134
1135 static void lib_link_ika(FileData *fd, Main *main)
1136 {
1137         Ika *ika;
1138         int a;
1139         Deform *def;
1140         
1141         ika= main->ika.first;
1142         while(ika) {
1143                 if(ika->id.flag & LIB_NEEDLINK) {
1144                         
1145                         ika->parent= newlibadr(fd, ika->id.lib, ika->parent);
1146                         
1147                         a= ika->totdef;
1148                         def= ika->def;
1149                         while(a--) {
1150                                 def->ob=  newlibadr(fd, ika->id.lib, def->ob);
1151                                 def++;
1152                         }
1153                         ika->id.flag -= LIB_NEEDLINK;
1154                 }
1155                 ika= ika->id.next;
1156         }
1157 }
1158
1159 static void direct_link_ika(FileData *fd, Ika *ika)
1160 {
1161         link_list(fd, &ika->limbbase);
1162
1163         ika->def= newdataadr(fd, ika->def);
1164
1165         /* error from V.138 and older */
1166         if(ika->def==0) ika->totdef= 0;
1167 }
1168
1169 /* ************ READ ARMATURE ***************** */
1170
1171 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1172 {
1173         bActionStrip *strip;
1174
1175         for (strip=striplist->first; strip; strip=strip->next){
1176                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1177                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1178         };
1179 }
1180
1181 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1182 {
1183         bConstraintChannel *chan;
1184
1185         for (chan=chanbase->first; chan; chan=chan->next){
1186                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1187         }
1188 }
1189
1190 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1191 {
1192         bConstraint *con;
1193
1194         for (con = conlist->first; con; con=con->next) {
1195                 /*  patch for error introduced by changing constraints (dunno how) */
1196                 if(con->data==NULL) {
1197                         con->type= CONSTRAINT_TYPE_NULL;
1198                 }
1199                 
1200                 switch (con->type) {
1201                 case CONSTRAINT_TYPE_ACTION:
1202                         {
1203                                 bActionConstraint *data;
1204                                 data= ((bActionConstraint*)con->data);
1205                                 data->tar = newlibadr(fd, id->lib, data->tar);
1206                                 data->act = newlibadr(fd, id->lib, data->act);
1207                         }
1208                         break;
1209                 case CONSTRAINT_TYPE_LOCLIKE:
1210                         {
1211                                 bLocateLikeConstraint *data;
1212                                 data= ((bLocateLikeConstraint*)con->data);
1213                                 data->tar = newlibadr(fd, id->lib, data->tar);
1214                         };
1215                         break;
1216                 case CONSTRAINT_TYPE_ROTLIKE:
1217                         {
1218                                 bRotateLikeConstraint *data;
1219                                 data= ((bRotateLikeConstraint*)con->data);
1220                                 data->tar = newlibadr(fd, id->lib, data->tar);
1221                         };
1222                         break;
1223                 case CONSTRAINT_TYPE_KINEMATIC:
1224                         {
1225                                 bKinematicConstraint *data;
1226                                 data = ((bKinematicConstraint*)con->data);
1227                                 data->tar = newlibadr(fd, id->lib, data->tar);
1228                         }
1229                         break;
1230                 case CONSTRAINT_TYPE_TRACKTO:
1231                         {
1232                                 bTrackToConstraint *data;
1233                                 data = ((bTrackToConstraint*)con->data);
1234                                 data->tar = newlibadr(fd, id->lib, data->tar);
1235                         }
1236                         break;
1237                 case CONSTRAINT_TYPE_LOCKTRACK:
1238                         {
1239                                 bLockTrackConstraint *data;
1240                                 data= ((bLockTrackConstraint*)con->data);
1241                                 data->tar = newlibadr(fd, id->lib, data->tar);
1242                         };
1243                         break;
1244                 case CONSTRAINT_TYPE_FOLLOWPATH:
1245                         {
1246                                 bFollowPathConstraint *data;
1247                                 data= ((bFollowPathConstraint*)con->data);
1248                                 data->tar = newlibadr(fd, id->lib, data->tar);
1249                         };
1250                         break;
1251                 case CONSTRAINT_TYPE_NULL:
1252                         break;
1253                 }
1254         }
1255 }
1256
1257 static void direct_link_constraints(FileData *fd, ListBase *lb)
1258 {
1259         bConstraint *cons;
1260
1261         link_list(fd, lb);
1262         for (cons=lb->first; cons; cons=cons->next) {
1263                 cons->data = newdataadr(fd, cons->data);
1264                 switch (cons->type) {
1265                 default:
1266                         break;
1267                 }
1268                 // Link data
1269         }
1270 }
1271
1272 static void lib_link_bone(FileData *fd, ID *id, Bone *bone)
1273 {
1274         Bone *curBone;
1275
1276 //      lib_link_constraints(fd, id, &bone->constraints);
1277
1278         for (curBone=bone->childbase.first; curBone; curBone=curBone->next) {
1279                 lib_link_bone(fd, id, curBone);
1280         }
1281 }
1282
1283
1284 static void lib_link_pose(FileData *fd, ID *id, bPose *pose)
1285 {
1286         bPoseChannel *chan;
1287
1288         if (!pose)
1289                 return;
1290
1291         for (chan = pose->chanbase.first; chan; chan=chan->next) {
1292                 lib_link_constraints(fd, id, &chan->constraints);
1293         }
1294 }
1295
1296 static void lib_link_armature(FileData *fd, Main *main)
1297 {
1298         bArmature *arm;
1299         Bone *bone;
1300
1301         arm= main->armature.first;
1302
1303         while(arm) {
1304                 if(arm->id.flag & LIB_NEEDLINK) {
1305                         arm->id.flag -= LIB_NEEDLINK;
1306                 }
1307
1308                 for (bone=arm->bonebase.first; bone; bone=bone->next) {
1309                         lib_link_bone(fd, &arm->id, bone);
1310                 }
1311                 
1312                 arm= arm->id.next;
1313         }
1314 }
1315
1316 static void lib_link_action(FileData *fd, Main *main)
1317 {
1318         bAction *act;
1319         bActionChannel *chan;
1320         
1321         act= main->action.first;
1322         while(act) {
1323                 if(act->id.flag & LIB_NEEDLINK) {
1324                         act->id.flag -= LIB_NEEDLINK;
1325                         
1326                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1327                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1328                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1329                         }
1330                         
1331                 }
1332                 act= act->id.next;
1333         }
1334 }
1335
1336 static void direct_link_bones(FileData *fd, Bone* bone)
1337 {
1338         Bone    *child;
1339
1340         bone->parent= newdataadr(fd, bone->parent);
1341
1342         link_list(fd, &bone->childbase);
1343
1344         for (child=bone->childbase.first; child; child=child->next) {
1345                 direct_link_bones(fd, child);
1346         }
1347 }
1348
1349
1350 static void direct_link_action(FileData *fd, bAction *act)
1351 {
1352         bActionChannel *achan;
1353
1354         link_list(fd, &act->chanbase);
1355         
1356         for (achan = act->chanbase.first; achan; achan=achan->next)
1357                 link_list(fd, &achan->constraintChannels);
1358
1359 }
1360
1361 static void direct_link_armature(FileData *fd, bArmature *arm)
1362 {
1363         Bone    *bone; 
1364
1365         link_list(fd, &arm->bonebase);
1366
1367         bone=arm->bonebase.first;
1368         while (bone) {
1369                 direct_link_bones(fd, bone);
1370                 bone=bone->next;
1371         }
1372 }
1373
1374 /* ************ READ CAMERA ***************** */
1375
1376 static void lib_link_camera(FileData *fd, Main *main)
1377 {
1378         Camera *ca;
1379         
1380         ca= main->camera.first;
1381         while(ca) {
1382                 if(ca->id.flag & LIB_NEEDLINK) {
1383                         
1384                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1385
1386                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1387                         
1388                         ca->id.flag -= LIB_NEEDLINK;
1389                 }
1390                 ca= ca->id.next;
1391         }
1392 }
1393
1394 static void direct_link_camera(FileData *fd, Camera *ca)
1395 {
1396         direct_link_scriptlink(fd, &ca->scriptlink);
1397 }
1398
1399         
1400 /* ************ READ LATTICE ***************** */
1401
1402 static void lib_link_latt(FileData *fd, Main *main)
1403 {
1404         Lattice *lt;
1405         
1406         lt= main->latt.first;
1407         while(lt) {
1408                 if(lt->id.flag & LIB_NEEDLINK) {
1409                         
1410                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
1411                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
1412                         
1413                         lt->id.flag -= LIB_NEEDLINK;
1414                 }
1415                 lt= lt->id.next;
1416         }
1417 }
1418
1419 static void direct_link_latt(FileData *fd, Lattice *lt)
1420 {
1421         lt->def= newdataadr(fd, lt->def);
1422 }
1423
1424 /* ************ READ LAMP ***************** */
1425
1426 static void lib_link_lamp(FileData *fd, Main *main)
1427 {
1428         Lamp *la;
1429         MTex *mtex;
1430         int a;
1431         
1432         la= main->lamp.first;
1433         while(la) {
1434                 if(la->id.flag & LIB_NEEDLINK) {
1435
1436                         for(a=0; a<8; a++) {
1437                                 mtex= la->mtex[a];
1438                                 if(mtex) {
1439                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1440                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1441                                 }
1442                         }
1443                 
1444                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1445                         
1446                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1447                         
1448                         la->id.flag -= LIB_NEEDLINK;
1449                 }
1450                 la= la->id.next;
1451         }
1452 }
1453
1454 static void direct_link_lamp(FileData *fd, Lamp *la)
1455 {
1456         int a;
1457
1458         direct_link_scriptlink(fd, &la->scriptlink);
1459                 
1460         for(a=0; a<8; a++) {
1461                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1462         }
1463 }
1464
1465 /* ************ READ keys ***************** */
1466
1467 static void lib_link_key(FileData *fd, Main *main)
1468 {
1469         Key *key;
1470         
1471         key= main->key.first;
1472         while(key) {
1473                 if(key->id.flag & LIB_NEEDLINK) {
1474                         
1475                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1476                         key->from= newlibadr(fd, key->id.lib, key->from);
1477                         
1478                         key->id.flag -= LIB_NEEDLINK;
1479                 }
1480                 key= key->id.next;
1481         }
1482 }
1483
1484 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1485 {
1486         int elemsize, a, b;
1487         char *data, *poin, *cp;
1488         
1489         elemsize= key->elemsize;
1490         data= kb->data;
1491
1492         for(a=0; a<kb->totelem; a++) {
1493         
1494                 cp= key->elemstr;       
1495                 poin= data;
1496                 
1497                 while( cp[0] ) {        /* cp[0]==amount */
1498                 
1499                         switch(cp[1]) {         /* cp[1]= type */
1500                         case IPO_FLOAT:
1501                         case IPO_BPOINT:
1502                         case IPO_BEZTRIPLE:
1503                                 b= cp[0];
1504                                 while(b--) {
1505                                         SWITCH_INT((*poin));
1506                                         poin+= 4;
1507                                 }
1508                                 break;
1509                         }
1510
1511                         cp+= 2;
1512                         
1513                 }
1514                 data+= elemsize;
1515         }
1516 }
1517
1518 static void direct_link_key(FileData *fd, Key *key)
1519 {
1520         KeyBlock *kb;
1521         
1522         link_list(fd, &(key->block));
1523         
1524         key->refkey= newdataadr(fd, key->refkey);
1525         
1526         kb= key->block.first;
1527         while(kb) {
1528                 
1529                 kb->data= newdataadr(fd, kb->data);
1530                 
1531                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1532                         switch_endian_keyblock(key, kb);
1533                         
1534                 kb= kb->next;
1535         }
1536 }
1537
1538 /* ************ READ mball ***************** */
1539
1540 static void lib_link_mball(FileData *fd, Main *main)
1541 {
1542         MetaBall *mb;
1543         int a;
1544         
1545         mb= main->mball.first;
1546         while(mb) {
1547                 if(mb->id.flag & LIB_NEEDLINK) {
1548                         
1549                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1550
1551                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1552
1553                         mb->id.flag -= LIB_NEEDLINK;
1554                 }
1555                 mb= mb->id.next;
1556         }
1557 }
1558
1559 static void direct_link_mball(FileData *fd, MetaBall *mb)
1560 {
1561         mb->mat= newdataadr(fd, mb->mat);
1562         test_pointer_array(fd, (void **)&mb->mat);
1563
1564         link_list(fd, &(mb->elems));
1565         
1566         mb->disp.first= mb->disp.last= 0;
1567         
1568         mb->bb= 0;
1569 }
1570
1571 /* ************ READ WORLD ***************** */
1572
1573 static void lib_link_world(FileData *fd, Main *main)
1574 {
1575         World *wrld;
1576         MTex *mtex;
1577         int a;
1578         
1579         wrld= main->world.first;
1580         while(wrld) {
1581                 if(wrld->id.flag & LIB_NEEDLINK) {
1582                 
1583                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
1584                         
1585                         for(a=0; a<8; a++) {
1586                                 mtex= wrld->mtex[a];
1587                                 if(mtex) {
1588                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
1589                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
1590                                 }
1591                         }
1592
1593                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
1594                         
1595                         wrld->id.flag -= LIB_NEEDLINK;
1596                 }
1597                 wrld= wrld->id.next;
1598         }
1599 }
1600
1601 static void direct_link_world(FileData *fd, World *wrld)
1602 {
1603         int a;
1604
1605         direct_link_scriptlink(fd, &wrld->scriptlink);
1606         
1607         for(a=0; a<8; a++) {
1608                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
1609         }
1610 }
1611
1612
1613 /* ************ READ IPO ***************** */
1614
1615 static void lib_link_ipo(FileData *fd, Main *main)
1616 {
1617         Ipo *ipo;
1618         
1619         ipo= main->ipo.first;
1620         while(ipo) {
1621                 if(ipo->id.flag & LIB_NEEDLINK) {
1622                         
1623                         ipo->id.flag -= LIB_NEEDLINK;
1624                 }
1625                 ipo= ipo->id.next;
1626         }
1627 }
1628
1629 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1630 {
1631         IpoCurve *icu;
1632         
1633         link_list(fd, &(ipo->curve));
1634         icu= ipo->curve.first;
1635         while(icu) {
1636                 icu->bezt= newdataadr(fd, icu->bezt);
1637                 icu->bp= newdataadr(fd, icu->bp);
1638                 icu= icu->next;
1639         }
1640 }
1641
1642 /* ************ READ VFONT ***************** */
1643
1644 static void lib_link_vfont(FileData *fd, Main *main)
1645 {
1646         VFont *vf;
1647         
1648         vf= main->vfont.first;
1649         while(vf) {
1650                 if(vf->id.flag & LIB_NEEDLINK) {
1651                         vf->id.flag -= LIB_NEEDLINK;
1652                 }
1653                 vf= vf->id.next;
1654         }       
1655 }
1656
1657 static void direct_link_vfont(FileData *fd, VFont *vf)
1658 {
1659         vf->data= NULL;
1660         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
1661 }
1662
1663 /* ************ READ TEXT ****************** */
1664
1665 static void lib_link_text(FileData *fd, Main *main)
1666 {
1667         Text *text;
1668         
1669         text= main->text.first;
1670         while(text) {
1671                 if(text->id.flag & LIB_NEEDLINK) {
1672                         text->id.flag -= LIB_NEEDLINK;
1673                 }
1674                 text= text->id.next;
1675         }       
1676 }
1677
1678 static void direct_link_text(FileData *fd, Text *text)
1679 {
1680         TextLine *ln;
1681         
1682         text->name= newdataadr(fd, text->name);
1683         
1684         text->undo_pos= -1;
1685         text->undo_len= TXT_INIT_UNDO;
1686         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
1687         
1688         text->compiled= NULL;
1689                 
1690 /*
1691         if(text->flags & TXT_ISEXT) {
1692                 reopen_text(text);
1693         } else {
1694 */
1695
1696         link_list(fd, &text->lines);
1697
1698         text->curl= newdataadr(fd, text->curl);
1699         text->sell= newdataadr(fd, text->sell);
1700
1701         ln= text->lines.first;
1702         while(ln) {
1703                 ln->line= newdataadr(fd, ln->line);
1704
1705                 if (ln->len != (int) strlen(ln->line)) {
1706                         printf("Error loading text, line lengths differ\n");
1707                         ln->len = strlen(ln->line);
1708                 }
1709
1710                 ln= ln->next;
1711         }
1712
1713         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
1714
1715         text->id.us= 1;
1716 }
1717
1718 /* ************ READ IMAGE ***************** */
1719
1720 static void lib_link_image(FileData *fd, Main *main)
1721 {
1722         Image *ima;
1723         
1724         ima= main->image.first;
1725         while (ima) {
1726                 if(ima->id.flag & LIB_NEEDLINK) {
1727                         
1728                         ima->id.flag -= LIB_NEEDLINK;
1729                 }
1730                 ima= ima->id.next;
1731         }
1732 }
1733
1734 static void direct_link_image(FileData *fd, Image *ima)
1735 {
1736         ima->ibuf= 0;
1737         ima->anim= 0;
1738         memset(ima->mipmap, 0, sizeof(ima->mipmap));
1739         ima->repbind= 0;
1740         ima->bindcode= 0;
1741                 
1742         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
1743
1744         ima->ok= 1;
1745 }
1746
1747
1748 /* ************ READ CURVE ***************** */
1749
1750 static void lib_link_curve(FileData *fd, Main *main)
1751 {
1752         Curve *cu;
1753         int a;
1754         
1755         cu= main->curve.first;
1756         while(cu) {
1757                 if(cu->id.flag & LIB_NEEDLINK) {
1758                 
1759                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
1760
1761                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
1762                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
1763                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
1764
1765                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
1766                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
1767                         
1768                         cu->id.flag -= LIB_NEEDLINK;
1769                 }
1770                 cu= cu->id.next;
1771         }
1772 }
1773
1774
1775 static void switch_endian_knots(Nurb *nu)
1776 {
1777         int len;
1778         
1779         if(nu->knotsu) {
1780                 len= KNOTSU(nu);
1781                 while(len--) {
1782                         SWITCH_INT(nu->knotsu[len]);
1783                 }
1784         }
1785         if(nu->knotsv) {
1786                 len= KNOTSV(nu);
1787                 while(len--) {
1788                         SWITCH_INT(nu->knotsv[len]);
1789                 }
1790         }
1791 }
1792
1793 static void direct_link_curve(FileData *fd, Curve *cu)
1794 {
1795         Nurb *nu;
1796         
1797         cu->mat= newdataadr(fd, cu->mat);
1798         test_pointer_array(fd, (void **)&cu->mat);
1799         cu->str= newdataadr(fd, cu->str);
1800
1801         if(cu->vfont==0) link_list(fd, &(cu->nurb));
1802         else {
1803                 cu->nurb.first=cu->nurb.last= 0;
1804         }
1805         
1806         cu->bev.first=cu->bev.last= 0;
1807         cu->disp.first=cu->disp.last= 0;
1808         cu->path= 0;
1809         
1810         nu= cu->nurb.first;
1811         while(nu) {
1812                 nu->bezt= newdataadr(fd, nu->bezt);
1813                 nu->bp= newdataadr(fd, nu->bp);
1814                 nu->knotsu= newdataadr(fd, nu->knotsu);
1815                 nu->knotsv= newdataadr(fd, nu->knotsv);
1816
1817                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1818                         switch_endian_knots(nu);
1819                 }
1820                 
1821                 nu= nu->next;
1822         }
1823         cu->bb= 0;
1824 }
1825
1826 /* ************ READ TEX ***************** */
1827
1828 static void lib_link_texture(FileData *fd, Main *main)
1829 {
1830         Tex *tex;
1831         
1832         tex= main->tex.first;
1833         while(tex) {
1834                 if(tex->id.flag & LIB_NEEDLINK) {
1835                 
1836                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
1837                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
1838                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
1839                         
1840                         tex->id.flag -= LIB_NEEDLINK;
1841                 }
1842                 tex= tex->id.next;
1843         }
1844 }
1845
1846 static void direct_link_texture(FileData *fd, Tex *tex)
1847 {
1848         tex->plugin= newdataadr(fd, tex->plugin);
1849         if(tex->plugin) {
1850                 tex->plugin->handle= 0;
1851                 open_plugin_tex(tex->plugin);
1852         }
1853         tex->coba= newdataadr(fd, tex->coba);
1854         tex->env= newdataadr(fd, tex->env);
1855         if(tex->env) {
1856                 tex->env->ima= 0;
1857                 memset(tex->env->cube, 0, 6*sizeof(void *));
1858                 tex->env->ok= 0;
1859         }
1860 }
1861
1862
1863
1864 /* ************ READ MATERIAL ***************** */
1865
1866 static void lib_link_material(FileData *fd, Main *main)
1867 {
1868         Material *ma;
1869         MTex *mtex;
1870         int a;
1871         
1872         ma= main->mat.first;
1873         while(ma) {
1874                 if(ma->id.flag & LIB_NEEDLINK) {
1875                 
1876                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
1877                         
1878                         for(a=0; a<8; a++) {
1879                                 mtex= ma->mtex[a];
1880                                 if(mtex) {
1881                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
1882                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
1883                                 }
1884                         }
1885                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
1886                         ma->id.flag -= LIB_NEEDLINK;
1887                 }
1888                 ma= ma->id.next;
1889         }
1890 }
1891
1892 static void direct_link_material(FileData *fd, Material *ma)
1893 {
1894         int a;
1895         
1896         direct_link_scriptlink(fd, &ma->scriptlink);
1897         
1898         for(a=0; a<8; a++) {
1899                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
1900         }
1901         ma->ren= 0;     /* should not be needed, nevertheless... */
1902 }
1903
1904 /* ************ READ MESH ***************** */
1905
1906 static void lib_link_mesh(FileData *fd, Main *main)
1907 {
1908         Mesh *me;
1909                 
1910         me= main->mesh.first;
1911         while(me) {
1912                 if(me->id.flag & LIB_NEEDLINK) {
1913                         int i;
1914
1915                         /* this check added for python created meshes */
1916                         if(me->mat) {
1917                                 for(i=0; i<me->totcol; i++)
1918                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
1919                         }
1920                         else me->totcol= 0;
1921                         
1922                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
1923                         me->key= newlibadr_us(fd, me->id.lib, me->key);
1924                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
1925                         
1926                         if(me->tface) {
1927                                 TFace *tfaces= me->tface;
1928                                 
1929                                 for (i=0; i<me->totface; i++) {
1930                                         TFace *tf= &tfaces[i];
1931
1932                                         tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
1933                                         if(tf->tpage) {
1934                                                 Image *ima= tf->tpage;
1935                                                 if(ima->id.us==0)
1936                                                         ima->id.us= 1;
1937                                         }
1938                                 }
1939                         }
1940                         me->id.flag -= LIB_NEEDLINK;
1941                 }
1942                 me= me->id.next;
1943         }
1944 }
1945
1946 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
1947 {
1948         int     i, j;
1949
1950         if (!mdverts)
1951                 return;
1952
1953         for (i=0; i<count; i++) {
1954                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
1955                 if (!mdverts[i].dw)
1956                         mdverts[i].totweight=0;
1957
1958                 for (j=0; j< mdverts[i].totweight; j++) {
1959                         mdverts[i].dw[j].data = NULL;   // not saved in file, clear pointer
1960                 }
1961         }
1962 }
1963
1964 static void direct_link_mesh(FileData *fd, Mesh *mesh)
1965 {
1966         mesh->mat= newdataadr(fd, mesh->mat);
1967         test_pointer_array(fd, (void **)&mesh->mat);
1968         mesh->mvert= newdataadr(fd, mesh->mvert);
1969
1970         mesh->dvert= newdataadr(fd, mesh->dvert);
1971         direct_link_dverts(fd, mesh->totvert, mesh->dvert);
1972
1973         mesh->mface= newdataadr(fd, mesh->mface);
1974         mesh->tface= newdataadr(fd, mesh->tface);
1975         mesh->mcol= newdataadr(fd, mesh->mcol);
1976         mesh->msticky= newdataadr(fd, mesh->msticky);
1977         
1978         mesh->disp.first= mesh->disp.last= 0;
1979         mesh->bb= 0;
1980         mesh->oc= 0;
1981         mesh->dface= 0;
1982         mesh->orco= 0;
1983         
1984         if (mesh->tface) {
1985                 TFace *tfaces= mesh->tface;
1986                 int i;
1987                 
1988                 for (i=0; i<mesh->totface; i++) {
1989                         TFace *tf= &tfaces[i];
1990
1991                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1992                                 SWITCH_INT(tf->col[0]);
1993                                 SWITCH_INT(tf->col[1]);
1994                                 SWITCH_INT(tf->col[2]);
1995                                 SWITCH_INT(tf->col[3]);
1996                         }
1997                 }
1998         }
1999 }
2000
2001 /* ************ READ OBJECT ***************** */
2002
2003 static void lib_link_object(FileData *fd, Main *main)
2004 {
2005         Object *ob;
2006         bSensor *sens;
2007         bController *cont;
2008         bActuator *act;
2009
2010         void *poin;
2011         int warn=0, a;
2012         
2013         ob= main->object.first;
2014         while(ob) {
2015                 if(ob->id.flag & LIB_NEEDLINK) {
2016         
2017                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2018                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2019                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2020                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2021
2022 //                      ob->activecon = newglobadr(fd, ob->activecon);
2023
2024                         poin= ob->data;         
2025                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2026                         
2027                         if(ob->data==NULL && poin!=NULL) {
2028                                 ob->type= OB_EMPTY;
2029                                 warn= 1;
2030                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2031                                 else printf("Object %s lost data. Lib:%x\n", ob->id.name+2, (unsigned int) ob->id.lib);
2032                         }
2033                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2034                         
2035                         ob->id.flag -= LIB_NEEDLINK;
2036                         /* if id.us==0 a new base will be created later on */
2037                         
2038                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2039                         lib_link_pose(fd, &ob->id, ob->pose);
2040                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2041                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2042                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2043                         
2044
2045                         sens= ob->sensors.first;
2046                         while(sens) {
2047                                 for(a=0; a<sens->totlinks; a++) {
2048                                         sens->links[a]= newglobadr(fd, sens->links[a]);
2049                                 }
2050                                 if(sens->type==SENS_TOUCH) {
2051                                         bTouchSensor *ts= sens->data;
2052                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2053                                 }
2054                                 else if(sens->type==SENS_MESSAGE) {
2055                                         bMessageSensor *ms= sens->data;
2056                                         ms->fromObject=
2057                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2058                                 }
2059                                 sens= sens->next;
2060                         }
2061                         
2062                         cont= ob->controllers.first;
2063                         while(cont) {
2064                                 for(a=0; a<cont->totlinks; a++) {
2065                                         cont->links[a]= newglobadr(fd, cont->links[a]);
2066                                 }
2067                                 if(cont->type==CONT_PYTHON) {
2068                                         bPythonCont *pc= cont->data;
2069                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2070                                 }
2071                                 cont->slinks= NULL;
2072                                 cont->totslinks= 0;
2073                                 
2074                                 cont= cont->next;
2075                         }
2076                         
2077                         act= ob->actuators.first;
2078                         while(act) {
2079                                 if(act->type==ACT_SOUND) {
2080                                         bSoundActuator *sa= act->data;
2081                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2082                                 }
2083                                 else if(act->type==ACT_CD) {
2084                                         /* bCDActuator *cda= act->data; */
2085                                 }
2086                                 else if(act->type==ACT_GAME) {
2087                                         /* bGameActuator *ga= act->data; */
2088                                 }
2089                                 else if(act->type==ACT_CAMERA) {
2090                                         bCameraActuator *ca= act->data;
2091                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2092                                 }
2093                                         /* leave this one, it's obsolete but necessary to read for conversion */
2094                                 else if(act->type==ACT_ADD_OBJECT) {
2095                                         bAddObjectActuator *eoa= act->data;
2096                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2097                                 }
2098                                 else if(act->type==ACT_EDIT_OBJECT) {
2099                                         bEditObjectActuator *eoa= act->data;
2100                                         if(eoa==NULL) {
2101                                                 init_actuator(act);
2102                                         }
2103                                         eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2104                                         eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2105                                 }
2106                                 else if(act->type==ACT_SCENE) {
2107                                         bSceneActuator *sa= act->data;
2108                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2109                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2110                                 }
2111                                 else if(act->type==ACT_ACTION) {
2112                                         bActionActuator *aa= act->data;
2113                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2114                                 }
2115                                 else if(act->type==ACT_PROPERTY) {
2116                                         bPropertyActuator *pa= act->data;
2117                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2118                                 }
2119                                 else if(act->type==ACT_MESSAGE) {
2120                                         bMessageActuator *ma= act->data;
2121                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2122                                 }
2123                                 act= act->next;
2124                         }
2125                         
2126                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2127                 }
2128                 ob= ob->id.next;
2129         }
2130         
2131         if(warn) error("WARNING IN CONSOLE");
2132 }
2133
2134
2135 static void direct_link_pose(FileData *fd, bPose *pose) {
2136
2137         bPoseChannel *chan;
2138
2139         if (!pose)
2140                 return;
2141
2142         link_list(fd, &pose->chanbase);
2143
2144         for (chan = pose->chanbase.first; chan; chan=chan->next) {
2145                 direct_link_constraints(fd, &chan->constraints);
2146         }
2147
2148 }
2149
2150 static void direct_link_object(FileData *fd, Object *ob)
2151 {
2152         PartEff *paf;
2153         bProperty *prop;
2154         bSensor *sens;
2155         bController *cont;
2156         bActuator *act;
2157
2158         ob->disp.first=ob->disp.last= 0;
2159
2160         ob->pose= newdataadr(fd, ob->pose);
2161         direct_link_pose(fd, ob->pose);
2162         
2163         link_list(fd, &ob->defbase);
2164         link_list(fd, &ob->nlastrips);
2165         link_list(fd, &ob->constraintChannels);
2166
2167         ob->activecon = newdataadr(fd, ob->activecon);
2168
2169         direct_link_scriptlink(fd, &ob->scriptlink);
2170
2171         ob->mat= newdataadr(fd, ob->mat);
2172         test_pointer_array(fd, (void **)&ob->mat);
2173         link_list(fd, &ob->effect);
2174         paf= ob->effect.first;
2175         while(paf) {
2176                 if(paf->type==EFF_PARTICLE) {
2177                         paf->keys= 0;
2178                 }
2179                 if(paf->type==EFF_WAVE) {
2180                         
2181                 }
2182                 paf= paf->next;
2183         }
2184
2185         link_list(fd, &ob->network);
2186         
2187         link_list(fd, &ob->prop);
2188         prop= ob->prop.first;
2189         while(prop) {
2190                 prop->poin= newdataadr(fd, prop->poin);
2191                 if(prop->poin==0) prop->poin= &prop->data;
2192                 prop= prop->next;
2193         }
2194
2195         link_list(fd, &ob->sensors);
2196         sens= ob->sensors.first;
2197         while(sens) {
2198                 sens->data= newdataadr(fd, sens->data); 
2199                 sens->links= newdataadr(fd, sens->links);
2200                 test_pointer_array(fd, (void **)&sens->links);
2201                 sens= sens->next;
2202         }
2203
2204         direct_link_constraints(fd, &ob->constraints);
2205
2206         link_glob_list(fd, &ob->controllers);
2207         cont= ob->controllers.first;
2208         while(cont) {
2209                 cont->data= newdataadr(fd, cont->data);
2210                 cont->links= newdataadr(fd, cont->links);
2211                 test_pointer_array(fd, (void **)&cont->links);
2212                 cont= cont->next;
2213         }
2214
2215         link_glob_list(fd, &ob->actuators);
2216         act= ob->actuators.first;
2217         while(act) {
2218                 act->data= newdataadr(fd, act->data);
2219                 act= act->next;
2220         }
2221
2222         ob->bb= 0;
2223 }
2224
2225 /* ************ READ SCENE ***************** */
2226
2227 static void lib_link_scene(FileData *fd, Main *main)
2228 {
2229         Scene *sce;
2230         Base *base, *next;
2231         Editing *ed;
2232         Sequence *seq;
2233         
2234         sce= main->scene.first;
2235         while(sce) {
2236                 if(sce->id.flag & LIB_NEEDLINK) {
2237                         sce->id.us= 1;
2238                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
2239                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
2240                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
2241                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
2242                         sce->group= newlibadr_us(fd, sce->id.lib, sce->group);
2243
2244                         base= sce->base.first;
2245                         while(base) {
2246                                 next= base->next;
2247                                 
2248                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
2249
2250                                 base->object= newlibadr_us_type(fd, ID_OB, base->object);
2251                                 
2252                                 if(base->object==0) {
2253                                         printf("LIB ERROR: base removed\n");
2254                                         BLI_remlink(&sce->base, base);
2255                                         if(base==sce->basact) sce->basact= 0;
2256                                         MEM_freeN(base);
2257                                 }
2258                                 base= next;
2259                         }
2260                         
2261                         ed= sce->ed;
2262                         if(ed) {
2263                                 WHILE_SEQ(ed->seqbasep) {
2264                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
2265                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
2266                                         if(seq->sound) {
2267                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
2268                                                 if (seq->sound) {
2269                                                         seq->sound->id.us++;
2270                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
2271                                                 }
2272                                         }
2273                                         seq->anim= 0;
2274                                 }
2275                                 END_SEQ
2276                         }
2277                         sce->id.flag -= LIB_NEEDLINK;
2278                 }
2279                 
2280                 lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
2281                 
2282                 sce= sce->id.next;
2283         }
2284 }
2285
2286 static void link_recurs_seq(FileData *fd, ListBase *lb)
2287 {
2288         Sequence *seq;
2289
2290         link_list(fd, lb);
2291         seq= lb->first;
2292         while(seq) {
2293                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
2294                 seq= seq->next;
2295         }
2296 }
2297
2298 static void direct_link_scene(FileData *fd, Scene *sce)
2299 {
2300         Editing *ed;
2301         Sequence *seq;
2302         StripElem *se;
2303         int a;
2304         
2305         link_list(fd, &(sce->base));
2306
2307         sce->basact= newdataadr(fd, sce->basact);
2308
2309         sce->radio= newdataadr(fd, sce->radio);
2310         sce->fcam= newdataadr(fd, sce->fcam);
2311
2312         sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
2313         if (sce->r.avicodecdata) {
2314                 sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
2315                 sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
2316         }
2317
2318         sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
2319         if (sce->r.qtcodecdata) {
2320                 sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
2321         }
2322
2323         if(sce->ed) {
2324                 ed= sce->ed= newdataadr(fd, sce->ed);
2325                 
2326                 ed->metastack.first= ed->metastack.last= 0;
2327                 
2328                 /* recursive link sequences, lb will be correctly initialized */
2329                 link_recurs_seq(fd, &ed->seqbase);
2330                 
2331                 ed->seqbasep= &ed->seqbase;
2332                 
2333                 WHILE_SEQ(ed->seqbasep) {
2334                         seq->seq1= newdataadr(fd, seq->seq1);
2335                         seq->seq2= newdataadr(fd, seq->seq2);
2336                         seq->seq3= newdataadr(fd, seq->seq3);
2337                         /* a patch: after introduction of effects with 3 input strips */
2338                         if(seq->seq3==0) seq->seq3= seq->seq2;
2339                         
2340                         seq->curelem= 0;
2341                         
2342                         seq->plugin= newdataadr(fd, seq->plugin);
2343                         if(seq->plugin) open_plugin_seq(seq->plugin, seq->name+2);
2344         
2345                         seq->strip= newdataadr(fd, seq->strip);
2346                         if(seq->strip && seq->strip->done==0) {
2347                                 seq->strip->done= 1;
2348                                 
2349                                 /* standard: strips from effects/metas are not written, but are mallocced */
2350                                 
2351                                 if(seq->type==SEQ_IMAGE) {
2352                                         seq->strip->stripdata= newdataadr(fd, seq->strip->stripdata);
2353                                         se= seq->strip->stripdata;
2354                                         if(se) {
2355                                                 for(a=0; a<seq->strip->len; a++, se++) {
2356                                                         se->ok= 1;
2357                                                         se->ibuf= 0;
2358                                                 }
2359                                         }
2360                                 }
2361                                 else if(seq->type==SEQ_MOVIE) {
2362                                         /* only first stripelem is in file */
2363                                         se= newdataadr(fd, seq->strip->stripdata);
2364                                         
2365                                         if(se) {
2366                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2367                                                 *seq->strip->stripdata= *se;
2368                                                 MEM_freeN(se);
2369                                                 
2370                                                 se= seq->strip->stripdata;
2371                                         
2372                                                 for(a=0; a<seq->strip->len; a++, se++) {
2373                                                         se->ok= 1;
2374                                                         se->ibuf= 0;
2375                                                         se->nr= a + 1;
2376                                                 }
2377                                         }
2378                                 }
2379                                 else if(seq->type==SEQ_SOUND) {
2380                                         /* only first stripelem is in file */
2381                                         se= newdataadr(fd, seq->strip->stripdata);
2382                                         
2383                                         if(se) {
2384                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2385                                                 *seq->strip->stripdata= *se;
2386                                                 MEM_freeN(se);
2387                                                 
2388                                                 se= seq->strip->stripdata;
2389                                                                                         
2390                                                 for(a=0; a<seq->strip->len; a++, se++) {
2391                                                         se->ok= 2; /* why? */
2392                                                         se->ibuf= 0;
2393                                                         se->nr= a + 1;
2394                                                 }
2395                                         }
2396                                 }                               
2397                                 else if(seq->len>0) 
2398                                         seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
2399
2400                         }
2401                 }
2402                 END_SEQ
2403         }
2404
2405         direct_link_scriptlink(fd, &sce->scriptlink);
2406 }
2407
2408 /* ************ READ SCREEN ***************** */
2409
2410 static void lib_link_screen(FileData *fd, Main *main)
2411 {
2412         bScreen *sc;
2413         ScrArea *sa;
2414         
2415         sc= main->screen.first;
2416         while(sc) {
2417                 if(sc->id.flag & LIB_NEEDLINK) {
2418                         sc->id.us= 1;
2419                         sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
2420                         
2421                         sa= sc->areabase.first;
2422                         while(sa) {
2423                                 SpaceLink *sl;
2424                                 
2425                                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
2426         
2427                                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2428                                         if(sl->spacetype==SPACE_VIEW3D) {
2429                                                 View3D *v3d= (View3D*) sl;
2430                                                 
2431                                                 v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
2432                                                 
2433                                                 if(v3d->bgpic) {
2434                                                         v3d->bgpic->ima= newlibadr_us(fd, sc->id.lib, v3d->bgpic->ima);
2435                                                         v3d->bgpic->tex= newlibadr_us(fd, sc->id.lib, v3d->bgpic->tex);
2436                                                         v3d->bgpic->rect= 0;
2437                                                 }
2438                                                 if(v3d->localvd) {
2439                                                         v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
2440                                                 }
2441                                         }
2442                                         else if(sl->spacetype==SPACE_IPO) {
2443                                                 SpaceIpo *sipo= (SpaceIpo *)sl;
2444                                                 sipo->editipo= 0;
2445                                                 sipo->from= newlibadr(fd, sc->id.lib, sipo->from);
2446                                                 sipo->ipokey.first= sipo->ipokey.last= 0;
2447                                                 sipo->ipo= newlibadr(fd, sc->id.lib, sipo->ipo);
2448                                         }
2449                                         else if(sl->spacetype==SPACE_BUTS) {
2450                                                 SpaceButs *sbuts= (SpaceButs *)sl;
2451                                                 sbuts->rect= 0;
2452                                                 sbuts->lockpoin= 0;
2453                                                 if(main->versionfile<132) set_rects_butspace(sbuts);
2454                                         }
2455                                         else if(sl->spacetype==SPACE_FILE) {
2456                                                 SpaceFile *sfile= (SpaceFile *)sl;
2457                                                 
2458                                                 sfile->filelist= 0;
2459                                                 sfile->libfiledata= 0;
2460                                                 sfile->returnfunc= 0;
2461                                         }
2462                                         else if(sl->spacetype==SPACE_IMASEL) {
2463                                                 check_imasel_copy((SpaceImaSel *)sl);
2464                                         }
2465                                         else if(sl->spacetype==SPACE_ACTION) {
2466                                                 SpaceAction *saction= (SpaceAction *)sl;
2467                                                 saction->action = newlibadr(fd, sc->id.lib, saction->action);
2468                                         }
2469                                         else if(sl->spacetype==SPACE_IMAGE) {
2470                                                 SpaceImage *sima= (SpaceImage *)sl;
2471                                                 
2472                                                 sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
2473                                         }
2474                                         else if(sl->spacetype==SPACE_NLA){
2475                                                 SpaceNla *snla= (SpaceNla *)sl; 
2476                                         }
2477                                         else if(sl->spacetype==SPACE_TEXT) {
2478                                                 SpaceText *st= (SpaceText *)sl;
2479                                 
2480                                                 st->text= newlibadr(fd, sc->id.lib, st->text);
2481
2482                                         }
2483                                         else if(sl->spacetype==SPACE_SCRIPT) {
2484                                                 SpaceScript *sc= (SpaceScript *)sl;
2485
2486                                                 sc->script = NULL;
2487                                         }
2488                                         else if(sl->spacetype==SPACE_OOPS) {
2489                                                 SpaceOops *so= (SpaceOops *)sl;
2490                                                 Oops *oops;
2491                                                 
2492                                                 oops= so->oops.first;
2493                                                 while(oops) {
2494                                                         oops->id= newlibadr(fd, 0, oops->id);
2495                                                         oops= oops->next;
2496                                                 }
2497                                                 so->lockpoin= 0;
2498                                         }
2499                                         else if(sl->spacetype==SPACE_SOUND) {
2500                                                 SpaceSound *ssound= (SpaceSound *)sl;
2501                                                 
2502                                                 ssound->sound= newlibadr_us(fd, sc->id.lib, ssound->sound);
2503                                         }
2504                                 }
2505                                 sa= sa->next;
2506                         }
2507                         sc->id.flag -= LIB_NEEDLINK;
2508                 }
2509                 sc= sc->id.next;
2510         }
2511 }
2512
2513 static void direct_link_screen(FileData *fd, bScreen *sc)
2514 {
2515         ScrArea *sa;
2516         ScrVert *sv;
2517         ScrEdge *se;
2518         Oops *oops;
2519
2520         link_list(fd, &(sc->vertbase));
2521         link_list(fd, &(sc->edgebase));
2522         link_list(fd, &(sc->areabase));
2523         sc->winakt= 0;
2524
2525         /* edges */
2526         se= sc->edgebase.first;
2527         while(se) {
2528                 se->v1= newdataadr(fd, se->v1);
2529                 se->v2= newdataadr(fd, se->v2);
2530                 if( (long)se->v1 > (long)se->v2) {
2531                         sv= se->v1;
2532                         se->v1= se->v2;
2533                         se->v2= sv;
2534                 }
2535                 
2536                 if(se->v1==NULL) {
2537                         printf("error reading screen... file corrupt\n");
2538                         se->v1= se->v2;
2539                 }
2540                 se= se->next;
2541         }
2542
2543         /* areas */
2544         sa= sc->areabase.first;
2545         while(sa) {
2546                 Panel *pa;
2547                 SpaceLink *sl;
2548                 
2549                 link_list(fd, &(sa->spacedata));
2550                 link_list(fd, &(sa->panels));
2551                 
2552                 for(pa= sa->panels.first; pa; pa=pa->next) {
2553                         pa->paneltab= newdataadr(fd, pa->paneltab);
2554                         pa->active= 0;
2555                 }
2556
2557                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
2558                         if (sl->spacetype==SPACE_VIEW3D) {
2559                                 View3D *v3d= (View3D*) sl;
2560                                 v3d->bgpic= newdataadr(fd, v3d->bgpic);
2561                                 v3d->localvd= newdataadr(fd, v3d->localvd);
2562                         }
2563                         else if (sl->spacetype==SPACE_OOPS) {
2564                                 SpaceOops *soops= (SpaceOops*) sl;
2565                                 link_list(fd, &(soops->oops));
2566                                 oops= soops->oops.first;
2567                                 while(oops) {
2568                                         oops->link.first= oops->link.last= 0;
2569                                         oops= oops->next;
2570                                 }
2571                         }
2572                 }
2573                 
2574                 sa->v1= newdataadr(fd, sa->v1);
2575                 sa->v2= newdataadr(fd, sa->v2);
2576                 sa->v3= newdataadr(fd, sa->v3);
2577                 sa->v4= newdataadr(fd, sa->v4);
2578                 
2579                 sa->win= sa->headwin= 0;
2580
2581                 sa->uiblocks.first= sa->uiblocks.last= NULL;
2582                 
2583                 sa= sa->next;
2584         }
2585
2586
2587 /* ********** READ LIBRARY *************** */
2588
2589
2590 static void direct_link_library(FileData *fd, Library *lib)
2591 {
2592         Main *newmain;
2593         
2594         /* new main */
2595         newmain= MEM_callocN(sizeof(Main), "directlink");
2596         BLI_addtail(&fd->mainlist, newmain);
2597         newmain->curlib= lib;
2598 }
2599
2600 static void lib_link_library(FileData *fd, Main *main)
2601 {
2602         Library *lib;
2603         
2604         lib= main->library.first;
2605         while(lib) {
2606                 lib->id.us= 1;
2607                 lib= lib->id.next;
2608         }
2609 }
2610
2611 /* ************** READ SOUND ******************* */
2612
2613 static void direct_link_sound(FileData *fd, bSound *sound)
2614 {
2615         sound->sample = NULL;
2616         sound->snd_sound = NULL;
2617
2618         sound->packedfile = direct_link_packedfile(fd, sound->packedfile);
2619         sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile);
2620 }
2621
2622 static void lib_link_sound(FileData *fd, Main *main)
2623 {
2624         bSound *sound;
2625         
2626         sound= main->sound.first;
2627         while(sound) {
2628                 if(sound->id.flag & LIB_NEEDLINK) {
2629                         sound->id.flag -= LIB_NEEDLINK;
2630                         sound->ipo= newlibadr_us(fd, sound->id.lib, sound->ipo);
2631                         sound->stream = 0;
2632                 }
2633                 sound= sound->id.next;
2634         }
2635 }
2636 /* ***************** READ GROUP *************** */
2637
2638 static void direct_link_group(FileData *fd, Group *group)
2639 {
2640         GroupObject *go;
2641         ObjectKey *ok;
2642         
2643         link_list(fd, &group->gobject);
2644         link_list(fd, &group->gkey);
2645         group->active= newdataadr(fd, group->active);
2646         
2647         go= group->gobject.first;
2648         while(go) {
2649                 link_list(fd, &go->okey);
2650                 ok= go->okey.first;
2651                 while(ok) {
2652                         ok->gkey= newdataadr(fd, ok->gkey);
2653                         ok= ok->next;
2654                 }
2655                 go= go->next;
2656         }
2657 }
2658
2659 static void lib_link_group(FileData *fd, Main *main)
2660 {
2661         Group *group= main->group.first;
2662         GroupObject *go;
2663         ObjectKey *ok;
2664         
2665         while(group) {
2666                 if(group->id.flag & LIB_NEEDLINK) {
2667                         group->id.flag -= LIB_NEEDLINK;
2668         
2669                         go= group->gobject.first;
2670                         while(go) {
2671                                 go->ob= newlibadr(fd, group->id.lib, go->ob);
2672                                 ok= go->okey.first;
2673                                 while(ok) {
2674                                         ok->parent= newlibadr(fd, group->id.lib, ok->parent);
2675                                         ok->track= newlibadr(fd, group->id.lib, ok->track);     
2676                                         ok->ipo= newlibadr_us(fd, group->id.lib, ok->ipo);      
2677                                         ok= ok->next;
2678                                 }
2679                                 go= go->next;
2680                         }
2681                 }
2682                 group= group->id.next;
2683         }
2684 }
2685
2686 /* ************** GENERAL & MAIN ******************** */
2687
2688 static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID **id_r)
2689 {
2690         /* this routine reads a libblock and its direct data. Use link functions
2691          * to connect it all
2692          */
2693         
2694         ID *id;
2695         ListBase *lb;
2696         
2697         if(bhead->code==ID_ID) {
2698                 ID *linkedid= (ID *)(bhead + 1); /*  BHEAD+DATA dependancy */
2699                 
2700                 lb= wich_libbase(main, GS(linkedid->name));
2701         }
2702         else {
2703                 lb= wich_libbase(main, bhead->code);
2704         }
2705         
2706         /* read libblock */
2707         id = read_struct(fd, bhead);
2708         if (id_r)
2709                 *id_r= id;
2710         if (!id)
2711                 return blo_nextbhead(fd, bhead);
2712                 
2713         oldnewmap_insert(fd->libmap, bhead->old, id, 1);
2714         BLI_addtail(lb, id);
2715         
2716         /* clear first 8 bits */
2717         id->flag= (id->flag & 0xFF00) | flag | LIB_NEEDLINK;
2718         id->lib= main->curlib;
2719         if(id->flag & LIB_FAKEUSER) id->us= 1;
2720         else id->us= 0;
2721         
2722         /* this case cannot be direct_linked: it's just the ID part */
2723         if(bhead->code==ID_ID) {
2724                 return blo_nextbhead(fd, bhead);
2725         }
2726         
2727         bhead = blo_nextbhead(fd, bhead);
2728         
2729                 /* read all data */
2730         while(bhead && bhead->code==DATA) {
2731                 void *data= read_struct(fd, bhead);
2732         
2733                 if (data) {
2734                         oldnewmap_insert(fd->datamap, bhead->old, data, 0);
2735                 }
2736         
2737                 bhead = blo_nextbhead(fd, bhead);
2738         }
2739         
2740         /* init pointers direct data */
2741         switch( GS(id->name) ) {
2742                 case ID_SCR:
2743                         direct_link_screen(fd, (bScreen *)id);
2744                         break;
2745                 case ID_SCE:
2746                         direct_link_scene(fd, (Scene *)id);
2747                         break;
2748                 case ID_OB:
2749                         direct_link_object(fd, (Object *)id);
2750                         break;
2751                 case ID_ME:
2752                         direct_link_mesh(fd, (Mesh *)id);
2753                         break;
2754                 case ID_CU:
2755                         direct_link_curve(fd, (Curve *)id);
2756                         break;
2757                 case ID_MB:
2758                         direct_link_mball(fd, (MetaBall *)id);
2759                         break;
2760                 case ID_MA:
2761                         direct_link_material(fd, (Material *)id);
2762                         break;
2763                 case ID_TE:
2764                         direct_link_texture(fd, (Tex *)id);
2765                         break;
2766                 case ID_IM:
2767                         direct_link_image(fd, (Image *)id);
2768                         break;
2769                 case ID_LA:
2770                         direct_link_lamp(fd, (Lamp *)id);
2771                         break;
2772                 case ID_VF:
2773                         direct_link_vfont(fd, (VFont *)id);
2774                         break;
2775                 case ID_TXT:
2776                         direct_link_text(fd, (Text *)id);
2777                         break;
2778                 case ID_IP:
2779                         direct_link_ipo(fd, (Ipo *)id);
2780                         break;
2781                 case ID_KE:
2782                         direct_link_key(fd, (Key *)id);
2783                         break;
2784                 case ID_LT:
2785                         direct_link_latt(fd, (Lattice *)id);
2786                         break;
2787                 case ID_IK:
2788                         direct_link_ika(fd, (Ika *)id);
2789                         break;
2790                 case ID_WO:
2791                         direct_link_world(fd, (World *)id);
2792                         break;
2793                 case ID_LI:
2794                         direct_link_library(fd, (Library *)id);
2795                         break;
2796                 case ID_CA:
2797                         direct_link_camera(fd, (Camera *)id);
2798                         break;
2799                 case ID_SO:
2800                         direct_link_sound(fd, (bSound *)id);
2801                         break;
2802                 case ID_GR:
2803                         direct_link_group(fd, (Group *)id);
2804                         break;
2805                 case ID_AR:
2806                         direct_link_armature(fd, (bArmature*)id);
2807                         break;
2808                 case ID_AC:
2809                         direct_link_action(fd, (bAction*)id);
2810                         break;
2811         }
2812         
2813         oldnewmap_free_unused(fd->datamap);
2814         oldnewmap_clear(fd->datamap);
2815                 
2816         return (bhead);
2817 }
2818
2819 static void link_global(FileData *fd, BlendFileData *bfd, FileGlobal *fg)
2820 {
2821         // this is nonsense... will get rid of it once (ton) 
2822         bfd->winpos= fg->winpos;
2823         bfd->fileflags= fg->fileflags;
2824         bfd->displaymode= fg->displaymode;
2825         bfd->globalf= fg->globalf;
2826         bfd->curscreen= newlibadr(fd, 0, fg->curscreen);
2827 }
2828
2829 static void vcol_to_fcol(Mesh *me)
2830 {
2831         MFace *mface;
2832         unsigned int *mcol, *mcoln, *mcolmain;
2833         int a;
2834         
2835         if(me->totface==0 || me->mcol==0) return;
2836         
2837         mcoln= mcolmain= MEM_mallocN(4*sizeof(int)*me->totface, "mcoln");
2838         mcol = (unsigned int *)me->mcol;
2839         mface= me->mface;
2840         for(a=me->totface; a>0; a--, mface++) {
2841                 mcoln[0]= mcol[mface->v1];
2842                 mcoln[1]= mcol[mface->v2];
2843                 mcoln[2]= mcol[mface->v3];
2844                 mcoln[3]= mcol[mface->v4];
2845                 mcoln+= 4;
2846         }
2847         
2848         MEM_freeN(me->mcol);
2849         me->mcol= (MCol *)mcolmain;
2850 }
2851
2852 static int map_223_keybd_code_to_224_keybd_code(int code)
2853 {
2854         switch (code) {
2855         case 312:       return F12KEY;
2856         case 159:       return PADSLASHKEY;
2857         case 161:       return PAD0;
2858         case 154:       return PAD1;
2859         case 150:       return PAD2;
2860         case 155:       return PAD3;
2861         case 151:       return PAD4;
2862         case 156:       return PAD5;
2863         case 152:       return PAD6;
2864         case 157:       return PAD7;
2865         case 153:       return PAD8;
2866         case 158:       return PAD9;
2867         default: return code;
2868         }
2869 }
2870
2871 static void do_versions(Main *main)
2872 {
2873         /* watch it: pointers from libdata have not been converted */
2874         
2875         if(main->versionfile == 100) {
2876                 /* tex->extend and tex->imageflag have changed: */
2877                 Tex *tex = main->tex.first;
2878                 while(tex) {
2879                         if(tex->id.flag & LIB_NEEDLINK) {
2880                                 
2881                                 if(tex->extend==0) {
2882                                         if(tex->xrepeat || tex->yrepeat) tex->extend= TEX_REPEAT;
2883                                         else {
2884                                                 tex->extend= TEX_EXTEND;
2885                                                 tex->xrepeat= tex->yrepeat= 1;
2886                                         }
2887                                 }
2888         
2889                                 if(tex->imaflag & TEX_ANIM5) {
2890                                         tex->imaflag |= TEX_MORKPATCH;
2891                                         tex->imaflag |= TEX_ANTIALI;
2892                                 }
2893                         }
2894                         tex= tex->id.next;
2895                 }
2896         }
2897         if(main->versionfile <= 101) {
2898                 /* frame mapping */
2899                 Scene *sce = main->scene.first;
2900                 while(sce) {
2901                         sce->r.framapto= 100;
2902                         sce->r.images= 100;
2903                         sce->r.framelen= 1.0;
2904                         sce= sce->id.next;
2905                 }
2906         }
2907         if(main->versionfile <= 102) {
2908                 /* init halo's at 1.0 */
2909                 Material *ma = main->mat.first;
2910                 while(ma) {
2911                         ma->add= 1.0;
2912                         ma= ma->id.next;
2913                 }
2914         }
2915         if(main->versionfile <= 103) {
2916                 /* new variable in object: colbits */
2917                 Object *ob = main->object.first;
2918                 int a;
2919                 while(ob) {
2920                         ob->colbits= 0;
2921                         if(ob->totcol) {
2922                                 for(a=0; a<ob->totcol; a++) {
2923                                         if(ob->mat[a]) ob->colbits |= (1<<a);
2924                                 }
2925                         }
2926                         ob= ob->id.next;
2927                 }
2928         }
2929         if(main->versionfile <= 104) {
2930                 /* timeoffs moved */
2931                 Object *ob = main->object.first;
2932                 while(ob) {
2933                         if(ob->transflag & 1) {
2934                                 ob->transflag -= 1;
2935                                 ob->ipoflag |= OB_OFFS_OB;
2936                         }
2937                         ob= ob->id.next;
2938                 }
2939         }
2940         if(main->versionfile <= 105) {
2941                 Object *ob = main->object.first;
2942                 while(ob) {
2943                         ob->dupon= 1; ob->dupoff= 0;
2944                         ob->dupsta= 1; ob->dupend= 100;
2945                         ob= ob->id.next;
2946                 }
2947         }
2948         if(main->versionfile <= 106) {
2949                 /* mcol changed */
2950                 Mesh *me = main->mesh.first;
2951                 while(me) {
2952                         if(me->mcol) vcol_to_fcol(me);
2953                         me= me->id.next;
2954                 }
2955                 
2956         }
2957         if(main->versionfile <= 107) {
2958                 Object *ob;
2959                 Scene *sce = main->scene.first;
2960                 while(sce) {
2961                         sce->r.mode |= R_GAMMA;
2962                         sce= sce->id.next;
2963                 }               
2964                 ob= main->object.first;
2965                 while(ob) {
2966                         ob->ipoflag |= OB_OFFS_PARENT;
2967                         if(ob->dt==0) ob->dt= 3;
2968                         ob= ob->id.next;
2969                 }
2970                 
2971         }
2972         if(main->versionfile <= 109) {
2973                 /* new variable: gridlines */
2974                 bScreen *sc = main->screen.first;
2975                 while(sc) {
2976                         ScrArea *sa= sc->areabase.first;
2977                         while(sa) {
2978                                 SpaceLink *sl= sa->spacedata.first;
2979                                 while (sl) {
2980                                         if (sl->spacetype==SPACE_VIEW3D) {
2981                                                 View3D *v3d= (View3D*) sl;
2982
2983                                                 if (v3d->gridlines==0) v3d->gridlines= 20;
2984                                         }
2985                                         sl= sl->next;
2986                                 }
2987                                 sa= sa->next;
2988                         }
2989                         sc= sc->id.next;
2990                 }
2991         }
2992         if(main->versionfile <= 112) {
2993                 Mesh *me = main->mesh.first;
2994                 while(me) {
2995                         me->cubemapsize= 1.0;
2996                         me= me->id.next;
2997                 }
2998         }
2999         if(main->versionfile <= 113) {
3000                 Material *ma = main->mat.first;
3001                 while(ma) {
3002                         if(ma->flaresize==0.0) ma->flaresize= 1.0;
3003                         ma->subsize= 1.0;
3004                         ma->flareboost= 1.0;
3005                         ma= ma->id.next;
3006                 }
3007         }
3008         if(main->versionfile <= 114) {
3009                 Mesh *me= main->mesh.first;
3010                 MFace *mface;
3011                 int a_int;
3012         
3013                 /* edge drawflags changed */
3014                 while(me) {
3015                         a_int= me->totface;
3016                         mface= me->mface;
3017                         while(a_int--) {
3018                                 if(mface->edcode & 16) {
3019                                         mface->edcode -= 16;
3020                                         mface->edcode |= ME_V3V1;
3021                                 }
3022                                 mface++;
3023                         }
3024                         me= me->id.next;
3025                 }
3026         }
3027         
3028         
3029         if(main->versionfile <= 134) {
3030                 Tex *tex = main->tex.first;
3031                 while (tex) {
3032                         if ((tex->rfac == 0.0) &&
3033                             (tex->gfac == 0.0) &&
3034                             (tex->bfac == 0.0)) {
3035                                 tex->rfac = 1.0;
3036                                 tex->gfac = 1.0;
3037                                 tex->bfac = 1.0;
3038                                 tex->filtersize = 1.0;
3039                         }
3040                         tex = tex->id.next;
3041                 }
3042         }
3043         if(main->versionfile <= 140) {
3044                 /* r-g-b-fac in texure */
3045                 Tex *tex = main->tex.first;
3046                 while (tex) {
3047                         if ((tex->rfac == 0.0) &&
3048                             (tex->gfac == 0.0) &&
3049                             (tex->bfac == 0.0)) {
3050                                 tex->rfac = 1.0;
3051                                 tex->gfac = 1.0;
3052                                 tex->bfac = 1.0;
3053                                 tex->filtersize = 1.0;
3054                         }
3055                         tex = tex->id.next;
3056                 }
3057         }
3058         if(main->versionfile <= 153) {
3059                 Scene *sce = main->scene.first;
3060                 while(sce) {
3061                         if(sce->r.blurfac==0.0) sce->r.blurfac= 1.0;
3062                         sce= sce->id.next;
3063                 }
3064         }
3065         if(main->versionfile <= 163) {
3066                 Scene *sce = main->scene.first;
3067                 while(sce) {
3068                         if(sce->r.frs_sec==0) sce->r.frs_sec= 25;
3069                         sce= sce->id.next;
3070                 }
3071         }
3072         if(main->versionfile <= 164) {
3073                 Mesh *me= main->mesh.first;
3074                 while(me) {
3075                         me->smoothresh= 30;
3076                         me= me->id.next;
3077                 }
3078         }
3079         if(main->versionfile <= 165) {
3080                 Mesh *me= main->mesh.first;
3081                 TFace *tface;
3082                 Ika *ika= main->ika.first;
3083                 Deform *def;
3084                 int nr;
3085                 char *cp;
3086                 
3087                 while(ika) {
3088                         ika->xyconstraint= .5;
3089                         
3090                         def= ika->def;
3091                         nr= ika->totdef;
3092                         while(nr--) {
3093                                 if(def->fac==0.0) def->fac= 1.0;
3094                                 def++;
3095                         }
3096                         ika= ika->id.next;
3097                 }
3098                 
3099                 while(me) {
3100                         if(me->tface) {
3101                                 nr= me->totface;
3102                                 tface= me->tface;
3103                                 while(nr--) {
3104                                         cp= (char *)&tface->col[0];
3105                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
3106                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
3107                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
3108                                         cp= (char *)&tface->col[1];
3109                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
3110                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
3111                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
3112                                         cp= (char *)&tface->col[2];
3113                                         if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
3114                                         if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
3115                                         if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
3116                                         cp= (char *)&tface->col[3];
3117                                       &