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