93bf8111c98a61d41fd1976d05719fb3eff4ed16
[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->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1336                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1337                         if(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                         
1343                         /* nodetree is integral part of texture, no libdata */
1344                         if(tex->nodetree) {
1345                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1346                                 write_nodetree(wd, tex->nodetree);
1347                         }
1348                         
1349                         write_previews(wd, tex->preview);
1350                 }
1351                 tex= tex->id.next;
1352         }
1353
1354         /* flush helps the compression for undo-save */
1355         mywrite(wd, MYWRITE_FLUSH, 0);
1356 }
1357
1358 static void write_materials(WriteData *wd, ListBase *idbase)
1359 {
1360         Material *ma;
1361         int a;
1362
1363         ma= idbase->first;
1364         while(ma) {
1365                 if(ma->id.us>0 || wd->current) {
1366                         /* write LibData */
1367                         writestruct(wd, ID_MA, "Material", 1, ma);
1368                         
1369                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1370                           of library blocks that implement this.*/
1371                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1372                           set yet :) */
1373                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1374
1375                         for(a=0; a<MAX_MTEX; a++) {
1376                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1377                         }
1378                         
1379                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1380                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1381                         
1382                         write_scriptlink(wd, &ma->scriptlink);
1383                         
1384                         /* nodetree is integral part of material, no libdata */
1385                         if(ma->nodetree) {
1386                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1387                                 write_nodetree(wd, ma->nodetree);
1388                         }
1389
1390                         write_previews(wd, ma->preview);                        
1391                 }
1392                 ma= ma->id.next;
1393         }
1394 }
1395
1396 static void write_worlds(WriteData *wd, ListBase *idbase)
1397 {
1398         World *wrld;
1399         int a;
1400
1401         wrld= idbase->first;
1402         while(wrld) {
1403                 if(wrld->id.us>0 || wd->current) {
1404                         /* write LibData */
1405                         writestruct(wd, ID_WO, "World", 1, wrld);
1406                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1407
1408                         for(a=0; a<MAX_MTEX; a++) {
1409                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1410                         }
1411
1412                         write_scriptlink(wd, &wrld->scriptlink);
1413
1414                         write_previews(wd, wrld->preview);
1415
1416                 }
1417                 wrld= wrld->id.next;
1418         }
1419 }
1420
1421 static void write_lamps(WriteData *wd, ListBase *idbase)
1422 {
1423         Lamp *la;
1424         int a;
1425
1426         la= idbase->first;
1427         while(la) {
1428                 if(la->id.us>0 || wd->current) {
1429                         /* write LibData */
1430                         writestruct(wd, ID_LA, "Lamp", 1, la);
1431                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1432
1433                         /* direct data */
1434                         for(a=0; a<MAX_MTEX; a++) {
1435                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1436                         }
1437
1438                         if(la->curfalloff)
1439                                 write_curvemapping(wd, la->curfalloff); 
1440                         
1441                         write_scriptlink(wd, &la->scriptlink);
1442
1443                         write_previews(wd, la->preview);
1444
1445                 }
1446                 la= la->id.next;
1447         }
1448 }
1449
1450
1451 static void write_scenes(WriteData *wd, ListBase *scebase)
1452 {
1453         Scene *sce;
1454         Base *base;
1455         Editing *ed;
1456         Sequence *seq;
1457         MetaStack *ms;
1458         Strip *strip;
1459         TimeMarker *marker;
1460         TransformOrientation *ts;
1461         SceneRenderLayer *srl;
1462         int a;
1463         
1464         sce= scebase->first;
1465         while(sce) {
1466                 /* write LibData */
1467                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1468                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1469
1470                 /* direct data */
1471                 base= sce->base.first;
1472                 while(base) {
1473                         writestruct(wd, DATA, "Base", 1, base);
1474                         base= base->next;
1475                 }
1476
1477                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1478                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1479
1480                 for(a=0; a<MAX_MTEX; ++a)
1481                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1482                 if(sce->sculptdata.cumap)
1483                         write_curvemapping(wd, sce->sculptdata.cumap);
1484
1485                 ed= sce->ed;
1486                 if(ed) {
1487                         writestruct(wd, DATA, "Editing", 1, ed);
1488
1489                         /* reset write flags too */
1490                         WHILE_SEQ(&ed->seqbase) {
1491                                 if(seq->strip) seq->strip->done= 0;
1492                                 writestruct(wd, DATA, "Sequence", 1, seq);
1493                         }
1494                         END_SEQ
1495
1496                         WHILE_SEQ(&ed->seqbase) {
1497                                 if(seq->strip && seq->strip->done==0) {
1498                                         /* write strip with 'done' at 0 because readfile */
1499
1500                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1501                                         if(seq->effectdata) {
1502                                                 switch(seq->type){
1503                                                 case SEQ_COLOR:
1504                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1505                                                         break;
1506                                                 case SEQ_SPEED:
1507                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1508                                                         break;
1509                                                 case SEQ_WIPE:
1510                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1511                                                         break;
1512                                                 case SEQ_GLOW:
1513                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1514                                                         break;
1515                                                 case SEQ_TRANSFORM:
1516                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1517                                                         break;
1518                                                 }
1519                                         }
1520
1521                                         strip= seq->strip;
1522                                         writestruct(wd, DATA, "Strip", 1, strip);
1523                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1524                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1525                                         }
1526                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1527                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1528                                         }
1529                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1530                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1531                                         }
1532                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1533                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1534                                         }
1535                                         if(seq->type==SEQ_IMAGE)
1536                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1537                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1538                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1539
1540                                         strip->done= 1;
1541                                 }
1542                         }
1543                         END_SEQ
1544                                 
1545                         /* new; meta stack too, even when its nasty restore code */
1546                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1547                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1548                         }
1549                 }
1550
1551                 write_scriptlink(wd, &sce->scriptlink);
1552
1553                 if (sce->r.avicodecdata) {
1554                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1555                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1556                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1557                 }
1558
1559                 if (sce->r.qtcodecdata) {
1560                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1561                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1562                 }
1563                 if (sce->r.ffcodecdata.properties) {
1564                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1565                 }
1566
1567                 /* writing dynamic list of TimeMarkers to the blend file */
1568                 for(marker= sce->markers.first; marker; marker= marker->next)
1569                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1570                 
1571                 /* writing dynamic list of TransformOrientations to the blend file */
1572                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1573                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1574                 
1575                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1576                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1577                 
1578                 if(sce->nodetree) {
1579                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1580                         write_nodetree(wd, sce->nodetree);
1581                 }
1582                 
1583                 sce= sce->id.next;
1584         }
1585         /* flush helps the compression for undo-save */
1586         mywrite(wd, MYWRITE_FLUSH, 0);
1587 }
1588
1589 static void write_gpencil(WriteData *wd, bGPdata *gpd)
1590 {
1591         bGPDlayer *gpl;
1592         bGPDframe *gpf;
1593         bGPDstroke *gps;
1594         
1595         /* write gpd data block to file */
1596         writestruct(wd, DATA, "bGPdata", 1, gpd);
1597         
1598         /* write grease-pencil layers to file */
1599         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1600                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1601                 
1602                 /* write this layer's frames to file */
1603                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1604                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
1605                         
1606                         /* write strokes */
1607                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
1608                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
1609                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1610                         }
1611                 }
1612         }
1613 }
1614
1615 static void write_screens(WriteData *wd, ListBase *scrbase)
1616 {
1617         bScreen *sc;
1618         ScrArea *sa;
1619         ScrVert *sv;
1620         ScrEdge *se;
1621
1622         sc= scrbase->first;
1623         while(sc) {
1624                 /* write LibData */
1625                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1626                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1627
1628                 /* direct data */
1629                 sv= sc->vertbase.first;
1630                 while(sv) {
1631                         writestruct(wd, DATA, "ScrVert", 1, sv);
1632                         sv= sv->next;
1633                 }
1634
1635                 se= sc->edgebase.first;
1636                 while(se) {
1637                         writestruct(wd, DATA, "ScrEdge", 1, se);
1638                         se= se->next;
1639                 }
1640
1641                 sa= sc->areabase.first;
1642                 while(sa) {
1643                         SpaceLink *sl;
1644                         Panel *pa;
1645
1646                         writestruct(wd, DATA, "ScrArea", 1, sa);
1647
1648                         pa= sa->panels.first;
1649                         while(pa) {
1650                                 writestruct(wd, DATA, "Panel", 1, pa);
1651                                 pa= pa->next;
1652                         }
1653
1654                         /* space handler scriptlinks */
1655                         write_scriptlink(wd, &sa->scriptlink);
1656
1657                         sl= sa->spacedata.first;
1658                         while(sl) {
1659                                 if(sl->spacetype==SPACE_VIEW3D) {
1660                                         View3D *v3d= (View3D *) sl;
1661                                         writestruct(wd, DATA, "View3D", 1, v3d);
1662                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1663                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1664                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1665                                         if(v3d->gpd) write_gpencil(wd, v3d->gpd);
1666                                 }
1667                                 else if(sl->spacetype==SPACE_IPO) {
1668                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1669                                 }
1670                                 else if(sl->spacetype==SPACE_BUTS) {
1671                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1672                                 }
1673                                 else if(sl->spacetype==SPACE_FILE) {
1674                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1675                                 }
1676                                 else if(sl->spacetype==SPACE_SEQ) {
1677                                         SpaceSeq *sseq= (SpaceSeq *)sl;
1678                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1679                                         if(sseq->gpd) write_gpencil(wd, sseq->gpd);
1680                                 }
1681                                 else if(sl->spacetype==SPACE_OOPS) {
1682                                         SpaceOops *so= (SpaceOops *)sl;
1683                                         Oops *oops;
1684
1685                                         /* cleanup */
1686                                         oops= so->oops.first;
1687                                         while(oops) {
1688                                                 Oops *oopsn= oops->next;
1689                                                 if(oops->id==0) {
1690                                                         BLI_remlink(&so->oops, oops);
1691                                                         free_oops(oops);
1692                                                 }
1693                                                 oops= oopsn;
1694                                         }
1695
1696                                         /* ater cleanup, because of listbase! */
1697                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1698
1699                                         oops= so->oops.first;
1700                                         while(oops) {
1701                                                 writestruct(wd, DATA, "Oops", 1, oops);
1702                                                 oops= oops->next;
1703                                         }
1704                                         /* outliner */
1705                                         if(so->treestore) {
1706                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1707                                                 if(so->treestore->data)
1708                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1709                                         }
1710                                 }
1711                                 else if(sl->spacetype==SPACE_IMAGE) {
1712                                         SpaceImage *sima= (SpaceImage *)sl;
1713                                         
1714                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1715                                         if(sima->cumap)
1716                                                 write_curvemapping(wd, sima->cumap);
1717                                         if(sima->gpd) 
1718                                                 write_gpencil(wd, sima->gpd);
1719                                 }
1720                                 else if(sl->spacetype==SPACE_IMASEL) {
1721                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1722                                 }
1723                                 else if(sl->spacetype==SPACE_TEXT) {
1724                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1725                                 }
1726                                 else if(sl->spacetype==SPACE_SCRIPT) {
1727                                         SpaceScript *sc = (SpaceScript*)sl;
1728                                         sc->but_refs = NULL;
1729                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1730                                 }
1731                                 else if(sl->spacetype==SPACE_ACTION) {
1732                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1733                                 }
1734                                 else if(sl->spacetype==SPACE_SOUND) {
1735                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1736                                 }
1737                                 else if(sl->spacetype==SPACE_NLA){
1738                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1739                                 }
1740                                 else if(sl->spacetype==SPACE_TIME){
1741                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1742                                 }
1743                                 else if(sl->spacetype==SPACE_NODE){
1744                                         SpaceNode *snode= (SpaceNode *)sl;
1745                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1746                                         if(snode->gpd) write_gpencil(wd, snode->gpd);
1747                                 }
1748                                 sl= sl->next;
1749                         }
1750
1751                         sa= sa->next;
1752                 }
1753
1754                 sc= sc->id.next;
1755         }
1756 }
1757
1758 static void write_libraries(WriteData *wd, Main *main)
1759 {
1760         ListBase *lbarray[30];
1761         ID *id;
1762         int a, tot, foundone;
1763
1764         for(; main; main= main->next) {
1765
1766                 a=tot= set_listbasepointers(main, lbarray);
1767
1768                 /* test: is lib being used */
1769                 foundone= 0;
1770                 while(tot--) {
1771                         for(id= lbarray[tot]->first; id; id= id->next) {
1772                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1773                                         foundone= 1;
1774                                         break;
1775                                 }
1776                         }
1777                         if(foundone) break;
1778                 }
1779
1780                 if(foundone) {
1781                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1782
1783                         while(a--) {
1784                                 for(id= lbarray[a]->first; id; id= id->next) {
1785                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1786                                                 writestruct(wd, ID_ID, "ID", 1, id);
1787                                         }
1788                                 }
1789                         }
1790                 }
1791         }
1792 }
1793
1794 static void write_bone(WriteData *wd, Bone* bone)
1795 {
1796         Bone*   cbone;
1797
1798         // PATCH for upward compatibility after 2.37+ armature recode
1799         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1800                 
1801         // Write this bone
1802         writestruct(wd, DATA, "Bone", 1, bone);
1803         
1804         // Write Children
1805         cbone= bone->childbase.first;
1806         while(cbone) {
1807                 write_bone(wd, cbone);
1808                 cbone= cbone->next;
1809         }
1810 }
1811
1812 static void write_armatures(WriteData *wd, ListBase *idbase)
1813 {
1814         bArmature       *arm;
1815         Bone            *bone;
1816
1817         arm=idbase->first;
1818         while (arm) {
1819                 if (arm->id.us>0 || wd->current) {
1820                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1821                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1822
1823                         /* Direct data */
1824                         bone= arm->bonebase.first;
1825                         while(bone) {
1826                                 write_bone(wd, bone);
1827                                 bone=bone->next;
1828                         }
1829                 }
1830                 arm=arm->id.next;
1831         }
1832
1833         /* flush helps the compression for undo-save */
1834         mywrite(wd, MYWRITE_FLUSH, 0);
1835 }
1836
1837 static void write_actions(WriteData *wd, ListBase *idbase)
1838 {
1839         bAction                 *act;
1840         bActionChannel  *chan;
1841         bActionGroup    *grp;
1842         TimeMarker *marker;
1843         
1844         for(act=idbase->first; act; act= act->id.next) {
1845                 if (act->id.us>0 || wd->current) {
1846                         writestruct(wd, ID_AC, "bAction", 1, act);
1847                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1848                         
1849                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1850                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1851                                 write_constraint_channels(wd, &chan->constraintChannels);
1852                         }
1853                         
1854                         for (grp=act->groups.first; grp; grp=grp->next) {
1855                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1856                         }
1857                         
1858                         for (marker=act->markers.first; marker; marker=marker->next) {
1859                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
1860                         }
1861                 }
1862         }
1863 }
1864
1865 static void write_texts(WriteData *wd, ListBase *idbase)
1866 {
1867         Text *text;
1868         TextLine *tmp;
1869         TextMarker *mrk;
1870
1871         text= idbase->first;
1872         while(text) {
1873                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1874
1875                 /* write LibData */
1876                 writestruct(wd, ID_TXT, "Text", 1, text);
1877                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1878                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1879
1880                 if(!(text->flags & TXT_ISEXT)) {
1881                         /* now write the text data, in two steps for optimization in the readfunction */
1882                         tmp= text->lines.first;
1883                         while (tmp) {
1884                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1885                                 tmp= tmp->next;
1886                         }
1887
1888                         tmp= text->lines.first;
1889                         while (tmp) {
1890                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1891                                 tmp= tmp->next;
1892                         }
1893
1894                         /* write markers */
1895                         mrk= text->markers.first;
1896                         while (mrk) {
1897                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
1898                                 mrk= mrk->next;
1899                         }
1900                 }
1901
1902
1903                 text= text->id.next;
1904         }
1905
1906         /* flush helps the compression for undo-save */
1907         mywrite(wd, MYWRITE_FLUSH, 0);
1908 }
1909
1910 static void write_sounds(WriteData *wd, ListBase *idbase)
1911 {
1912         bSound *sound;
1913         bSample *sample;
1914
1915         PackedFile * pf;
1916
1917         // set all samples to unsaved status
1918
1919         sample = samples->first; // samples is a global defined in sound.c
1920         while (sample) {
1921                 sample->flags |= SAMPLE_NEEDS_SAVE;
1922                 sample = sample->id.next;
1923         }
1924
1925         sound= idbase->first;
1926         while(sound) {
1927                 if(sound->id.us>0 || wd->current) {
1928                         // do we need to save the packedfile as well ?
1929                         sample = sound->sample;
1930                         if (sample) {
1931                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1932                                         sound->newpackedfile = sample->packedfile;
1933                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1934                                 } else {
1935                                         sound->newpackedfile = NULL;
1936                                 }
1937                         }
1938
1939                         /* write LibData */
1940                         writestruct(wd, ID_SO, "bSound", 1, sound);
1941                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1942
1943                         if (sound->newpackedfile) {
1944                                 pf = sound->newpackedfile;
1945                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1946                                 writedata(wd, DATA, pf->size, pf->data);
1947                         }
1948
1949                         if (sample) {
1950                                 sound->newpackedfile = sample->packedfile;
1951                         }
1952                 }
1953                 sound= sound->id.next;
1954         }
1955
1956         /* flush helps the compression for undo-save */
1957         mywrite(wd, MYWRITE_FLUSH, 0);
1958 }
1959
1960 static void write_groups(WriteData *wd, ListBase *idbase)
1961 {
1962         Group *group;
1963         GroupObject *go;
1964
1965         for(group= idbase->first; group; group= group->id.next) {
1966                 if(group->id.us>0 || wd->current) {
1967                         /* write LibData */
1968                         writestruct(wd, ID_GR, "Group", 1, group);
1969                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1970
1971                         go= group->gobject.first;
1972                         while(go) {
1973                                 writestruct(wd, DATA, "GroupObject", 1, go);
1974                                 go= go->next;
1975                         }
1976                 }
1977         }
1978 }
1979
1980 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1981 {
1982         bNodeTree *ntree;
1983         
1984         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1985                 if (ntree->id.us>0 || wd->current) {
1986                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1987                         write_nodetree(wd, ntree);
1988                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1989                 }
1990         }
1991 }
1992
1993 static void write_brushes(WriteData *wd, ListBase *idbase)
1994 {
1995         Brush *brush;
1996         int a;
1997         
1998         for(brush=idbase->first; brush; brush= brush->id.next) {
1999                 if(brush->id.us>0 || wd->current) {
2000                         writestruct(wd, ID_BR, "Brush", 1, brush);
2001                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2002                         for(a=0; a<MAX_MTEX; a++)
2003                                 if(brush->mtex[a])
2004                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
2005                 }
2006         }
2007 }
2008
2009 static void write_scripts(WriteData *wd, ListBase *idbase)
2010 {
2011         Script *script;
2012         
2013         for(script=idbase->first; script; script= script->id.next) {
2014                 if(script->id.us>0 || wd->current) {
2015                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2016                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2017                 }
2018         }
2019 }
2020
2021 static void write_global(WriteData *wd)
2022 {
2023         FileGlobal fg;
2024         char subvstr[8];
2025         
2026         fg.curscreen= G.curscreen;
2027         fg.curscene= G.scene;
2028         fg.displaymode= G.displaymode;
2029         fg.winpos= G.winpos;
2030         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2031         fg.globalf= G.f;
2032
2033         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2034         memcpy(fg.subvstr, subvstr, 4);
2035         
2036         fg.subversion= BLENDER_SUBVERSION;
2037         fg.minversion= BLENDER_MINVERSION;
2038         fg.minsubversion= BLENDER_MINSUBVERSION;
2039         
2040         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2041 }
2042
2043 /* if MemFile * there's filesave to memory */
2044 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
2045 {
2046         BHead bhead;
2047         ListBase mainlist;
2048         char buf[16];
2049         WriteData *wd;
2050
2051         blo_split_main(&mainlist, G.main);
2052
2053         wd= bgnwrite(handle, compare, current, write_flags);
2054         
2055         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
2056         mywrite(wd, buf, 12);
2057
2058         write_renderinfo(wd);
2059         write_global(wd);
2060
2061         if(current==NULL)
2062                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
2063         write_scenes   (wd, &G.main->scene);
2064         write_curves   (wd, &G.main->curve);
2065         write_mballs   (wd, &G.main->mball);
2066         write_images   (wd, &G.main->image);
2067         write_cameras  (wd, &G.main->camera);
2068         write_lamps    (wd, &G.main->lamp);
2069         write_lattices (wd, &G.main->latt);
2070         write_vfonts   (wd, &G.main->vfont);
2071         write_ipos     (wd, &G.main->ipo);
2072         write_keys     (wd, &G.main->key);
2073         write_worlds   (wd, &G.main->world);
2074         write_texts    (wd, &G.main->text);
2075         write_sounds   (wd, &G.main->sound);
2076         write_groups   (wd, &G.main->group);
2077         write_armatures(wd, &G.main->armature);
2078         write_actions  (wd, &G.main->action);
2079         write_objects  (wd, &G.main->object);
2080         write_materials(wd, &G.main->mat);
2081         write_textures (wd, &G.main->tex);
2082         write_meshs    (wd, &G.main->mesh);
2083         write_particlesettings(wd, &G.main->particle);
2084         write_nodetrees(wd, &G.main->nodetree);
2085         write_brushes  (wd, &G.main->brush);
2086         write_scripts  (wd, &G.main->script);
2087         if(current==NULL)       
2088                 write_libraries(wd,  G.main->next); /* no library save in undo */
2089
2090         if (write_user_block) {
2091                 write_userdef(wd);
2092         }
2093
2094         /* dna as last, because (to be implemented) test for which structs are written */
2095         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2096
2097         /* end of file */
2098         memset(&bhead, 0, sizeof(BHead));
2099         bhead.code= ENDB;
2100         mywrite(wd, &bhead, sizeof(BHead));
2101
2102         blo_join_main(&mainlist);
2103         G.main= mainlist.first;
2104
2105         return endwrite(wd);
2106 }
2107
2108 /* return: success (1) */
2109 int BLO_write_file(char *dir, int write_flags, char **error_r)
2110 {
2111         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2112         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2113         int file, err, write_user_block;
2114
2115         sprintf(tempname, "%s@", dir);
2116
2117         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2118         if(file == -1) {
2119                 *error_r= "Unable to open";
2120                 return 0;
2121         }
2122
2123         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
2124
2125         write_user_block= BLI_streq(dir, userfilename);
2126
2127         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
2128         close(file);
2129
2130         if(!err) {
2131                 if(write_flags & G_FILE_COMPRESS)
2132                 {       
2133                         // compressed files have the same ending as regular files... only from 2.4!!!
2134                         
2135                         int ret = BLI_gzip(tempname, dir);
2136                         
2137                         if(-1==ret) {
2138                                 *error_r= "Failed opening .gz file";
2139                                 return 0;
2140                         }
2141                         if(-2==ret) {
2142                                 *error_r= "Failed opening .blend file for compression";
2143                                 return 0;
2144                         }
2145                 }
2146                 else
2147                 if(BLI_rename(tempname, dir) != 0) {
2148                         *error_r= "Can't change old file. File saved with @";
2149                         return 0;
2150                 }
2151
2152                 
2153         } else {
2154                 *error_r= strerror(errno);
2155                 remove(tempname);
2156
2157                 return 0;
2158         }
2159
2160         return 1;
2161 }
2162
2163 /* return: success (1) */
2164 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
2165 {
2166         int err;
2167
2168         err= write_file_handle(0, compare, current, 0, write_flags);
2169         
2170         if(err==0) return 1;
2171         return 0;
2172 }
2173
2174
2175         /* Runtime writing */
2176
2177 #ifdef WIN32
2178 #define PATHSEPERATOR           "\\"
2179 #else
2180 #define PATHSEPERATOR           "/"
2181 #endif
2182
2183 char *get_install_dir(void) {
2184         extern char bprogname[];
2185         char *tmpname = BLI_strdup(bprogname);
2186         char *cut;
2187
2188 #ifdef __APPLE__
2189         cut = strstr(tmpname, ".app");
2190         if (cut) cut[0] = 0;
2191 #endif
2192
2193         cut = BLI_last_slash(tmpname);
2194
2195         if (cut) {
2196                 cut[0] = 0;
2197                 return tmpname;
2198         } else {
2199                 MEM_freeN(tmpname);
2200                 return NULL;
2201         }
2202 }
2203
2204 static char *get_runtime_path(char *exename) {
2205         char *installpath= get_install_dir();
2206
2207         if (!installpath) {
2208                 return NULL;
2209         } else {
2210                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2211
2212                 if (path == NULL) {
2213                         MEM_freeN(installpath);
2214                         return NULL;
2215                 }
2216
2217                 strcpy(path, installpath);
2218                 strcat(path, PATHSEPERATOR);
2219                 strcat(path, exename);
2220
2221                 MEM_freeN(installpath);
2222
2223                 return path;
2224         }
2225 }
2226
2227 #ifdef __APPLE__
2228
2229 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2230 {
2231         char *cause = NULL, *runtime = get_runtime_path(exename);
2232         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2233         int progfd = -1;
2234
2235         if (!runtime) {
2236                 cause= "Unable to find runtime";
2237                 goto cleanup;
2238         }
2239         //printf("runtimepath %s\n", runtime);
2240                 
2241         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2242         if (progfd==-1) {
2243                 cause= "Unable to find runtime";
2244                 goto cleanup;
2245         }
2246
2247         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2248         //printf("command %s\n", command);
2249         if (system(command) == -1) {
2250                 cause = "Couldn't copy runtime";
2251         }
2252
2253 cleanup:
2254         if (progfd!=-1)
2255                 close(progfd);
2256         if (runtime)
2257                 MEM_freeN(runtime);
2258
2259         if (cause) {
2260                 *cause_r= cause;
2261                 return 0;
2262         } else
2263                 return 1;
2264 }
2265
2266 void BLO_write_runtime(char *file, char *exename) {
2267         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2268         int outfd = -1;
2269         char *cause= NULL;
2270
2271         // remove existing file / bundle
2272         //printf("Delete file %s\n", file);
2273         BLI_delete(file, 0, TRUE);
2274
2275         if (!recursive_copy_runtime(file, exename, &cause))
2276                 goto cleanup;
2277
2278         strcpy(gamename, file);
2279         strcat(gamename, "/Contents/Resources/game.blend");
2280         //printf("gamename %s\n", gamename);
2281         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2282         if (outfd != -1) {
2283
2284                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2285
2286                 if (write(outfd, " ", 1) != 1) {
2287                         cause= "Unable to write to output file";
2288                         goto cleanup;
2289                 }
2290         } else {
2291                 cause = "Unable to open blenderfile";
2292         }
2293
2294 cleanup:
2295         if (outfd!=-1)
2296                 close(outfd);
2297
2298         if (cause)
2299                 error("Unable to make runtime: %s", cause);
2300 }
2301
2302 #else /* !__APPLE__ */
2303
2304 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2305         char *cause= NULL, *runtime= get_runtime_path(exename);
2306         unsigned char buf[1024];
2307         int count, progfd= -1;
2308
2309         if (!BLI_exists(runtime)) {
2310                 cause= "Unable to find runtime";
2311                 goto cleanup;
2312         }
2313
2314         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2315         if (progfd==-1) {
2316                 cause= "Unable to find runtime";
2317                 goto cleanup;
2318         }
2319
2320         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2321                 if (write(handle, buf, count)!=count) {
2322                         cause= "Unable to write to output file";
2323                         goto cleanup;
2324                 }
2325         }
2326
2327 cleanup:
2328         if (progfd!=-1)
2329                 close(progfd);
2330         if (runtime)
2331                 MEM_freeN(runtime);
2332
2333         if (cause) {
2334                 *cause_r= cause;
2335                 return 0;
2336         } else
2337                 return 1;
2338 }
2339
2340 static int handle_write_msb_int(int handle, int i) {
2341         unsigned char buf[4];
2342         buf[0]= (i>>24)&0xFF;
2343         buf[1]= (i>>16)&0xFF;
2344         buf[2]= (i>>8)&0xFF;
2345         buf[3]= (i>>0)&0xFF;
2346
2347         return (write(handle, buf, 4)==4);
2348 }
2349
2350 void BLO_write_runtime(char *file, char *exename) {
2351         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2352         char *cause= NULL;
2353         int datastart;
2354
2355         if (!outfd) {
2356                 cause= "Unable to open output file";
2357                 goto cleanup;
2358         }
2359         if (!handle_append_runtime(outfd, exename, &cause))
2360                 goto cleanup;
2361
2362         datastart= lseek(outfd, 0, SEEK_CUR);
2363
2364         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2365
2366         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2367                 cause= "Unable to write to output file";
2368                 goto cleanup;
2369         }
2370
2371 cleanup:
2372         if (outfd!=-1)
2373                 close(outfd);
2374
2375         if (cause)
2376                 error("Unable to make runtime: %s", cause);
2377 }
2378
2379 #endif /* !__APPLE__ */