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