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