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