Merging r39717 through r39983 from trunk into soc-2011-tomato
[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_genfile.h"
103 #include "DNA_group_types.h"
104 #include "DNA_gpencil_types.h"
105 #include "DNA_fileglobal_types.h"
106 #include "DNA_key_types.h"
107 #include "DNA_lattice_types.h"
108 #include "DNA_lamp_types.h"
109 #include "DNA_meta_types.h"
110 #include "DNA_mesh_types.h"
111 #include "DNA_meshdata_types.h"
112 #include "DNA_material_types.h"
113 #include "DNA_node_types.h"
114 #include "DNA_object_types.h"
115 #include "DNA_object_force.h"
116 #include "DNA_packedFile_types.h"
117 #include "DNA_particle_types.h"
118 #include "DNA_property_types.h"
119 #include "DNA_scene_types.h"
120 #include "DNA_sdna_types.h"
121 #include "DNA_sequence_types.h"
122 #include "DNA_sensor_types.h"
123 #include "DNA_smoke_types.h"
124 #include "DNA_space_types.h"
125 #include "DNA_screen_types.h"
126 #include "DNA_speaker_types.h"
127 #include "DNA_sound_types.h"
128 #include "DNA_text_types.h"
129 #include "DNA_view3d_types.h"
130 #include "DNA_vfont_types.h"
131 #include "DNA_world_types.h"
132 #include "DNA_windowmanager_types.h"
133 #include "DNA_movieclip_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                 default:
1151                         ; /* error: don't know how to write this file */
1152                 }
1153
1154                 act= act->next;
1155         }
1156 }
1157
1158 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1159 {
1160         /* sanity checks */
1161         if (mpath == NULL)
1162                 return;
1163         
1164         /* firstly, just write the motionpath struct */
1165         writestruct(wd, DATA, "bMotionPath", 1, mpath);
1166         
1167         /* now write the array of data */
1168         writestruct(wd, DATA, "bMotionPathVert", mpath->length, mpath->points);
1169 }
1170
1171 static void write_constraints(WriteData *wd, ListBase *conlist)
1172 {
1173         bConstraint *con;
1174
1175         for (con=conlist->first; con; con=con->next) {
1176                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1177                 
1178                 /* Write the specific data */
1179                 if (cti && con->data) {
1180                         /* firstly, just write the plain con->data struct */
1181                         writestruct(wd, DATA, cti->structName, 1, con->data);
1182                         
1183                         /* do any constraint specific stuff */
1184                         switch (con->type) {
1185                                 case CONSTRAINT_TYPE_PYTHON:
1186                                 {
1187                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1188                                         bConstraintTarget *ct;
1189                                         
1190                                         /* write targets */
1191                                         for (ct= data->targets.first; ct; ct= ct->next)
1192                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1193                                         
1194                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1195                                          of library blocks that implement this.*/
1196                                         IDP_WriteProperty(data->prop, wd);
1197                                 }
1198                                         break;
1199                                 case CONSTRAINT_TYPE_SPLINEIK: 
1200                                 {
1201                                         bSplineIKConstraint *data= (bSplineIKConstraint*)con->data;
1202                                         
1203                                         /* write points array */
1204                                         writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
1205                                 }
1206                                         break;
1207                         }
1208                 }
1209                 
1210                 /* Write the constraint */
1211                 writestruct(wd, DATA, "bConstraint", 1, con);
1212         }
1213 }
1214
1215 static void write_pose(WriteData *wd, bPose *pose)
1216 {
1217         bPoseChannel *chan;
1218         bActionGroup *grp;
1219
1220         /* Write each channel */
1221         if (!pose)
1222                 return;
1223
1224         /* Write channels */
1225         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1226                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1227                  of library blocks that implement this.*/
1228                 if (chan->prop)
1229                         IDP_WriteProperty(chan->prop, wd);
1230                 
1231                 write_constraints(wd, &chan->constraints);
1232                 
1233                 write_motionpath(wd, chan->mpath);
1234                 
1235                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1236                 if (chan->bone) 
1237                         chan->selectflag= chan->bone->flag & BONE_SELECTED; /* gets restored on read, for library armatures */
1238                 
1239                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1240         }
1241         
1242         /* Write groups */
1243         for (grp=pose->agroups.first; grp; grp=grp->next) 
1244                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1245
1246         /* write IK param */
1247         if (pose->ikparam) {
1248                 char *structname = (char *)get_ikparam_name(pose);
1249                 if (structname)
1250                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1251         }
1252
1253         /* Write this pose */
1254         writestruct(wd, DATA, "bPose", 1, pose);
1255
1256 }
1257
1258 static void write_defgroups(WriteData *wd, ListBase *defbase)
1259 {
1260         bDeformGroup    *defgroup;
1261
1262         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1263                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1264 }
1265
1266 static void write_modifiers(WriteData *wd, ListBase *modbase)
1267 {
1268         ModifierData *md;
1269
1270         if (modbase == NULL) return;
1271         for (md=modbase->first; md; md= md->next) {
1272                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1273                 if (mti == NULL) return;
1274                 
1275                 writestruct(wd, DATA, mti->structName, 1, md);
1276                         
1277                 if (md->type==eModifierType_Hook) {
1278                         HookModifierData *hmd = (HookModifierData*) md;
1279                         
1280                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1281                 }
1282                 else if(md->type==eModifierType_Cloth) {
1283                         ClothModifierData *clmd = (ClothModifierData*) md;
1284                         
1285                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1286                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1287                         writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
1288                         write_pointcaches(wd, &clmd->ptcaches);
1289                 } 
1290                 else if(md->type==eModifierType_Smoke) {
1291                         SmokeModifierData *smd = (SmokeModifierData*) md;
1292                         
1293                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1294                         {
1295                                 if(smd->domain)
1296                                 {
1297                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1298
1299                                         /* create fake pointcache so that old blender versions can read it */
1300                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1301                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE|PTCACHE_FAKE_SMOKE;
1302                                         smd->domain->point_cache[1]->step = 1;
1303
1304                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1305                                 }
1306                                 
1307                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1308
1309                                 if(smd->domain) {
1310                                         /* cleanup the fake pointcache */
1311                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1312                                         smd->domain->point_cache[1] = NULL;
1313                                         
1314                                         writestruct(wd, DATA, "EffectorWeights", 1, smd->domain->effector_weights);
1315                                 }
1316                         }
1317                         else if(smd->type & MOD_SMOKE_TYPE_FLOW)
1318                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1319                         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1320                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1321                 } 
1322                 else if(md->type==eModifierType_Fluidsim) {
1323                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1324                         
1325                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1326                 } 
1327                 else if (md->type==eModifierType_Collision) {
1328                         
1329                         /*
1330                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1331                         // TODO: CollisionModifier should use pointcache 
1332                         // + have proper reset events before enabling this
1333                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1334                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1335                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1336                         */
1337                 }
1338                 else if (md->type==eModifierType_MeshDeform) {
1339                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1340                         int size = mmd->dyngridsize;
1341
1342                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->bindinfluences);
1343                         writedata(wd, DATA, sizeof(int)*(mmd->totvert+1), mmd->bindoffsets);
1344                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1345                                 mmd->bindcagecos);
1346                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1347                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1348                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1349                 }
1350                 else if (md->type==eModifierType_Warp) {
1351                         WarpModifierData *tmd = (WarpModifierData*) md;
1352                         if(tmd->curfalloff) {
1353                                 write_curvemapping(wd, tmd->curfalloff);
1354                         }
1355                 }
1356         }
1357 }
1358
1359 static void write_objects(WriteData *wd, ListBase *idbase)
1360 {
1361         Object *ob;
1362         
1363         ob= idbase->first;
1364         while(ob) {
1365                 if(ob->id.us>0 || wd->current) {
1366                         /* write LibData */
1367                         writestruct(wd, ID_OB, "Object", 1, ob);
1368                         
1369                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1370                           of library blocks that implement this.*/
1371                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1372                         
1373                         if (ob->adt) write_animdata(wd, ob->adt);
1374                         
1375                         /* direct data */
1376                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1377                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1378                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1379                         write_properties(wd, &ob->prop);
1380                         write_sensors(wd, &ob->sensors);
1381                         write_controllers(wd, &ob->controllers);
1382                         write_actuators(wd, &ob->actuators);
1383
1384                         if (ob->type == OB_ARMATURE) {
1385                                 bArmature *arm = ob->data;
1386                                 if (arm && ob->pose && arm->act_bone) {
1387                                         BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1388                                 }
1389                         }
1390
1391                         write_pose(wd, ob->pose);
1392                         write_defgroups(wd, &ob->defbase);
1393                         write_constraints(wd, &ob->constraints);
1394                         write_motionpath(wd, ob->mpath);
1395                         
1396                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1397                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1398                         if(ob->soft) {
1399                                 write_pointcaches(wd, &ob->soft->ptcaches);
1400                                 writestruct(wd, DATA, "EffectorWeights", 1, ob->soft->effector_weights);
1401                         }
1402                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1403                         
1404                         write_particlesystems(wd, &ob->particlesystem);
1405                         write_modifiers(wd, &ob->modifiers);
1406                 }
1407                 ob= ob->id.next;
1408         }
1409
1410         /* flush helps the compression for undo-save */
1411         mywrite(wd, MYWRITE_FLUSH, 0);
1412 }
1413
1414
1415 static void write_vfonts(WriteData *wd, ListBase *idbase)
1416 {
1417         VFont *vf;
1418         PackedFile * pf;
1419
1420         vf= idbase->first;
1421         while(vf) {
1422                 if(vf->id.us>0 || wd->current) {
1423                         /* write LibData */
1424                         writestruct(wd, ID_VF, "VFont", 1, vf);
1425                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1426
1427                         /* direct data */
1428
1429                         if (vf->packedfile) {
1430                                 pf = vf->packedfile;
1431                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1432                                 writedata(wd, DATA, pf->size, pf->data);
1433                         }
1434                 }
1435
1436                 vf= vf->id.next;
1437         }
1438 }
1439
1440
1441 static void write_keys(WriteData *wd, ListBase *idbase)
1442 {
1443         Key *key;
1444         KeyBlock *kb;
1445
1446         key= idbase->first;
1447         while(key) {
1448                 if(key->id.us>0 || wd->current) {
1449                         /* write LibData */
1450                         writestruct(wd, ID_KE, "Key", 1, key);
1451                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1452                         
1453                         if (key->adt) write_animdata(wd, key->adt);
1454                         
1455                         /* direct data */
1456                         kb= key->block.first;
1457                         while(kb) {
1458                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1459                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1460                                 kb= kb->next;
1461                         }
1462                 }
1463
1464                 key= key->id.next;
1465         }
1466         /* flush helps the compression for undo-save */
1467         mywrite(wd, MYWRITE_FLUSH, 0);
1468 }
1469
1470 static void write_cameras(WriteData *wd, ListBase *idbase)
1471 {
1472         Camera *cam;
1473
1474         cam= idbase->first;
1475         while(cam) {
1476                 if(cam->id.us>0 || wd->current) {
1477                         /* write LibData */
1478                         writestruct(wd, ID_CA, "Camera", 1, cam);
1479                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1480                         
1481                         if (cam->adt) write_animdata(wd, cam->adt);
1482                 }
1483
1484                 cam= cam->id.next;
1485         }
1486 }
1487
1488 static void write_mballs(WriteData *wd, ListBase *idbase)
1489 {
1490         MetaBall *mb;
1491         MetaElem *ml;
1492
1493         mb= idbase->first;
1494         while(mb) {
1495                 if(mb->id.us>0 || wd->current) {
1496                         /* write LibData */
1497                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1498                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1499
1500                         /* direct data */
1501                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1502                         if (mb->adt) write_animdata(wd, mb->adt);
1503
1504                         ml= mb->elems.first;
1505                         while(ml) {
1506                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1507                                 ml= ml->next;
1508                         }
1509                 }
1510                 mb= mb->id.next;
1511         }
1512 }
1513
1514 static int amount_of_chars(char *str)
1515 {
1516         // Since the data is saved as UTF-8 to the cu->str
1517         // The cu->len is not same as the strlen(cu->str)
1518         return strlen(str);
1519 }
1520
1521 static void write_curves(WriteData *wd, ListBase *idbase)
1522 {
1523         Curve *cu;
1524         Nurb *nu;
1525
1526         cu= idbase->first;
1527         while(cu) {
1528                 if(cu->id.us>0 || wd->current) {
1529                         /* write LibData */
1530                         writestruct(wd, ID_CU, "Curve", 1, cu);
1531                         
1532                         /* direct data */
1533                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1534                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1535                         if (cu->adt) write_animdata(wd, cu->adt);
1536                         
1537                         if(cu->vfont) {
1538                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1539                                 writestruct(wd, DATA, "CharInfo", cu->len+1, cu->strinfo);
1540                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1541                         }
1542                         else {
1543                                 /* is also the order of reading */
1544                                 nu= cu->nurb.first;
1545                                 while(nu) {
1546                                         writestruct(wd, DATA, "Nurb", 1, nu);
1547                                         nu= nu->next;
1548                                 }
1549                                 nu= cu->nurb.first;
1550                                 while(nu) {
1551                                         if(nu->type == CU_BEZIER)
1552                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1553                                         else {
1554                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1555                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1556                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1557                                         }
1558                                         nu= nu->next;
1559                                 }
1560                         }
1561                 }
1562                 cu= cu->id.next;
1563         }
1564
1565         /* flush helps the compression for undo-save */
1566         mywrite(wd, MYWRITE_FLUSH, 0);
1567 }
1568
1569 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1570 {
1571         if (dvlist) {
1572                 int i;
1573                 
1574                 /* Write the dvert list */
1575                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1576                 
1577                 /* Write deformation data for each dvert */
1578                 for (i=0; i<count; i++) {
1579                         if (dvlist[i].dw)
1580                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1581                 }
1582         }
1583 }
1584
1585 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1586 {
1587         if(mdlist) {
1588                 int i;
1589                 
1590                 writestruct(wd, DATA, "MDisps", count, mdlist);
1591                 if(!external) {
1592                         for(i = 0; i < count; ++i) {
1593                                 if(mdlist[i].disps)
1594                                         writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1595                         }
1596                 }
1597         }
1598 }
1599
1600 static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data, int partial_type, int partial_count)
1601 {
1602         int i;
1603
1604         /* write external customdata (not for undo) */
1605         if(data->external && !wd->current)
1606                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1607
1608         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1609
1610         for (i=0; i<data->totlayer; i++) {
1611                 CustomDataLayer *layer= &data->layers[i];
1612                 const char *structname;
1613                 int structnum, datasize;
1614
1615                 if (layer->type == CD_MDEFORMVERT) {
1616                         /* layer types that allocate own memory need special handling */
1617                         write_dverts(wd, count, layer->data);
1618                 }
1619                 else if (layer->type == CD_MDISPS) {
1620                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1621                 }
1622                 else {
1623                         CustomData_file_write_info(layer->type, &structname, &structnum);
1624                         if (structnum) {
1625                                 /* when using partial visibility, the MEdge and MFace layers
1626                                    are smaller than the original, so their type and count is
1627                                    passed to make this work */
1628                                 if (layer->type != partial_type) datasize= structnum*count;
1629                                 else datasize= structnum*partial_count;
1630
1631                                 writestruct(wd, DATA, structname, datasize, layer->data);
1632                         }
1633                         else
1634                                 printf("error: this CustomDataLayer must not be written to file\n");
1635                 }
1636         }
1637
1638         if(data->external)
1639                 writestruct(wd, DATA, "CustomDataExternal", 1, data->external);
1640 }
1641
1642 static void write_meshs(WriteData *wd, ListBase *idbase)
1643 {
1644         Mesh *mesh;
1645
1646         mesh= idbase->first;
1647         while(mesh) {
1648                 if(mesh->id.us>0 || wd->current) {
1649                         /* write LibData */
1650                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1651
1652                         /* direct data */
1653                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1654                         if (mesh->adt) write_animdata(wd, mesh->adt);
1655
1656                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1657
1658                         if(mesh->pv) {
1659                                 write_customdata(wd, &mesh->id, mesh->pv->totvert, &mesh->vdata, -1, 0);
1660                                 write_customdata(wd, &mesh->id, mesh->pv->totedge, &mesh->edata,
1661                                         CD_MEDGE, mesh->totedge);
1662                                 write_customdata(wd, &mesh->id, mesh->pv->totface, &mesh->fdata,
1663                                         CD_MFACE, mesh->totface);
1664                         }
1665                         else {
1666                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1667                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1668                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1669                         }
1670
1671                         /* PMV data */
1672                         if(mesh->pv) {
1673                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1674                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1675                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1676                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1677                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1678                         }
1679                 }
1680                 mesh= mesh->id.next;
1681         }
1682 }
1683
1684 static void write_lattices(WriteData *wd, ListBase *idbase)
1685 {
1686         Lattice *lt;
1687         
1688         lt= idbase->first;
1689         while(lt) {
1690                 if(lt->id.us>0 || wd->current) {
1691                         /* write LibData */
1692                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1693                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1694                         
1695                         /* write animdata */
1696                         if (lt->adt) write_animdata(wd, lt->adt);
1697                         
1698                         /* direct data */
1699                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1700                         
1701                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1702                         
1703                 }
1704                 lt= lt->id.next;
1705         }
1706 }
1707
1708 static void write_previews(WriteData *wd, PreviewImage *prv)
1709 {
1710         if (prv) {
1711                 short w = prv->w[1];
1712                 short h = prv->h[1];
1713                 unsigned int *rect = prv->rect[1];
1714                 /* don't write out large previews if not requested */
1715                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1716                         prv->w[1] = 0;
1717                         prv->h[1] = 0;
1718                         prv->rect[1] = NULL;
1719                 }
1720                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1721                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1722                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1723
1724                 /* restore preview, we still want to keep it in memory even if not saved to file */
1725                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1726                         prv->w[1] = w;
1727                         prv->h[1] = h;
1728                         prv->rect[1] = rect;
1729                 }
1730         }
1731 }
1732
1733 static void write_images(WriteData *wd, ListBase *idbase)
1734 {
1735         Image *ima;
1736         PackedFile * pf;
1737
1738
1739         ima= idbase->first;
1740         while(ima) {
1741                 if(ima->id.us>0 || wd->current) {
1742                         /* write LibData */
1743                         writestruct(wd, ID_IM, "Image", 1, ima);
1744                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1745
1746                         if (ima->packedfile) {
1747                                 pf = ima->packedfile;
1748                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1749                                 writedata(wd, DATA, pf->size, pf->data);
1750                         }
1751
1752                         write_previews(wd, ima->preview);
1753                 }
1754                 ima= ima->id.next;
1755         }
1756         /* flush helps the compression for undo-save */
1757         mywrite(wd, MYWRITE_FLUSH, 0);
1758 }
1759
1760 static void write_textures(WriteData *wd, ListBase *idbase)
1761 {
1762         Tex *tex;
1763
1764         tex= idbase->first;
1765         while(tex) {
1766                 if(tex->id.us>0 || wd->current) {
1767                         /* write LibData */
1768                         writestruct(wd, ID_TE, "Tex", 1, tex);
1769                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1770
1771                         if (tex->adt) write_animdata(wd, tex->adt);
1772
1773                         /* direct data */
1774                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1775                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1776                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1777                         if(tex->type == TEX_POINTDENSITY && tex->pd) {
1778                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
1779                                 if(tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
1780                                 if(tex->pd->falloff_curve) write_curvemapping(wd, tex->pd->falloff_curve);
1781                         }
1782                         if(tex->type == TEX_VOXELDATA && tex->vd) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
1783                         
1784                         /* nodetree is integral part of texture, no libdata */
1785                         if(tex->nodetree) {
1786                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1787                                 write_nodetree(wd, tex->nodetree);
1788                         }
1789                         
1790                         write_previews(wd, tex->preview);
1791                 }
1792                 tex= tex->id.next;
1793         }
1794
1795         /* flush helps the compression for undo-save */
1796         mywrite(wd, MYWRITE_FLUSH, 0);
1797 }
1798
1799 static void write_materials(WriteData *wd, ListBase *idbase)
1800 {
1801         Material *ma;
1802         int a;
1803
1804         ma= idbase->first;
1805         while(ma) {
1806                 if(ma->id.us>0 || wd->current) {
1807                         /* write LibData */
1808                         writestruct(wd, ID_MA, "Material", 1, ma);
1809                         
1810                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1811                           of library blocks that implement this.*/
1812                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1813                           set yet :) */
1814                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1815                         
1816                         if (ma->adt) write_animdata(wd, ma->adt);
1817
1818                         for(a=0; a<MAX_MTEX; a++) {
1819                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1820                         }
1821                         
1822                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1823                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1824                         
1825                         /* nodetree is integral part of material, no libdata */
1826                         if(ma->nodetree) {
1827                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1828                                 write_nodetree(wd, ma->nodetree);
1829                         }
1830
1831                         write_previews(wd, ma->preview);                        
1832                 }
1833                 ma= ma->id.next;
1834         }
1835 }
1836
1837 static void write_worlds(WriteData *wd, ListBase *idbase)
1838 {
1839         World *wrld;
1840         int a;
1841
1842         wrld= idbase->first;
1843         while(wrld) {
1844                 if(wrld->id.us>0 || wd->current) {
1845                         /* write LibData */
1846                         writestruct(wd, ID_WO, "World", 1, wrld);
1847                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1848                         
1849                         if (wrld->adt) write_animdata(wd, wrld->adt);
1850                         
1851                         for(a=0; a<MAX_MTEX; a++) {
1852                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1853                         }
1854                         
1855                         write_previews(wd, wrld->preview);
1856                 }
1857                 wrld= wrld->id.next;
1858         }
1859 }
1860
1861 static void write_lamps(WriteData *wd, ListBase *idbase)
1862 {
1863         Lamp *la;
1864         int a;
1865
1866         la= idbase->first;
1867         while(la) {
1868                 if(la->id.us>0 || wd->current) {
1869                         /* write LibData */
1870                         writestruct(wd, ID_LA, "Lamp", 1, la);
1871                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1872                         
1873                         if (la->adt) write_animdata(wd, la->adt);
1874                         
1875                         /* direct data */
1876                         for(a=0; a<MAX_MTEX; a++) {
1877                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1878                         }
1879                         
1880                         if(la->curfalloff)
1881                                 write_curvemapping(wd, la->curfalloff); 
1882                         
1883                         write_previews(wd, la->preview);
1884                         
1885                 }
1886                 la= la->id.next;
1887         }
1888 }
1889
1890
1891 static void write_scenes(WriteData *wd, ListBase *scebase)
1892 {
1893         Scene *sce;
1894         Base *base;
1895         Editing *ed;
1896         Sequence *seq;
1897         MetaStack *ms;
1898         Strip *strip;
1899         TimeMarker *marker;
1900         TransformOrientation *ts;
1901         SceneRenderLayer *srl;
1902         ToolSettings *tos;
1903         
1904         sce= scebase->first;
1905         while(sce) {
1906                 /* write LibData */
1907                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1908                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1909                 
1910                 if (sce->adt) write_animdata(wd, sce->adt);
1911                 write_keyingsets(wd, &sce->keyingsets);
1912                 
1913                 /* direct data */
1914                 base= sce->base.first;
1915                 while(base) {
1916                         writestruct(wd, DATA, "Base", 1, base);
1917                         base= base->next;
1918                 }
1919                 
1920                 tos = sce->toolsettings;
1921                 writestruct(wd, DATA, "ToolSettings", 1, tos);
1922                 if(tos->vpaint) {
1923                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
1924                 }
1925                 if(tos->wpaint) {
1926                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
1927                 }
1928                 if(tos->sculpt) {
1929                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
1930                 }
1931
1932                 // write_paint(wd, &tos->imapaint.paint);
1933
1934                 ed= sce->ed;
1935                 if(ed) {
1936                         writestruct(wd, DATA, "Editing", 1, ed);
1937                         
1938                         /* reset write flags too */
1939                         
1940                         SEQ_BEGIN(ed, seq) {
1941                                 if(seq->strip) seq->strip->done= 0;
1942                                 writestruct(wd, DATA, "Sequence", 1, seq);
1943                         }
1944                         SEQ_END
1945                         
1946                         SEQ_BEGIN(ed, seq) {
1947                                 if(seq->strip && seq->strip->done==0) {
1948                                         /* write strip with 'done' at 0 because readfile */
1949                                         
1950                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1951                                         if(seq->effectdata) {
1952                                                 switch(seq->type){
1953                                                 case SEQ_COLOR:
1954                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1955                                                         break;
1956                                                 case SEQ_SPEED:
1957                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1958                                                         break;
1959                                                 case SEQ_WIPE:
1960                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1961                                                         break;
1962                                                 case SEQ_GLOW:
1963                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1964                                                         break;
1965                                                 case SEQ_TRANSFORM:
1966                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1967                                                         break;
1968                                                 }
1969                                         }
1970                                         
1971                                         strip= seq->strip;
1972                                         writestruct(wd, DATA, "Strip", 1, strip);
1973                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1974                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1975                                         }
1976                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1977                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1978                                         }
1979                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1980                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1981                                         }
1982                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1983                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1984                                         }
1985                                         if(seq->type==SEQ_IMAGE)
1986                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1987                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1988                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1989                                         
1990                                         strip->done= 1;
1991                                 }
1992                         }
1993                         SEQ_END
1994                                 
1995                         /* new; meta stack too, even when its nasty restore code */
1996                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1997                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1998                         }
1999                 }
2000                 
2001                 if (sce->r.avicodecdata) {
2002                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
2003                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2004                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2005                 }
2006
2007                 if (sce->r.qtcodecdata) {
2008                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
2009                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
2010                 }
2011                 if (sce->r.ffcodecdata.properties) {
2012                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2013                 }
2014
2015                 /* writing dynamic list of TimeMarkers to the blend file */
2016                 for(marker= sce->markers.first; marker; marker= marker->next)
2017                         writestruct(wd, DATA, "TimeMarker", 1, marker);
2018                 
2019                 /* writing dynamic list of TransformOrientations to the blend file */
2020                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
2021                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
2022                 
2023                 for(srl= sce->r.layers.first; srl; srl= srl->next)
2024                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
2025                 
2026                 if(sce->nodetree) {
2027                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
2028                         write_nodetree(wd, sce->nodetree);
2029                 }
2030                 
2031                 sce= sce->id.next;
2032         }
2033         /* flush helps the compression for undo-save */
2034         mywrite(wd, MYWRITE_FLUSH, 0);
2035 }
2036
2037 static void write_gpencils(WriteData *wd, ListBase *lb)
2038 {
2039         bGPdata *gpd;
2040         bGPDlayer *gpl;
2041         bGPDframe *gpf;
2042         bGPDstroke *gps;
2043         
2044         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
2045                 if (gpd->id.us>0 || wd->current) {
2046                         /* write gpd data block to file */
2047                         writestruct(wd, ID_GD, "bGPdata", 1, gpd);
2048                         
2049                         /* write grease-pencil layers to file */
2050                         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
2051                                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
2052                                 
2053                                 /* write this layer's frames to file */
2054                                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
2055                                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
2056                                         
2057                                         /* write strokes */
2058                                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
2059                                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
2060                                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
2061                                         }
2062                                 }
2063                         }
2064                 }
2065         }
2066 }
2067
2068 static void write_windowmanagers(WriteData *wd, ListBase *lb)
2069 {
2070         wmWindowManager *wm;
2071         wmWindow *win;
2072         
2073         for(wm= lb->first; wm; wm= wm->id.next) {
2074                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
2075                 
2076                 for(win= wm->windows.first; win; win= win->next)
2077                         writestruct(wd, DATA, "wmWindow", 1, win);
2078         }
2079 }
2080
2081 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2082 {       
2083         writestruct(wd, DATA, "ARegion", 1, ar);
2084         
2085         if(ar->regiondata) {
2086                 switch(spacetype) {
2087                         case SPACE_VIEW3D:
2088                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
2089                                         RegionView3D *rv3d= ar->regiondata;
2090                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
2091                                         
2092                                         if(rv3d->localvd)
2093                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
2094                                         if(rv3d->clipbb) 
2095                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
2096
2097                                 }
2098                                 else
2099                                         printf("regiondata write missing!\n");
2100                                 break;
2101                         default:
2102                                 printf("regiondata write missing!\n");
2103                 }
2104         }
2105 }
2106
2107 static void write_screens(WriteData *wd, ListBase *scrbase)
2108 {
2109         bScreen *sc;
2110         ScrArea *sa;
2111         ScrVert *sv;
2112         ScrEdge *se;
2113
2114         sc= scrbase->first;
2115         while(sc) {
2116                 
2117                 /* write LibData */
2118                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2119                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2120                 if (sc->id.properties) 
2121                         IDP_WriteProperty(sc->id.properties, wd);
2122                 
2123                 /* direct data */
2124                 for(sv= sc->vertbase.first; sv; sv= sv->next)
2125                         writestruct(wd, DATA, "ScrVert", 1, sv);
2126                 
2127                 for(se= sc->edgebase.first; se; se= se->next) 
2128                         writestruct(wd, DATA, "ScrEdge", 1, se);
2129                 
2130                 for(sa= sc->areabase.first; sa; sa= sa->next) {
2131                         SpaceLink *sl;
2132                         Panel *pa;
2133                         ARegion *ar;
2134                         
2135                         writestruct(wd, DATA, "ScrArea", 1, sa);
2136                         
2137                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
2138                                 write_region(wd, ar, sa->spacetype);
2139                                 
2140                                 for(pa= ar->panels.first; pa; pa= pa->next)
2141                                         writestruct(wd, DATA, "Panel", 1, pa);
2142                         }
2143                         
2144                         sl= sa->spacedata.first;
2145                         while(sl) {
2146                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
2147                                         write_region(wd, ar, sl->spacetype);
2148                                 
2149                                 if(sl->spacetype==SPACE_VIEW3D) {
2150                                         View3D *v3d= (View3D *) sl;
2151                                         BGpic *bgpic;
2152                                         writestruct(wd, DATA, "View3D", 1, v3d);
2153                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2154                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2155                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2156                                 }
2157                                 else if(sl->spacetype==SPACE_IPO) {
2158                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2159                                         ListBase tmpGhosts = sipo->ghostCurves;
2160                                         
2161                                         /* temporarily disable ghost curves when saving */
2162                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2163                                         
2164                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2165                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2166                                         
2167                                         /* reenable ghost curves */
2168                                         sipo->ghostCurves= tmpGhosts;
2169                                 }
2170                                 else if(sl->spacetype==SPACE_BUTS) {
2171                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2172                                 }
2173                                 else if(sl->spacetype==SPACE_FILE) {
2174                                         SpaceFile *sfile= (SpaceFile *)sl;
2175
2176                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2177                                         if(sfile->params)
2178                                                 writestruct(wd, DATA, "FileSelectParams", 1, sfile->params);
2179                                 }
2180                                 else if(sl->spacetype==SPACE_SEQ) {
2181                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2182                                 }
2183                                 else if(sl->spacetype==SPACE_OUTLINER) {
2184                                         SpaceOops *so= (SpaceOops *)sl;
2185                                         
2186                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2187
2188                                         /* outliner */
2189                                         if(so->treestore) {
2190                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2191                                                 if(so->treestore->data)
2192                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2193                                         }
2194                                 }
2195                                 else if(sl->spacetype==SPACE_IMAGE) {
2196                                         SpaceImage *sima= (SpaceImage *)sl;
2197                                         
2198                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2199                                         if(sima->cumap)
2200                                                 write_curvemapping(wd, sima->cumap);
2201                                 }
2202                                 else if(sl->spacetype==SPACE_IMASEL) {
2203                                         // XXX: depreceated... do we still want to keep this?
2204                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
2205                                 }
2206                                 else if(sl->spacetype==SPACE_TEXT) {
2207                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2208                                 }
2209                                 else if(sl->spacetype==SPACE_SCRIPT) {
2210                                         SpaceScript *scr = (SpaceScript*)sl;
2211                                         scr->but_refs = NULL;
2212                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2213                                 }
2214                                 else if(sl->spacetype==SPACE_ACTION) {
2215                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2216                                 }
2217                                 else if(sl->spacetype==SPACE_SOUND) {
2218                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
2219                                 }
2220                                 else if(sl->spacetype==SPACE_NLA){
2221                                         SpaceNla *snla= (SpaceNla *)sl;
2222                                         
2223                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2224                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2225                                 }
2226                                 else if(sl->spacetype==SPACE_TIME){
2227                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2228                                 }
2229                                 else if(sl->spacetype==SPACE_NODE){
2230                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2231                                 }
2232                                 else if(sl->spacetype==SPACE_LOGIC){
2233                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2234                                 }
2235                                 else if(sl->spacetype==SPACE_CONSOLE) {
2236                                         SpaceConsole *con = (SpaceConsole*)sl;
2237                                         ConsoleLine *cl;
2238
2239                                         for (cl=con->history.first; cl; cl=cl->next) {
2240                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2241                                                 writestruct(wd, DATA, "ConsoleLine", 1, cl);
2242                                                 writedata(wd, DATA, cl->len+1, cl->line);
2243                                         }
2244                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2245
2246                                 }
2247                                 else if(sl->spacetype==SPACE_USERPREF) {
2248                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2249                                 }
2250                                 else if(sl->spacetype==SPACE_CLIP) {
2251                                         writestruct(wd, DATA, "SpaceClip", 1, sl);
2252                                 }
2253
2254                                 sl= sl->next;
2255                         }
2256                 }
2257
2258                 sc= sc->id.next;
2259         }
2260 }
2261
2262 static void write_libraries(WriteData *wd, Main *main)
2263 {
2264         ListBase *lbarray[30];
2265         ID *id;
2266         int a, tot, foundone;
2267
2268         for(; main; main= main->next) {
2269
2270                 a=tot= set_listbasepointers(main, lbarray);
2271
2272                 /* test: is lib being used */
2273                 foundone= 0;
2274                 while(tot--) {
2275                         for(id= lbarray[tot]->first; id; id= id->next) {
2276                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2277                                         foundone= 1;
2278                                         break;
2279                                 }
2280                         }
2281                         if(foundone) break;
2282                 }
2283
2284                 if(foundone) {
2285                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2286
2287                         while(a--) {
2288                                 for(id= lbarray[a]->first; id; id= id->next) {
2289                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2290                                                 writestruct(wd, ID_ID, "ID", 1, id);
2291                                         }
2292                                 }
2293                         }
2294                 }
2295         }
2296 }
2297
2298 static void write_bone(WriteData *wd, Bone* bone)
2299 {
2300         Bone*   cbone;
2301
2302         // PATCH for upward compatibility after 2.37+ armature recode
2303         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2304                 
2305         // Write this bone
2306         writestruct(wd, DATA, "Bone", 1, bone);
2307
2308         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2309          of library blocks that implement this.*/
2310         if (bone->prop)
2311                 IDP_WriteProperty(bone->prop, wd);
2312         
2313         // Write Children
2314         cbone= bone->childbase.first;
2315         while(cbone) {
2316                 write_bone(wd, cbone);
2317                 cbone= cbone->next;
2318         }
2319 }
2320
2321 static void write_armatures(WriteData *wd, ListBase *idbase)
2322 {
2323         bArmature       *arm;
2324         Bone            *bone;
2325
2326         arm=idbase->first;
2327         while (arm) {
2328                 if (arm->id.us>0 || wd->current) {
2329                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2330                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2331
2332                         if (arm->adt) write_animdata(wd, arm->adt);
2333
2334                         /* Direct data */
2335                         bone= arm->bonebase.first;
2336                         while(bone) {
2337                                 write_bone(wd, bone);
2338                                 bone=bone->next;
2339                         }
2340                 }
2341                 arm=arm->id.next;
2342         }
2343
2344         /* flush helps the compression for undo-save */
2345         mywrite(wd, MYWRITE_FLUSH, 0);
2346 }
2347
2348 static void write_texts(WriteData *wd, ListBase *idbase)
2349 {
2350         Text *text;
2351         TextLine *tmp;
2352         TextMarker *mrk;
2353
2354         text= idbase->first;
2355         while(text) {
2356                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2357
2358                 /* write LibData */
2359                 writestruct(wd, ID_TXT, "Text", 1, text);
2360                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2361                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2362
2363                 if(!(text->flags & TXT_ISEXT)) {
2364                         /* now write the text data, in two steps for optimization in the readfunction */
2365                         tmp= text->lines.first;
2366                         while (tmp) {
2367                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2368                                 tmp= tmp->next;
2369                         }
2370
2371                         tmp= text->lines.first;
2372                         while (tmp) {
2373                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2374                                 tmp= tmp->next;
2375                         }
2376
2377                         /* write markers */
2378                         mrk= text->markers.first;
2379                         while (mrk) {
2380                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2381                                 mrk= mrk->next;
2382                         }
2383                 }
2384
2385
2386                 text= text->id.next;
2387         }
2388
2389         /* flush helps the compression for undo-save */
2390         mywrite(wd, MYWRITE_FLUSH, 0);
2391 }
2392
2393 static void write_speakers(WriteData *wd, ListBase *idbase)
2394 {
2395         Speaker *spk;
2396
2397         spk= idbase->first;
2398         while(spk) {
2399                 if(spk->id.us>0 || wd->current) {
2400                         /* write LibData */
2401                         writestruct(wd, ID_SPK, "Speaker", 1, spk);
2402                         if (spk->id.properties) IDP_WriteProperty(spk->id.properties, wd);
2403
2404                         if (spk->adt) write_animdata(wd, spk->adt);
2405                 }
2406                 spk= spk->id.next;
2407         }
2408 }
2409
2410 static void write_sounds(WriteData *wd, ListBase *idbase)
2411 {
2412         bSound *sound;
2413
2414         PackedFile * pf;
2415
2416         sound= idbase->first;
2417         while(sound) {
2418                 if(sound->id.us>0 || wd->current) {
2419                         /* write LibData */
2420                         writestruct(wd, ID_SO, "bSound", 1, sound);
2421                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2422
2423                         if (sound->packedfile) {
2424                                 pf = sound->packedfile;
2425                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2426                                 writedata(wd, DATA, pf->size, pf->data);
2427                         }
2428                 }
2429                 sound= sound->id.next;
2430         }
2431
2432         /* flush helps the compression for undo-save */
2433         mywrite(wd, MYWRITE_FLUSH, 0);
2434 }
2435
2436 static void write_groups(WriteData *wd, ListBase *idbase)
2437 {
2438         Group *group;
2439         GroupObject *go;
2440
2441         for(group= idbase->first; group; group= group->id.next) {
2442                 if(group->id.us>0 || wd->current) {
2443                         /* write LibData */
2444                         writestruct(wd, ID_GR, "Group", 1, group);
2445                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2446
2447                         go= group->gobject.first;
2448                         while(go) {
2449                                 writestruct(wd, DATA, "GroupObject", 1, go);
2450                                 go= go->next;
2451                         }
2452                 }
2453         }
2454 }
2455
2456 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2457 {
2458         bNodeTree *ntree;
2459         
2460         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2461                 if (ntree->id.us>0 || wd->current) {
2462                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2463                         write_nodetree(wd, ntree);
2464                         
2465                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2466                         
2467                         if (ntree->adt) write_animdata(wd, ntree->adt);
2468                 }
2469         }
2470 }
2471
2472 static void write_brushes(WriteData *wd, ListBase *idbase)
2473 {
2474         Brush *brush;
2475         
2476         for(brush=idbase->first; brush; brush= brush->id.next) {
2477                 if(brush->id.us>0 || wd->current) {
2478                         writestruct(wd, ID_BR, "Brush", 1, brush);
2479                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2480                         
2481                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2482                         
2483                         if(brush->curve)
2484                                 write_curvemapping(wd, brush->curve);
2485                 }
2486         }
2487 }
2488
2489 static void write_scripts(WriteData *wd, ListBase *idbase)
2490 {
2491         Script *script;
2492         
2493         for(script=idbase->first; script; script= script->id.next) {
2494                 if(script->id.us>0 || wd->current) {
2495                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2496                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2497                 }
2498         }
2499 }
2500
2501 static void write_movieclips(WriteData *wd, ListBase *idbase)
2502 {
2503         MovieClip *clip;
2504
2505         clip= idbase->first;
2506         while(clip) {
2507                 if(clip->id.us>0 || wd->current) {
2508                         MovieTracking *tracking= &clip->tracking;
2509                         MovieTrackingTrack *track;
2510                         writestruct(wd, ID_MC, "MovieClip", 1, clip);
2511
2512                         if(tracking->reconstruction.camnr)
2513                                 writestruct(wd, DATA, "MovieReconstructedCamera", tracking->reconstruction.camnr, tracking->reconstruction.cameras);
2514
2515                         track= tracking->tracks.first;
2516                         while(track) {
2517                                 writestruct(wd, DATA, "MovieTrackingTrack", 1, track);
2518
2519                                 if(track->markers)
2520                                         writestruct(wd, DATA, "MovieTrackingMarker", track->markersnr, track->markers);
2521
2522                                 track= track->next;
2523                         }
2524                 }
2525
2526                 clip= clip->id.next;
2527         }
2528
2529         /* flush helps the compression for undo-save */
2530         mywrite(wd, MYWRITE_FLUSH, 0);
2531 }
2532
2533 /* context is usually defined by WM, two cases where no WM is available:
2534  * - for forward compatibility, curscreen has to be saved
2535  * - for undofile, curscene needs to be saved */
2536 static void write_global(WriteData *wd, int fileflags, Main *mainvar)
2537 {
2538         FileGlobal fg;
2539         bScreen *screen;
2540         char subvstr[8];
2541         
2542         /* prevent mem checkers from complaining */
2543         fg.pads= fg.pad= 0;
2544         memset(fg.filename, 0, sizeof(fg.filename));
2545
2546         current_screen_compat(mainvar, &screen);
2547
2548         /* XXX still remap G */
2549         fg.curscreen= screen;
2550         fg.curscene= screen->scene;
2551         fg.displaymode= G.displaymode;
2552         fg.winpos= G.winpos;
2553         fg.fileflags= (fileflags & ~(G_FILE_NO_UI|G_FILE_RELATIVE_REMAP));      // prevent to save this, is not good convention, and feature with concerns...
2554         fg.globalf= G.f;
2555         BLI_strncpy(fg.filename, mainvar->name, sizeof(fg.filename));
2556
2557         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2558         memcpy(fg.subvstr, subvstr, 4);
2559         
2560         fg.subversion= BLENDER_SUBVERSION;
2561         fg.minversion= BLENDER_MINVERSION;
2562         fg.minsubversion= BLENDER_MINSUBVERSION;
2563 #ifdef WITH_BUILDINFO
2564         {
2565                 extern char build_rev[];
2566                 fg.revision= atoi(build_rev);
2567         }
2568 #else
2569         fg.revision= 0;
2570 #endif
2571         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2572 }
2573
2574 /* preview image, first 2 values are width and height
2575  * second are an RGBA image (unsigned char)
2576  * note, this uses 'TEST' since new types will segfault on file load for older blender versions.
2577  */
2578 static void write_thumb(WriteData *wd, int *img)
2579 {
2580         if(img)
2581                 writedata(wd, TEST, (2 + img[0] * img[1]) * sizeof(int), img);
2582 }
2583
2584 /* if MemFile * there's filesave to memory */
2585 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2586                                                          int write_user_block, int write_flags, int *thumb)
2587 {
2588         BHead bhead;
2589         ListBase mainlist;
2590         char buf[16];
2591         WriteData *wd;
2592
2593         blo_split_main(&mainlist, mainvar);
2594
2595         wd= bgnwrite(handle, compare, current);
2596         
2597         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2598         mywrite(wd, buf, 12);
2599
2600         write_renderinfo(wd, mainvar);
2601         write_thumb(wd, thumb);
2602         write_global(wd, write_flags, mainvar);
2603
2604         /* no UI save in undo */
2605         if(current==NULL) {
2606                 write_windowmanagers(wd, &mainvar->wm);
2607                 write_screens  (wd, &mainvar->screen);
2608         }
2609         write_movieclips (wd, &mainvar->movieclip);
2610         write_scenes   (wd, &mainvar->scene);
2611         write_curves   (wd, &mainvar->curve);
2612         write_mballs   (wd, &mainvar->mball);
2613         write_images   (wd, &mainvar->image);
2614         write_cameras  (wd, &mainvar->camera);
2615         write_lamps    (wd, &mainvar->lamp);
2616         write_lattices (wd, &mainvar->latt);
2617         write_vfonts   (wd, &mainvar->vfont);
2618         write_keys     (wd, &mainvar->key);
2619         write_worlds   (wd, &mainvar->world);
2620         write_texts    (wd, &mainvar->text);
2621         write_speakers (wd, &mainvar->speaker);
2622         write_sounds   (wd, &mainvar->sound);
2623         write_groups   (wd, &mainvar->group);
2624         write_armatures(wd, &mainvar->armature);
2625         write_actions  (wd, &mainvar->action);
2626         write_objects  (wd, &mainvar->object);
2627         write_materials(wd, &mainvar->mat);
2628         write_textures (wd, &mainvar->tex);
2629         write_meshs    (wd, &mainvar->mesh);
2630         write_particlesettings(wd, &mainvar->particle);
2631         write_nodetrees(wd, &mainvar->nodetree);
2632         write_brushes  (wd, &mainvar->brush);
2633         write_scripts  (wd, &mainvar->script);
2634         write_gpencils (wd, &mainvar->gpencil);
2635         write_libraries(wd,  mainvar->next);
2636
2637         if (write_user_block) {
2638                 write_userdef(wd);
2639         }
2640                                                         
2641         /* dna as last, because (to be implemented) test for which structs are written */
2642         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2643
2644         /* end of file */
2645         memset(&bhead, 0, sizeof(BHead));
2646         bhead.code= ENDB;
2647         mywrite(wd, &bhead, sizeof(BHead));
2648
2649         blo_join_main(&mainlist);
2650
2651         return endwrite(wd);
2652 }
2653
2654 /* do reverse file history: .blend1 -> .blend2, .blend -> .blend1 */
2655 /* return: success(0), failure(1) */
2656 static int do_history(const char *name, ReportList *reports)
2657 {
2658         char tempname1[FILE_MAXDIR+FILE_MAXFILE], tempname2[FILE_MAXDIR+FILE_MAXFILE];
2659         int hisnr= U.versions;
2660         
2661         if(U.versions==0) return 0;
2662         if(strlen(name)<2) {
2663                 BKE_report(reports, RPT_ERROR, "Unable to make version backup: filename too short");
2664                 return 1;
2665         }
2666                 
2667         while(hisnr > 1) {
2668                 BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr-1);
2669                 BLI_snprintf(tempname2, sizeof(tempname2), "%s%d", name, hisnr);
2670         
2671                 if(BLI_rename(tempname1, tempname2)) {
2672                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
2673                         return 1;
2674                 }       
2675                 hisnr--;
2676         }
2677
2678         /* is needed when hisnr==1 */
2679         BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr);
2680
2681         if(BLI_rename(name, tempname1)) {
2682                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
2683                 return 1;
2684         }
2685
2686         return 0;
2687 }
2688
2689 /* return: success (1) */
2690 int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportList *reports, int *thumb)
2691 {
2692         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2693         char tempname[FILE_MAXDIR+FILE_MAXFILE+1];
2694         int file, err, write_user_block;
2695
2696         /* open temporary file, so we preserve the original in case we crash */
2697         BLI_snprintf(tempname, sizeof(tempname), "%s@", filepath);
2698
2699         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2700         if(file == -1) {
2701                 BKE_reportf(reports, RPT_ERROR, "Can't open file %s for writing: %s.", tempname, strerror(errno));
2702                 return 0;
2703         }
2704
2705         /* remapping of relative paths to new file location */
2706         if(write_flags & G_FILE_RELATIVE_REMAP) {
2707                 char dir1[FILE_MAXDIR+FILE_MAXFILE];
2708                 char dir2[FILE_MAXDIR+FILE_MAXFILE];
2709                 BLI_split_dirfile(filepath, dir1, NULL);
2710                 BLI_split_dirfile(mainvar->name, dir2, NULL);
2711
2712                 /* just incase there is some subtle difference */
2713                 BLI_cleanup_dir(mainvar->name, dir1);
2714                 BLI_cleanup_dir(mainvar->name, dir2);
2715
2716                 if(BLI_path_cmp(dir1, dir2)==0) {
2717                         write_flags &= ~G_FILE_RELATIVE_REMAP;
2718                 }
2719                 else {
2720                         if(G.relbase_valid) {
2721                                 /* blend may not have been saved before. Tn this case
2722                                  * we should not have any relative paths, but if there
2723                                  * is somehow, an invalid or empty G.main->name it will
2724                                  * print an error, dont try make the absolute in this case. */
2725                                 makeFilesAbsolute(mainvar, G.main->name, NULL);
2726                         }
2727                 }
2728         }
2729
2730         BLI_make_file_string(G.main->name, userfilename, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
2731         write_user_block= (BLI_path_cmp(filepath, userfilename) == 0);
2732
2733         if(write_flags & G_FILE_RELATIVE_REMAP)
2734                 makeFilesRelative(mainvar, filepath, NULL); /* note, making relative to something OTHER then G.main->name */
2735
2736         /* actual file writing */
2737         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags, thumb);
2738         close(file);
2739
2740         if (err) {
2741                 BKE_report(reports, RPT_ERROR, strerror(errno));
2742                 remove(tempname);
2743
2744                 return 0;
2745         }
2746
2747         /* file save to temporary file was successful */
2748         /* now do reverse file history (move .blend1 -> .blend2, .blend -> .blend1) */
2749         if (write_flags & G_FILE_HISTORY) { 
2750                 int err_hist = do_history(filepath, reports);
2751                 if (err_hist) {
2752                         BKE_report(reports, RPT_ERROR, "Version backup failed. File saved with @");
2753                         return 0;
2754                 }
2755         }
2756
2757         if(write_flags & G_FILE_COMPRESS) {
2758                 /* compressed files have the same ending as regular files... only from 2.4!!! */
2759                 char gzname[FILE_MAXDIR+FILE_MAXFILE+4];
2760                 int ret;
2761
2762                 /* first write compressed to separate @.gz */
2763                 BLI_snprintf(gzname, sizeof(gzname), "%s@.gz", filepath);
2764                 ret = BLI_gzip(tempname, gzname);
2765                 
2766                 if(0==ret) {
2767                         /* now rename to real file name, and delete temp @ file too */
2768                         if(BLI_rename(gzname, filepath) != 0) {
2769                                 BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @.");
2770                                 return 0;
2771                         }
2772
2773                         BLI_delete(tempname, 0, 0);
2774                 }
2775                 else if(-1==ret) {
2776                         BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2777                         return 0;
2778                 }
2779                 else if(-2==ret) {
2780                         BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2781                         return 0;
2782                 }
2783         }
2784         else if(BLI_rename(tempname, filepath) != 0) {
2785                 BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2786                 return 0;
2787         }
2788
2789         return 1;
2790 }
2791
2792 /* return: success (1) */
2793 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags)
2794 {
2795         int err;
2796
2797         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags, NULL);
2798         
2799         if(err==0) return 1;
2800         return 0;
2801 }