Merge of itasc branch. Project files, scons and cmake should be working. Makefile...
[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
614         part= idbase->first;
615         while(part) {
616                 if(part->id.us>0 || wd->current) {
617                         /* write LibData */
618                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
619                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
620                         if (part->adt) write_animdata(wd, part->adt);
621                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
622                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
623
624                         if(part->boids && part->phystype == PART_PHYS_BOIDS) {
625                                 BoidState *state = part->boids->states.first;
626
627                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
628
629                                 for(; state; state=state->next)
630                                         write_boid_state(wd, state);
631                         }
632                 }
633                 part= part->id.next;
634         }
635 }
636 static void write_particlesystems(WriteData *wd, ListBase *particles)
637 {
638         ParticleSystem *psys= particles->first;
639         ParticleTarget *pt;
640         int a;
641
642         for(; psys; psys=psys->next) {
643                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
644
645                 if(psys->particles) {
646                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
647
648                         if(psys->particles->hair) {
649                                 ParticleData *pa = psys->particles;
650
651                                 for(a=0; a<psys->totpart; a++, pa++)
652                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
653                         }
654
655                         if(psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
656                                 writestruct(wd, DATA, "BoidParticle", psys->totpart, psys->particles->boid);
657                 }
658                 pt = psys->targets.first;
659                 for(; pt; pt=pt->next)
660                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
661
662                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
663
664                 if(psys->clmd) {
665                         writestruct(wd, DATA, "ClothModifierData", 1, psys->clmd);
666                         writestruct(wd, DATA, "ClothSimSettings", 1, psys->clmd->sim_parms);
667                         writestruct(wd, DATA, "ClothCollSettings", 1, psys->clmd->coll_parms);
668                 }
669                 
670                 write_pointcaches(wd, &psys->ptcaches);
671         }
672 }
673
674 static void write_properties(WriteData *wd, ListBase *lb)
675 {
676         bProperty *prop;
677
678         prop= lb->first;
679         while(prop) {
680                 writestruct(wd, DATA, "bProperty", 1, prop);
681
682                 if(prop->poin && prop->poin != &prop->data)
683                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
684
685                 prop= prop->next;
686         }
687 }
688
689 static void write_sensors(WriteData *wd, ListBase *lb)
690 {
691         bSensor *sens;
692
693         sens= lb->first;
694         while(sens) {
695                 writestruct(wd, DATA, "bSensor", 1, sens);
696
697                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
698
699                 switch(sens->type) {
700                 case SENS_NEAR:
701                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
702                         break;
703                 case SENS_MOUSE:
704                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
705                         break;
706                 case SENS_TOUCH:
707                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
708                         break;
709                 case SENS_KEYBOARD:
710                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
711                         break;
712                 case SENS_PROPERTY:
713                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
714                         break;
715                 case SENS_ARMATURE:
716                         writestruct(wd, DATA, "bArmatureSensor", 1, sens->data);
717                         break;
718                 case SENS_ACTUATOR:
719                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
720                         break;
721                 case SENS_DELAY:
722                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
723                         break;
724                 case SENS_COLLISION:
725                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
726                         break;
727                 case SENS_RADAR:
728                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
729                         break;
730                 case SENS_RANDOM:
731                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
732                         break;
733                 case SENS_RAY:
734                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
735                         break;
736                 case SENS_MESSAGE:
737                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
738                         break;
739                 case SENS_JOYSTICK:
740                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
741                         break;
742                 default:
743                         ; /* error: don't know how to write this file */
744                 }
745
746                 sens= sens->next;
747         }
748 }
749
750 static void write_controllers(WriteData *wd, ListBase *lb)
751 {
752         bController *cont;
753
754         cont= lb->first;
755         while(cont) {
756                 writestruct(wd, DATA, "bController", 1, cont);
757
758                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
759
760                 switch(cont->type) {
761                 case CONT_EXPRESSION:
762                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
763                         break;
764                 case CONT_PYTHON:
765                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
766                         break;
767                 default:
768                         ; /* error: don't know how to write this file */
769                 }
770
771                 cont= cont->next;
772         }
773 }
774
775 static void write_actuators(WriteData *wd, ListBase *lb)
776 {
777         bActuator *act;
778
779         act= lb->first;
780         while(act) {
781                 writestruct(wd, DATA, "bActuator", 1, act);
782
783                 switch(act->type) {
784                 case ACT_ACTION:
785                 case ACT_SHAPEACTION:
786                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
787                         break;
788                 case ACT_SOUND:
789                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
790                         break;
791                 case ACT_OBJECT:
792                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
793                         break;
794                 case ACT_IPO:
795                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
796                         break;
797                 case ACT_PROPERTY:
798                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
799                         break;
800                 case ACT_CAMERA:
801                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
802                         break;
803                 case ACT_CONSTRAINT:
804                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
805                         break;
806                 case ACT_EDIT_OBJECT:
807                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
808                         break;
809                 case ACT_SCENE:
810                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
811                         break;
812                 case ACT_GROUP:
813                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
814                         break;
815                 case ACT_RANDOM:
816                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
817                         break;
818                 case ACT_MESSAGE:
819                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
820                         break;
821                 case ACT_GAME:
822                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
823                         break;
824                 case ACT_VISIBILITY:
825                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
826                         break;
827                 case ACT_2DFILTER:
828                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
829                         break;
830                 case ACT_PARENT:
831                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
832                         break;
833                 case ACT_STATE:
834                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
835                         break;
836                 case ACT_ARMATURE:
837                         writestruct(wd, DATA, "bArmatureActuator", 1, act->data);
838                         break;
839                 default:
840                         ; /* error: don't know how to write this file */
841                 }
842
843                 act= act->next;
844         }
845 }
846
847 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
848 {
849         FModifier *fcm;
850         
851         /* Modifiers */
852         for (fcm= fmodifiers->first; fcm; fcm= fcm->next) {
853                 FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
854                 
855                 /* Write the specific data */
856                 if (fmi && fcm->data) {
857                         /* firstly, just write the plain fmi->data struct */
858                         writestruct(wd, DATA, fmi->structName, 1, fcm->data);
859                         
860                         /* do any modifier specific stuff */
861                         switch (fcm->type) {
862                                 case FMODIFIER_TYPE_GENERATOR:
863                                 {
864                                         FMod_Generator *data= (FMod_Generator *)fcm->data;
865                                         
866                                         /* write coefficients array */
867                                         if (data->coefficients)
868                                                 writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
869                                 }
870                                         break;
871                                 case FMODIFIER_TYPE_ENVELOPE:
872                                 {
873                                         FMod_Envelope *data= (FMod_Envelope *)fcm->data;
874                                         
875                                         /* write envelope data */
876                                         if (data->data)
877                                                 writedata(wd, DATA, sizeof(FCM_EnvelopeData)*(data->totvert), data->data);
878                                 }
879                                         break;
880                                 case FMODIFIER_TYPE_PYTHON:
881                                 {
882                                         FMod_Python *data = (FMod_Python *)fcm->data;
883                                         
884                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
885                                          of library blocks that implement this.*/
886                                         IDP_WriteProperty(data->prop, wd);
887                                 }
888                                         break;
889                         }
890                 }
891                 
892                 /* Write the modifier */
893                 writestruct(wd, DATA, "FModifier", 1, fcm);
894         }
895 }
896
897 static void write_fcurves(WriteData *wd, ListBase *fcurves)
898 {
899         FCurve *fcu;
900         
901         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
902                 /* F-Curve */
903                 writestruct(wd, DATA, "FCurve", 1, fcu);
904                 
905                 /* curve data */
906                 if (fcu->bezt)          
907                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
908                 if (fcu->fpt)
909                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
910                         
911                 if (fcu->rna_path)
912                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
913                 
914                 /* driver data */
915                 if (fcu->driver) {
916                         ChannelDriver *driver= fcu->driver;
917                         DriverTarget *dtar;
918                         
919                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
920                         
921                         /* targets */
922                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
923                                 writestruct(wd, DATA, "DriverTarget", 1, dtar);
924                                 
925                                 if (dtar->rna_path)
926                                         writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
927                         }
928                 }
929                 
930                 /* write F-Modifiers */
931                 write_fmodifiers(wd, &fcu->modifiers);
932         }
933 }
934
935 static void write_actions(WriteData *wd, ListBase *idbase)
936 {
937         bAction *act;
938         bActionGroup *grp;
939         TimeMarker *marker;
940         
941         for(act=idbase->first; act; act= act->id.next) {
942                 if (act->id.us>0 || wd->current) {
943                         writestruct(wd, ID_AC, "bAction", 1, act);
944                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
945                         
946                         write_fcurves(wd, &act->curves);
947                         
948                         for (grp=act->groups.first; grp; grp=grp->next) {
949                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
950                         }
951                         
952                         for (marker=act->markers.first; marker; marker=marker->next) {
953                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
954                         }
955                 }
956         }
957         
958         /* flush helps the compression for undo-save */
959         mywrite(wd, MYWRITE_FLUSH, 0);
960 }
961
962 static void write_keyingsets(WriteData *wd, ListBase *list)
963 {
964         KeyingSet *ks;
965         KS_Path *ksp;
966         
967         for (ks= list->first; ks; ks= ks->next) {
968                 /* KeyingSet */
969                 writestruct(wd, DATA, "KeyingSet", 1, ks);
970                 
971                 /* Paths */
972                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
973                         /* Path */
974                         writestruct(wd, DATA, "KS_Path", 1, ksp);
975                         
976                         if (ksp->rna_path)
977                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
978                 }
979         }
980 }
981
982 static void write_nlastrips(WriteData *wd, ListBase *strips)
983 {
984         NlaStrip *strip;
985         
986         for (strip= strips->first; strip; strip= strip->next) {
987                 /* write the strip first */
988                 writestruct(wd, DATA, "NlaStrip", 1, strip);
989                 
990                 /* write the strip's F-Curves and modifiers */
991                 write_fcurves(wd, &strip->fcurves);
992                 write_fmodifiers(wd, &strip->modifiers);
993                 
994                 /* write the strip's children */
995                 write_nlastrips(wd, &strip->strips);
996         }
997 }
998
999 static void write_nladata(WriteData *wd, ListBase *nlabase)
1000 {
1001         NlaTrack *nlt;
1002         
1003         /* write all the tracks */
1004         for (nlt= nlabase->first; nlt; nlt= nlt->next) {
1005                 /* write the track first */
1006                 writestruct(wd, DATA, "NlaTrack", 1, nlt);
1007                 
1008                 /* write the track's strips */
1009                 write_nlastrips(wd, &nlt->strips);
1010         }
1011 }
1012
1013 static void write_animdata(WriteData *wd, AnimData *adt)
1014 {
1015         AnimOverride *aor;
1016         
1017         /* firstly, just write the AnimData block */
1018         writestruct(wd, DATA, "AnimData", 1, adt);
1019         
1020         /* write drivers */
1021         write_fcurves(wd, &adt->drivers);
1022         
1023         /* write overrides */
1024         // FIXME: are these needed?
1025         for (aor= adt->overrides.first; aor; aor= aor->next) {
1026                 /* overrides consist of base data + rna_path */
1027                 writestruct(wd, DATA, "AnimOverride", 1, aor);
1028                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
1029         }
1030         
1031         // TODO write the remaps (if they are needed)
1032         
1033         /* write NLA data */
1034         write_nladata(wd, &adt->nla_tracks);
1035 }
1036
1037 static void write_constraints(WriteData *wd, ListBase *conlist)
1038 {
1039         bConstraint *con;
1040
1041         for (con=conlist->first; con; con=con->next) {
1042                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1043                 
1044                 /* Write the specific data */
1045                 if (cti && con->data) {
1046                         /* firstly, just write the plain con->data struct */
1047                         writestruct(wd, DATA, cti->structName, 1, con->data);
1048                         
1049                         /* do any constraint specific stuff */
1050                         switch (con->type) {
1051                                 case CONSTRAINT_TYPE_PYTHON:
1052                                 {
1053                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1054                                         bConstraintTarget *ct;
1055                                         
1056                                         /* write targets */
1057                                         for (ct= data->targets.first; ct; ct= ct->next)
1058                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1059                                         
1060                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1061                                          of library blocks that implement this.*/
1062                                         IDP_WriteProperty(data->prop, wd);
1063                                 }
1064                                 break;
1065                         }
1066                 }
1067                 
1068                 /* Write the constraint */
1069                 writestruct(wd, DATA, "bConstraint", 1, con);
1070         }
1071 }
1072
1073 static void write_pose(WriteData *wd, bPose *pose)
1074 {
1075         bPoseChannel *chan;
1076         bActionGroup *grp;
1077
1078         /* Write each channel */
1079         if (!pose)
1080                 return;
1081
1082         /* Write channels */
1083         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1084                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1085                  of library blocks that implement this.*/
1086                 if (chan->prop)
1087                         IDP_WriteProperty(chan->prop, wd);
1088                 
1089                 write_constraints(wd, &chan->constraints);
1090                 
1091                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1092                 if (chan->bone) 
1093                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
1094                 
1095                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1096         }
1097         
1098         /* Write groups */
1099         for (grp=pose->agroups.first; grp; grp=grp->next) 
1100                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1101
1102         /* write IK param */
1103         if (pose->ikparam) {
1104                 const char *structname = get_ikparam_name(pose);
1105                 if (structname)
1106                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1107         }
1108
1109         /* Write this pose */
1110         writestruct(wd, DATA, "bPose", 1, pose);
1111
1112 }
1113
1114 static void write_defgroups(WriteData *wd, ListBase *defbase)
1115 {
1116         bDeformGroup    *defgroup;
1117
1118         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1119                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1120 }
1121
1122 static void write_modifiers(WriteData *wd, ListBase *modbase)
1123 {
1124         ModifierData *md;
1125
1126         if (modbase == NULL) return;
1127         for (md=modbase->first; md; md= md->next) {
1128                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1129                 if (mti == NULL) return;
1130                 
1131                 writestruct(wd, DATA, mti->structName, 1, md);
1132                         
1133                 if (md->type==eModifierType_Hook) {
1134                         HookModifierData *hmd = (HookModifierData*) md;
1135                         
1136                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1137                 }
1138                 else if(md->type==eModifierType_Cloth) {
1139                         ClothModifierData *clmd = (ClothModifierData*) md;
1140                         
1141                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1142                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1143                         write_pointcaches(wd, &clmd->ptcaches);
1144                 } 
1145                 else if(md->type==eModifierType_Smoke) {
1146                         SmokeModifierData *smd = (SmokeModifierData*) md;
1147                         
1148                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1149                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1150                         else if(smd->type & MOD_SMOKE_TYPE_FLOW)
1151                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1152                         /*
1153                         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1154                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1155                         */
1156
1157                         if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain)
1158                         {
1159                                 write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1160                                 write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1161                         }
1162                 } 
1163                 else if(md->type==eModifierType_Fluidsim) {
1164                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1165                         
1166                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1167                 } 
1168                 else if (md->type==eModifierType_Collision) {
1169                         
1170                         /*
1171                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1172                         // TODO: CollisionModifier should use pointcache 
1173                         // + have proper reset events before enabling this
1174                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1175                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1176                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1177                         */
1178                 }
1179                 else if (md->type==eModifierType_MeshDeform) {
1180                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1181                         int size = mmd->dyngridsize;
1182
1183                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
1184                                 mmd->bindweights);
1185                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1186                                 mmd->bindcos);
1187                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1188                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1189                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1190                 }
1191                 else if (md->type==eModifierType_Multires) {
1192                         MultiresModifierData *mmd = (MultiresModifierData*) md;
1193
1194                         if(mmd->undo_verts)
1195                                 writestruct(wd, DATA, "MVert", mmd->undo_verts_tot, mmd->undo_verts);
1196                 }
1197         }
1198 }
1199
1200 static void write_objects(WriteData *wd, ListBase *idbase)
1201 {
1202         Object *ob;
1203         
1204         ob= idbase->first;
1205         while(ob) {
1206                 if(ob->id.us>0 || wd->current) {
1207                         /* write LibData */
1208                         writestruct(wd, ID_OB, "Object", 1, ob);
1209                         
1210                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1211                           of library blocks that implement this.*/
1212                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1213                         
1214                         if (ob->adt) write_animdata(wd, ob->adt);
1215                         
1216                         /* direct data */
1217                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1218                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1219                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1220                         write_properties(wd, &ob->prop);
1221                         write_sensors(wd, &ob->sensors);
1222                         write_controllers(wd, &ob->controllers);
1223                         write_actuators(wd, &ob->actuators);
1224                         write_pose(wd, ob->pose);
1225                         write_defgroups(wd, &ob->defbase);
1226                         write_constraints(wd, &ob->constraints);
1227                         
1228                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1229                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1230                         if(ob->soft) write_pointcaches(wd, &ob->soft->ptcaches);
1231                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1232                         
1233                         write_particlesystems(wd, &ob->particlesystem);
1234                         write_modifiers(wd, &ob->modifiers);
1235                 }
1236                 ob= ob->id.next;
1237         }
1238
1239         /* flush helps the compression for undo-save */
1240         mywrite(wd, MYWRITE_FLUSH, 0);
1241 }
1242
1243
1244 static void write_vfonts(WriteData *wd, ListBase *idbase)
1245 {
1246         VFont *vf;
1247         PackedFile * pf;
1248
1249         vf= idbase->first;
1250         while(vf) {
1251                 if(vf->id.us>0 || wd->current) {
1252                         /* write LibData */
1253                         writestruct(wd, ID_VF, "VFont", 1, vf);
1254                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1255
1256                         /* direct data */
1257
1258                         if (vf->packedfile) {
1259                                 pf = vf->packedfile;
1260                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1261                                 writedata(wd, DATA, pf->size, pf->data);
1262                         }
1263                 }
1264
1265                 vf= vf->id.next;
1266         }
1267 }
1268
1269
1270 static void write_keys(WriteData *wd, ListBase *idbase)
1271 {
1272         Key *key;
1273         KeyBlock *kb;
1274
1275         key= idbase->first;
1276         while(key) {
1277                 if(key->id.us>0 || wd->current) {
1278                         /* write LibData */
1279                         writestruct(wd, ID_KE, "Key", 1, key);
1280                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1281                         
1282                         if (key->adt) write_animdata(wd, key->adt);
1283                         
1284                         /* direct data */
1285                         kb= key->block.first;
1286                         while(kb) {
1287                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1288                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1289                                 kb= kb->next;
1290                         }
1291                 }
1292
1293                 key= key->id.next;
1294         }
1295         /* flush helps the compression for undo-save */
1296         mywrite(wd, MYWRITE_FLUSH, 0);
1297 }
1298
1299 static void write_cameras(WriteData *wd, ListBase *idbase)
1300 {
1301         Camera *cam;
1302
1303         cam= idbase->first;
1304         while(cam) {
1305                 if(cam->id.us>0 || wd->current) {
1306                         /* write LibData */
1307                         writestruct(wd, ID_CA, "Camera", 1, cam);
1308                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1309                         
1310                         if (cam->adt) write_animdata(wd, cam->adt);
1311                 }
1312
1313                 cam= cam->id.next;
1314         }
1315 }
1316
1317 static void write_mballs(WriteData *wd, ListBase *idbase)
1318 {
1319         MetaBall *mb;
1320         MetaElem *ml;
1321
1322         mb= idbase->first;
1323         while(mb) {
1324                 if(mb->id.us>0 || wd->current) {
1325                         /* write LibData */
1326                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1327                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1328
1329                         /* direct data */
1330                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1331                         if (mb->adt) write_animdata(wd, mb->adt);
1332
1333                         ml= mb->elems.first;
1334                         while(ml) {
1335                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1336                                 ml= ml->next;
1337                         }
1338                 }
1339                 mb= mb->id.next;
1340         }
1341 }
1342
1343 static int amount_of_chars(char *str)
1344 {
1345         // Since the data is saved as UTF-8 to the cu->str
1346         // The cu->len is not same as the strlen(cu->str)
1347         return strlen(str);
1348 }
1349
1350 static void write_curves(WriteData *wd, ListBase *idbase)
1351 {
1352         Curve *cu;
1353         Nurb *nu;
1354
1355         cu= idbase->first;
1356         while(cu) {
1357                 if(cu->id.us>0 || wd->current) {
1358                         /* write LibData */
1359                         writestruct(wd, ID_CU, "Curve", 1, cu);
1360                         
1361                         /* direct data */
1362                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1363                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1364                         if (cu->adt) write_animdata(wd, cu->adt);
1365                         
1366                         if(cu->vfont) {
1367                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1368                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1369                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1370                         }
1371                         else {
1372                                 /* is also the order of reading */
1373                                 nu= cu->nurb.first;
1374                                 while(nu) {
1375                                         writestruct(wd, DATA, "Nurb", 1, nu);
1376                                         nu= nu->next;
1377                                 }
1378                                 nu= cu->nurb.first;
1379                                 while(nu) {
1380                                         if(nu->type == CU_BEZIER)
1381                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1382                                         else {
1383                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1384                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1385                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1386                                         }
1387                                         nu= nu->next;
1388                                 }
1389                         }
1390                 }
1391                 cu= cu->id.next;
1392         }
1393
1394         /* flush helps the compression for undo-save */
1395         mywrite(wd, MYWRITE_FLUSH, 0);
1396 }
1397
1398 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1399 {
1400         if (dvlist) {
1401                 int i;
1402                 
1403                 /* Write the dvert list */
1404                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1405                 
1406                 /* Write deformation data for each dvert */
1407                 for (i=0; i<count; i++) {
1408                         if (dvlist[i].dw)
1409                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1410                 }
1411         }
1412 }
1413
1414 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist)
1415 {
1416         if(mdlist) {
1417                 int i;
1418                 
1419                 writestruct(wd, DATA, "MDisps", count, mdlist);
1420                 for(i = 0; i < count; ++i) {
1421                         if(mdlist[i].disps)
1422                                 writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1423                 }
1424         }
1425 }
1426
1427 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1428 {
1429         int i;
1430
1431         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1432
1433         for (i=0; i<data->totlayer; i++) {
1434                 CustomDataLayer *layer= &data->layers[i];
1435                 char *structname;
1436                 int structnum, datasize;
1437
1438                 if (layer->type == CD_MDEFORMVERT) {
1439                         /* layer types that allocate own memory need special handling */
1440                         write_dverts(wd, count, layer->data);
1441                 }
1442                 else if (layer->type == CD_MDISPS) {
1443                         write_mdisps(wd, count, layer->data);
1444                 }
1445                 else {
1446                         CustomData_file_write_info(layer->type, &structname, &structnum);
1447                         if (structnum) {
1448                                 /* when using partial visibility, the MEdge and MFace layers
1449                                    are smaller than the original, so their type and count is
1450                                    passed to make this work */
1451                                 if (layer->type != partial_type) datasize= structnum*count;
1452                                 else datasize= structnum*partial_count;
1453
1454                                 writestruct(wd, DATA, structname, datasize, layer->data);
1455                         }
1456                         else
1457                                 printf("error: this CustomDataLayer must not be written to file\n");
1458                 }
1459         }
1460 }
1461
1462 static void write_meshs(WriteData *wd, ListBase *idbase)
1463 {
1464         Mesh *mesh;
1465
1466         mesh= idbase->first;
1467         while(mesh) {
1468                 if(mesh->id.us>0 || wd->current) {
1469                         /* write LibData */
1470                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1471
1472                         /* direct data */
1473                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1474
1475                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1476
1477                         if(mesh->pv) {
1478                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1479                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1480                                         CD_MEDGE, mesh->totedge);
1481                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1482                                         CD_MFACE, mesh->totface);
1483                         }
1484                         else {
1485                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1486                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1487                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1488                         }
1489
1490                         /* PMV data */
1491                         if(mesh->pv) {
1492                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1493                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1494                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1495                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1496                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1497                         }
1498                 }
1499                 mesh= mesh->id.next;
1500         }
1501 }
1502
1503 static void write_lattices(WriteData *wd, ListBase *idbase)
1504 {
1505         Lattice *lt;
1506         
1507         lt= idbase->first;
1508         while(lt) {
1509                 if(lt->id.us>0 || wd->current) {
1510                         /* write LibData */
1511                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1512                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1513
1514                         /* direct data */
1515                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1516                         
1517                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1518                         
1519                 }
1520                 lt= lt->id.next;
1521         }
1522 }
1523
1524 static void write_previews(WriteData *wd, PreviewImage *prv)
1525 {
1526         if (prv) {
1527                 short w = prv->w[1];
1528                 short h = prv->h[1];
1529                 unsigned int *rect = prv->rect[1];
1530                 /* don't write out large previews if not requested */
1531                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1532                         prv->w[1] = 0;
1533                         prv->h[1] = 0;
1534                         prv->rect[1] = NULL;
1535                 }
1536                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1537                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1538                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1539
1540                 /* restore preview, we still want to keep it in memory even if not saved to file */
1541                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1542                         prv->w[1] = w;
1543                         prv->h[1] = h;
1544                         prv->rect[1] = rect;
1545                 }
1546         }
1547 }
1548
1549 static void write_images(WriteData *wd, ListBase *idbase)
1550 {
1551         Image *ima;
1552         PackedFile * pf;
1553
1554
1555         ima= idbase->first;
1556         while(ima) {
1557                 if(ima->id.us>0 || wd->current) {
1558                         /* write LibData */
1559                         writestruct(wd, ID_IM, "Image", 1, ima);
1560                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1561
1562                         if (ima->packedfile) {
1563                                 pf = ima->packedfile;
1564                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1565                                 writedata(wd, DATA, pf->size, pf->data);
1566                         }
1567
1568                         write_previews(wd, ima->preview);
1569
1570                         /* exception: render text only saved in undo files (wd->current) */
1571                         if (ima->render_text && wd->current)
1572                                 writedata(wd, DATA, IMA_RW_MAXTEXT, ima->render_text);
1573                 }
1574                 ima= ima->id.next;
1575         }
1576         /* flush helps the compression for undo-save */
1577         mywrite(wd, MYWRITE_FLUSH, 0);
1578 }
1579
1580 static void write_textures(WriteData *wd, ListBase *idbase)
1581 {
1582         Tex *tex;
1583
1584         tex= idbase->first;
1585         while(tex) {
1586                 if(tex->id.us>0 || wd->current) {
1587                         /* write LibData */
1588                         writestruct(wd, ID_TE, "Tex", 1, tex);
1589                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1590
1591                         if (tex->adt) write_animdata(wd, tex->adt);
1592
1593                         /* direct data */
1594                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1595                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1596                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1597                         if(tex->type == TEX_POINTDENSITY && tex->pd) {
1598                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
1599                                 if(tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
1600                         }
1601                         if(tex->type == TEX_VOXELDATA && tex->vd) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
1602                         
1603                         /* nodetree is integral part of texture, no libdata */
1604                         if(tex->nodetree) {
1605                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1606                                 write_nodetree(wd, tex->nodetree);
1607                         }
1608                         
1609                         write_previews(wd, tex->preview);
1610                 }
1611                 tex= tex->id.next;
1612         }
1613
1614         /* flush helps the compression for undo-save */
1615         mywrite(wd, MYWRITE_FLUSH, 0);
1616 }
1617
1618 static void write_materials(WriteData *wd, ListBase *idbase)
1619 {
1620         Material *ma;
1621         int a;
1622
1623         ma= idbase->first;
1624         while(ma) {
1625                 if(ma->id.us>0 || wd->current) {
1626                         /* write LibData */
1627                         writestruct(wd, ID_MA, "Material", 1, ma);
1628                         
1629                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1630                           of library blocks that implement this.*/
1631                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1632                           set yet :) */
1633                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1634                         
1635                         if (ma->adt) write_animdata(wd, ma->adt);
1636
1637                         for(a=0; a<MAX_MTEX; a++) {
1638                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1639                         }
1640                         
1641                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1642                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1643                         
1644                         /* nodetree is integral part of material, no libdata */
1645                         if(ma->nodetree) {
1646                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1647                                 write_nodetree(wd, ma->nodetree);
1648                         }
1649
1650                         write_previews(wd, ma->preview);                        
1651                 }
1652                 ma= ma->id.next;
1653         }
1654 }
1655
1656 static void write_worlds(WriteData *wd, ListBase *idbase)
1657 {
1658         World *wrld;
1659         int a;
1660
1661         wrld= idbase->first;
1662         while(wrld) {
1663                 if(wrld->id.us>0 || wd->current) {
1664                         /* write LibData */
1665                         writestruct(wd, ID_WO, "World", 1, wrld);
1666                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1667                         
1668                         if (wrld->adt) write_animdata(wd, wrld->adt);
1669                         
1670                         for(a=0; a<MAX_MTEX; a++) {
1671                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1672                         }
1673                         
1674                         write_previews(wd, wrld->preview);
1675                 }
1676                 wrld= wrld->id.next;
1677         }
1678 }
1679
1680 static void write_lamps(WriteData *wd, ListBase *idbase)
1681 {
1682         Lamp *la;
1683         int a;
1684
1685         la= idbase->first;
1686         while(la) {
1687                 if(la->id.us>0 || wd->current) {
1688                         /* write LibData */
1689                         writestruct(wd, ID_LA, "Lamp", 1, la);
1690                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1691                         
1692                         if (la->adt) write_animdata(wd, la->adt);
1693                         
1694                         /* direct data */
1695                         for(a=0; a<MAX_MTEX; a++) {
1696                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1697                         }
1698                         
1699                         if(la->curfalloff)
1700                                 write_curvemapping(wd, la->curfalloff); 
1701                         
1702                         write_previews(wd, la->preview);
1703                         
1704                 }
1705                 la= la->id.next;
1706         }
1707 }
1708
1709 static void write_paint(WriteData *wd, Paint *p)
1710 {
1711         if(p && p->brushes)
1712                 writedata(wd, DATA, p->brush_count * sizeof(Brush*), p->brushes);
1713 }
1714
1715 static void write_scenes(WriteData *wd, ListBase *scebase)
1716 {
1717         Scene *sce;
1718         Base *base;
1719         Editing *ed;
1720         Sequence *seq;
1721         MetaStack *ms;
1722         Strip *strip;
1723         TimeMarker *marker;
1724         TransformOrientation *ts;
1725         SceneRenderLayer *srl;
1726         ToolSettings *tos;
1727         
1728         sce= scebase->first;
1729         while(sce) {
1730                 /* write LibData */
1731                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1732                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1733                 
1734                 if (sce->adt) write_animdata(wd, sce->adt);
1735                 write_keyingsets(wd, &sce->keyingsets);
1736                 
1737                 /* direct data */
1738                 base= sce->base.first;
1739                 while(base) {
1740                         writestruct(wd, DATA, "Base", 1, base);
1741                         base= base->next;
1742                 }
1743                 
1744                 tos = sce->toolsettings;
1745                 writestruct(wd, DATA, "ToolSettings", 1, tos);
1746                 if(tos->vpaint) {
1747                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
1748                         write_paint(wd, &tos->vpaint->paint);
1749                 }
1750                 if(tos->wpaint) {
1751                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
1752                         write_paint(wd, &tos->wpaint->paint);
1753                 }
1754                 if(tos->sculpt) {
1755                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
1756                         write_paint(wd, &tos->sculpt->paint);
1757                 }
1758
1759                 write_paint(wd, &tos->imapaint.paint);
1760
1761                 ed= sce->ed;
1762                 if(ed) {
1763                         writestruct(wd, DATA, "Editing", 1, ed);
1764                         
1765                         /* reset write flags too */
1766                         
1767                         SEQ_BEGIN(ed, seq) {
1768                                 if(seq->strip) seq->strip->done= 0;
1769                                 writestruct(wd, DATA, "Sequence", 1, seq);
1770                         }
1771                         SEQ_END
1772                         
1773                         SEQ_BEGIN(ed, seq) {
1774                                 if(seq->strip && seq->strip->done==0) {
1775                                         /* write strip with 'done' at 0 because readfile */
1776                                         
1777                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1778                                         if(seq->effectdata) {
1779                                                 switch(seq->type){
1780                                                 case SEQ_COLOR:
1781                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1782                                                         break;
1783                                                 case SEQ_SPEED:
1784                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1785                                                         break;
1786                                                 case SEQ_WIPE:
1787                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1788                                                         break;
1789                                                 case SEQ_GLOW:
1790                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1791                                                         break;
1792                                                 case SEQ_TRANSFORM:
1793                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1794                                                         break;
1795                                                 }
1796                                         }
1797                                         
1798                                         strip= seq->strip;
1799                                         writestruct(wd, DATA, "Strip", 1, strip);
1800                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1801                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1802                                         }
1803                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1804                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1805                                         }
1806                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1807                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1808                                         }
1809                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1810                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1811                                         }
1812                                         if(seq->type==SEQ_IMAGE)
1813                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1814                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1815                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1816                                         
1817                                         strip->done= 1;
1818                                 }
1819                         }
1820                         SEQ_END
1821                                 
1822                         /* new; meta stack too, even when its nasty restore code */
1823                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1824                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1825                         }
1826                 }
1827                 
1828                 if (sce->r.avicodecdata) {
1829                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1830                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1831                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1832                 }
1833
1834                 if (sce->r.qtcodecdata) {
1835                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1836                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1837                 }
1838                 if (sce->r.ffcodecdata.properties) {
1839                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1840                 }
1841
1842                 /* writing dynamic list of TimeMarkers to the blend file */
1843                 for(marker= sce->markers.first; marker; marker= marker->next)
1844                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1845                 
1846                 /* writing dynamic list of TransformOrientations to the blend file */
1847                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1848                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1849                 
1850                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1851                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1852                 
1853                 if(sce->nodetree) {
1854                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1855                         write_nodetree(wd, sce->nodetree);
1856                 }
1857                 
1858                 sce= sce->id.next;
1859         }
1860         /* flush helps the compression for undo-save */
1861         mywrite(wd, MYWRITE_FLUSH, 0);
1862 }
1863
1864 static void write_gpencils(WriteData *wd, ListBase *lb)
1865 {
1866         bGPdata *gpd;
1867         bGPDlayer *gpl;
1868         bGPDframe *gpf;
1869         bGPDstroke *gps;
1870         
1871         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1872                 /* write gpd data block to file */
1873                 writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1874                 
1875                 /* write grease-pencil layers to file */
1876                 for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1877                         writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1878                         
1879                         /* write this layer's frames to file */
1880                         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1881                                 writestruct(wd, DATA, "bGPDframe", 1, gpf);
1882                                 
1883                                 /* write strokes */
1884                                 for (gps= gpf->strokes.first; gps; gps= gps->next) {
1885                                         writestruct(wd, DATA, "bGPDstroke", 1, gps);
1886                                         writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1887                                 }
1888                         }
1889                 }
1890         }
1891 }
1892
1893 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1894 {
1895         wmWindowManager *wm;
1896         wmWindow *win;
1897         
1898         for(wm= lb->first; wm; wm= wm->id.next) {
1899                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1900                 
1901                 for(win= wm->windows.first; win; win= win->next)
1902                         writestruct(wd, DATA, "wmWindow", 1, win);
1903         }
1904 }
1905
1906 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1907 {       
1908         writestruct(wd, DATA, "ARegion", 1, ar);
1909         
1910         if(ar->regiondata) {
1911                 switch(spacetype) {
1912                         case SPACE_VIEW3D:
1913                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1914                                         RegionView3D *rv3d= ar->regiondata;
1915                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
1916                                         
1917                                         if(rv3d->localvd)
1918                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
1919                                         if(rv3d->clipbb) 
1920                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
1921
1922                                 }
1923                                 else
1924                                         printf("regiondata write missing!\n");
1925                                 break;
1926                         default:
1927                                 printf("regiondata write missing!\n");
1928                 }
1929         }
1930 }
1931
1932 static void write_screens(WriteData *wd, ListBase *scrbase)
1933 {
1934         bScreen *sc;
1935         ScrArea *sa;
1936         ScrVert *sv;
1937         ScrEdge *se;
1938
1939         sc= scrbase->first;
1940         while(sc) {
1941                 
1942                 /* write LibData */
1943                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
1944                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
1945                 if (sc->id.properties) 
1946                         IDP_WriteProperty(sc->id.properties, wd);
1947                 
1948                 /* direct data */
1949                 for(sv= sc->vertbase.first; sv; sv= sv->next)
1950                         writestruct(wd, DATA, "ScrVert", 1, sv);
1951                 
1952                 for(se= sc->edgebase.first; se; se= se->next) 
1953                         writestruct(wd, DATA, "ScrEdge", 1, se);
1954                 
1955                 for(sa= sc->areabase.first; sa; sa= sa->next) {
1956                         SpaceLink *sl;
1957                         Panel *pa;
1958                         ARegion *ar;
1959                         
1960                         writestruct(wd, DATA, "ScrArea", 1, sa);
1961                         
1962                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
1963                                 write_region(wd, ar, sa->spacetype);
1964                                 
1965                                 for(pa= ar->panels.first; pa; pa= pa->next)
1966                                         writestruct(wd, DATA, "Panel", 1, pa);
1967                         }
1968                         
1969                         sl= sa->spacedata.first;
1970                         while(sl) {
1971                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
1972                                         write_region(wd, ar, sl->spacetype);
1973                                 
1974                                 if(sl->spacetype==SPACE_VIEW3D) {
1975                                         View3D *v3d= (View3D *) sl;
1976                                         writestruct(wd, DATA, "View3D", 1, v3d);
1977                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1978                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1979                                 }
1980                                 else if(sl->spacetype==SPACE_IPO) {
1981                                         SpaceIpo *sipo= (SpaceIpo *)sl;
1982                                         ListBase tmpGhosts = sipo->ghostCurves;
1983                                         
1984                                         /* temporarily disable ghost curves when saving */
1985                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
1986                                         
1987                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1988                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
1989                                         
1990                                         /* reenable ghost curves */
1991                                         sipo->ghostCurves= tmpGhosts;
1992                                 }
1993                                 else if(sl->spacetype==SPACE_BUTS) {
1994                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1995                                 }
1996                                 else if(sl->spacetype==SPACE_FILE) {
1997                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1998                                 }
1999                                 else if(sl->spacetype==SPACE_SEQ) {
2000                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2001                                 }
2002                                 else if(sl->spacetype==SPACE_OUTLINER) {
2003                                         SpaceOops *so= (SpaceOops *)sl;
2004                                         
2005                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2006
2007                                         /* outliner */
2008                                         if(so->treestore) {
2009                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2010                                                 if(so->treestore->data)
2011                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2012                                         }
2013                                 }
2014                                 else if(sl->spacetype==SPACE_IMAGE) {
2015                                         SpaceImage *sima= (SpaceImage *)sl;
2016                                         
2017                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2018                                         if(sima->cumap)
2019                                                 write_curvemapping(wd, sima->cumap);
2020                                 }
2021                                 else if(sl->spacetype==SPACE_IMASEL) {
2022                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
2023                                 }
2024                                 else if(sl->spacetype==SPACE_TEXT) {
2025                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2026                                 }
2027                                 else if(sl->spacetype==SPACE_SCRIPT) {
2028                                         SpaceScript *sc = (SpaceScript*)sl;
2029                                         sc->but_refs = NULL;
2030                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2031                                 }
2032                                 else if(sl->spacetype==SPACE_ACTION) {
2033                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2034                                 }
2035                                 else if(sl->spacetype==SPACE_SOUND) {
2036                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
2037                                 }
2038                                 else if(sl->spacetype==SPACE_NLA){
2039                                         SpaceNla *snla= (SpaceNla *)sl;
2040                                         
2041                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2042                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2043                                 }
2044                                 else if(sl->spacetype==SPACE_TIME){
2045                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2046                                 }
2047                                 else if(sl->spacetype==SPACE_NODE){
2048                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2049                                 }
2050                                 else if(sl->spacetype==SPACE_LOGIC){
2051                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2052                                 }
2053                                 else if(sl->spacetype==SPACE_CONSOLE) {
2054                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2055                                 }
2056                                 else if(sl->spacetype==SPACE_USERPREF) {
2057                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2058                                 }
2059
2060                                 sl= sl->next;
2061                         }
2062                 }
2063
2064                 sc= sc->id.next;
2065         }
2066 }
2067
2068 static void write_libraries(WriteData *wd, Main *main)
2069 {
2070         ListBase *lbarray[30];
2071         ID *id;
2072         int a, tot, foundone;
2073
2074         for(; main; main= main->next) {
2075
2076                 a=tot= set_listbasepointers(main, lbarray);
2077
2078                 /* test: is lib being used */
2079                 foundone= 0;
2080                 while(tot--) {
2081                         for(id= lbarray[tot]->first; id; id= id->next) {
2082                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2083                                         foundone= 1;
2084                                         break;
2085                                 }
2086                         }
2087                         if(foundone) break;
2088                 }
2089
2090                 if(foundone) {
2091                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2092
2093                         while(a--) {
2094                                 for(id= lbarray[a]->first; id; id= id->next) {
2095                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2096                                                 writestruct(wd, ID_ID, "ID", 1, id);
2097                                         }
2098                                 }
2099                         }
2100                 }
2101         }
2102 }
2103
2104 static void write_bone(WriteData *wd, Bone* bone)
2105 {
2106         Bone*   cbone;
2107
2108         // PATCH for upward compatibility after 2.37+ armature recode
2109         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2110                 
2111         // Write this bone
2112         writestruct(wd, DATA, "Bone", 1, bone);
2113         
2114         // Write Children
2115         cbone= bone->childbase.first;
2116         while(cbone) {
2117                 write_bone(wd, cbone);
2118                 cbone= cbone->next;
2119         }
2120 }
2121
2122 static void write_armatures(WriteData *wd, ListBase *idbase)
2123 {
2124         bArmature       *arm;
2125         Bone            *bone;
2126
2127         arm=idbase->first;
2128         while (arm) {
2129                 if (arm->id.us>0 || wd->current) {
2130                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2131                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2132
2133                         if (arm->adt) write_animdata(wd, arm->adt);
2134
2135                         /* Direct data */
2136                         bone= arm->bonebase.first;
2137                         while(bone) {
2138                                 write_bone(wd, bone);
2139                                 bone=bone->next;
2140                         }
2141                 }
2142                 arm=arm->id.next;
2143         }
2144
2145         /* flush helps the compression for undo-save */
2146         mywrite(wd, MYWRITE_FLUSH, 0);
2147 }
2148
2149 static void write_texts(WriteData *wd, ListBase *idbase)
2150 {
2151         Text *text;
2152         TextLine *tmp;
2153         TextMarker *mrk;
2154
2155         text= idbase->first;
2156         while(text) {
2157                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2158
2159                 /* write LibData */
2160                 writestruct(wd, ID_TXT, "Text", 1, text);
2161                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2162                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2163
2164                 if(!(text->flags & TXT_ISEXT)) {
2165                         /* now write the text data, in two steps for optimization in the readfunction */
2166                         tmp= text->lines.first;
2167                         while (tmp) {
2168                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2169                                 tmp= tmp->next;
2170                         }
2171
2172                         tmp= text->lines.first;
2173                         while (tmp) {
2174                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2175                                 tmp= tmp->next;
2176                         }
2177
2178                         /* write markers */
2179                         mrk= text->markers.first;
2180                         while (mrk) {
2181                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2182                                 mrk= mrk->next;
2183                         }
2184                 }
2185
2186
2187                 text= text->id.next;
2188         }
2189
2190         /* flush helps the compression for undo-save */
2191         mywrite(wd, MYWRITE_FLUSH, 0);
2192 }
2193
2194 static void write_sounds(WriteData *wd, ListBase *idbase)
2195 {
2196         bSound *sound;
2197
2198         PackedFile * pf;
2199
2200         sound= idbase->first;
2201         while(sound) {
2202                 if(sound->id.us>0 || wd->current) {
2203                         /* write LibData */
2204                         writestruct(wd, ID_SO, "bSound", 1, sound);
2205                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2206
2207                         if (sound->packedfile) {
2208                                 pf = sound->packedfile;
2209                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2210                                 writedata(wd, DATA, pf->size, pf->data);
2211                         }
2212                 }
2213                 sound= sound->id.next;
2214         }
2215
2216         /* flush helps the compression for undo-save */
2217         mywrite(wd, MYWRITE_FLUSH, 0);
2218 }
2219
2220 static void write_groups(WriteData *wd, ListBase *idbase)
2221 {
2222         Group *group;
2223         GroupObject *go;
2224
2225         for(group= idbase->first; group; group= group->id.next) {
2226                 if(group->id.us>0 || wd->current) {
2227                         /* write LibData */
2228                         writestruct(wd, ID_GR, "Group", 1, group);
2229                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2230
2231                         go= group->gobject.first;
2232                         while(go) {
2233                                 writestruct(wd, DATA, "GroupObject", 1, go);
2234                                 go= go->next;
2235                         }
2236                 }
2237         }
2238 }
2239
2240 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2241 {
2242         bNodeTree *ntree;
2243         
2244         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2245                 if (ntree->id.us>0 || wd->current) {
2246                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2247                         write_nodetree(wd, ntree);
2248                         
2249                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2250                         
2251                         if (ntree->adt) write_animdata(wd, ntree->adt);
2252                 }
2253         }
2254 }
2255
2256 static void write_brushes(WriteData *wd, ListBase *idbase)
2257 {
2258         Brush *brush;
2259         int a;
2260         
2261         for(brush=idbase->first; brush; brush= brush->id.next) {
2262                 if(brush->id.us>0 || wd->current) {
2263                         writestruct(wd, ID_BR, "Brush", 1, brush);
2264                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2265                         for(a=0; a<MAX_MTEX; a++)
2266                                 if(brush->mtex[a])
2267                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
2268
2269                         if(brush->curve)
2270                                 write_curvemapping(wd, brush->curve);
2271                 }
2272         }
2273 }
2274
2275 static void write_scripts(WriteData *wd, ListBase *idbase)
2276 {
2277         Script *script;
2278         
2279         for(script=idbase->first; script; script= script->id.next) {
2280                 if(script->id.us>0 || wd->current) {
2281                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2282                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2283                 }
2284         }
2285 }
2286
2287 /* context is usually defined by WM, two cases where no WM is available:
2288  * - for forward compatibility, curscreen has to be saved
2289  * - for undofile, curscene needs to be saved */
2290 static void write_global(WriteData *wd, Main *mainvar)
2291 {
2292         FileGlobal fg;
2293         bScreen *screen;
2294         char subvstr[8];
2295         
2296         current_screen_compat(mainvar, &screen);
2297
2298         /* XXX still remap G */
2299         fg.curscreen= screen;
2300         fg.curscene= screen->scene;
2301         fg.displaymode= G.displaymode;
2302         fg.winpos= G.winpos;
2303         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2304         fg.globalf= G.f;
2305
2306         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2307         memcpy(fg.subvstr, subvstr, 4);
2308         
2309         fg.subversion= BLENDER_SUBVERSION;
2310         fg.minversion= BLENDER_MINVERSION;
2311         fg.minsubversion= BLENDER_MINSUBVERSION;
2312         fg.pads= 0; /* prevent mem checkers from complaining */
2313         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2314 }
2315
2316 /* if MemFile * there's filesave to memory */
2317 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2318                                                          int write_user_block, int write_flags)
2319 {
2320         BHead bhead;
2321         ListBase mainlist;
2322         char buf[16];
2323         WriteData *wd;
2324
2325         blo_split_main(&mainlist, mainvar);
2326
2327         wd= bgnwrite(handle, compare, current, write_flags);
2328         
2329         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2330         mywrite(wd, buf, 12);
2331
2332         write_renderinfo(wd, mainvar);
2333         write_global(wd, mainvar);
2334
2335         /* no UI save in undo */
2336         if(current==NULL) {
2337                 write_windowmanagers(wd, &mainvar->wm);
2338                 write_screens  (wd, &mainvar->screen);
2339         }
2340         write_scenes   (wd, &mainvar->scene);
2341         write_curves   (wd, &mainvar->curve);
2342         write_mballs   (wd, &mainvar->mball);
2343         write_images   (wd, &mainvar->image);
2344         write_cameras  (wd, &mainvar->camera);
2345         write_lamps    (wd, &mainvar->lamp);
2346         write_lattices (wd, &mainvar->latt);
2347         write_vfonts   (wd, &mainvar->vfont);
2348         write_keys     (wd, &mainvar->key);
2349         write_worlds   (wd, &mainvar->world);
2350         write_texts    (wd, &mainvar->text);
2351         write_sounds   (wd, &mainvar->sound);
2352         write_groups   (wd, &mainvar->group);
2353         write_armatures(wd, &mainvar->armature);
2354         write_actions  (wd, &mainvar->action);
2355         write_objects  (wd, &mainvar->object);
2356         write_materials(wd, &mainvar->mat);
2357         write_textures (wd, &mainvar->tex);
2358         write_meshs    (wd, &mainvar->mesh);
2359         write_particlesettings(wd, &mainvar->particle);
2360         write_nodetrees(wd, &mainvar->nodetree);
2361         write_brushes  (wd, &mainvar->brush);
2362         write_scripts  (wd, &mainvar->script);
2363         write_gpencils (wd, &mainvar->gpencil);
2364         if(current==NULL)       
2365                 write_libraries(wd,  mainvar->next); /* no library save in undo */
2366
2367         if (write_user_block) {
2368                 write_userdef(wd);
2369         }
2370                                                         
2371         /* dna as last, because (to be implemented) test for which structs are written */
2372         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2373
2374         /* end of file */
2375         memset(&bhead, 0, sizeof(BHead));
2376         bhead.code= ENDB;
2377         mywrite(wd, &bhead, sizeof(BHead));
2378
2379         blo_join_main(&mainlist);
2380
2381         return endwrite(wd);
2382 }
2383
2384 /* return: success (1) */
2385 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports)
2386 {
2387         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2388         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2389         int file, err, write_user_block;
2390
2391         sprintf(tempname, "%s@", dir);
2392
2393         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2394         if(file == -1) {
2395                 BKE_report(reports, RPT_ERROR, "Unable to open file for writing.");
2396                 return 0;
2397         }
2398
2399         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B25.blend");
2400         write_user_block= BLI_streq(dir, userfilename);
2401
2402         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags);
2403         close(file);
2404
2405         if(!err) {
2406                 if(write_flags & G_FILE_COMPRESS)
2407                 {       
2408                         // compressed files have the same ending as regular files... only from 2.4!!!
2409                         
2410                         int ret = BLI_gzip(tempname, dir);
2411                         
2412                         if(-1==ret) {
2413                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2414                                 return 0;
2415                         }
2416                         if(-2==ret) {
2417                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2418                                 return 0;
2419                         }
2420                 }
2421                 else
2422                 if(BLI_rename(tempname, dir) != 0) {
2423                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2424                         return 0;
2425                 }
2426
2427                 
2428         } else {
2429                 BKE_report(reports, RPT_ERROR, strerror(errno));
2430                 remove(tempname);
2431
2432                 return 0;
2433         }
2434
2435         return 1;
2436 }
2437
2438 /* return: success (1) */
2439 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags, ReportList *reports)
2440 {
2441         int err;
2442
2443         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags);
2444         
2445         if(err==0) return 1;
2446         return 0;
2447 }
2448
2449
2450         /* Runtime writing */
2451
2452 #ifdef WIN32
2453 #define PATHSEPERATOR           "\\"
2454 #else
2455 #define PATHSEPERATOR           "/"
2456 #endif
2457
2458 static char *get_runtime_path(char *exename) {
2459         char *installpath= get_install_dir();
2460
2461         if (!installpath) {
2462                 return NULL;
2463         } else {
2464                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2465
2466                 if (path == NULL) {
2467                         MEM_freeN(installpath);
2468                         return NULL;
2469                 }
2470
2471                 strcpy(path, installpath);
2472                 strcat(path, PATHSEPERATOR);
2473                 strcat(path, exename);
2474
2475                 MEM_freeN(installpath);
2476
2477                 return path;
2478         }
2479 }
2480
2481 #ifdef __APPLE__
2482
2483 static int recursive_copy_runtime(char *outname, char *exename, ReportList *reports)
2484 {
2485         char *runtime = get_runtime_path(exename);
2486         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2487         int progfd = -1, error= 0;
2488
2489         if (!runtime) {
2490                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2491                 error= 1;
2492                 goto cleanup;
2493         }
2494         //printf("runtimepath %s\n", runtime);
2495                 
2496         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2497         if (progfd==-1) {
2498                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2499                 error= 1;
2500                 goto cleanup;
2501         }
2502
2503         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2504         //printf("command %s\n", command);
2505         if (system(command) == -1) {
2506                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2507                 error= 1;
2508         }
2509
2510 cleanup:
2511         if (progfd!=-1)
2512                 close(progfd);
2513         if (runtime)
2514                 MEM_freeN(runtime);
2515
2516         return !error;
2517 }
2518
2519 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports) 
2520 {
2521         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2522         int outfd = -1, error= 0;
2523
2524         // remove existing file / bundle
2525         //printf("Delete file %s\n", file);
2526         BLI_delete(file, 0, TRUE);
2527
2528         if (!recursive_copy_runtime(file, exename, reports)) {
2529                 error= 1;
2530                 goto cleanup;
2531         }
2532
2533         strcpy(gamename, file);
2534         strcat(gamename, "/Contents/Resources/game.blend");
2535         //printf("gamename %s\n", gamename);
2536         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2537         if (outfd != -1) {
2538
2539                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2540
2541                 if (write(outfd, " ", 1) != 1) {
2542                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2543                         error= 1;
2544                         goto cleanup;
2545                 }
2546         } else {
2547                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2548                 error= 1;
2549         }
2550
2551 cleanup:
2552         if (outfd!=-1)
2553                 close(outfd);
2554
2555         BKE_reports_prepend(reports, "Unable to make runtime: ");
2556         return !error;
2557 }
2558
2559 #else /* !__APPLE__ */
2560
2561 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2562 {
2563         char *runtime= get_runtime_path(exename);
2564         unsigned char buf[1024];
2565         int count, progfd= -1, error= 0;
2566
2567         if (!BLI_exists(runtime)) {
2568                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2569                 error= 1;
2570                 goto cleanup;
2571         }
2572
2573         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2574         if (progfd==-1) {
2575                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2576                 error= 1;
2577                 goto cleanup;
2578         }
2579
2580         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2581                 if (write(handle, buf, count)!=count) {
2582                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2583                         error= 1;
2584                         goto cleanup;
2585                 }
2586         }
2587
2588 cleanup:
2589         if (progfd!=-1)
2590                 close(progfd);
2591         if (runtime)
2592                 MEM_freeN(runtime);
2593
2594         return !error;
2595 }
2596
2597 static int handle_write_msb_int(int handle, int i) 
2598 {
2599         unsigned char buf[4];
2600         buf[0]= (i>>24)&0xFF;
2601         buf[1]= (i>>16)&0xFF;
2602         buf[2]= (i>>8)&0xFF;
2603         buf[3]= (i>>0)&0xFF;
2604
2605         return (write(handle, buf, 4)==4);
2606 }
2607
2608 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports)
2609 {
2610         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2611         int datastart, error= 0;
2612
2613         if (!outfd) {
2614                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2615                 error= 1;
2616                 goto cleanup;
2617         }
2618         if (!handle_append_runtime(outfd, exename, reports)) {
2619                 error= 1;
2620                 goto cleanup;
2621         }
2622
2623         datastart= lseek(outfd, 0, SEEK_CUR);
2624
2625         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2626
2627         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2628                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2629                 error= 1;
2630                 goto cleanup;
2631         }
2632
2633 cleanup:
2634         if (outfd!=-1)
2635                 close(outfd);
2636
2637         BKE_reports_prepend(reports, "Unable to make runtime: ");
2638         return !error;
2639 }
2640
2641 #endif /* !__APPLE__ */