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