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