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