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