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