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