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