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