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