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