NLA SoC: Merge from 2.5
[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 /* TODO: replace *cache with *cachelist once it's coded */
553 #define PTCACHE_WRITE_PSYS      0
554 static void write_pointcaches(WriteData *wd, PointCache *cache, int type)
555 {
556         writestruct(wd, DATA, "PointCache", 1, cache);
557
558         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
559                 PTCacheMem *pm = cache->mem_cache.first;
560
561                 for(; pm; pm=pm->next) {
562                         writestruct(wd, DATA, "PTCacheMem", 1, pm);
563                         if(type==PTCACHE_WRITE_PSYS)
564                                 writestruct(wd, DATA, "ParticleKey", pm->totpoint, pm->data);
565                 }
566         }
567 }
568 static void write_particlesettings(WriteData *wd, ListBase *idbase)
569 {
570         ParticleSettings *part;
571
572         part= idbase->first;
573         while(part) {
574                 if(part->id.us>0 || wd->current) {
575                         /* write LibData */
576                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
577                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
578                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
579                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
580                 }
581                 part= part->id.next;
582         }
583 }
584 static void write_particlesystems(WriteData *wd, ListBase *particles)
585 {
586         ParticleSystem *psys= particles->first;
587         int a;
588
589         for(; psys; psys=psys->next) {
590                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
591
592                 if(psys->particles) {
593                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
594
595                         if(psys->particles->hair) {
596                                 ParticleData *pa = psys->particles;
597
598                                 for(a=0; a<psys->totpart; a++, pa++)
599                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
600                         }
601                 }
602                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
603                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
604                 if(psys->soft) write_pointcaches(wd, psys->soft->pointcache, PTCACHE_WRITE_PSYS);
605                 write_pointcaches(wd, psys->pointcache, PTCACHE_WRITE_PSYS);
606         }
607 }
608
609 static void write_properties(WriteData *wd, ListBase *lb)
610 {
611         bProperty *prop;
612
613         prop= lb->first;
614         while(prop) {
615                 writestruct(wd, DATA, "bProperty", 1, prop);
616
617                 if(prop->poin && prop->poin != &prop->data)
618                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
619
620                 prop= prop->next;
621         }
622 }
623
624 static void write_sensors(WriteData *wd, ListBase *lb)
625 {
626         bSensor *sens;
627
628         sens= lb->first;
629         while(sens) {
630                 writestruct(wd, DATA, "bSensor", 1, sens);
631
632                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
633
634                 switch(sens->type) {
635                 case SENS_NEAR:
636                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
637                         break;
638                 case SENS_MOUSE:
639                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
640                         break;
641                 case SENS_TOUCH:
642                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
643                         break;
644                 case SENS_KEYBOARD:
645                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
646                         break;
647                 case SENS_PROPERTY:
648                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
649                         break;
650                 case SENS_ACTUATOR:
651                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
652                         break;
653                 case SENS_DELAY:
654                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
655                         break;
656                 case SENS_COLLISION:
657                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
658                         break;
659                 case SENS_RADAR:
660                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
661                         break;
662                 case SENS_RANDOM:
663                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
664                         break;
665                 case SENS_RAY:
666                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
667                         break;
668                 case SENS_MESSAGE:
669                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
670                         break;
671                 case SENS_JOYSTICK:
672                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
673                         break;
674                 default:
675                         ; /* error: don't know how to write this file */
676                 }
677
678                 sens= sens->next;
679         }
680 }
681
682 static void write_controllers(WriteData *wd, ListBase *lb)
683 {
684         bController *cont;
685
686         cont= lb->first;
687         while(cont) {
688                 writestruct(wd, DATA, "bController", 1, cont);
689
690                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
691
692                 switch(cont->type) {
693                 case CONT_EXPRESSION:
694                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
695                         break;
696                 case CONT_PYTHON:
697                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
698                         break;
699                 default:
700                         ; /* error: don't know how to write this file */
701                 }
702
703                 cont= cont->next;
704         }
705 }
706
707 static void write_actuators(WriteData *wd, ListBase *lb)
708 {
709         bActuator *act;
710
711         act= lb->first;
712         while(act) {
713                 writestruct(wd, DATA, "bActuator", 1, act);
714
715                 switch(act->type) {
716                 case ACT_ACTION:
717                 case ACT_SHAPEACTION:
718                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
719                         break;
720                 case ACT_SOUND:
721                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
722                         break;
723                 case ACT_CD:
724                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
725                         break;
726                 case ACT_OBJECT:
727                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
728                         break;
729                 case ACT_IPO:
730                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
731                         break;
732                 case ACT_PROPERTY:
733                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
734                         break;
735                 case ACT_CAMERA:
736                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
737                         break;
738                 case ACT_CONSTRAINT:
739                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
740                         break;
741                 case ACT_EDIT_OBJECT:
742                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
743                         break;
744                 case ACT_SCENE:
745                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
746                         break;
747                 case ACT_GROUP:
748                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
749                         break;
750                 case ACT_RANDOM:
751                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
752                         break;
753                 case ACT_MESSAGE:
754                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
755                         break;
756                 case ACT_GAME:
757                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
758                         break;
759                 case ACT_VISIBILITY:
760                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
761                         break;
762                 case ACT_2DFILTER:
763                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
764                         break;
765                 case ACT_PARENT:
766                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
767                         break;
768                 case ACT_STATE:
769                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
770                         break;
771                 default:
772                         ; /* error: don't know how to write this file */
773                 }
774
775                 act= act->next;
776         }
777 }
778
779 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
780 {
781         FModifier *fcm;
782         
783         /* Modifiers */
784         for (fcm= fmodifiers->first; fcm; fcm= fcm->next) {
785                 FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
786                 
787                 /* Write the specific data */
788                 if (fmi && fcm->data) {
789                         /* firstly, just write the plain fmi->data struct */
790                         writestruct(wd, DATA, fmi->structName, 1, fcm->data);
791                         
792                         /* do any modifier specific stuff */
793                         switch (fcm->type) {
794                                 case FMODIFIER_TYPE_GENERATOR:
795                                 {
796                                         FMod_Generator *data= (FMod_Generator *)fcm->data;
797                                         
798                                         /* write coefficients array */
799                                         if (data->coefficients)
800                                                 writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
801                                 }
802                                         break;
803                                 case FMODIFIER_TYPE_ENVELOPE:
804                                 {
805                                         FMod_Envelope *data= (FMod_Envelope *)fcm->data;
806                                         
807                                         /* write envelope data */
808                                         if (data->data)
809                                                 writedata(wd, DATA, sizeof(FCM_EnvelopeData)*(data->totvert), data->data);
810                                 }
811                                         break;
812                                 case FMODIFIER_TYPE_PYTHON:
813                                 {
814                                         FMod_Python *data = (FMod_Python *)fcm->data;
815                                         
816                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
817                                          of library blocks that implement this.*/
818                                         IDP_WriteProperty(data->prop, wd);
819                                 }
820                                         break;
821                         }
822                 }
823                 
824                 /* Write the modifier */
825                 writestruct(wd, DATA, "FModifier", 1, fcm);
826         }
827 }
828
829 static void write_fcurves(WriteData *wd, ListBase *fcurves)
830 {
831         FCurve *fcu;
832         
833         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
834                 /* F-Curve */
835                 writestruct(wd, DATA, "FCurve", 1, fcu);
836                 
837                 /* curve data */
838                 if (fcu->bezt)          
839                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
840                 if (fcu->fpt)
841                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
842                         
843                 if (fcu->rna_path)
844                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
845                 
846                 /* driver data */
847                 if (fcu->driver) {
848                         ChannelDriver *driver= fcu->driver;
849                         DriverTarget *dtar;
850                         
851                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
852                         
853                         /* targets */
854                         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
855                                 writestruct(wd, DATA, "DriverTarget", 1, dtar);
856                                 
857                                 if (dtar->rna_path)
858                                         writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
859                         }
860                 }
861                 
862                 /* write F-Modifiers */
863                 write_fmodifiers(wd, &fcu->modifiers);
864         }
865 }
866
867 static void write_actions(WriteData *wd, ListBase *idbase)
868 {
869         bAction *act;
870         bActionGroup *grp;
871         TimeMarker *marker;
872         
873         for(act=idbase->first; act; act= act->id.next) {
874                 if (act->id.us>0 || wd->current) {
875                         writestruct(wd, ID_AC, "bAction", 1, act);
876                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
877                         
878                         write_fcurves(wd, &act->curves);
879                         
880                         for (grp=act->groups.first; grp; grp=grp->next) {
881                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
882                         }
883                         
884                         for (marker=act->markers.first; marker; marker=marker->next) {
885                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
886                         }
887                 }
888         }
889         
890         /* flush helps the compression for undo-save */
891         mywrite(wd, MYWRITE_FLUSH, 0);
892 }
893
894 static void write_keyingsets(WriteData *wd, ListBase *list)
895 {
896         KeyingSet *ks;
897         KS_Path *ksp;
898         
899         for (ks= list->first; ks; ks= ks->next) {
900                 /* KeyingSet */
901                 writestruct(wd, DATA, "KeyingSet", 1, ks);
902                 
903                 /* Paths */
904                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
905                         /* Path */
906                         writestruct(wd, DATA, "KS_Path", 1, ksp);
907                         
908                         if (ksp->rna_path)
909                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
910                 }
911         }
912 }
913
914 static void write_nladata(WriteData *wd, ListBase *nlabase)
915 {
916         NlaTrack *nlt;
917         NlaStrip *strip;
918         
919         /* write all the tracks */
920         for (nlt= nlabase->first; nlt; nlt= nlt->next) {
921                 /* write the track first */
922                 writestruct(wd, DATA, "NlaTrack", 1, nlt);
923                 
924                 for (strip= nlt->strips.first; strip; strip= strip->next) {
925                         /* write the strip first */
926                         writestruct(wd, DATA, "NlaStrip", 1, strip);
927                         
928                         /* write the strip's F-Curves and modifiers */
929                         write_fcurves(wd, &strip->fcurves);
930                         write_fmodifiers(wd, &strip->modifiers);
931                         
932                         // TODO write the remaps
933                 }
934         }
935 }
936
937 static void write_animdata(WriteData *wd, AnimData *adt)
938 {
939         AnimOverride *aor;
940         
941         /* firstly, just write the AnimData block */
942         writestruct(wd, DATA, "AnimData", 1, adt);
943         
944         /* write drivers */
945         write_fcurves(wd, &adt->drivers);
946         
947         /* write overrides */
948         // FIXME: are these needed?
949         for (aor= adt->overrides.first; aor; aor= aor->next) {
950                 /* overrides consist of base data + rna_path */
951                 writestruct(wd, DATA, "AnimOverride", 1, aor);
952                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
953         }
954         
955         // TODO write the remaps (if they are needed)
956         
957         /* write NLA data */
958         write_nladata(wd, &adt->nla_tracks);
959 }
960
961 static void write_constraints(WriteData *wd, ListBase *conlist)
962 {
963         bConstraint *con;
964
965         for (con=conlist->first; con; con=con->next) {
966                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
967                 
968                 /* Write the specific data */
969                 if (cti && con->data) {
970                         /* firstly, just write the plain con->data struct */
971                         writestruct(wd, DATA, cti->structName, 1, con->data);
972                         
973                         /* do any constraint specific stuff */
974                         switch (con->type) {
975                                 case CONSTRAINT_TYPE_PYTHON:
976                                 {
977                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
978                                         bConstraintTarget *ct;
979                                         
980                                         /* write targets */
981                                         for (ct= data->targets.first; ct; ct= ct->next)
982                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
983                                         
984                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
985                                          of library blocks that implement this.*/
986                                         IDP_WriteProperty(data->prop, wd);
987                                 }
988                                 break;
989                         }
990                 }
991                 
992                 /* Write the constraint */
993                 writestruct(wd, DATA, "bConstraint", 1, con);
994         }
995 }
996
997 static void write_pose(WriteData *wd, bPose *pose)
998 {
999         bPoseChannel *chan;
1000         bActionGroup *grp;
1001
1002         /* Write each channel */
1003         if (!pose)
1004                 return;
1005
1006         /* Write channels */
1007         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1008                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1009                  of library blocks that implement this.*/
1010                 if (chan->prop)
1011                         IDP_WriteProperty(chan->prop, wd);
1012                 
1013                 write_constraints(wd, &chan->constraints);
1014                 
1015                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1016                 if (chan->bone) 
1017                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
1018                 
1019                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1020         }
1021         
1022         /* Write groups */
1023         for (grp=pose->agroups.first; grp; grp=grp->next) 
1024                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1025
1026         /* Write this pose */
1027         writestruct(wd, DATA, "bPose", 1, pose);
1028 }
1029
1030 static void write_defgroups(WriteData *wd, ListBase *defbase)
1031 {
1032         bDeformGroup    *defgroup;
1033
1034         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1035                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1036 }
1037
1038 static void write_modifiers(WriteData *wd, ListBase *modbase, int write_undo)
1039 {
1040         ModifierData *md;
1041
1042         if (modbase == NULL) return;
1043         for (md=modbase->first; md; md= md->next) {
1044                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1045                 if (mti == NULL) return;
1046                 
1047                 writestruct(wd, DATA, mti->structName, 1, md);
1048                         
1049                 if (md->type==eModifierType_Hook) {
1050                         HookModifierData *hmd = (HookModifierData*) md;
1051                         
1052                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1053                 }
1054                 else if(md->type==eModifierType_Cloth) {
1055                         ClothModifierData *clmd = (ClothModifierData*) md;
1056                         
1057                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1058                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1059                         writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
1060                 } 
1061                 else if(md->type==eModifierType_Fluidsim) {
1062                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1063                         
1064                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1065                 } 
1066                 else if (md->type==eModifierType_Collision) {
1067                         
1068                         /*
1069                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1070                         // TODO: CollisionModifier should use pointcache 
1071                         // + have proper reset events before enabling this
1072                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1073                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1074                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1075                         */
1076                 }
1077                 else if (md->type==eModifierType_MeshDeform) {
1078                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1079                         int size = mmd->dyngridsize;
1080
1081                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
1082                                 mmd->bindweights);
1083                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1084                                 mmd->bindcos);
1085                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1086                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1087                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1088                 }
1089                 else if (md->type==eModifierType_Multires) {
1090                         MultiresModifierData *mmd = (MultiresModifierData*) md;
1091
1092                         if(mmd->undo_verts && write_undo)
1093                                 writestruct(wd, DATA, "MVert", mmd->undo_verts_tot, mmd->undo_verts);
1094                 }
1095         }
1096 }
1097
1098 static void write_objects(WriteData *wd, ListBase *idbase, int write_undo)
1099 {
1100         Object *ob;
1101         
1102         ob= idbase->first;
1103         while(ob) {
1104                 if(ob->id.us>0 || wd->current) {
1105                         /* write LibData */
1106                         writestruct(wd, ID_OB, "Object", 1, ob);
1107                         
1108                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1109                           of library blocks that implement this.*/
1110                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1111                         
1112                         if (ob->adt) write_animdata(wd, ob->adt);
1113                         
1114                         /* direct data */
1115                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1116                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1117                         write_properties(wd, &ob->prop);
1118                         write_sensors(wd, &ob->sensors);
1119                         write_controllers(wd, &ob->controllers);
1120                         write_actuators(wd, &ob->actuators);
1121                         write_scriptlink(wd, &ob->scriptlink);
1122                         write_pose(wd, ob->pose);
1123                         write_defgroups(wd, &ob->defbase);
1124                         write_constraints(wd, &ob->constraints);
1125                         
1126                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1127                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1128                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
1129                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1130                         
1131                         write_particlesystems(wd, &ob->particlesystem);
1132                         write_modifiers(wd, &ob->modifiers, write_undo);
1133                 }
1134                 ob= ob->id.next;
1135         }
1136
1137         /* flush helps the compression for undo-save */
1138         mywrite(wd, MYWRITE_FLUSH, 0);
1139 }
1140
1141
1142 static void write_vfonts(WriteData *wd, ListBase *idbase)
1143 {
1144         VFont *vf;
1145         PackedFile * pf;
1146
1147         vf= idbase->first;
1148         while(vf) {
1149                 if(vf->id.us>0 || wd->current) {
1150                         /* write LibData */
1151                         writestruct(wd, ID_VF, "VFont", 1, vf);
1152                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1153
1154                         /* direct data */
1155
1156                         if (vf->packedfile) {
1157                                 pf = vf->packedfile;
1158                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1159                                 writedata(wd, DATA, pf->size, pf->data);
1160                         }
1161                 }
1162
1163                 vf= vf->id.next;
1164         }
1165 }
1166
1167
1168 static void write_keys(WriteData *wd, ListBase *idbase)
1169 {
1170         Key *key;
1171         KeyBlock *kb;
1172
1173         key= idbase->first;
1174         while(key) {
1175                 if(key->id.us>0 || wd->current) {
1176                         /* write LibData */
1177                         writestruct(wd, ID_KE, "Key", 1, key);
1178                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1179                         
1180                         if (key->adt) write_animdata(wd, key->adt);
1181                         
1182                         /* direct data */
1183                         kb= key->block.first;
1184                         while(kb) {
1185                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1186                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1187                                 kb= kb->next;
1188                         }
1189                 }
1190
1191                 key= key->id.next;
1192         }
1193         /* flush helps the compression for undo-save */
1194         mywrite(wd, MYWRITE_FLUSH, 0);
1195 }
1196
1197 static void write_cameras(WriteData *wd, ListBase *idbase)
1198 {
1199         Camera *cam;
1200
1201         cam= idbase->first;
1202         while(cam) {
1203                 if(cam->id.us>0 || wd->current) {
1204                         /* write LibData */
1205                         writestruct(wd, ID_CA, "Camera", 1, cam);
1206                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1207                         
1208                         if (cam->adt) write_animdata(wd, cam->adt);
1209                         
1210                         /* direct data */
1211                         write_scriptlink(wd, &cam->scriptlink);
1212                 }
1213
1214                 cam= cam->id.next;
1215         }
1216 }
1217
1218 static void write_mballs(WriteData *wd, ListBase *idbase)
1219 {
1220         MetaBall *mb;
1221         MetaElem *ml;
1222
1223         mb= idbase->first;
1224         while(mb) {
1225                 if(mb->id.us>0 || wd->current) {
1226                         /* write LibData */
1227                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1228                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1229
1230                         /* direct data */
1231                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1232
1233                         ml= mb->elems.first;
1234                         while(ml) {
1235                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1236                                 ml= ml->next;
1237                         }
1238                 }
1239                 mb= mb->id.next;
1240         }
1241 }
1242
1243 static int amount_of_chars(char *str)
1244 {
1245         // Since the data is saved as UTF-8 to the cu->str
1246         // The cu->len is not same as the strlen(cu->str)
1247         return strlen(str);
1248 }
1249
1250 static void write_curves(WriteData *wd, ListBase *idbase)
1251 {
1252         Curve *cu;
1253         Nurb *nu;
1254
1255         cu= idbase->first;
1256         while(cu) {
1257                 if(cu->id.us>0 || wd->current) {
1258                         /* write LibData */
1259                         writestruct(wd, ID_CU, "Curve", 1, cu);
1260                         
1261                         /* direct data */
1262                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1263                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1264                         if (cu->adt) write_animdata(wd, cu->adt);
1265                         
1266                         if(cu->vfont) {
1267                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1268                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1269                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1270                         }
1271                         else {
1272                                 /* is also the order of reading */
1273                                 nu= cu->nurb.first;
1274                                 while(nu) {
1275                                         writestruct(wd, DATA, "Nurb", 1, nu);
1276                                         nu= nu->next;
1277                                 }
1278                                 nu= cu->nurb.first;
1279                                 while(nu) {
1280                                         if( (nu->type & 7)==CU_BEZIER)
1281                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1282                                         else {
1283                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1284                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1285                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1286                                         }
1287                                         nu= nu->next;
1288                                 }
1289                         }
1290                 }
1291                 cu= cu->id.next;
1292         }
1293
1294         /* flush helps the compression for undo-save */
1295         mywrite(wd, MYWRITE_FLUSH, 0);
1296 }
1297
1298 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1299 {
1300         if (dvlist) {
1301                 int i;
1302                 
1303                 /* Write the dvert list */
1304                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1305                 
1306                 /* Write deformation data for each dvert */
1307                 for (i=0; i<count; i++) {
1308                         if (dvlist[i].dw)
1309                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1310                 }
1311         }
1312 }
1313
1314 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist)
1315 {
1316         if(mdlist) {
1317                 int i;
1318                 
1319                 writestruct(wd, DATA, "MDisps", count, mdlist);
1320                 for(i = 0; i < count; ++i) {
1321                         if(mdlist[i].disps)
1322                                 writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1323                 }
1324         }
1325 }
1326
1327 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1328 {
1329         int i;
1330
1331         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1332
1333         for (i=0; i<data->totlayer; i++) {
1334                 CustomDataLayer *layer= &data->layers[i];
1335                 char *structname;
1336                 int structnum, datasize;
1337
1338                 if (layer->type == CD_MDEFORMVERT) {
1339                         /* layer types that allocate own memory need special handling */
1340                         write_dverts(wd, count, layer->data);
1341                 }
1342                 else if (layer->type == CD_MDISPS) {
1343                         write_mdisps(wd, count, layer->data);
1344                 }
1345                 else {
1346                         CustomData_file_write_info(layer->type, &structname, &structnum);
1347                         if (structnum) {
1348                                 /* when using partial visibility, the MEdge and MFace layers
1349                                    are smaller than the original, so their type and count is
1350                                    passed to make this work */
1351                                 if (layer->type != partial_type) datasize= structnum*count;
1352                                 else datasize= structnum*partial_count;
1353
1354                                 writestruct(wd, DATA, structname, datasize, layer->data);
1355                         }
1356                         else
1357                                 printf("error: this CustomDataLayer must not be written to file\n");
1358                 }
1359         }
1360 }
1361
1362 static void write_meshs(WriteData *wd, ListBase *idbase)
1363 {
1364         Mesh *mesh;
1365
1366         mesh= idbase->first;
1367         while(mesh) {
1368                 if(mesh->id.us>0 || wd->current) {
1369                         /* write LibData */
1370                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1371
1372                         /* direct data */
1373                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1374
1375                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1376
1377                         if(mesh->pv) {
1378                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1379                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1380                                         CD_MEDGE, mesh->totedge);
1381                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1382                                         CD_MFACE, mesh->totface);
1383                         }
1384                         else {
1385                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1386                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1387                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1388                         }
1389
1390                         /* PMV data */
1391                         if(mesh->pv) {
1392                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1393                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1394                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1395                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1396                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1397                         }
1398                 }
1399                 mesh= mesh->id.next;
1400         }
1401 }
1402
1403 static void write_lattices(WriteData *wd, ListBase *idbase)
1404 {
1405         Lattice *lt;
1406         
1407         lt= idbase->first;
1408         while(lt) {
1409                 if(lt->id.us>0 || wd->current) {
1410                         /* write LibData */
1411                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1412                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1413
1414                         /* direct data */
1415                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1416                         
1417                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1418                         
1419                 }
1420                 lt= lt->id.next;
1421         }
1422 }
1423
1424 static void write_previews(WriteData *wd, PreviewImage *prv)
1425 {
1426         if (prv) {
1427                 short w = prv->w[1];
1428                 short h = prv->h[1];
1429                 unsigned int *rect = prv->rect[1];
1430                 /* don't write out large previews if not requested */
1431                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1432                         prv->w[1] = 0;
1433                         prv->h[1] = 0;
1434                         prv->rect[1] = NULL;
1435                 }
1436                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1437                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1438                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1439
1440                 /* restore preview, we still want to keep it in memory even if not saved to file */
1441                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1442                         prv->w[1] = w;
1443                         prv->h[1] = h;
1444                         prv->rect[1] = rect;
1445                 }
1446         }
1447 }
1448
1449 static void write_images(WriteData *wd, ListBase *idbase)
1450 {
1451         Image *ima;
1452         PackedFile * pf;
1453
1454
1455         ima= idbase->first;
1456         while(ima) {
1457                 if(ima->id.us>0 || wd->current) {
1458                         /* write LibData */
1459                         writestruct(wd, ID_IM, "Image", 1, ima);
1460                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1461
1462                         if (ima->packedfile) {
1463                                 pf = ima->packedfile;
1464                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1465                                 writedata(wd, DATA, pf->size, pf->data);
1466                         }
1467
1468                         write_previews(wd, ima->preview);
1469
1470                         }
1471                 ima= ima->id.next;
1472         }
1473         /* flush helps the compression for undo-save */
1474         mywrite(wd, MYWRITE_FLUSH, 0);
1475 }
1476
1477 static void write_textures(WriteData *wd, ListBase *idbase)
1478 {
1479         Tex *tex;
1480
1481         tex= idbase->first;
1482         while(tex) {
1483                 if(tex->id.us>0 || wd->current) {
1484                         /* write LibData */
1485                         writestruct(wd, ID_TE, "Tex", 1, tex);
1486                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1487
1488                         if (tex->adt) write_animdata(wd, tex->adt);
1489
1490                         /* direct data */
1491                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1492                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1493                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1494                         
1495                         /* nodetree is integral part of texture, no libdata */
1496                         if(tex->nodetree) {
1497                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1498                                 write_nodetree(wd, tex->nodetree);
1499                         }
1500                         
1501                         write_previews(wd, tex->preview);
1502                 }
1503                 tex= tex->id.next;
1504         }
1505
1506         /* flush helps the compression for undo-save */
1507         mywrite(wd, MYWRITE_FLUSH, 0);
1508 }
1509
1510 static void write_materials(WriteData *wd, ListBase *idbase)
1511 {
1512         Material *ma;
1513         int a;
1514
1515         ma= idbase->first;
1516         while(ma) {
1517                 if(ma->id.us>0 || wd->current) {
1518                         /* write LibData */
1519                         writestruct(wd, ID_MA, "Material", 1, ma);
1520                         
1521                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1522                           of library blocks that implement this.*/
1523                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1524                           set yet :) */
1525                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1526                         
1527                         if (ma->adt) write_animdata(wd, ma->adt);
1528
1529                         for(a=0; a<MAX_MTEX; a++) {
1530                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1531                         }
1532                         
1533                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1534                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1535                         
1536                         write_scriptlink(wd, &ma->scriptlink);
1537                         
1538                         /* nodetree is integral part of material, no libdata */
1539                         if(ma->nodetree) {
1540                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1541                                 write_nodetree(wd, ma->nodetree);
1542                         }
1543
1544                         write_previews(wd, ma->preview);                        
1545                 }
1546                 ma= ma->id.next;
1547         }
1548 }
1549
1550 static void write_worlds(WriteData *wd, ListBase *idbase)
1551 {
1552         World *wrld;
1553         int a;
1554
1555         wrld= idbase->first;
1556         while(wrld) {
1557                 if(wrld->id.us>0 || wd->current) {
1558                         /* write LibData */
1559                         writestruct(wd, ID_WO, "World", 1, wrld);
1560                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1561                         
1562                         if (wrld->adt) write_animdata(wd, wrld->adt);
1563                         
1564                         for(a=0; a<MAX_MTEX; a++) {
1565                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1566                         }
1567                         
1568                         write_scriptlink(wd, &wrld->scriptlink);
1569                         
1570                         write_previews(wd, wrld->preview);
1571                 }
1572                 wrld= wrld->id.next;
1573         }
1574 }
1575
1576 static void write_lamps(WriteData *wd, ListBase *idbase)
1577 {
1578         Lamp *la;
1579         int a;
1580
1581         la= idbase->first;
1582         while(la) {
1583                 if(la->id.us>0 || wd->current) {
1584                         /* write LibData */
1585                         writestruct(wd, ID_LA, "Lamp", 1, la);
1586                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1587                         
1588                         if (la->adt) write_animdata(wd, la->adt);
1589                         
1590                         /* direct data */
1591                         for(a=0; a<MAX_MTEX; a++) {
1592                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1593                         }
1594                         
1595                         if(la->curfalloff)
1596                                 write_curvemapping(wd, la->curfalloff); 
1597                         
1598                         write_scriptlink(wd, &la->scriptlink);
1599                         
1600                         write_previews(wd, la->preview);
1601                         
1602                 }
1603                 la= la->id.next;
1604         }
1605 }
1606
1607
1608 static void write_scenes(WriteData *wd, ListBase *scebase)
1609 {
1610         Scene *sce;
1611         Base *base;
1612         Editing *ed;
1613         Sequence *seq;
1614         MetaStack *ms;
1615         Strip *strip;
1616         TimeMarker *marker;
1617         TransformOrientation *ts;
1618         SceneRenderLayer *srl;
1619         
1620         sce= scebase->first;
1621         while(sce) {
1622                 /* write LibData */
1623                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1624                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1625                 
1626                 if (sce->adt) write_animdata(wd, sce->adt);
1627                 write_keyingsets(wd, &sce->keyingsets);
1628                 
1629                 /* direct data */
1630                 base= sce->base.first;
1631                 while(base) {
1632                         writestruct(wd, DATA, "Base", 1, base);
1633                         base= base->next;
1634                 }
1635                 
1636                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1637                 if(sce->toolsettings->vpaint)
1638                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->vpaint);
1639                 if(sce->toolsettings->wpaint)
1640                         writestruct(wd, DATA, "VPaint", 1, sce->toolsettings->wpaint);
1641                 if(sce->toolsettings->sculpt)
1642                         writestruct(wd, DATA, "Sculpt", 1, sce->toolsettings->sculpt);
1643
1644                 ed= sce->ed;
1645                 if(ed) {
1646                         writestruct(wd, DATA, "Editing", 1, ed);
1647                         
1648                         /* reset write flags too */
1649                         
1650                         SEQ_BEGIN(ed, seq) {
1651                                 if(seq->strip) seq->strip->done= 0;
1652                                 writestruct(wd, DATA, "Sequence", 1, seq);
1653                         }
1654                         SEQ_END
1655                         
1656                         SEQ_BEGIN(ed, seq) {
1657                                 if(seq->strip && seq->strip->done==0) {
1658                                         /* write strip with 'done' at 0 because readfile */
1659                                         
1660                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1661                                         if(seq->effectdata) {
1662                                                 switch(seq->type){
1663                                                 case SEQ_COLOR:
1664                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1665                                                         break;
1666                                                 case SEQ_SPEED:
1667                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1668                                                         break;
1669                                                 case SEQ_WIPE:
1670                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1671                                                         break;
1672                                                 case SEQ_GLOW:
1673                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1674                                                         break;
1675                                                 case SEQ_TRANSFORM:
1676                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1677                                                         break;
1678                                                 }
1679                                         }
1680                                         
1681                                         strip= seq->strip;
1682                                         writestruct(wd, DATA, "Strip", 1, strip);
1683                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1684                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1685                                         }
1686                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1687                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1688                                         }
1689                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1690                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1691                                         }
1692                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1693                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1694                                         }
1695                                         if(seq->type==SEQ_IMAGE)
1696                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1697                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1698                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1699                                         
1700                                         strip->done= 1;
1701                                 }
1702                         }
1703                         SEQ_END
1704                                 
1705                         /* new; meta stack too, even when its nasty restore code */
1706                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1707                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1708                         }
1709                 }
1710                 
1711                 write_scriptlink(wd, &sce->scriptlink);
1712                 
1713                 if (sce->r.avicodecdata) {
1714                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1715                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1716                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1717                 }
1718
1719                 if (sce->r.qtcodecdata) {
1720                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1721                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1722                 }
1723                 if (sce->r.ffcodecdata.properties) {
1724                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1725                 }
1726
1727                 /* writing dynamic list of TimeMarkers to the blend file */
1728                 for(marker= sce->markers.first; marker; marker= marker->next)
1729                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1730                 
1731                 /* writing dynamic list of TransformOrientations to the blend file */
1732                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1733                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1734                 
1735                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1736                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1737                 
1738                 if(sce->nodetree) {
1739                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1740                         write_nodetree(wd, sce->nodetree);
1741                 }
1742                 
1743                 sce= sce->id.next;
1744         }
1745         /* flush helps the compression for undo-save */
1746         mywrite(wd, MYWRITE_FLUSH, 0);
1747 }
1748
1749 static void write_gpencils(WriteData *wd, ListBase *lb)
1750 {
1751         bGPdata *gpd;
1752         bGPDlayer *gpl;
1753         bGPDframe *gpf;
1754         bGPDstroke *gps;
1755         
1756         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1757                 /* write gpd data block to file */
1758                 writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1759                 
1760                 /* write grease-pencil layers to file */
1761                 for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1762                         writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1763                         
1764                         /* write this layer's frames to file */
1765                         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1766                                 writestruct(wd, DATA, "bGPDframe", 1, gpf);
1767                                 
1768                                 /* write strokes */
1769                                 for (gps= gpf->strokes.first; gps; gps= gps->next) {
1770                                         writestruct(wd, DATA, "bGPDstroke", 1, gps);
1771                                         writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1772                                 }
1773                         }
1774                 }
1775         }
1776 }
1777
1778 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1779 {
1780         wmWindowManager *wm;
1781         wmWindow *win;
1782         
1783         for(wm= lb->first; wm; wm= wm->id.next) {
1784                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1785                 
1786                 for(win= wm->windows.first; win; win= win->next)
1787                         writestruct(wd, DATA, "wmWindow", 1, win);
1788         }
1789 }
1790
1791 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1792 {       
1793         writestruct(wd, DATA, "ARegion", 1, ar);
1794         
1795         if(ar->regiondata) {
1796                 switch(spacetype) {
1797                         case SPACE_VIEW3D:
1798                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1799                                         RegionView3D *rv3d= ar->regiondata;
1800                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
1801                                         
1802                                         if(rv3d->localvd)
1803                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
1804                                         if(rv3d->clipbb) 
1805                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
1806
1807                                 }
1808                                 else
1809                                         printf("regiondata write missing!\n");
1810                                 break;
1811                         default:
1812                                 printf("regiondata write missing!\n");
1813                 }
1814         }
1815 }
1816
1817 static void write_screens(WriteData *wd, ListBase *scrbase)
1818 {
1819         bScreen *sc;
1820         ScrArea *sa;
1821         ScrVert *sv;
1822         ScrEdge *se;
1823
1824         sc= scrbase->first;
1825         while(sc) {
1826                 
1827                 /* write LibData */
1828                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
1829                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
1830                 if (sc->id.properties) 
1831                         IDP_WriteProperty(sc->id.properties, wd);
1832                 
1833                 /* direct data */
1834                 for(sv= sc->vertbase.first; sv; sv= sv->next)
1835                         writestruct(wd, DATA, "ScrVert", 1, sv);
1836                 
1837                 for(se= sc->edgebase.first; se; se= se->next) 
1838                         writestruct(wd, DATA, "ScrEdge", 1, se);
1839                 
1840                 for(sa= sc->areabase.first; sa; sa= sa->next) {
1841                         SpaceLink *sl;
1842                         Panel *pa;
1843                         ARegion *ar;
1844                         
1845                         writestruct(wd, DATA, "ScrArea", 1, sa);
1846                         
1847                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
1848                                 write_region(wd, ar, sa->spacetype);
1849                                 
1850                                 for(pa= ar->panels.first; pa; pa= pa->next)
1851                                         writestruct(wd, DATA, "Panel", 1, pa);
1852                         }
1853                         
1854                         /* space handler scriptlinks */
1855                         write_scriptlink(wd, &sa->scriptlink);
1856                         
1857                         sl= sa->spacedata.first;
1858                         while(sl) {
1859                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
1860                                         write_region(wd, ar, sl->spacetype);
1861                                 
1862                                 if(sl->spacetype==SPACE_VIEW3D) {
1863                                         View3D *v3d= (View3D *) sl;
1864                                         writestruct(wd, DATA, "View3D", 1, v3d);
1865                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1866                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1867                                 }
1868                                 else if(sl->spacetype==SPACE_IPO) {
1869                                         SpaceIpo *sipo= (SpaceIpo *)sl;
1870                                         ListBase tmpGhosts = sipo->ghostCurves;
1871                                         
1872                                         /* temporarily disable ghost curves when saving */
1873                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
1874                                         
1875                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1876                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
1877                                         
1878                                         /* reenable ghost curves */
1879                                         sipo->ghostCurves= tmpGhosts;
1880                                 }
1881                                 else if(sl->spacetype==SPACE_BUTS) {
1882                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1883                                 }
1884                                 else if(sl->spacetype==SPACE_FILE) {
1885                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1886                                 }
1887                                 else if(sl->spacetype==SPACE_SEQ) {
1888                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1889                                 }
1890                                 else if(sl->spacetype==SPACE_OUTLINER) {
1891                                         SpaceOops *so= (SpaceOops *)sl;
1892                                         
1893                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1894
1895                                         /* outliner */
1896                                         if(so->treestore) {
1897                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1898                                                 if(so->treestore->data)
1899                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1900                                         }
1901                                 }
1902                                 else if(sl->spacetype==SPACE_IMAGE) {
1903                                         SpaceImage *sima= (SpaceImage *)sl;
1904                                         
1905                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1906                                         if(sima->cumap)
1907                                                 write_curvemapping(wd, sima->cumap);
1908                                 }
1909                                 else if(sl->spacetype==SPACE_IMASEL) {
1910                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1911                                 }
1912                                 else if(sl->spacetype==SPACE_TEXT) {
1913                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1914                                 }
1915                                 else if(sl->spacetype==SPACE_SCRIPT) {
1916                                         SpaceScript *sc = (SpaceScript*)sl;
1917                                         sc->but_refs = NULL;
1918                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1919                                 }
1920                                 else if(sl->spacetype==SPACE_ACTION) {
1921                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1922                                 }
1923                                 else if(sl->spacetype==SPACE_SOUND) {
1924                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1925                                 }
1926                                 else if(sl->spacetype==SPACE_NLA){
1927                                         SpaceNla *snla= (SpaceNla *)sl;
1928                                         
1929                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
1930                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
1931                                 }
1932                                 else if(sl->spacetype==SPACE_TIME){
1933                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1934                                 }
1935                                 else if(sl->spacetype==SPACE_NODE){
1936                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1937                                 }
1938                                 else if(sl->spacetype==SPACE_LOGIC){
1939                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
1940                                 }
1941                                 sl= sl->next;
1942                         }
1943                 }
1944
1945                 sc= sc->id.next;
1946         }
1947 }
1948
1949 static void write_libraries(WriteData *wd, Main *main)
1950 {
1951         ListBase *lbarray[30];
1952         ID *id;
1953         int a, tot, foundone;
1954
1955         for(; main; main= main->next) {
1956
1957                 a=tot= set_listbasepointers(main, lbarray);
1958
1959                 /* test: is lib being used */
1960                 foundone= 0;
1961                 while(tot--) {
1962                         for(id= lbarray[tot]->first; id; id= id->next) {
1963                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1964                                         foundone= 1;
1965                                         break;
1966                                 }
1967                         }
1968                         if(foundone) break;
1969                 }
1970
1971                 if(foundone) {
1972                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1973
1974                         while(a--) {
1975                                 for(id= lbarray[a]->first; id; id= id->next) {
1976                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1977                                                 writestruct(wd, ID_ID, "ID", 1, id);
1978                                         }
1979                                 }
1980                         }
1981                 }
1982         }
1983 }
1984
1985 static void write_bone(WriteData *wd, Bone* bone)
1986 {
1987         Bone*   cbone;
1988
1989         // PATCH for upward compatibility after 2.37+ armature recode
1990         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1991                 
1992         // Write this bone
1993         writestruct(wd, DATA, "Bone", 1, bone);
1994         
1995         // Write Children
1996         cbone= bone->childbase.first;
1997         while(cbone) {
1998                 write_bone(wd, cbone);
1999                 cbone= cbone->next;
2000         }
2001 }
2002
2003 static void write_armatures(WriteData *wd, ListBase *idbase)
2004 {
2005         bArmature       *arm;
2006         Bone            *bone;
2007
2008         arm=idbase->first;
2009         while (arm) {
2010                 if (arm->id.us>0 || wd->current) {
2011                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2012                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2013
2014                         /* Direct data */
2015                         bone= arm->bonebase.first;
2016                         while(bone) {
2017                                 write_bone(wd, bone);
2018                                 bone=bone->next;
2019                         }
2020                 }
2021                 arm=arm->id.next;
2022         }
2023
2024         /* flush helps the compression for undo-save */
2025         mywrite(wd, MYWRITE_FLUSH, 0);
2026 }
2027
2028 static void write_texts(WriteData *wd, ListBase *idbase)
2029 {
2030         Text *text;
2031         TextLine *tmp;
2032         TextMarker *mrk;
2033
2034         text= idbase->first;
2035         while(text) {
2036                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2037
2038                 /* write LibData */
2039                 writestruct(wd, ID_TXT, "Text", 1, text);
2040                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2041                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2042
2043                 if(!(text->flags & TXT_ISEXT)) {
2044                         /* now write the text data, in two steps for optimization in the readfunction */
2045                         tmp= text->lines.first;
2046                         while (tmp) {
2047                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2048                                 tmp= tmp->next;
2049                         }
2050
2051                         tmp= text->lines.first;
2052                         while (tmp) {
2053                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2054                                 tmp= tmp->next;
2055                         }
2056
2057                         /* write markers */
2058                         mrk= text->markers.first;
2059                         while (mrk) {
2060                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2061                                 mrk= mrk->next;
2062                         }
2063                 }
2064
2065
2066                 text= text->id.next;
2067         }
2068
2069         /* flush helps the compression for undo-save */
2070         mywrite(wd, MYWRITE_FLUSH, 0);
2071 }
2072
2073 static void write_sounds(WriteData *wd, ListBase *idbase)
2074 {
2075         bSound *sound;
2076         bSample *sample;
2077
2078         PackedFile * pf;
2079
2080         // set all samples to unsaved status
2081
2082         sample = samples->first; // samples is a global defined in sound.c
2083         while (sample) {
2084                 sample->flags |= SAMPLE_NEEDS_SAVE;
2085                 sample = sample->id.next;
2086         }
2087
2088         sound= idbase->first;
2089         while(sound) {
2090                 if(sound->id.us>0 || wd->current) {
2091                         // do we need to save the packedfile as well ?
2092                         sample = sound->sample;
2093                         if (sample) {
2094                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
2095                                         sound->newpackedfile = sample->packedfile;
2096                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
2097                                 } else {
2098                                         sound->newpackedfile = NULL;
2099                                 }
2100                         }
2101
2102                         /* write LibData */
2103                         writestruct(wd, ID_SO, "bSound", 1, sound);
2104                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2105
2106                         if (sound->newpackedfile) {
2107                                 pf = sound->newpackedfile;
2108                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2109                                 writedata(wd, DATA, pf->size, pf->data);
2110                         }
2111
2112                         if (sample) {
2113                                 sound->newpackedfile = sample->packedfile;
2114                         }
2115                 }
2116                 sound= sound->id.next;
2117         }
2118
2119         /* flush helps the compression for undo-save */
2120         mywrite(wd, MYWRITE_FLUSH, 0);
2121 }
2122
2123 static void write_groups(WriteData *wd, ListBase *idbase)
2124 {
2125         Group *group;
2126         GroupObject *go;
2127
2128         for(group= idbase->first; group; group= group->id.next) {
2129                 if(group->id.us>0 || wd->current) {
2130                         /* write LibData */
2131                         writestruct(wd, ID_GR, "Group", 1, group);
2132                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2133
2134                         go= group->gobject.first;
2135                         while(go) {
2136                                 writestruct(wd, DATA, "GroupObject", 1, go);
2137                                 go= go->next;
2138                         }
2139                 }
2140         }
2141 }
2142
2143 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2144 {
2145         bNodeTree *ntree;
2146         
2147         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2148                 if (ntree->id.us>0 || wd->current) {
2149                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2150                         write_nodetree(wd, ntree);
2151                         
2152                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2153                         
2154                         if (ntree->adt) write_animdata(wd, ntree->adt);
2155                 }
2156         }
2157 }
2158
2159 static void write_brushes(WriteData *wd, ListBase *idbase)
2160 {
2161         Brush *brush;
2162         int a;
2163         
2164         for(brush=idbase->first; brush; brush= brush->id.next) {
2165                 if(brush->id.us>0 || wd->current) {
2166                         writestruct(wd, ID_BR, "Brush", 1, brush);
2167                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2168                         for(a=0; a<MAX_MTEX; a++)
2169                                 if(brush->mtex[a])
2170                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
2171
2172                         if(brush->curve)
2173                                 write_curvemapping(wd, brush->curve);
2174                 }
2175         }
2176 }
2177
2178 static void write_scripts(WriteData *wd, ListBase *idbase)
2179 {
2180         Script *script;
2181         
2182         for(script=idbase->first; script; script= script->id.next) {
2183                 if(script->id.us>0 || wd->current) {
2184                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2185                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2186                 }
2187         }
2188 }
2189
2190 /* context is usually defined by WM, two cases where no WM is available:
2191  * - for forward compatibility, curscreen has to be saved
2192  * - for undofile, curscene needs to be saved */
2193 static void write_global(WriteData *wd, Main *mainvar)
2194 {
2195         FileGlobal fg;
2196         bScreen *screen;
2197         char subvstr[8];
2198         
2199         current_screen_compat(mainvar, &screen);
2200
2201         /* XXX still remap G */
2202         fg.curscreen= screen;
2203         fg.curscene= screen->scene;
2204         fg.displaymode= G.displaymode;
2205         fg.winpos= G.winpos;
2206         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2207         fg.globalf= G.f;
2208
2209         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2210         memcpy(fg.subvstr, subvstr, 4);
2211         
2212         fg.subversion= BLENDER_SUBVERSION;
2213         fg.minversion= BLENDER_MINVERSION;
2214         fg.minsubversion= BLENDER_MINSUBVERSION;
2215         fg.pads= 0; /* prevent mem checkers from complaining */
2216         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2217 }
2218
2219 /* if MemFile * there's filesave to memory */
2220 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2221                                                          int write_user_block, int write_flags)
2222 {
2223         BHead bhead;
2224         ListBase mainlist;
2225         char buf[16];
2226         WriteData *wd;
2227
2228         blo_split_main(&mainlist, mainvar);
2229
2230         wd= bgnwrite(handle, compare, current, write_flags);
2231         
2232         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2233         mywrite(wd, buf, 12);
2234
2235         write_renderinfo(wd, mainvar);
2236         write_global(wd, mainvar);
2237
2238         /* no UI save in undo */
2239         if(current==NULL) {
2240                 write_windowmanagers(wd, &mainvar->wm);
2241                 write_screens  (wd, &mainvar->screen);
2242         }
2243         write_scenes   (wd, &mainvar->scene);
2244         write_curves   (wd, &mainvar->curve);
2245         write_mballs   (wd, &mainvar->mball);
2246         write_images   (wd, &mainvar->image);
2247         write_cameras  (wd, &mainvar->camera);
2248         write_lamps    (wd, &mainvar->lamp);
2249         write_lattices (wd, &mainvar->latt);
2250         write_vfonts   (wd, &mainvar->vfont);
2251         write_keys     (wd, &mainvar->key);
2252         write_worlds   (wd, &mainvar->world);
2253         write_texts    (wd, &mainvar->text);
2254         write_sounds   (wd, &mainvar->sound);
2255         write_groups   (wd, &mainvar->group);
2256         write_armatures(wd, &mainvar->armature);
2257         write_actions  (wd, &mainvar->action);
2258         write_objects  (wd, &mainvar->object, (current != NULL));
2259         write_materials(wd, &mainvar->mat);
2260         write_textures (wd, &mainvar->tex);
2261         write_meshs    (wd, &mainvar->mesh);
2262         write_particlesettings(wd, &mainvar->particle);
2263         write_nodetrees(wd, &mainvar->nodetree);
2264         write_brushes  (wd, &mainvar->brush);
2265         write_scripts  (wd, &mainvar->script);
2266         write_gpencils (wd, &mainvar->gpencil);
2267         if(current==NULL)       
2268                 write_libraries(wd,  mainvar->next); /* no library save in undo */
2269
2270         if (write_user_block) {
2271                 write_userdef(wd);
2272         }
2273                                                         
2274         /* dna as last, because (to be implemented) test for which structs are written */
2275         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2276
2277         /* end of file */
2278         memset(&bhead, 0, sizeof(BHead));
2279         bhead.code= ENDB;
2280         mywrite(wd, &bhead, sizeof(BHead));
2281
2282         blo_join_main(&mainlist);
2283
2284         return endwrite(wd);
2285 }
2286
2287 /* return: success (1) */
2288 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports)
2289 {
2290         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2291         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2292         int file, err, write_user_block;
2293
2294         sprintf(tempname, "%s@", dir);
2295
2296         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2297         if(file == -1) {
2298                 BKE_report(reports, RPT_ERROR, "Unable to open file for writing.");
2299                 return 0;
2300         }
2301
2302         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B25.blend");
2303         write_user_block= BLI_streq(dir, userfilename);
2304
2305         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags);
2306         close(file);
2307
2308         if(!err) {
2309                 if(write_flags & G_FILE_COMPRESS)
2310                 {       
2311                         // compressed files have the same ending as regular files... only from 2.4!!!
2312                         
2313                         int ret = BLI_gzip(tempname, dir);
2314                         
2315                         if(-1==ret) {
2316                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2317                                 return 0;
2318                         }
2319                         if(-2==ret) {
2320                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2321                                 return 0;
2322                         }
2323                 }
2324                 else
2325                 if(BLI_rename(tempname, dir) != 0) {
2326                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2327                         return 0;
2328                 }
2329
2330                 
2331         } else {
2332                 BKE_report(reports, RPT_ERROR, strerror(errno));
2333                 remove(tempname);
2334
2335                 return 0;
2336         }
2337
2338         return 1;
2339 }
2340
2341 /* return: success (1) */
2342 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags, ReportList *reports)
2343 {
2344         int err;
2345
2346         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags);
2347         
2348         if(err==0) return 1;
2349         return 0;
2350 }
2351
2352
2353         /* Runtime writing */
2354
2355 #ifdef WIN32
2356 #define PATHSEPERATOR           "\\"
2357 #else
2358 #define PATHSEPERATOR           "/"
2359 #endif
2360
2361 static char *get_runtime_path(char *exename) {
2362         char *installpath= get_install_dir();
2363
2364         if (!installpath) {
2365                 return NULL;
2366         } else {
2367                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2368
2369                 if (path == NULL) {
2370                         MEM_freeN(installpath);
2371                         return NULL;
2372                 }
2373
2374                 strcpy(path, installpath);
2375                 strcat(path, PATHSEPERATOR);
2376                 strcat(path, exename);
2377
2378                 MEM_freeN(installpath);
2379
2380                 return path;
2381         }
2382 }
2383
2384 #ifdef __APPLE__
2385
2386 static int recursive_copy_runtime(char *outname, char *exename, ReportList *reports)
2387 {
2388         char *runtime = get_runtime_path(exename);
2389         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2390         int progfd = -1, error= 0;
2391
2392         if (!runtime) {
2393                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2394                 error= 1;
2395                 goto cleanup;
2396         }
2397         //printf("runtimepath %s\n", runtime);
2398                 
2399         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2400         if (progfd==-1) {
2401                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2402                 error= 1;
2403                 goto cleanup;
2404         }
2405
2406         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2407         //printf("command %s\n", command);
2408         if (system(command) == -1) {
2409                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2410                 error= 1;
2411         }
2412
2413 cleanup:
2414         if (progfd!=-1)
2415                 close(progfd);
2416         if (runtime)
2417                 MEM_freeN(runtime);
2418
2419         return !error;
2420 }
2421
2422 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports) 
2423 {
2424         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2425         int outfd = -1, error= 0;
2426
2427         // remove existing file / bundle
2428         //printf("Delete file %s\n", file);
2429         BLI_delete(file, 0, TRUE);
2430
2431         if (!recursive_copy_runtime(file, exename, reports)) {
2432                 error= 1;
2433                 goto cleanup;
2434         }
2435
2436         strcpy(gamename, file);
2437         strcat(gamename, "/Contents/Resources/game.blend");
2438         //printf("gamename %s\n", gamename);
2439         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2440         if (outfd != -1) {
2441
2442                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2443
2444                 if (write(outfd, " ", 1) != 1) {
2445                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2446                         error= 1;
2447                         goto cleanup;
2448                 }
2449         } else {
2450                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2451                 error= 1;
2452         }
2453
2454 cleanup:
2455         if (outfd!=-1)
2456                 close(outfd);
2457
2458         BKE_reports_prepend(reports, "Unable to make runtime: ");
2459         return !error;
2460 }
2461
2462 #else /* !__APPLE__ */
2463
2464 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2465 {
2466         char *runtime= get_runtime_path(exename);
2467         unsigned char buf[1024];
2468         int count, progfd= -1, error= 0;
2469
2470         if (!BLI_exists(runtime)) {
2471                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2472                 error= 1;
2473                 goto cleanup;
2474         }
2475
2476         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2477         if (progfd==-1) {
2478                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2479                 error= 1;
2480                 goto cleanup;
2481         }
2482
2483         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2484                 if (write(handle, buf, count)!=count) {
2485                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2486                         error= 1;
2487                         goto cleanup;
2488                 }
2489         }
2490
2491 cleanup:
2492         if (progfd!=-1)
2493                 close(progfd);
2494         if (runtime)
2495                 MEM_freeN(runtime);
2496
2497         return !error;
2498 }
2499
2500 static int handle_write_msb_int(int handle, int i) 
2501 {
2502         unsigned char buf[4];
2503         buf[0]= (i>>24)&0xFF;
2504         buf[1]= (i>>16)&0xFF;
2505         buf[2]= (i>>8)&0xFF;
2506         buf[3]= (i>>0)&0xFF;
2507
2508         return (write(handle, buf, 4)==4);
2509 }
2510
2511 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports)
2512 {
2513         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2514         int datastart, error= 0;
2515
2516         if (!outfd) {
2517                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2518                 error= 1;
2519                 goto cleanup;
2520         }
2521         if (!handle_append_runtime(outfd, exename, reports)) {
2522                 error= 1;
2523                 goto cleanup;
2524         }
2525
2526         datastart= lseek(outfd, 0, SEEK_CUR);
2527
2528         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2529
2530         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2531                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2532                 error= 1;
2533                 goto cleanup;
2534         }
2535
2536 cleanup:
2537         if (outfd!=-1)
2538                 close(outfd);
2539
2540         BKE_reports_prepend(reports, "Unable to make runtime: ");
2541         return !error;
2542 }
2543
2544 #endif /* !__APPLE__ */