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