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