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