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