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