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