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