New point cache file format:
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  *
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /*
30 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
31
32 start file:
33         BLENDER_V100    12 bytes  (versie 1.00)
34                                         V = big endian, v = little endian
35                                         _ = 4 byte pointer, - = 8 byte pointer
36
37 datablocks:             also see struct BHead
38         <bh.code>                       4 chars
39         <bh.len>                        int,  len data after BHead
40         <bh.old>                        void,  old pointer
41         <bh.SDNAnr>                     int
42         <bh.nr>                         int, in case of array: amount of structs
43         data
44         ...
45         ...
46
47 Almost all data in Blender are structures. Each struct saved
48 gets a BHead header.  With BHead the struct can be linked again
49 and compared with StructDNA .
50
51 WRITE
52
53 Preferred writing order: (not really a must, but why would you do it random?)
54 Any case: direct data is ALWAYS after the lib block
55
56 (Local file data)
57 - for each LibBlock
58         - write LibBlock
59         - write associated direct data
60 (External file data)
61 - per library
62         - write library block
63         - per LibBlock
64                 - write the ID of LibBlock
65 - write FileGlobal (some global vars)
66 - write SDNA
67 - write USER if filename is ~/.B.blend
68 */
69
70
71 #ifdef HAVE_CONFIG_H
72 #include <config.h>
73 #endif
74
75 #include "zlib.h"
76
77 #ifndef WIN32
78 #include <unistd.h>
79 #else
80 #include "winsock2.h"
81 #include "BLI_winstuff.h"
82 #include <io.h>
83 #include <process.h> // for getpid
84 #endif
85
86 #include <math.h>
87 #include <fcntl.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <stdlib.h>
91
92 #include "DNA_anim_types.h"
93 #include "DNA_armature_types.h"
94 #include "DNA_action_types.h"
95 #include "DNA_actuator_types.h"
96 #include "DNA_boid_types.h"
97 #include "DNA_brush_types.h"
98 #include "DNA_camera_types.h"
99 #include "DNA_cloth_types.h"
100 #include "DNA_color_types.h"
101 #include "DNA_constraint_types.h"
102 #include "DNA_controller_types.h"
103 #include "DNA_curve_types.h"
104 #include "DNA_customdata_types.h"
105 #include "DNA_effect_types.h"
106 #include "DNA_genfile.h"
107 #include "DNA_group_types.h"
108 #include "DNA_gpencil_types.h"
109 #include "DNA_image_types.h"
110 #include "DNA_ipo_types.h"      // XXX depreceated - animsys
111 #include "DNA_fileglobal_types.h"
112 #include "DNA_key_types.h"
113 #include "DNA_lattice_types.h"
114 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
115 #include "DNA_lamp_types.h"
116 #include "DNA_meta_types.h"
117 #include "DNA_mesh_types.h"
118 #include "DNA_meshdata_types.h"
119 #include "DNA_material_types.h"
120 #include "DNA_modifier_types.h"
121 #include "DNA_nla_types.h"
122 #include "DNA_node_types.h"
123 #include "DNA_object_types.h"
124 #include "DNA_object_force.h"
125 #include "DNA_outliner_types.h"
126 #include "DNA_packedFile_types.h"
127 #include "DNA_particle_types.h"
128 #include "DNA_property_types.h"
129 #include "DNA_scene_types.h"
130 #include "DNA_sdna_types.h"
131 #include "DNA_sequence_types.h"
132 #include "DNA_sensor_types.h"
133 #include "DNA_smoke_types.h"
134 #include "DNA_space_types.h"
135 #include "DNA_screen_types.h"
136 #include "DNA_sound_types.h"
137 #include "DNA_texture_types.h"
138 #include "DNA_text_types.h"
139 #include "DNA_view3d_types.h"
140 #include "DNA_vfont_types.h"
141 #include "DNA_userdef_types.h"
142 #include "DNA_world_types.h"
143 #include "DNA_windowmanager_types.h"
144
145 #include "MEM_guardedalloc.h" // MEM_freeN
146 #include "BLI_blenlib.h"
147 #include "BLI_linklist.h"
148
149 #include "BKE_action.h"
150 #include "BKE_blender.h"
151 #include "BKE_cloth.h"
152 #include "BKE_curve.h"
153 #include "BKE_customdata.h"
154 #include "BKE_constraint.h"
155 #include "BKE_global.h" // for G
156 #include "BKE_library.h" // for  set_listbasepointers
157 #include "BKE_main.h"
158 #include "BKE_node.h"
159 #include "BKE_packedFile.h" // for packAll
160 #include "BKE_pointcache.h"
161 #include "BKE_report.h"
162 #include "BKE_screen.h" // for waitcursor
163 #include "BKE_sequence.h"
164 #include "BKE_sound.h" /* ... and for samples */
165 #include "BKE_utildefines.h" // for defines
166 #include "BKE_modifier.h"
167 #include "BKE_idprop.h"
168 #include "BKE_fcurve.h"
169
170 #include "BLO_writefile.h"
171 #include "BLO_readfile.h"
172 #include "BLO_undofile.h"
173
174 #include "readfile.h"
175
176 #include <errno.h>
177
178 /* ********* my write, buffered writing with minimum size chunks ************ */
179
180 #define MYWRITE_BUFFER_SIZE     100000
181 #define MYWRITE_MAX_CHUNK       32768
182
183 typedef struct {
184         struct SDNA *sdna;
185
186         int file;
187         unsigned char *buf;
188         MemFile *compare, *current;
189         
190         int tot, count, error, memsize;
191 } WriteData;
192
193 static WriteData *writedata_new(int file)
194 {
195         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
196
197                 /* XXX, see note about this in readfile.c, remove
198                  * once we have an xp lock - zr
199                  */
200
201         if (wd == NULL) return NULL;
202
203         wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
204
205         wd->file= file;
206
207         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
208
209         return wd;
210 }
211
212 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
213 {
214         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
215         if (wd->error) return;
216
217         /* memory based save */
218         if(wd->current) {
219                 add_memfilechunk(NULL, wd->current, mem, memlen);
220         }
221         else {
222                 if (write(wd->file, mem, memlen) != memlen)
223                         wd->error= 1;
224                 
225         }
226 }
227
228 static void writedata_free(WriteData *wd)
229 {
230         DNA_sdna_free(wd->sdna);
231
232         MEM_freeN(wd->buf);
233         MEM_freeN(wd);
234 }
235
236 /***/
237
238 int mywfile;
239
240 /**
241  * Low level WRITE(2) wrapper that buffers data
242  * @param adr Pointer to new chunk of data
243  * @param len Length of new chunk of data
244  * @warning Talks to other functions with global parameters
245  */
246  
247 #define MYWRITE_FLUSH           NULL
248
249 static void mywrite( WriteData *wd, void *adr, int len)
250 {
251         if (wd->error) return;
252
253         /* flush helps compression for undo-save */
254         if(adr==MYWRITE_FLUSH) {
255                 if(wd->count) {
256                         writedata_do_write(wd, wd->buf, wd->count);
257                         wd->count= 0;
258                 }
259                 return;
260         }
261
262         wd->tot+= len;
263         
264         /* if we have a single big chunk, write existing data in
265          * buffer and write out big chunk in smaller pieces */
266         if(len>MYWRITE_MAX_CHUNK) {
267                 if(wd->count) {
268                         writedata_do_write(wd, wd->buf, wd->count);
269                         wd->count= 0;
270                 }
271
272                 do {
273                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
274                         writedata_do_write(wd, adr, writelen);
275                         adr = (char*)adr + writelen;
276                         len -= writelen;
277                 } while(len > 0);
278
279                 return;
280         }
281
282         /* if data would overflow buffer, write out the buffer */
283         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
284                 writedata_do_write(wd, wd->buf, wd->count);
285                 wd->count= 0;
286         }
287
288         /* append data at end of buffer */
289         memcpy(&wd->buf[wd->count], adr, len);
290         wd->count+= len;
291 }
292
293 /**
294  * BeGiN initializer for mywrite
295  * @param file File descriptor
296  * @param write_flags Write parameters
297  * @warning Talks to other functions with global parameters
298  */
299 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
300 {
301         WriteData *wd= writedata_new(file);
302
303         if (wd == NULL) return NULL;
304
305         wd->compare= compare;
306         wd->current= current;
307         /* this inits comparing */
308         add_memfilechunk(compare, NULL, NULL, 0);
309         
310         return wd;
311 }
312
313 /**
314  * END the mywrite wrapper
315  * @return 1 if write failed
316  * @return unknown global variable otherwise
317  * @warning Talks to other functions with global parameters
318  */
319 static int endwrite(WriteData *wd)
320 {
321         int err;
322
323         if (wd->count) {
324                 writedata_do_write(wd, wd->buf, wd->count);
325                 wd->count= 0;
326         }
327         
328         err= wd->error;
329         writedata_free(wd);
330
331         return err;
332 }
333
334 /* ********** WRITE FILE ****************** */
335
336 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
337 {
338         BHead bh;
339         short *sp;
340
341         if(adr==NULL || nr==0) return;
342
343         /* init BHead */
344         bh.code= filecode;
345         bh.old= adr;
346         bh.nr= nr;
347
348         bh.SDNAnr= DNA_struct_find_nr(wd->sdna, structname);
349         if(bh.SDNAnr== -1) {
350                 printf("error: can't find SDNA code <%s>\n", structname);
351                 return;
352         }
353         sp= wd->sdna->structs[bh.SDNAnr];
354
355         bh.len= nr*wd->sdna->typelens[sp[0]];
356
357         if(bh.len==0) return;
358
359         mywrite(wd, &bh, sizeof(BHead));
360         mywrite(wd, adr, bh.len);
361 }
362
363 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
364 {
365         BHead bh;
366
367         if(adr==0) return;
368         if(len==0) return;
369
370         len+= 3;
371         len-= ( len % 4);
372
373         /* init BHead */
374         bh.code= filecode;
375         bh.old= adr;
376         bh.nr= 1;
377         bh.SDNAnr= 0;
378         bh.len= len;
379
380         mywrite(wd, &bh, sizeof(BHead));
381         if(len) mywrite(wd, adr, len);
382 }
383
384 /* *************** writing some direct data structs used in more code parts **************** */
385 /*These functions are used by blender's .blend system for file saving/loading.*/
386 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
387 void IDP_WriteProperty(IDProperty *prop, void *wd);
388 static void write_animdata(WriteData *wd, AnimData *adt); // XXX code needs reshuffling, but not before NLA SoC is merged back into 2.5
389
390 static void IDP_WriteArray(IDProperty *prop, void *wd)
391 {
392         /*REMEMBER to set totalen to len in the linking code!!*/
393         if (prop->data.pointer) {
394                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
395
396                 if(prop->subtype == IDP_GROUP) {
397                         IDProperty **array= prop->data.pointer;
398                         int a;
399
400                         for(a=0; a<prop->len; a++)
401                                 IDP_WriteProperty(array[a], wd);
402                 }
403         }
404 }
405
406 static void IDP_WriteIDPArray(IDProperty *prop, void *wd)
407 {
408         /*REMEMBER to set totalen to len in the linking code!!*/
409         if (prop->data.pointer) {
410                 IDProperty **array = prop->data.pointer;
411                 int a;
412
413                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
414
415                 for(a=0; a<prop->len; a++)
416                         IDP_WriteProperty(array[a], wd);
417         }
418 }
419
420 static void IDP_WriteString(IDProperty *prop, void *wd)
421 {
422         /*REMEMBER to set totalen to len in the linking code!!*/
423         writedata(wd, DATA, prop->len+1, prop->data.pointer);
424 }
425
426 static void IDP_WriteGroup(IDProperty *prop, void *wd)
427 {
428         IDProperty *loop;
429
430         for (loop=prop->data.group.first; loop; loop=loop->next) {
431                 IDP_WriteProperty(loop, wd);
432         }
433 }
434
435 /* Functions to read/write ID Properties */
436 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
437 {
438         switch (prop->type) {
439                 case IDP_GROUP:
440                         IDP_WriteGroup(prop, wd);
441                         break;
442                 case IDP_STRING:
443                         IDP_WriteString(prop, wd);
444                         break;
445                 case IDP_ARRAY:
446                         IDP_WriteArray(prop, wd);
447                         break;
448                 case IDP_IDPARRAY:
449                         IDP_WriteIDPArray(prop, wd);
450                         break;
451         }
452 }
453
454 void IDP_WriteProperty(IDProperty *prop, void *wd)
455 {
456         writestruct(wd, DATA, "IDProperty", 1, prop);
457         IDP_WriteProperty_OnlyData(prop, wd);
458 }
459
460 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
461 {
462         int a;
463         
464         writestruct(wd, DATA, "CurveMapping", 1, cumap);
465         for(a=0; a<CM_TOT; a++)
466                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
467 }
468
469 /* this is only direct data, tree itself should have been written */
470 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
471 {
472         bNode *node;
473         bNodeSocket *sock;
474         bNodeLink *link;
475         
476         /* for link_list() speed, we write per list */
477         
478         for(node= ntree->nodes.first; node; node= node->next)
479                 writestruct(wd, DATA, "bNode", 1, node);
480
481         for(node= ntree->nodes.first; node; node= node->next) {
482                 if(node->storage && node->type!=NODE_DYNAMIC) {
483                         /* could be handlerized at some point, now only 1 exception still */
484                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
485                                 write_curvemapping(wd, node->storage);
486                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
487                                 write_curvemapping(wd, node->storage);
488                         else if(ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) )
489                                 write_curvemapping(wd, node->storage);
490                         else 
491                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
492                 }
493                 for(sock= node->inputs.first; sock; sock= sock->next)
494                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
495                 for(sock= node->outputs.first; sock; sock= sock->next)
496                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
497         }
498         
499         for(link= ntree->links.first; link; link= link->next)
500                 writestruct(wd, DATA, "bNodeLink", 1, link);
501 }
502
503 static void current_screen_compat(Main *mainvar, bScreen **screen)
504 {
505         wmWindowManager *wm;
506         wmWindow *window;
507
508         /* find a global current screen in the first open window, to have
509          * a reasonable default for reading in older versions */
510         wm= mainvar->wm.first;
511         window= (wm)? wm->windows.first: NULL;
512         *screen= (window)? window->screen: NULL;
513 }
514
515 static void write_renderinfo(WriteData *wd, Main *mainvar)              /* for renderdeamon */
516 {
517         bScreen *curscreen;
518         Scene *sce;
519         int data[8];
520
521         /* XXX in future, handle multiple windows with multiple screnes? */
522         current_screen_compat(mainvar, &curscreen);
523
524         for(sce= mainvar->scene.first; sce; sce= sce->id.next) {
525                 if(sce->id.lib==NULL  && ( sce==curscreen->scene || (sce->r.scemode & R_BG_RENDER)) ) {
526                         data[0]= sce->r.sfra;
527                         data[1]= sce->r.efra;
528
529                         memset(data+2, 0, sizeof(int)*6);
530                         strncpy((char *)(data+2), sce->id.name+2, 21);
531
532                         writedata(wd, REND, 32, data);
533                 }
534         }
535 }
536
537 static void write_userdef(WriteData *wd)
538 {
539         bTheme *btheme;
540
541         writestruct(wd, USER, "UserDef", 1, &U);
542
543         btheme= U.themes.first;
544         while(btheme) {
545                 writestruct(wd, DATA, "bTheme", 1, btheme);
546                 btheme= btheme->next;
547         }
548 }
549
550 static void write_boid_state(WriteData *wd, BoidState *state)
551 {
552         BoidRule *rule = state->rules.first;
553         //BoidCondition *cond = state->conditions.first;
554
555         writestruct(wd, DATA, "BoidState", 1, state);
556
557         for(; rule; rule=rule->next) {
558                 switch(rule->type) {
559                         case eBoidRuleType_Goal:
560                         case eBoidRuleType_Avoid:
561                                 writestruct(wd, DATA, "BoidRuleGoalAvoid", 1, rule);
562                                 break;
563                         case eBoidRuleType_AvoidCollision:
564                                 writestruct(wd, DATA, "BoidRuleAvoidCollision", 1, rule);
565                                 break;
566                         case eBoidRuleType_FollowLeader:
567                                 writestruct(wd, DATA, "BoidRuleFollowLeader", 1, rule);
568                                 break;
569                         case eBoidRuleType_AverageSpeed:
570                                 writestruct(wd, DATA, "BoidRuleAverageSpeed", 1, rule);
571                                 break;
572                         case eBoidRuleType_Fight:
573                                 writestruct(wd, DATA, "BoidRuleFight", 1, rule);
574                                 break;
575                         default:
576                                 writestruct(wd, DATA, "BoidRule", 1, rule);
577                                 break;
578                 }
579         }
580         //for(; cond; cond=cond->next)
581         //      writestruct(wd, DATA, "BoidCondition", 1, cond);
582 }
583 /* TODO: replace *cache with *cachelist once it's coded */
584 #define PTCACHE_WRITE_PSYS      0
585 #define PTCACHE_WRITE_CLOTH     1
586 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
587 {
588         PointCache *cache = ptcaches->first;
589         int i;
590
591         for(; cache; cache=cache->next) {
592                 writestruct(wd, DATA, "PointCache", 1, cache);
593
594                 if((cache->flag & PTCACHE_DISK_CACHE)==0) {
595                         PTCacheMem *pm = cache->mem_cache.first;
596
597                         for(; pm; pm=pm->next) {
598                                 writestruct(wd, DATA, "PTCacheMem", 1, pm);
599                                 if(pm->index_array)
600                                         writedata(wd, DATA, sizeof(int) * pm->totpoint, pm->index_array);
601                                 
602                                 for(i=0; i<BPHYS_TOT_DATA; i++) {
603                                         if(pm->data[i] && pm->data_types & (1<<i))
604                                                 writedata(wd, DATA, BKE_ptcache_data_size(i) * pm->totpoint, pm->data[i]);
605                                 }
606                         }
607                 }
608         }
609 }
610 static void write_particlesettings(WriteData *wd, ListBase *idbase)
611 {
612         ParticleSettings *part;
613
614         part= idbase->first;
615         while(part) {
616                 if(part->id.us>0 || wd->current) {
617                         /* write LibData */
618                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
619                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
620                         if (part->adt) write_animdata(wd, part->adt);
621                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
622                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
623
624                         if(part->boids && part->phystype == PART_PHYS_BOIDS) {
625                                 BoidState *state = part->boids->states.first;
626
627                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
628
629                                 for(; state; state=state->next)
630                                         write_boid_state(wd, state);
631                         }
632                 }
633                 part= part->id.next;
634         }
635 }
636 static void write_particlesystems(WriteData *wd, ListBase *particles)
637 {
638         ParticleSystem *psys= particles->first;
639         ParticleTarget *pt;
640         int a;
641
642         for(; psys; psys=psys->next) {
643                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
644
645                 if(psys->particles) {
646                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
647
648                         if(psys->particles->hair) {
649                                 ParticleData *pa = psys->particles;
650
651                                 for(a=0; a<psys->totpart; a++, pa++)
652                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
653                         }
654
655                         if(psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
656                                 writestruct(wd, DATA, "BoidData", psys->totpart, psys->particles->boid);
657                 }
658                 pt = psys->targets.first;
659                 for(; pt; pt=pt->next)
660                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
661
662                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
663                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
664                 if(psys->soft) write_pointcaches(wd, &psys->soft->ptcaches);
665                 write_pointcaches(wd, &psys->ptcaches);
666         }
667 }
668
669 static void write_properties(WriteData *wd, ListBase *lb)
670 {
671         bProperty *prop;
672
673         prop= lb->first;
674         while(prop) {
675                 writestruct(wd, DATA, "bProperty", 1, prop);
676
677                 if(prop->poin && prop->poin != &prop->data)
678                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
679
680                 prop= prop->next;
681         }
682 }
683
684 static void write_sensors(WriteData *wd, ListBase *lb)
685 {
686         bSensor *sens;
687
688         sens= lb->first;
689         while(sens) {
690                 writestruct(wd, DATA, "bSensor", 1, sens);
691
692                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
693
694                 switch(sens->type) {
695                 case SENS_NEAR:
696                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
697                         break;
698                 case SENS_MOUSE:
699                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
700                         break;
701                 case SENS_TOUCH:
702                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
703                         break;
704                 case SENS_KEYBOARD:
705                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
706                         break;
707                 case SENS_PROPERTY:
708                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
709                         break;
710                 case SENS_ACTUATOR:
711                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
712                         break;
713                 case SENS_DELAY:
714                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
715                         break;
716                 case SENS_COLLISION:
717                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
718                         break;
719                 case SENS_RADAR:
720                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
721                         break;
722                 case SENS_RANDOM:
723                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
724                         break;
725                 case SENS_RAY:
726                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
727                         break;
728                 case SENS_MESSAGE:
729                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
730                         break;
731                 case SENS_JOYSTICK:
732                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
733                         break;
734                 default:
735                         ; /* error: don't know how to write this file */
736                 }
737
738                 sens= sens->next;
739         }
740 }
741
742 static void write_controllers(WriteData *wd, ListBase *lb)
743 {
744         bController *cont;
745
746         cont= lb->first;
747         while(cont) {
748                 writestruct(wd, DATA, "bController", 1, cont);
749
750                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
751
752                 switch(cont->type) {
753                 case CONT_EXPRESSION:
754                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
755                         break;
756                 case CONT_PYTHON:
757                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
758                         break;
759                 default:
760                         ; /* error: don't know how to write this file */
761                 }
762
763                 cont= cont->next;
764         }
765 }
766
767 static void write_actuators(WriteData *wd, ListBase *lb)
768 {
769         bActuator *act;
770
771         act= lb->first;
772         while(act) {
773                 writestruct(wd, DATA, "bActuator", 1, act);
774
775                 switch(act->type) {
776                 case ACT_ACTION:
777                 case ACT_SHAPEACTION:
778                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
779                         break;
780                 case ACT_SOUND:
781                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
782                         break;
783                 case ACT_OBJECT:
784                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
785                         break;
786                 case ACT_IPO:
787                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
788                         break;
789                 case ACT_PROPERTY:
790                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
791                         break;
792                 case ACT_CAMERA:
793                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
794                         break;
795                 case ACT_CONSTRAINT:
796                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
797                         break;
798                 case ACT_EDIT_OBJECT:
799                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
800                         break;
801                 case ACT_SCENE:
802                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
803                         break;
804                 case ACT_GROUP:
805                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
806                         break;
807                 case ACT_RANDOM:
808                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
809                         break;
810                 case ACT_MESSAGE:
811                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
812                         break;
813                 case ACT_GAME:
814                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
815                         break;
816                 case ACT_VISIBILITY:
817                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
818                         break;
819                 case ACT_2DFILTER:
820                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
821                         break;
822                 case ACT_PARENT:
823                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
824                         break;
825                 case ACT_STATE:
826                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
827                         break;
828                 default:
829                         ; /* error: don't know how to write this file */
830                 }
831
832                 act= act->next;
833         }
834 }
835
836 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
837 {
838         FModifier *fcm;
839         
840         /* Modifiers */
841         for (fcm= fmodifiers->first; fcm; fcm= fcm->next) {
842                 FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
843                 
844                 /* Write the specific data */
845                 if (fmi && fcm->data) {
846                         /* firstly, just write the plain fmi->data struct */
847                         writestruct(wd, DATA, fmi->structName, 1, fcm->data);
848                         
849                         /* do any modifier specific stuff */
850                         switch (fcm->type) {
851                                 case FMODIFIER_TYPE_GENERATOR:
852                                 {
853                                         FMod_Generator *data= (FMod_Generator *)fcm->data;
854                                         
855                                         /* write coefficients array */
856                                         if (data->coefficients)
857                                                 writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
858                                 }
859                                         break;
860                                 case FMODIFIER_TYPE_ENVELOPE:
861                                 {
862                                         FMod_Envelope *data= (FMod_Envelope *)fcm->data;
863                                         
864                                         /* write envelope data */
865                                         if (data->data)
866                                                 writedata(wd, DATA, sizeof(FCM_EnvelopeData)*(data->totvert), data->data);
867                                 }
868                                         break;
869                                 case FMODIFIER_TYPE_PYTHON:
870                                 {
871                                         FMod_Python *data = (FMod_Python *)fcm->data;
872                                         
873                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
874                                          of library blocks that implement this.*/
875                                         IDP_WriteProperty(data->prop, wd);
876                                 }
877                                         break;
878                         }
879                 }
880                 
881                 /* Write the modifier */
882                 writestruct(wd, DATA, "FModifier", 1, fcm);
883         }
884 }
885
886 static void write_fcurves(WriteData *wd, ListBase *fcurves)
887 {
888         FCurve *fcu;
889         
890         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
891                 /* F-Curve */
892                 writestruct(wd, DATA, "FCurve", 1, fcu);
893                 
894                 /* curve data */
895                 if (fcu->bezt)          
896                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
897                 if (fcu->fpt)
898                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
899                         
900                 if (fcu->rna_path)
901                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
902                 
903                 /* driver data */
904                 if (fcu->driver) {
905                         ChannelDriver *driver= fcu->driver;
906                         DriverTarget *dtar;
907                         
908                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
909                         
910                         /* targets */
911                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
912                                 writestruct(wd, DATA, "DriverTarget", 1, dtar);
913                                 
914                                 if (dtar->rna_path)
915                                         writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
916                         }
917                 }
918                 
919                 /* write F-Modifiers */
920                 write_fmodifiers(wd, &fcu->modifiers);
921         }
922 }
923
924 static void write_actions(WriteData *wd, ListBase *idbase)
925 {
926         bAction *act;
927         bActionGroup *grp;
928         TimeMarker *marker;
929         
930         for(act=idbase->first; act; act= act->id.next) {
931                 if (act->id.us>0 || wd->current) {
932                         writestruct(wd, ID_AC, "bAction", 1, act);
933                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
934                         
935                         write_fcurves(wd, &act->curves);
936                         
937                         for (grp=act->groups.first; grp; grp=grp->next) {
938                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
939                         }
940                         
941                         for (marker=act->markers.first; marker; marker=marker->next) {
942                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
943                         }
944                 }
945         }
946         
947         /* flush helps the compression for undo-save */
948         mywrite(wd, MYWRITE_FLUSH, 0);
949 }
950
951 static void write_keyingsets(WriteData *wd, ListBase *list)
952 {
953         KeyingSet *ks;
954         KS_Path *ksp;
955         
956         for (ks= list->first; ks; ks= ks->next) {
957                 /* KeyingSet */
958                 writestruct(wd, DATA, "KeyingSet", 1, ks);
959                 
960                 /* Paths */
961                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
962                         /* Path */
963                         writestruct(wd, DATA, "KS_Path", 1, ksp);
964                         
965                         if (ksp->rna_path)
966                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
967                 }
968         }
969 }
970
971 static void write_nlastrips(WriteData *wd, ListBase *strips)
972 {
973         NlaStrip *strip;
974         
975         for (strip= strips->first; strip; strip= strip->next) {
976                 /* write the strip first */
977                 writestruct(wd, DATA, "NlaStrip", 1, strip);
978                 
979                 /* write the strip's F-Curves and modifiers */
980                 write_fcurves(wd, &strip->fcurves);
981                 write_fmodifiers(wd, &strip->modifiers);
982                 
983                 /* write the strip's children */
984                 write_nlastrips(wd, &strip->strips);
985         }
986 }
987
988 static void write_nladata(WriteData *wd, ListBase *nlabase)
989 {
990         NlaTrack *nlt;
991         
992         /* write all the tracks */
993         for (nlt= nlabase->first; nlt; nlt= nlt->next) {
994                 /* write the track first */
995                 writestruct(wd, DATA, "NlaTrack", 1, nlt);
996                 
997                 /* write the track's strips */
998                 write_nlastrips(wd, &nlt->strips);
999         }
1000 }
1001
1002 static void write_animdata(WriteData *wd, AnimData *adt)
1003 {
1004         AnimOverride *aor;
1005         
1006         /* firstly, just write the AnimData block */
1007         writestruct(wd, DATA, "AnimData", 1, adt);
1008         
1009         /* write drivers */
1010         write_fcurves(wd, &adt->drivers);
1011         
1012         /* write overrides */
1013         // FIXME: are these needed?
1014         for (aor= adt->overrides.first; aor; aor= aor->next) {
1015                 /* overrides consist of base data + rna_path */
1016                 writestruct(wd, DATA, "AnimOverride", 1, aor);
1017                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
1018         }
1019         
1020         // TODO write the remaps (if they are needed)
1021         
1022         /* write NLA data */
1023         write_nladata(wd, &adt->nla_tracks);
1024 }
1025
1026 static void write_constraints(WriteData *wd, ListBase *conlist)
1027 {
1028         bConstraint *con;
1029
1030         for (con=conlist->first; con; con=con->next) {
1031                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1032                 
1033                 /* Write the specific data */
1034                 if (cti && con->data) {
1035                         /* firstly, just write the plain con->data struct */
1036                         writestruct(wd, DATA, cti->structName, 1, con->data);
1037                         
1038                         /* do any constraint specific stuff */
1039                         switch (con->type) {
1040                                 case CONSTRAINT_TYPE_PYTHON:
1041                                 {
1042                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1043                                         bConstraintTarget *ct;
1044                                         
1045                                         /* write targets */
1046                                         for (ct= data->targets.first; ct; ct= ct->next)
1047                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1048                                         
1049                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1050                                          of library blocks that implement this.*/
1051                                         IDP_WriteProperty(data->prop, wd);
1052                                 }
1053                                 break;
1054                         }
1055                 }
1056                 
1057                 /* Write the constraint */
1058                 writestruct(wd, DATA, "bConstraint", 1, con);
1059         }
1060 }
1061
1062 static void write_pose(WriteData *wd, bPose *pose)
1063 {
1064         bPoseChannel *chan;
1065         bActionGroup *grp;
1066
1067         /* Write each channel */
1068         if (!pose)
1069                 return;
1070
1071         /* Write channels */
1072         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1073                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1074                  of library blocks that implement this.*/
1075                 if (chan->prop)
1076                         IDP_WriteProperty(chan->prop, wd);
1077                 
1078                 write_constraints(wd, &chan->constraints);
1079                 
1080                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1081                 if (chan->bone) 
1082                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
1083                 
1084                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1085         }
1086         
1087         /* Write groups */
1088         for (grp=pose->agroups.first; grp; grp=grp->next) 
1089                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1090
1091         /* Write this pose */
1092         writestruct(wd, DATA, "bPose", 1, pose);
1093 }
1094
1095 static void write_defgroups(WriteData *wd, ListBase *defbase)
1096 {
1097         bDeformGroup    *defgroup;
1098
1099         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1100                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1101 }
1102
1103 static void write_modifiers(WriteData *wd, ListBase *modbase, int write_undo)
1104 {
1105         ModifierData *md;
1106
1107         if (modbase == NULL) return;
1108         for (md=modbase->first; md; md= md->next) {
1109                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1110                 if (mti == NULL) return;
1111                 
1112                 writestruct(wd, DATA, mti->structName, 1, md);
1113                         
1114                 if (md->type==eModifierType_Hook) {
1115                         HookModifierData *hmd = (HookModifierData*) md;
1116                         
1117                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1118                 }
1119                 else if(md->type==eModifierType_Cloth) {
1120                         ClothModifierData *clmd = (ClothModifierData*) md;
1121                         
1122                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1123                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1124                         write_pointcaches(wd, &clmd->ptcaches);
1125                 } 
1126                 else if(md->type==eModifierType_Smoke) {
1127                         SmokeModifierData *smd = (SmokeModifierData*) md;
1128                         
1129                         if(smd->type==MOD_SMOKE_TYPE_DOMAIN)
1130                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1131                         else if(smd->type==MOD_SMOKE_TYPE_FLOW)
1132                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1133                         /*
1134                         else if(smd->type==MOD_SMOKE_TYPE_COLL)
1135                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1136                         */
1137                 } 
1138                 else if(md->type==eModifierType_Fluidsim) {
1139                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1140                         
1141                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1142                 } 
1143                 else if (md->type==eModifierType_Collision) {
1144                         
1145                         /*
1146                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1147                         // TODO: CollisionModifier should use pointcache 
1148                         // + have proper reset events before enabling this
1149                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1150                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1151                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1152                         */
1153                 }
1154                 else if (md->type==eModifierType_MeshDeform) {
1155                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1156                         int size = mmd->dyngridsize;
1157
1158                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
1159                                 mmd->bindweights);
1160                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1161                                 mmd->bindcos);
1162                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1163                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1164                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1165                 }
1166                 else if (md->type==eModifierType_Multires) {
1167                         MultiresModifierData *mmd = (MultiresModifierData*) md;
1168
1169                         if(mmd->undo_verts && write_undo)
1170                                 writestruct(wd, DATA, "MVert", mmd->undo_verts_tot, mmd->undo_verts);
1171                 }
1172         }
1173 }
1174
1175 static void write_objects(WriteData *wd, ListBase *idbase, int write_undo)
1176 {
1177         Object *ob;
1178         
1179         ob= idbase->first;
1180         while(ob) {
1181                 if(ob->id.us>0 || wd->current) {
1182                         /* write LibData */
1183                         writestruct(wd, ID_OB, "Object", 1, ob);
1184                         
1185                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1186                           of library blocks that implement this.*/
1187                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1188                         
1189                         if (ob->adt) write_animdata(wd, ob->adt);
1190                         
1191                         /* direct data */
1192                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1193                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1194                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1195                         write_properties(wd, &ob->prop);
1196                         write_sensors(wd, &ob->sensors);
1197                         write_controllers(wd, &ob->controllers);
1198                         write_actuators(wd, &ob->actuators);
1199                         write_pose(wd, ob->pose);
1200                         write_defgroups(wd, &ob->defbase);
1201                         write_constraints(wd, &ob->constraints);
1202                         
1203                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1204                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1205                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
1206                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1207                         
1208                         write_particlesystems(wd, &ob->particlesystem);
1209                         write_modifiers(wd, &ob->modifiers, write_undo);
1210                 }
1211                 ob= ob->id.next;
1212         }
1213
1214         /* flush helps the compression for undo-save */
1215         mywrite(wd, MYWRITE_FLUSH, 0);
1216 }
1217
1218
1219 static void write_vfonts(WriteData *wd, ListBase *idbase)
1220 {
1221         VFont *vf;
1222         PackedFile * pf;
1223
1224         vf= idbase->first;
1225         while(vf) {
1226                 if(vf->id.us>0 || wd->current) {
1227                         /* write LibData */
1228                         writestruct(wd, ID_VF, "VFont", 1, vf);
1229                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1230
1231                         /* direct data */
1232
1233                         if (vf->packedfile) {
1234                                 pf = vf->packedfile;
1235                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1236                                 writedata(wd, DATA, pf->size, pf->data);
1237                         }
1238                 }
1239
1240                 vf= vf->id.next;
1241         }
1242 }
1243
1244
1245 static void write_keys(WriteData *wd, ListBase *idbase)
1246 {
1247         Key *key;
1248         KeyBlock *kb;
1249
1250         key= idbase->first;
1251         while(key) {
1252                 if(key->id.us>0 || wd->current) {
1253                         /* write LibData */
1254                         writestruct(wd, ID_KE, "Key", 1, key);
1255                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1256                         
1257                         if (key->adt) write_animdata(wd, key->adt);
1258                         
1259                         /* direct data */
1260                         kb= key->block.first;
1261                         while(kb) {
1262                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1263                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1264                                 kb= kb->next;
1265                         }
1266                 }
1267
1268                 key= key->id.next;
1269         }
1270         /* flush helps the compression for undo-save */
1271         mywrite(wd, MYWRITE_FLUSH, 0);
1272 }
1273
1274 static void write_cameras(WriteData *wd, ListBase *idbase)
1275 {
1276         Camera *cam;
1277
1278         cam= idbase->first;
1279         while(cam) {
1280                 if(cam->id.us>0 || wd->current) {
1281                         /* write LibData */
1282                         writestruct(wd, ID_CA, "Camera", 1, cam);
1283                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1284                         
1285                         if (cam->adt) write_animdata(wd, cam->adt);
1286                 }
1287
1288                 cam= cam->id.next;
1289         }
1290 }
1291
1292 static void write_mballs(WriteData *wd, ListBase *idbase)
1293 {
1294         MetaBall *mb;
1295         MetaElem *ml;
1296
1297         mb= idbase->first;
1298         while(mb) {
1299                 if(mb->id.us>0 || wd->current) {
1300                         /* write LibData */
1301                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1302                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1303
1304                         /* direct data */
1305                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1306                         if (mb->adt) write_animdata(wd, mb->adt);
1307
1308                         ml= mb->elems.first;
1309                         while(ml) {
1310                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1311                                 ml= ml->next;
1312                         }
1313                 }
1314                 mb= mb->id.next;
1315         }
1316 }
1317
1318 static int amount_of_chars(char *str)
1319 {
1320         // Since the data is saved as UTF-8 to the cu->str
1321         // The cu->len is not same as the strlen(cu->str)
1322         return strlen(str);
1323 }
1324
1325 static void write_curves(WriteData *wd, ListBase *idbase)
1326 {
1327         Curve *cu;
1328         Nurb *nu;
1329
1330         cu= idbase->first;
1331         while(cu) {
1332                 if(cu->id.us>0 || wd->current) {
1333                         /* write LibData */
1334                         writestruct(wd, ID_CU, "Curve", 1, cu);
1335                         
1336                         /* direct data */
1337                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1338                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1339                         if (cu->adt) write_animdata(wd, cu->adt);
1340                         
1341                         if(cu->vfont) {
1342                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1343                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1344                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1345                         }
1346                         else {
1347                                 /* is also the order of reading */
1348                                 nu= cu->nurb.first;
1349                                 while(nu) {
1350                                         writestruct(wd, DATA, "Nurb", 1, nu);
1351                                         nu= nu->next;
1352                                 }
1353                                 nu= cu->nurb.first;
1354                                 while(nu) {
1355                                         if( (nu->type & 7)==CU_BEZIER)
1356                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1357                                         else {
1358                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1359                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1360                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1361                                         }
1362                                         nu= nu->next;
1363                                 }
1364                         }
1365                 }
1366                 cu= cu->id.next;
1367         }
1368
1369         /* flush helps the compression for undo-save */
1370         mywrite(wd, MYWRITE_FLUSH, 0);
1371 }
1372
1373 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1374 {
1375         if (dvlist) {
1376                 int i;
1377                 
1378                 /* Write the dvert list */
1379                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1380                 
1381                 /* Write deformation data for each dvert */
1382                 for (i=0; i<count; i++) {
1383                         if (dvlist[i].dw)
1384                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1385                 }
1386         }
1387 }
1388
1389 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist)
1390 {
1391         if(mdlist) {
1392                 int i;
1393                 
1394                 writestruct(wd, DATA, "MDisps", count, mdlist);
1395                 for(i = 0; i < count; ++i) {
1396                         if(mdlist[i].disps)
1397                                 writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1398                 }
1399         }
1400 }
1401
1402 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1403 {
1404         int i;
1405
1406         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1407
1408         for (i=0; i<data->totlayer; i++) {
1409                 CustomDataLayer *layer= &data->layers[i];
1410                 char *structname;
1411                 int structnum, datasize;
1412
1413                 if (layer->type == CD_MDEFORMVERT) {
1414                         /* layer types that allocate own memory need special handling */
1415                         write_dverts(wd, count, layer->data);
1416                 }
1417                 else if (layer->type == CD_MDISPS) {
1418                         write_mdisps(wd, count, layer->data);
1419                 }
1420                 else {
1421                         CustomData_file_write_info(layer->type, &structname, &structnum);
1422                         if (structnum) {
1423                                 /* when using partial visibility, the MEdge and MFace layers
1424                                    are smaller than the original, so their type and count is
1425                                    passed to make this work */
1426                                 if (layer->type != partial_type) datasize= structnum*count;
1427                                 else datasize= structnum*partial_count;
1428
1429                                 writestruct(wd, DATA, structname, datasize, layer->data);
1430                         }
1431                         else
1432                                 printf("error: this CustomDataLayer must not be written to file\n");
1433                 }
1434         }
1435 }
1436
1437 static void write_meshs(WriteData *wd, ListBase *idbase)
1438 {
1439         Mesh *mesh;
1440
1441         mesh= idbase->first;
1442         while(mesh) {
1443                 if(mesh->id.us>0 || wd->current) {
1444                         /* write LibData */
1445                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1446
1447                         /* direct data */
1448                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1449
1450                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1451
1452                         if(mesh->pv) {
1453                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1454                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1455                                         CD_MEDGE, mesh->totedge);
1456                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1457                                         CD_MFACE, mesh->totface);
1458                         }
1459                         else {
1460                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1461                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1462                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1463                         }
1464
1465                         /* PMV data */
1466                         if(mesh->pv) {
1467                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1468                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1469                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1470                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1471                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1472                         }
1473                 }
1474                 mesh= mesh->id.next;
1475         }
1476 }
1477
1478 static void write_lattices(WriteData *wd, ListBase *idbase)
1479 {
1480         Lattice *lt;
1481         
1482         lt= idbase->first;
1483         while(lt) {
1484                 if(lt->id.us>0 || wd->current) {
1485                         /* write LibData */
1486                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1487                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1488
1489                         /* direct data */
1490                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1491                         
1492                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1493                         
1494                 }
1495                 lt= lt->id.next;
1496         }
1497 }
1498
1499 static void write_previews(WriteData *wd, PreviewImage *prv)
1500 {
1501         if (prv) {
1502                 short w = prv->w[1];
1503                 short h = prv->h[1];
1504                 unsigned int *rect = prv->rect[1];
1505                 /* don't write out large previews if not requested */
1506                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1507                         prv->w[1] = 0;
1508                         prv->h[1] = 0;
1509                         prv->rect[1] = NULL;
1510                 }
1511                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1512                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1513                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1514
1515                 /* restore preview, we still want to keep it in memory even if not saved to file */
1516                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1517                         prv->w[1] = w;
1518                         prv->h[1] = h;
1519                         prv->rect[1] = rect;
1520                 }
1521         }
1522 }
1523
1524 static void write_images(WriteData *wd, ListBase *idbase)
1525 {
1526         Image *ima;
1527         PackedFile * pf;
1528
1529
1530         ima= idbase->first;
1531         while(ima) {
1532                 if(ima->id.us>0 || wd->current) {
1533                         /* write LibData */
1534                         writestruct(wd, ID_IM, "Image", 1, ima);
1535                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1536
1537                         if (ima->packedfile) {
1538                                 pf = ima->packedfile;
1539                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1540                                 writedata(wd, DATA, pf->size, pf->data);
1541                         }
1542
1543                         write_previews(wd, ima->preview);
1544
1545                         /* exception: render text only saved in undo files (wd->current) */
1546                         if (ima->render_text && wd->current)
1547                                 writedata(wd, DATA, IMA_RW_MAXTEXT, ima->render_text);
1548                 }
1549                 ima= ima->id.next;
1550         }
1551         /* flush helps the compression for undo-save */
1552         mywrite(wd, MYWRITE_FLUSH, 0);
1553 }
1554
1555 static void write_textures(WriteData *wd, ListBase *idbase)
1556 {
1557         Tex *tex;
1558
1559         tex= idbase->first;
1560         while(tex) {
1561                 if(tex->id.us>0 || wd->current) {
1562                         /* write LibData */
1563                         writestruct(wd, ID_TE, "Tex", 1, tex);
1564                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1565
1566                         if (tex->adt) write_animdata(wd, tex->adt);
1567
1568                         /* direct data */
1569                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1570                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1571                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1572                         
1573                         /* nodetree is integral part of texture, no libdata */
1574                         if(tex->nodetree) {
1575                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1576                                 write_nodetree(wd, tex->nodetree);
1577                         }
1578                         
1579                         write_previews(wd, tex->preview);
1580                 }
1581                 tex= tex->id.next;
1582         }
1583
1584         /* flush helps the compression for undo-save */
1585         mywrite(wd, MYWRITE_FLUSH, 0);
1586 }
1587
1588 static void write_materials(WriteData *wd, ListBase *idbase)
1589 {
1590         Material *ma;
1591         int a;
1592
1593         ma= idbase->first;
1594         while(ma) {
1595                 if(ma->id.us>0 || wd->current) {
1596                         /* write LibData */
1597                         writestruct(wd, ID_MA, "Material", 1, ma);
1598                         
1599                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1600                           of library blocks that implement this.*/
1601                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1602                           set yet :) */
1603                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1604                         
1605                         if (ma->adt) write_animdata(wd, ma->adt);
1606
1607                         for(a=0; a<MAX_MTEX; a++) {
1608                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1609                         }
1610                         
1611                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1612                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1613                         
1614                         /* nodetree is integral part of material, no libdata */
1615                         if(ma->nodetree) {
1616                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1617                                 write_nodetree(wd, ma->nodetree);
1618                         }
1619
1620                         write_previews(wd, ma->preview);                        
1621                 }
1622                 ma= ma->id.next;
1623         }
1624 }
1625
1626 static void write_worlds(WriteData *wd, ListBase *idbase)
1627 {
1628         World *wrld;
1629         int a;
1630
1631         wrld= idbase->first;
1632         while(wrld) {
1633                 if(wrld->id.us>0 || wd->current) {
1634                         /* write LibData */
1635                         writestruct(wd, ID_WO, "World", 1, wrld);
1636                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1637                         
1638                         if (wrld->adt) write_animdata(wd, wrld->adt);
1639                         
1640                         for(a=0; a<MAX_MTEX; a++) {
1641                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1642                         }
1643                         
1644                         write_previews(wd, wrld->preview);
1645                 }
1646                 wrld= wrld->id.next;
1647         }
1648 }
1649
1650 static void write_lamps(WriteData *wd, ListBase *idbase)
1651 {
1652         Lamp *la;
1653         int a;
1654
1655         la= idbase->first;
1656         while(la) {
1657                 if(la->id.us>0 || wd->current) {
1658                         /* write LibData */
1659                         writestruct(wd, ID_LA, "Lamp", 1, la);
1660                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1661                         
1662                         if (la->adt) write_animdata(wd, la->adt);
1663                         
1664                         /* direct data */
1665                         for(a=0; a<MAX_MTEX; a++) {
1666                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1667                         }
1668                         
1669                         if(la->curfalloff)
1670                                 write_curvemapping(wd, la->curfalloff); 
1671                         
1672                         write_previews(wd, la->preview);
1673                         
1674                 }
1675                 la= la->id.next;
1676         }
1677 }
1678
1679
1680 static void write_scenes(WriteData *wd, ListBase *scebase)
1681 {
1682         Scene *sce;
1683         Base *base;
1684         Editing *ed;
1685         Sequence *seq;
1686         MetaStack *ms;
1687         Strip *strip;
1688         TimeMarker *marker;
1689         TransformOrientation *ts;
1690         SceneRenderLayer *srl;
1691         
1692         sce= scebase->first;
1693         while(sce) {
1694                 /* write LibData */
1695                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1696                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1697                 
1698                 if (sce->adt) write_animdata(wd, sce->adt);
1699                 write_keyingsets(wd, &sce->keyingsets);
1700                 
1701                 /* direct data */
1702                 base= sce->base.first;
1703                 while(base) {
1704                         writestruct(wd, DATA, "Base", 1, base);
1705                         base= base->next;
1706                 }
1707                 
1708                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1709                 if(sce->toolsettings->vpaint)
1710                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->vpaint);
1711                 if(sce->toolsettings->wpaint)
1712                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->wpaint);
1713                 if(sce->toolsettings->sculpt)
1714                         writestruct(wd, DATA, "Sculpt", 1, sce->toolsettings->sculpt);
1715
1716                 ed= sce->ed;
1717                 if(ed) {
1718                         writestruct(wd, DATA, "Editing", 1, ed);
1719                         
1720                         /* reset write flags too */
1721                         
1722                         SEQ_BEGIN(ed, seq) {
1723                                 if(seq->strip) seq->strip->done= 0;
1724                                 writestruct(wd, DATA, "Sequence", 1, seq);
1725                         }
1726                         SEQ_END
1727                         
1728                         SEQ_BEGIN(ed, seq) {
1729                                 if(seq->strip && seq->strip->done==0) {
1730                                         /* write strip with 'done' at 0 because readfile */
1731                                         
1732                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1733                                         if(seq->effectdata) {
1734                                                 switch(seq->type){
1735                                                 case SEQ_COLOR:
1736                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1737                                                         break;
1738                                                 case SEQ_SPEED:
1739                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1740                                                         break;
1741                                                 case SEQ_WIPE:
1742                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1743                                                         break;
1744                                                 case SEQ_GLOW:
1745                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1746                                                         break;
1747                                                 case SEQ_TRANSFORM:
1748                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1749                                                         break;
1750                                                 }
1751                                         }
1752                                         
1753                                         strip= seq->strip;
1754                                         writestruct(wd, DATA, "Strip", 1, strip);
1755                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1756                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1757                                         }
1758                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1759                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1760                                         }
1761                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1762                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1763                                         }
1764                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1765                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1766                                         }
1767                                         if(seq->type==SEQ_IMAGE)
1768                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1769                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1770                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1771                                         
1772                                         strip->done= 1;
1773                                 }
1774                         }
1775                         SEQ_END
1776                                 
1777                         /* new; meta stack too, even when its nasty restore code */
1778                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1779                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1780                         }
1781                 }
1782                 
1783                 if (sce->r.avicodecdata) {
1784                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1785                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1786                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1787                 }
1788
1789                 if (sce->r.qtcodecdata) {
1790                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1791                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1792                 }
1793                 if (sce->r.ffcodecdata.properties) {
1794                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1795                 }
1796
1797                 /* writing dynamic list of TimeMarkers to the blend file */
1798                 for(marker= sce->markers.first; marker; marker= marker->next)
1799                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1800                 
1801                 /* writing dynamic list of TransformOrientations to the blend file */
1802                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1803                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1804                 
1805                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1806                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1807                 
1808                 if(sce->nodetree) {
1809                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1810                         write_nodetree(wd, sce->nodetree);
1811                 }
1812                 
1813                 sce= sce->id.next;
1814         }
1815         /* flush helps the compression for undo-save */
1816         mywrite(wd, MYWRITE_FLUSH, 0);
1817 }
1818
1819 static void write_gpencils(WriteData *wd, ListBase *lb)
1820 {
1821         bGPdata *gpd;
1822         bGPDlayer *gpl;
1823         bGPDframe *gpf;
1824         bGPDstroke *gps;
1825         
1826         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1827                 /* write gpd data block to file */
1828                 writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1829                 
1830                 /* write grease-pencil layers to file */
1831                 for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1832                         writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1833                         
1834                         /* write this layer's frames to file */
1835                         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1836                                 writestruct(wd, DATA, "bGPDframe", 1, gpf);
1837                                 
1838                                 /* write strokes */
1839                                 for (gps= gpf->strokes.first; gps; gps= gps->next) {
1840                                         writestruct(wd, DATA, "bGPDstroke", 1, gps);
1841                                         writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1842                                 }
1843                         }
1844                 }
1845         }
1846 }
1847
1848 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1849 {
1850         wmWindowManager *wm;
1851         wmWindow *win;
1852         
1853         for(wm= lb->first; wm; wm= wm->id.next) {
1854                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1855                 
1856                 for(win= wm->windows.first; win; win= win->next)
1857                         writestruct(wd, DATA, "wmWindow", 1, win);
1858         }
1859 }
1860
1861 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1862 {       
1863         writestruct(wd, DATA, "ARegion", 1, ar);
1864         
1865         if(ar->regiondata) {
1866                 switch(spacetype) {
1867                         case SPACE_VIEW3D:
1868                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1869                                         RegionView3D *rv3d= ar->regiondata;
1870                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
1871                                         
1872                                         if(rv3d->localvd)
1873                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
1874                                         if(rv3d->clipbb) 
1875                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
1876
1877                                 }
1878                                 else
1879                                         printf("regiondata write missing!\n");
1880                                 break;
1881                         default:
1882                                 printf("regiondata write missing!\n");
1883                 }
1884         }
1885 }
1886
1887 static void write_screens(WriteData *wd, ListBase *scrbase)
1888 {
1889         bScreen *sc;
1890         ScrArea *sa;
1891         ScrVert *sv;
1892         ScrEdge *se;
1893
1894         sc= scrbase->first;
1895         while(sc) {
1896                 
1897                 /* write LibData */
1898                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
1899                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
1900                 if (sc->id.properties) 
1901                         IDP_WriteProperty(sc->id.properties, wd);
1902                 
1903                 /* direct data */
1904                 for(sv= sc->vertbase.first; sv; sv= sv->next)
1905                         writestruct(wd, DATA, "ScrVert", 1, sv);
1906                 
1907                 for(se= sc->edgebase.first; se; se= se->next) 
1908                         writestruct(wd, DATA, "ScrEdge", 1, se);
1909                 
1910                 for(sa= sc->areabase.first; sa; sa= sa->next) {
1911                         SpaceLink *sl;
1912                         Panel *pa;
1913                         ARegion *ar;
1914                         
1915                         writestruct(wd, DATA, "ScrArea", 1, sa);
1916                         
1917                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
1918                                 write_region(wd, ar, sa->spacetype);
1919                                 
1920                                 for(pa= ar->panels.first; pa; pa= pa->next)
1921                                         writestruct(wd, DATA, "Panel", 1, pa);
1922                         }
1923                         
1924                         sl= sa->spacedata.first;
1925                         while(sl) {
1926                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
1927                                         write_region(wd, ar, sl->spacetype);
1928                                 
1929                                 if(sl->spacetype==SPACE_VIEW3D) {
1930                                         View3D *v3d= (View3D *) sl;
1931                                         writestruct(wd, DATA, "View3D", 1, v3d);
1932                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1933                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1934                                 }
1935                                 else if(sl->spacetype==SPACE_IPO) {
1936                                         SpaceIpo *sipo= (SpaceIpo *)sl;
1937                                         ListBase tmpGhosts = sipo->ghostCurves;
1938                                         
1939                                         /* temporarily disable ghost curves when saving */
1940                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
1941                                         
1942                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1943                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
1944                                         
1945                                         /* reenable ghost curves */
1946                                         sipo->ghostCurves= tmpGhosts;
1947                                 }
1948                                 else if(sl->spacetype==SPACE_BUTS) {
1949                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1950                                 }
1951                                 else if(sl->spacetype==SPACE_FILE) {
1952                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1953                                 }
1954                                 else if(sl->spacetype==SPACE_SEQ) {
1955                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1956                                 }
1957                                 else if(sl->spacetype==SPACE_OUTLINER) {
1958                                         SpaceOops *so= (SpaceOops *)sl;
1959                                         
1960                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1961
1962                                         /* outliner */
1963                                         if(so->treestore) {
1964                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1965                                                 if(so->treestore->data)
1966                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1967                                         }
1968                                 }
1969                                 else if(sl->spacetype==SPACE_IMAGE) {
1970                                         SpaceImage *sima= (SpaceImage *)sl;
1971                                         
1972                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1973                                         if(sima->cumap)
1974                                                 write_curvemapping(wd, sima->cumap);
1975                                 }
1976                                 else if(sl->spacetype==SPACE_IMASEL) {
1977                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1978                                 }
1979                                 else if(sl->spacetype==SPACE_TEXT) {
1980                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1981                                 }
1982                                 else if(sl->spacetype==SPACE_SCRIPT) {
1983                                         SpaceScript *sc = (SpaceScript*)sl;
1984                                         sc->but_refs = NULL;
1985                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1986                                 }
1987                                 else if(sl->spacetype==SPACE_ACTION) {
1988                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1989                                 }
1990                                 else if(sl->spacetype==SPACE_SOUND) {
1991                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1992                                 }
1993                                 else if(sl->spacetype==SPACE_NLA){
1994                                         SpaceNla *snla= (SpaceNla *)sl;
1995                                         
1996                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
1997                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
1998                                 }
1999                                 else if(sl->spacetype==SPACE_TIME){
2000                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2001                                 }
2002                                 else if(sl->spacetype==SPACE_NODE){
2003                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2004                                 }
2005                                 else if(sl->spacetype==SPACE_LOGIC){
2006                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2007                                 }
2008                                 else if(sl->spacetype==SPACE_CONSOLE) {
2009                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2010                                 }
2011                                 sl= sl->next;
2012                         }
2013                 }
2014
2015                 sc= sc->id.next;
2016         }
2017 }
2018
2019 static void write_libraries(WriteData *wd, Main *main)
2020 {
2021         ListBase *lbarray[30];
2022         ID *id;
2023         int a, tot, foundone;
2024
2025         for(; main; main= main->next) {
2026
2027                 a=tot= set_listbasepointers(main, lbarray);
2028
2029                 /* test: is lib being used */
2030                 foundone= 0;
2031                 while(tot--) {
2032                         for(id= lbarray[tot]->first; id; id= id->next) {
2033                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2034                                         foundone= 1;
2035                                         break;
2036                                 }
2037                         }
2038                         if(foundone) break;
2039                 }
2040
2041                 if(foundone) {
2042                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2043
2044                         while(a--) {
2045                                 for(id= lbarray[a]->first; id; id= id->next) {
2046                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2047                                                 writestruct(wd, ID_ID, "ID", 1, id);
2048                                         }
2049                                 }
2050                         }
2051                 }
2052         }
2053 }
2054
2055 static void write_bone(WriteData *wd, Bone* bone)
2056 {
2057         Bone*   cbone;
2058
2059         // PATCH for upward compatibility after 2.37+ armature recode
2060         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2061                 
2062         // Write this bone
2063         writestruct(wd, DATA, "Bone", 1, bone);
2064         
2065         // Write Children
2066         cbone= bone->childbase.first;
2067         while(cbone) {
2068                 write_bone(wd, cbone);
2069                 cbone= cbone->next;
2070         }
2071 }
2072
2073 static void write_armatures(WriteData *wd, ListBase *idbase)
2074 {
2075         bArmature       *arm;
2076         Bone            *bone;
2077
2078         arm=idbase->first;
2079         while (arm) {
2080                 if (arm->id.us>0 || wd->current) {
2081                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2082                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2083
2084                         /* Direct data */
2085                         bone= arm->bonebase.first;
2086                         while(bone) {
2087                                 write_bone(wd, bone);
2088                                 bone=bone->next;
2089                         }
2090                 }
2091                 arm=arm->id.next;
2092         }
2093
2094         /* flush helps the compression for undo-save */
2095         mywrite(wd, MYWRITE_FLUSH, 0);
2096 }
2097
2098 static void write_texts(WriteData *wd, ListBase *idbase)
2099 {
2100         Text *text;
2101         TextLine *tmp;
2102         TextMarker *mrk;
2103
2104         text= idbase->first;
2105         while(text) {
2106                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2107
2108                 /* write LibData */
2109                 writestruct(wd, ID_TXT, "Text", 1, text);
2110                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2111                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2112
2113                 if(!(text->flags & TXT_ISEXT)) {
2114                         /* now write the text data, in two steps for optimization in the readfunction */
2115                         tmp= text->lines.first;
2116                         while (tmp) {
2117                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2118                                 tmp= tmp->next;
2119                         }
2120
2121                         tmp= text->lines.first;
2122                         while (tmp) {
2123                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2124                                 tmp= tmp->next;
2125                         }
2126
2127                         /* write markers */
2128                         mrk= text->markers.first;
2129                         while (mrk) {
2130                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2131                                 mrk= mrk->next;
2132                         }
2133                 }
2134
2135
2136                 text= text->id.next;
2137         }
2138
2139         /* flush helps the compression for undo-save */
2140         mywrite(wd, MYWRITE_FLUSH, 0);
2141 }
2142
2143 static void write_sounds(WriteData *wd, ListBase *idbase)
2144 {
2145         bSound *sound;
2146
2147         PackedFile * pf;
2148
2149         sound= idbase->first;
2150         while(sound) {
2151                 if(sound->id.us>0 || wd->current) {
2152                         /* write LibData */
2153                         writestruct(wd, ID_SO, "bSound", 1, sound);
2154                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2155
2156                         if (sound->packedfile) {
2157                                 pf = sound->packedfile;
2158                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2159                                 writedata(wd, DATA, pf->size, pf->data);
2160                         }
2161                 }
2162                 sound= sound->id.next;
2163         }
2164
2165         /* flush helps the compression for undo-save */
2166         mywrite(wd, MYWRITE_FLUSH, 0);
2167 }
2168
2169 static void write_groups(WriteData *wd, ListBase *idbase)
2170 {
2171         Group *group;
2172         GroupObject *go;
2173
2174         for(group= idbase->first; group; group= group->id.next) {
2175                 if(group->id.us>0 || wd->current) {
2176                         /* write LibData */
2177                         writestruct(wd, ID_GR, "Group", 1, group);
2178                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2179
2180                         go= group->gobject.first;
2181                         while(go) {
2182                                 writestruct(wd, DATA, "GroupObject", 1, go);
2183                                 go= go->next;
2184                         }
2185                 }
2186         }
2187 }
2188
2189 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2190 {
2191         bNodeTree *ntree;
2192         
2193         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2194                 if (ntree->id.us>0 || wd->current) {
2195                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2196                         write_nodetree(wd, ntree);
2197                         
2198                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2199                         
2200                         if (ntree->adt) write_animdata(wd, ntree->adt);
2201                 }
2202         }
2203 }
2204
2205 static void write_brushes(WriteData *wd, ListBase *idbase)
2206 {
2207         Brush *brush;
2208         int a;
2209         
2210         for(brush=idbase->first; brush; brush= brush->id.next) {
2211                 if(brush->id.us>0 || wd->current) {
2212                         writestruct(wd, ID_BR, "Brush", 1, brush);
2213                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2214                         for(a=0; a<MAX_MTEX; a++)
2215                                 if(brush->mtex[a])
2216                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
2217
2218                         if(brush->curve)
2219                                 write_curvemapping(wd, brush->curve);
2220                 }
2221         }
2222 }
2223
2224 static void write_scripts(WriteData *wd, ListBase *idbase)
2225 {
2226         Script *script;
2227         
2228         for(script=idbase->first; script; script= script->id.next) {
2229                 if(script->id.us>0 || wd->current) {
2230                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2231                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2232                 }
2233         }
2234 }
2235
2236 /* context is usually defined by WM, two cases where no WM is available:
2237  * - for forward compatibility, curscreen has to be saved
2238  * - for undofile, curscene needs to be saved */
2239 static void write_global(WriteData *wd, Main *mainvar)
2240 {
2241         FileGlobal fg;
2242         bScreen *screen;
2243         char subvstr[8];
2244         
2245         current_screen_compat(mainvar, &screen);
2246
2247         /* XXX still remap G */
2248         fg.curscreen= screen;
2249         fg.curscene= screen->scene;
2250         fg.displaymode= G.displaymode;
2251         fg.winpos= G.winpos;
2252         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2253         fg.globalf= G.f;
2254
2255         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2256         memcpy(fg.subvstr, subvstr, 4);
2257         
2258         fg.subversion= BLENDER_SUBVERSION;
2259         fg.minversion= BLENDER_MINVERSION;
2260         fg.minsubversion= BLENDER_MINSUBVERSION;
2261         fg.pads= 0; /* prevent mem checkers from complaining */
2262         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2263 }
2264
2265 /* if MemFile * there's filesave to memory */
2266 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2267                                                          int write_user_block, int write_flags)
2268 {
2269         BHead bhead;
2270         ListBase mainlist;
2271         char buf[16];
2272         WriteData *wd;
2273
2274         blo_split_main(&mainlist, mainvar);
2275
2276         wd= bgnwrite(handle, compare, current, write_flags);
2277         
2278         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2279         mywrite(wd, buf, 12);
2280
2281         write_renderinfo(wd, mainvar);
2282         write_global(wd, mainvar);
2283
2284         /* no UI save in undo */
2285         if(current==NULL) {
2286                 write_windowmanagers(wd, &mainvar->wm);
2287                 write_screens  (wd, &mainvar->screen);
2288         }
2289         write_scenes   (wd, &mainvar->scene);
2290         write_curves   (wd, &mainvar->curve);
2291         write_mballs   (wd, &mainvar->mball);
2292         write_images   (wd, &mainvar->image);
2293         write_cameras  (wd, &mainvar->camera);
2294         write_lamps    (wd, &mainvar->lamp);
2295         write_lattices (wd, &mainvar->latt);
2296         write_vfonts   (wd, &mainvar->vfont);
2297         write_keys     (wd, &mainvar->key);
2298         write_worlds   (wd, &mainvar->world);
2299         write_texts    (wd, &mainvar->text);
2300         write_sounds   (wd, &mainvar->sound);
2301         write_groups   (wd, &mainvar->group);
2302         write_armatures(wd, &mainvar->armature);
2303         write_actions  (wd, &mainvar->action);
2304         write_objects  (wd, &mainvar->object, (current != NULL));
2305         write_materials(wd, &mainvar->mat);
2306         write_textures (wd, &mainvar->tex);
2307         write_meshs    (wd, &mainvar->mesh);
2308         write_particlesettings(wd, &mainvar->particle);
2309         write_nodetrees(wd, &mainvar->nodetree);
2310         write_brushes  (wd, &mainvar->brush);
2311         write_scripts  (wd, &mainvar->script);
2312         write_gpencils (wd, &mainvar->gpencil);
2313         if(current==NULL)       
2314                 write_libraries(wd,  mainvar->next); /* no library save in undo */
2315
2316         if (write_user_block) {
2317                 write_userdef(wd);
2318         }
2319                                                         
2320         /* dna as last, because (to be implemented) test for which structs are written */
2321         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2322
2323         /* end of file */
2324         memset(&bhead, 0, sizeof(BHead));
2325         bhead.code= ENDB;
2326         mywrite(wd, &bhead, sizeof(BHead));
2327
2328         blo_join_main(&mainlist);
2329
2330         return endwrite(wd);
2331 }
2332
2333 /* return: success (1) */
2334 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports)
2335 {
2336         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2337         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2338         int file, err, write_user_block;
2339
2340         sprintf(tempname, "%s@", dir);
2341
2342         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2343         if(file == -1) {
2344                 BKE_report(reports, RPT_ERROR, "Unable to open file for writing.");
2345                 return 0;
2346         }
2347
2348         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B25.blend");
2349         write_user_block= BLI_streq(dir, userfilename);
2350
2351         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags);
2352         close(file);
2353
2354         if(!err) {
2355                 if(write_flags & G_FILE_COMPRESS)
2356                 {       
2357                         // compressed files have the same ending as regular files... only from 2.4!!!
2358                         
2359                         int ret = BLI_gzip(tempname, dir);
2360                         
2361                         if(-1==ret) {
2362                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2363                                 return 0;
2364                         }
2365                         if(-2==ret) {
2366                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2367                                 return 0;
2368                         }
2369                 }
2370                 else
2371                 if(BLI_rename(tempname, dir) != 0) {
2372                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2373                         return 0;
2374                 }
2375
2376                 
2377         } else {
2378                 BKE_report(reports, RPT_ERROR, strerror(errno));
2379                 remove(tempname);
2380
2381                 return 0;
2382         }
2383
2384         return 1;
2385 }
2386
2387 /* return: success (1) */
2388 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags, ReportList *reports)
2389 {
2390         int err;
2391
2392         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags);
2393         
2394         if(err==0) return 1;
2395         return 0;
2396 }
2397
2398
2399         /* Runtime writing */
2400
2401 #ifdef WIN32
2402 #define PATHSEPERATOR           "\\"
2403 #else
2404 #define PATHSEPERATOR           "/"
2405 #endif
2406
2407 static char *get_runtime_path(char *exename) {
2408         char *installpath= get_install_dir();
2409
2410         if (!installpath) {
2411                 return NULL;
2412         } else {
2413                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2414
2415                 if (path == NULL) {
2416                         MEM_freeN(installpath);
2417                         return NULL;
2418                 }
2419
2420                 strcpy(path, installpath);
2421                 strcat(path, PATHSEPERATOR);
2422                 strcat(path, exename);
2423
2424                 MEM_freeN(installpath);
2425
2426                 return path;
2427         }
2428 }
2429
2430 #ifdef __APPLE__
2431
2432 static int recursive_copy_runtime(char *outname, char *exename, ReportList *reports)
2433 {
2434         char *runtime = get_runtime_path(exename);
2435         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2436         int progfd = -1, error= 0;
2437
2438         if (!runtime) {
2439                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2440                 error= 1;
2441                 goto cleanup;
2442         }
2443         //printf("runtimepath %s\n", runtime);
2444                 
2445         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2446         if (progfd==-1) {
2447                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2448                 error= 1;
2449                 goto cleanup;
2450         }
2451
2452         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2453         //printf("command %s\n", command);
2454         if (system(command) == -1) {
2455                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2456                 error= 1;
2457         }
2458
2459 cleanup:
2460         if (progfd!=-1)
2461                 close(progfd);
2462         if (runtime)
2463                 MEM_freeN(runtime);
2464
2465         return !error;
2466 }
2467
2468 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports) 
2469 {
2470         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2471         int outfd = -1, error= 0;
2472
2473         // remove existing file / bundle
2474         //printf("Delete file %s\n", file);
2475         BLI_delete(file, 0, TRUE);
2476
2477         if (!recursive_copy_runtime(file, exename, reports)) {
2478                 error= 1;
2479                 goto cleanup;
2480         }
2481
2482         strcpy(gamename, file);
2483         strcat(gamename, "/Contents/Resources/game.blend");
2484         //printf("gamename %s\n", gamename);
2485         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2486         if (outfd != -1) {
2487
2488                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2489
2490                 if (write(outfd, " ", 1) != 1) {
2491                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2492                         error= 1;
2493                         goto cleanup;
2494                 }
2495         } else {
2496                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2497                 error= 1;
2498         }
2499
2500 cleanup:
2501         if (outfd!=-1)
2502                 close(outfd);
2503
2504         BKE_reports_prepend(reports, "Unable to make runtime: ");
2505         return !error;
2506 }
2507
2508 #else /* !__APPLE__ */
2509
2510 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2511 {
2512         char *runtime= get_runtime_path(exename);
2513         unsigned char buf[1024];
2514         int count, progfd= -1, error= 0;
2515
2516         if (!BLI_exists(runtime)) {
2517                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2518                 error= 1;
2519                 goto cleanup;
2520         }
2521
2522         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2523         if (progfd==-1) {
2524                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2525                 error= 1;
2526                 goto cleanup;
2527         }
2528
2529         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2530                 if (write(handle, buf, count)!=count) {
2531                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2532                         error= 1;
2533                         goto cleanup;
2534                 }
2535         }
2536
2537 cleanup:
2538         if (progfd!=-1)
2539                 close(progfd);
2540         if (runtime)
2541                 MEM_freeN(runtime);
2542
2543         return !error;
2544 }
2545
2546 static int handle_write_msb_int(int handle, int i) 
2547 {
2548         unsigned char buf[4];
2549         buf[0]= (i>>24)&0xFF;
2550         buf[1]= (i>>16)&0xFF;
2551         buf[2]= (i>>8)&0xFF;
2552         buf[3]= (i>>0)&0xFF;
2553
2554         return (write(handle, buf, 4)==4);
2555 }
2556
2557 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports)
2558 {
2559         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2560         int datastart, error= 0;
2561
2562         if (!outfd) {
2563                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2564                 error= 1;
2565                 goto cleanup;
2566         }
2567         if (!handle_append_runtime(outfd, exename, reports)) {
2568                 error= 1;
2569                 goto cleanup;
2570         }
2571
2572         datastart= lseek(outfd, 0, SEEK_CUR);
2573
2574         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2575
2576         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2577                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2578                 error= 1;
2579                 goto cleanup;
2580         }
2581
2582 cleanup:
2583         if (outfd!=-1)
2584                 close(outfd);
2585
2586         BKE_reports_prepend(reports, "Unable to make runtime: ");
2587         return !error;
2588 }
2589
2590 #endif /* !__APPLE__ */