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