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