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