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