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