2ac3063f2484898286af3d7d987b47e26a6a4ffa
[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_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_TRACKTO:
716                         writestruct(wd, DATA, "bTrackToConstraint", 1, con->data);
717                         break;
718                 case CONSTRAINT_TYPE_KINEMATIC:
719                         writestruct(wd, DATA, "bKinematicConstraint", 1, con->data);
720                         break;
721                 case CONSTRAINT_TYPE_ROTLIKE:
722                         writestruct(wd, DATA, "bRotateLikeConstraint", 1, con->data);
723                         break;
724                 case CONSTRAINT_TYPE_LOCLIKE:
725                         writestruct(wd, DATA, "bLocateLikeConstraint", 1, con->data);
726                         break;
727                 case CONSTRAINT_TYPE_SIZELIKE:
728                         writestruct(wd, DATA, "bSizeLikeConstraint", 1, con->data);
729                         break;
730                 case CONSTRAINT_TYPE_ACTION:
731                         writestruct(wd, DATA, "bActionConstraint", 1, con->data);
732                         break;
733                 case CONSTRAINT_TYPE_LOCKTRACK:
734                         writestruct(wd, DATA, "bLockTrackConstraint", 1, con->data);
735                         break;
736                 case CONSTRAINT_TYPE_FOLLOWPATH:
737                         writestruct(wd, DATA, "bFollowPathConstraint", 1, con->data);
738                         break;
739                 case CONSTRAINT_TYPE_STRETCHTO:
740                         writestruct(wd, DATA, "bStretchToConstraint", 1, con->data);
741                         break;
742                 case CONSTRAINT_TYPE_MINMAX:
743                         writestruct(wd, DATA, "bMinMaxConstraint", 1, con->data);
744                         break;
745                 case CONSTRAINT_TYPE_LOCLIMIT:
746                         writestruct(wd, DATA, "bLocLimitConstraint", 1, con->data);
747                         break;
748                 case CONSTRAINT_TYPE_ROTLIMIT:
749                         writestruct(wd, DATA, "bRotLimitConstraint", 1, con->data);
750                         break;
751                 case CONSTRAINT_TYPE_SIZELIMIT:
752                         writestruct(wd, DATA, "bSizeLimitConstraint", 1, con->data);
753                         break;
754                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
755                         writestruct(wd, DATA, "bRigidBodyJointConstraint", 1, con->data);
756                         break;
757                 case CONSTRAINT_TYPE_CLAMPTO:
758                         writestruct(wd, DATA, "bClampToConstraint", 1, con->data);
759                         break;
760                 default:
761                         break;
762                 }
763                 /* Write the constraint */
764                 writestruct(wd, DATA, "bConstraint", 1, con);
765         }
766 }
767
768 static void write_pose(WriteData *wd, bPose *pose)
769 {
770         bPoseChannel    *chan;
771
772         /* Write each channel */
773
774         if (!pose)
775                 return;
776
777         // Write channels
778         for (chan=pose->chanbase.first; chan; chan=chan->next) {
779                 write_constraints(wd, &chan->constraints);
780                 chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); // gets restored on read, for library armatures
781                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
782         }
783
784         // Write this pose
785         writestruct(wd, DATA, "bPose", 1, pose);
786 }
787
788 static void write_defgroups(WriteData *wd, ListBase *defbase)
789 {
790         bDeformGroup    *defgroup;
791
792         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
793                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
794 }
795
796 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
797 {
798         bConstraintChannel *chan;
799
800         for (chan = chanbase->first; chan; chan=chan->next)
801                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
802
803 }
804
805 static void write_modifiers(WriteData *wd, ListBase *modbase)
806 {
807         ModifierData *md;
808
809         if (modbase == NULL) return;
810         for (md=modbase->first; md; md= md->next) {
811                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
812                 if (mti == NULL) return;
813
814                 writestruct(wd, DATA, mti->structName, 1, md);
815
816                 if (md->type==eModifierType_Hook) {
817                         HookModifierData *hmd = (HookModifierData*) md;
818
819                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
820                 }
821         }
822 }
823
824 static void write_objects(WriteData *wd, ListBase *idbase)
825 {
826         Object *ob;
827         int a;
828         
829         ob= idbase->first;
830         while(ob) {
831                 if(ob->id.us>0 || wd->current) {
832                         /* write LibData */
833 #ifdef WITH_VERSE
834                         /* pointer at vnode stored in file have to be NULL */
835                         struct VNode *vnode = (VNode*)ob->vnode;
836                         if(vnode) ob->vnode = NULL;
837 #endif
838                         writestruct(wd, ID_OB, "Object", 1, ob);
839 #ifdef WITH_VERSE
840                         if(vnode) ob->vnode = (void*)vnode;
841 #endif
842
843                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
844                           of library blocks that implement this.*/
845                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
846
847                         /* direct data */
848                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
849                         write_effects(wd, &ob->effect);
850                         write_properties(wd, &ob->prop);
851                         write_sensors(wd, &ob->sensors);
852                         write_controllers(wd, &ob->controllers);
853                         write_actuators(wd, &ob->actuators);
854                         write_scriptlink(wd, &ob->scriptlink);
855                         write_pose(wd, ob->pose);
856                         write_defgroups(wd, &ob->defbase);
857                         write_constraints(wd, &ob->constraints);
858                         write_constraint_channels(wd, &ob->constraintChannels);
859                         write_nlastrips(wd, &ob->nlastrips);
860                         
861                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
862                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
863                         if(ob->soft) {
864                                 SoftBody *sb= ob->soft;
865                                 if(sb->keys) {
866                                         writedata(wd, DATA, sizeof(void *)*sb->totkey, sb->keys);
867                                         for(a=0; a<sb->totkey; a++) {
868                                                 writestruct(wd, DATA, "SBVertex", sb->totpoint, sb->keys[a]);
869                                         }
870                                 }
871                         }
872                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
873                         
874                         write_modifiers(wd, &ob->modifiers);
875                 }
876                 ob= ob->id.next;
877         }
878
879         /* flush helps the compression for undo-save */
880         mywrite(wd, MYWRITE_FLUSH, 0);
881 }
882
883
884 static void write_vfonts(WriteData *wd, ListBase *idbase)
885 {
886         VFont *vf;
887         PackedFile * pf;
888
889         vf= idbase->first;
890         while(vf) {
891                 if(vf->id.us>0 || wd->current) {
892                         /* write LibData */
893                         writestruct(wd, ID_VF, "VFont", 1, vf);
894                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
895
896                         /* direct data */
897
898                         if (vf->packedfile) {
899                                 pf = vf->packedfile;
900                                 writestruct(wd, DATA, "PackedFile", 1, pf);
901                                 writedata(wd, DATA, pf->size, pf->data);
902                         }
903                 }
904
905                 vf= vf->id.next;
906         }
907 }
908
909 static void write_ipos(WriteData *wd, ListBase *idbase)
910 {
911         Ipo *ipo;
912         IpoCurve *icu;
913
914         ipo= idbase->first;
915         while(ipo) {
916                 if(ipo->id.us>0 || wd->current) {
917                         /* write LibData */
918                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
919                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
920
921                         /* direct data */
922                         icu= ipo->curve.first;
923                         while(icu) {
924                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
925                                 icu= icu->next;
926                         }
927
928                         icu= ipo->curve.first;
929                         while(icu) {
930                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
931                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
932                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
933                                 icu= icu->next;
934                         }
935                 }
936
937                 ipo= ipo->id.next;
938         }
939
940         /* flush helps the compression for undo-save */
941         mywrite(wd, MYWRITE_FLUSH, 0);
942 }
943
944 static void write_keys(WriteData *wd, ListBase *idbase)
945 {
946         Key *key;
947         KeyBlock *kb;
948
949         key= idbase->first;
950         while(key) {
951                 if(key->id.us>0 || wd->current) {
952                         /* write LibData */
953                         writestruct(wd, ID_KE, "Key", 1, key);
954                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
955
956                         /* direct data */
957                         kb= key->block.first;
958                         while(kb) {
959                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
960                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
961                                 kb= kb->next;
962                         }
963                 }
964
965                 key= key->id.next;
966         }
967         /* flush helps the compression for undo-save */
968         mywrite(wd, MYWRITE_FLUSH, 0);
969 }
970
971 static void write_cameras(WriteData *wd, ListBase *idbase)
972 {
973         Camera *cam;
974
975         cam= idbase->first;
976         while(cam) {
977                 if(cam->id.us>0 || wd->current) {
978                         /* write LibData */
979                         writestruct(wd, ID_CA, "Camera", 1, cam);
980                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
981
982                         /* direct data */
983                         write_scriptlink(wd, &cam->scriptlink);
984                 }
985
986                 cam= cam->id.next;
987         }
988 }
989
990 static void write_mballs(WriteData *wd, ListBase *idbase)
991 {
992         MetaBall *mb;
993         MetaElem *ml;
994
995         mb= idbase->first;
996         while(mb) {
997                 if(mb->id.us>0 || wd->current) {
998                         /* write LibData */
999                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1000                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1001
1002                         /* direct data */
1003                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1004
1005                         ml= mb->elems.first;
1006                         while(ml) {
1007                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1008                                 ml= ml->next;
1009                         }
1010                 }
1011                 mb= mb->id.next;
1012         }
1013 }
1014
1015 int amount_of_chars(char *str)
1016 {
1017         // Since the data is saved as UTF-8 to the cu->str
1018         // The cu->len is not same as the strlen(cu->str)
1019         return strlen(str);
1020 }
1021
1022 static void write_curves(WriteData *wd, ListBase *idbase)
1023 {
1024         Curve *cu;
1025         Nurb *nu;
1026
1027         cu= idbase->first;
1028         while(cu) {
1029                 if(cu->id.us>0 || wd->current) {
1030                         /* write LibData */
1031                         writestruct(wd, ID_CU, "Curve", 1, cu);
1032
1033                         /* direct data */
1034                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1035                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1036
1037                         if(cu->vfont) {
1038                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1039                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1040                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1041                         }
1042                         else {
1043                                 /* is also the order of reading */
1044                                 nu= cu->nurb.first;
1045                                 while(nu) {
1046                                         writestruct(wd, DATA, "Nurb", 1, nu);
1047                                         nu= nu->next;
1048                                 }
1049                                 nu= cu->nurb.first;
1050                                 while(nu) {
1051                                         if( (nu->type & 7)==CU_BEZIER)
1052                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1053                                         else {
1054                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1055                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1056                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1057                                         }
1058                                         nu= nu->next;
1059                                 }
1060                         }
1061                 }
1062                 cu= cu->id.next;
1063         }
1064
1065         /* flush helps the compression for undo-save */
1066         mywrite(wd, MYWRITE_FLUSH, 0);
1067 }
1068
1069 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1070 {
1071         if (dvlist) {
1072                 int     i;
1073                 
1074                 /* Write the dvert list */
1075                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1076                 
1077                 /* Write deformation data for each dvert */
1078                 for (i=0; i<count; i++) {
1079                         if (dvlist[i].dw)
1080                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1081                 }
1082         }
1083 }
1084
1085 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1086 {
1087         int i;
1088
1089         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1090
1091         for (i=0; i<data->totlayer; i++) {
1092                 CustomDataLayer *layer= &data->layers[i];
1093                 char *structname;
1094                 int structnum, datasize;
1095
1096                 if (layer->type == CD_MDEFORMVERT) {
1097                         /* layer types that allocate own memory need special handling */
1098                         write_dverts(wd, count, layer->data);
1099                 }
1100                 else {
1101                         CustomData_file_write_info(layer->type, &structname, &structnum);
1102                         if (structnum) {
1103                                 /* when using partial visibility, the MEdge and MFace layers
1104                                    are smaller than the original, so their type and count is
1105                                    passed to make this work */
1106                                 if (layer->type != partial_type) datasize= structnum*count;
1107                                 else datasize= structnum*partial_count;
1108
1109                                 writestruct(wd, DATA, structname, datasize, layer->data);
1110                         }
1111                         else
1112                                 printf("error: this CustomDataLayer must not be written to file\n");
1113                 }
1114         }
1115 }
1116
1117 static void write_meshs(WriteData *wd, ListBase *idbase)
1118 {
1119         Mesh *mesh;
1120         MultiresLevel *lvl;
1121
1122         mesh= idbase->first;
1123         while(mesh) {
1124                 if(mesh->id.us>0 || wd->current) {
1125                         /* write LibData */
1126 #ifdef WITH_VERSE
1127                         struct VNode *vnode = (VNode*)mesh->vnode;
1128                         if(vnode) {
1129                                 /* mesh has to be created from verse geometry node*/
1130                                 create_meshdata_from_geom_node(mesh, vnode);
1131                                 /* pointer at verse node can't be stored in file */
1132                                 mesh->vnode = NULL;
1133                         }
1134 #endif
1135
1136                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1137 #ifdef WITH_VERSE
1138                         if(vnode) mesh->vnode = (void*)vnode;
1139 #endif
1140
1141                         /* direct data */
1142                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1143
1144                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1145
1146                         if(mesh->pv) {
1147                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1148                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1149                                         CD_MEDGE, mesh->totedge);
1150                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1151                                         CD_MFACE, mesh->totface);
1152                         }
1153                         else {
1154                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1155                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1156                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1157                         }
1158
1159                         /* Multires data */
1160                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1161                         if(mesh->mr) {
1162                                 lvl= mesh->mr->levels.first;
1163                                 if(lvl) {
1164                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1165                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1166                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1167                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1168                                 }
1169
1170                                 for(; lvl; lvl= lvl->next) {
1171                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1172                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1173                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1174                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1175                                 }
1176
1177                                 lvl= mesh->mr->levels.last;
1178                                 if(lvl)
1179                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1180                         }
1181
1182                         /* PMV data */
1183                         if(mesh->pv) {
1184                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1185                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1186                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1187                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1188                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1189                         }
1190                 }
1191                 mesh= mesh->id.next;
1192         }
1193 }
1194
1195 static void write_lattices(WriteData *wd, ListBase *idbase)
1196 {
1197         Lattice *lt;
1198         
1199         lt= idbase->first;
1200         while(lt) {
1201                 if(lt->id.us>0 || wd->current) {
1202                         /* write LibData */
1203                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1204                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1205
1206                         /* direct data */
1207                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1208                         
1209                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1210                         
1211                 }
1212                 lt= lt->id.next;
1213         }
1214 }
1215
1216 static void write_images(WriteData *wd, ListBase *idbase)
1217 {
1218         Image *ima;
1219         PackedFile * pf;
1220         PreviewImage *prv;
1221
1222         ima= idbase->first;
1223         while(ima) {
1224                 if(ima->id.us>0 || wd->current) {
1225                         /* write LibData */
1226                         writestruct(wd, ID_IM, "Image", 1, ima);
1227                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1228
1229                         if (ima->packedfile) {
1230                                 pf = ima->packedfile;
1231                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1232                                 writedata(wd, DATA, pf->size, pf->data);
1233                         }
1234
1235                         if (ima->preview) {
1236                                 prv = ima->preview;
1237                                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1238                                 writedata(wd, DATA, prv->w*prv->h*sizeof(unsigned int), prv->rect);
1239                         }
1240                 }
1241                 ima= ima->id.next;
1242         }
1243         /* flush helps the compression for undo-save */
1244         mywrite(wd, MYWRITE_FLUSH, 0);
1245 }
1246
1247 static void write_textures(WriteData *wd, ListBase *idbase)
1248 {
1249         Tex *tex;
1250
1251         tex= idbase->first;
1252         while(tex) {
1253                 if(tex->id.us>0 || wd->current) {
1254                         /* write LibData */
1255                         writestruct(wd, ID_TE, "Tex", 1, tex);
1256                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1257
1258                         /* direct data */
1259                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1260                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1261                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1262                 }
1263                 tex= tex->id.next;
1264         }
1265
1266         /* flush helps the compression for undo-save */
1267         mywrite(wd, MYWRITE_FLUSH, 0);
1268 }
1269
1270 static void write_materials(WriteData *wd, ListBase *idbase)
1271 {
1272         Material *ma;
1273         int a;
1274
1275         ma= idbase->first;
1276         while(ma) {
1277                 if(ma->id.us>0 || wd->current) {
1278                         /* write LibData */
1279                         writestruct(wd, ID_MA, "Material", 1, ma);
1280                         
1281                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1282                           of library blocks that implement this.*/
1283                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1284                           set yet :) */
1285                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1286
1287                         for(a=0; a<MAX_MTEX; a++) {
1288                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1289                         }
1290                         
1291                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1292                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1293                         
1294                         write_scriptlink(wd, &ma->scriptlink);
1295                         
1296                         /* nodetree is integral part of material, no libdata */
1297                         if(ma->nodetree) {
1298                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1299                                 write_nodetree(wd, ma->nodetree);
1300                         }
1301                 }
1302                 ma= ma->id.next;
1303         }
1304 }
1305
1306 static void write_worlds(WriteData *wd, ListBase *idbase)
1307 {
1308         World *wrld;
1309         int a;
1310
1311         wrld= idbase->first;
1312         while(wrld) {
1313                 if(wrld->id.us>0 || wd->current) {
1314                         /* write LibData */
1315                         writestruct(wd, ID_WO, "World", 1, wrld);
1316                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1317
1318                         for(a=0; a<MAX_MTEX; a++) {
1319                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1320                         }
1321
1322                         write_scriptlink(wd, &wrld->scriptlink);
1323                 }
1324                 wrld= wrld->id.next;
1325         }
1326 }
1327
1328 static void write_lamps(WriteData *wd, ListBase *idbase)
1329 {
1330         Lamp *la;
1331         int a;
1332
1333         la= idbase->first;
1334         while(la) {
1335                 if(la->id.us>0 || wd->current) {
1336                         /* write LibData */
1337                         writestruct(wd, ID_LA, "Lamp", 1, la);
1338                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1339
1340                         /* direct data */
1341                         for(a=0; a<MAX_MTEX; a++) {
1342                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1343                         }
1344
1345                         write_scriptlink(wd, &la->scriptlink);
1346                 }
1347                 la= la->id.next;
1348         }
1349 }
1350
1351
1352 static void write_scenes(WriteData *wd, ListBase *scebase)
1353 {
1354         Scene *sce;
1355         Base *base;
1356         Editing *ed;
1357         Sequence *seq;
1358         MetaStack *ms;
1359         Strip *strip;
1360         TimeMarker *marker;
1361         SceneRenderLayer *srl;
1362         int a;
1363         
1364         sce= scebase->first;
1365         while(sce) {
1366                 /* write LibData */
1367                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1368                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1369
1370                 /* direct data */
1371                 base= sce->base.first;
1372                 while(base) {
1373                         writestruct(wd, DATA, "Base", 1, base);
1374                         base= base->next;
1375                 }
1376
1377                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1378                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1379
1380                 for(a=0; a<MAX_MTEX; ++a)
1381                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1382
1383                 ed= sce->ed;
1384                 if(ed) {
1385                         writestruct(wd, DATA, "Editing", 1, ed);
1386
1387                         /* reset write flags too */
1388                         WHILE_SEQ(&ed->seqbase) {
1389                                 if(seq->strip) seq->strip->done= 0;
1390                                 writestruct(wd, DATA, "Sequence", 1, seq);
1391                         }
1392                         END_SEQ
1393
1394                         WHILE_SEQ(&ed->seqbase) {
1395                                 if(seq->strip && seq->strip->done==0) {
1396                                         /* write strip with 'done' at 0 because readfile */
1397
1398                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1399                                         if(seq->effectdata) {
1400                                                 switch(seq->type){
1401                                                 case SEQ_COLOR:
1402                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1403                                                         break;
1404                                                 case SEQ_SPEED:
1405                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1406                                                         break;
1407                                                 case SEQ_WIPE:
1408                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1409                                                         break;
1410                                                 case SEQ_GLOW:
1411                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1412                                                         break;
1413                                                 case SEQ_TRANSFORM:
1414                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1415                                                         break;
1416                                                 }
1417                                         }
1418
1419                                         strip= seq->strip;
1420                                         writestruct(wd, DATA, "Strip", 1, strip);
1421
1422                                         if(seq->type==SEQ_IMAGE)
1423                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1424                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1425                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1426
1427                                         strip->done= 1;
1428                                 }
1429                         }
1430                         END_SEQ
1431                                 
1432                         /* new; meta stack too, even when its nasty restore code */
1433                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1434                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1435                         }
1436                 }
1437
1438                 write_scriptlink(wd, &sce->scriptlink);
1439
1440                 if (sce->r.avicodecdata) {
1441                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1442                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1443                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1444                 }
1445
1446                 if (sce->r.qtcodecdata) {
1447                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1448                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1449                 }
1450
1451                 /* writing dynamic list of TimeMarkers to the blend file */
1452                 for(marker= sce->markers.first; marker; marker= marker->next)
1453                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1454                 
1455                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1456                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1457                 
1458                 if(sce->nodetree) {
1459                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1460                         write_nodetree(wd, sce->nodetree);
1461                 }
1462                 
1463                 sce= sce->id.next;
1464         }
1465         /* flush helps the compression for undo-save */
1466         mywrite(wd, MYWRITE_FLUSH, 0);
1467 }
1468
1469 static void write_screens(WriteData *wd, ListBase *scrbase)
1470 {
1471         bScreen *sc;
1472         ScrArea *sa;
1473         ScrVert *sv;
1474         ScrEdge *se;
1475
1476         sc= scrbase->first;
1477         while(sc) {
1478                 /* write LibData */
1479                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1480                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1481
1482                 /* direct data */
1483                 sv= sc->vertbase.first;
1484                 while(sv) {
1485                         writestruct(wd, DATA, "ScrVert", 1, sv);
1486                         sv= sv->next;
1487                 }
1488
1489                 se= sc->edgebase.first;
1490                 while(se) {
1491                         writestruct(wd, DATA, "ScrEdge", 1, se);
1492                         se= se->next;
1493                 }
1494
1495                 sa= sc->areabase.first;
1496                 while(sa) {
1497                         SpaceLink *sl;
1498                         Panel *pa;
1499
1500                         writestruct(wd, DATA, "ScrArea", 1, sa);
1501
1502                         pa= sa->panels.first;
1503                         while(pa) {
1504                                 writestruct(wd, DATA, "Panel", 1, pa);
1505                                 pa= pa->next;
1506                         }
1507
1508                         /* space handler scriptlinks */
1509                         write_scriptlink(wd, &sa->scriptlink);
1510
1511                         sl= sa->spacedata.first;
1512                         while(sl) {
1513                                 if(sl->spacetype==SPACE_VIEW3D) {
1514                                         View3D *v3d= (View3D*) sl;
1515                                         writestruct(wd, DATA, "View3D", 1, v3d);
1516                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1517                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1518                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1519                                 }
1520                                 else if(sl->spacetype==SPACE_IPO) {
1521                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1522                                 }
1523                                 else if(sl->spacetype==SPACE_BUTS) {
1524                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1525                                 }
1526                                 else if(sl->spacetype==SPACE_FILE) {
1527                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1528                                 }
1529                                 else if(sl->spacetype==SPACE_SEQ) {
1530                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1531                                 }
1532                                 else if(sl->spacetype==SPACE_OOPS) {
1533                                         SpaceOops *so= (SpaceOops *)sl;
1534                                         Oops *oops;
1535
1536                                         /* cleanup */
1537                                         oops= so->oops.first;
1538                                         while(oops) {
1539                                                 Oops *oopsn= oops->next;
1540                                                 if(oops->id==0) {
1541                                                         BLI_remlink(&so->oops, oops);
1542                                                         free_oops(oops);
1543                                                 }
1544                                                 oops= oopsn;
1545                                         }
1546
1547                                         /* ater cleanup, because of listbase! */
1548                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1549
1550                                         oops= so->oops.first;
1551                                         while(oops) {
1552                                                 writestruct(wd, DATA, "Oops", 1, oops);
1553                                                 oops= oops->next;
1554                                         }
1555                                         /* outliner */
1556                                         if(so->treestore) {
1557                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1558                                                 if(so->treestore->data)
1559                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1560                                         }
1561                                 }
1562                                 else if(sl->spacetype==SPACE_IMAGE) {
1563                                         SpaceImage *sima= (SpaceImage *)sl;
1564                                         
1565                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1566                                         if(sima->cumap)
1567                                                 write_curvemapping(wd, sima->cumap);                                    
1568                                 }
1569                                 else if(sl->spacetype==SPACE_IMASEL) {
1570                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1571                                 }
1572                                 else if(sl->spacetype==SPACE_TEXT) {
1573                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1574                                 }
1575                                 else if(sl->spacetype==SPACE_SCRIPT) {
1576                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1577                                 }
1578                                 else if(sl->spacetype==SPACE_ACTION) {
1579                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1580                                 }
1581                                 else if(sl->spacetype==SPACE_SOUND) {
1582                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1583                                 }
1584                                 else if(sl->spacetype==SPACE_NLA){
1585                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1586                                 }
1587                                 else if(sl->spacetype==SPACE_TIME){
1588                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1589                                 }
1590                                 else if(sl->spacetype==SPACE_NODE){
1591                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1592                                 }
1593                                 sl= sl->next;
1594                         }
1595
1596                         sa= sa->next;
1597                 }
1598
1599                 sc= sc->id.next;
1600         }
1601 }
1602
1603 static void write_libraries(WriteData *wd, Main *main)
1604 {
1605         ListBase *lbarray[30];
1606         ID *id;
1607         int a, tot, foundone;
1608
1609         for(; main; main= main->next) {
1610
1611                 a=tot= set_listbasepointers(main, lbarray);
1612
1613                 /* test: is lib being used */
1614                 foundone= 0;
1615                 while(tot--) {
1616                         for(id= lbarray[tot]->first; id; id= id->next) {
1617                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1618                                         foundone= 1;
1619                                         break;
1620                                 }
1621                         }
1622                         if(foundone) break;
1623                 }
1624
1625                 if(foundone) {
1626                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1627
1628                         while(a--) {
1629                                 for(id= lbarray[a]->first; id; id= id->next) {
1630                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1631                                                 writestruct(wd, ID_ID, "ID", 1, id);
1632                                         }
1633                                 }
1634                         }
1635                 }
1636         }
1637 }
1638
1639 static void write_bone(WriteData *wd, Bone* bone)
1640 {
1641         Bone*   cbone;
1642
1643         // PATCH for upward compatibility after 2.37+ armature recode
1644         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1645                 
1646         // Write this bone
1647         writestruct(wd, DATA, "Bone", 1, bone);
1648         
1649         // Write Children
1650         cbone= bone->childbase.first;
1651         while(cbone) {
1652                 write_bone(wd, cbone);
1653                 cbone= cbone->next;
1654         }
1655 }
1656
1657 static void write_armatures(WriteData *wd, ListBase *idbase)
1658 {
1659         bArmature       *arm;
1660         Bone            *bone;
1661
1662         arm=idbase->first;
1663         while (arm) {
1664                 if (arm->id.us>0 || wd->current) {
1665                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1666                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1667
1668                         /* Direct data */
1669                         bone= arm->bonebase.first;
1670                         while(bone) {
1671                                 write_bone(wd, bone);
1672                                 bone=bone->next;
1673                         }
1674                 }
1675                 arm=arm->id.next;
1676         }
1677
1678         /* flush helps the compression for undo-save */
1679         mywrite(wd, MYWRITE_FLUSH, 0);
1680 }
1681
1682 static void write_actions(WriteData *wd, ListBase *idbase)
1683 {
1684         bAction                 *act;
1685         bActionChannel  *chan;
1686         
1687         for(act=idbase->first; act; act= act->id.next) {
1688                 if (act->id.us>0 || wd->current) {
1689                         writestruct(wd, ID_AC, "bAction", 1, act);
1690                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1691
1692                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1693                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1694                                 write_constraint_channels(wd, &chan->constraintChannels);
1695                         }
1696                 }
1697         }
1698 }
1699
1700 static void write_texts(WriteData *wd, ListBase *idbase)
1701 {
1702         Text *text;
1703         TextLine *tmp;
1704
1705         text= idbase->first;
1706         while(text) {
1707                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1708
1709                 /* write LibData */
1710                 writestruct(wd, ID_TXT, "Text", 1, text);
1711                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1712                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1713
1714                 if(!(text->flags & TXT_ISEXT)) {
1715                         /* now write the text data, in two steps for optimization in the readfunction */
1716                         tmp= text->lines.first;
1717                         while (tmp) {
1718                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1719                                 tmp= tmp->next;
1720                         }
1721
1722                         tmp= text->lines.first;
1723                         while (tmp) {
1724                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1725                                 tmp= tmp->next;
1726                         }
1727                 }
1728                 text= text->id.next;
1729         }
1730
1731         /* flush helps the compression for undo-save */
1732         mywrite(wd, MYWRITE_FLUSH, 0);
1733 }
1734
1735 static void write_sounds(WriteData *wd, ListBase *idbase)
1736 {
1737         bSound *sound;
1738         bSample *sample;
1739
1740         PackedFile * pf;
1741
1742         // set all samples to unsaved status
1743
1744         sample = samples->first;
1745         while (sample) {
1746                 sample->flags |= SAMPLE_NEEDS_SAVE;
1747                 sample = sample->id.next;
1748         }
1749
1750         sound= idbase->first;
1751         while(sound) {
1752                 if(sound->id.us>0 || wd->current) {
1753                         // do we need to save the packedfile as well ?
1754                         sample = sound->sample;
1755                         if (sample) {
1756                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1757                                         sound->newpackedfile = sample->packedfile;
1758                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1759                                 } else {
1760                                         sound->newpackedfile = NULL;
1761                                 }
1762                         }
1763
1764                         /* write LibData */
1765                         writestruct(wd, ID_SO, "bSound", 1, sound);
1766                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1767
1768                         if (sound->newpackedfile) {
1769                                 pf = sound->newpackedfile;
1770                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1771                                 writedata(wd, DATA, pf->size, pf->data);
1772                         }
1773
1774                         if (sample) {
1775                                 sound->newpackedfile = sample->packedfile;
1776                         }
1777                 }
1778                 sound= sound->id.next;
1779         }
1780
1781         /* flush helps the compression for undo-save */
1782         mywrite(wd, MYWRITE_FLUSH, 0);
1783 }
1784
1785 static void write_groups(WriteData *wd, ListBase *idbase)
1786 {
1787         Group *group;
1788         GroupObject *go;
1789
1790         for(group= idbase->first; group; group= group->id.next) {
1791                 if(group->id.us>0 || wd->current) {
1792                         /* write LibData */
1793                         writestruct(wd, ID_GR, "Group", 1, group);
1794                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1795
1796                         go= group->gobject.first;
1797                         while(go) {
1798                                 writestruct(wd, DATA, "GroupObject", 1, go);
1799                                 go= go->next;
1800                         }
1801                 }
1802         }
1803 }
1804
1805 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1806 {
1807         bNodeTree *ntree;
1808         
1809         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1810                 if (ntree->id.us>0 || wd->current) {
1811                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1812                         write_nodetree(wd, ntree);
1813                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1814                 }
1815         }
1816 }
1817
1818 static void write_brushes(WriteData *wd, ListBase *idbase)
1819 {
1820         Brush *brush;
1821         int a;
1822         
1823         for(brush=idbase->first; brush; brush= brush->id.next) {
1824                 if(brush->id.us>0 || wd->current) {
1825                         writestruct(wd, ID_BR, "Brush", 1, brush);
1826                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1827                         for(a=0; a<MAX_MTEX; a++)
1828                                 if(brush->mtex[a])
1829                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1830                 }
1831         }
1832 }
1833
1834 static void write_global(WriteData *wd)
1835 {
1836         FileGlobal fg;
1837         char subvstr[8];
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
1846         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1847         memcpy(fg.subvstr, subvstr, 4);
1848         
1849         fg.subversion= BLENDER_SUBVERSION;
1850         fg.minversion= BLENDER_MINVERSION;
1851         fg.minsubversion= BLENDER_MINSUBVERSION;
1852         
1853         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1854 }
1855
1856 /* if MemFile * there's filesave to memory */
1857 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1858 {
1859         BHead bhead;
1860         ListBase mainlist;
1861         char buf[16];
1862         WriteData *wd;
1863
1864         blo_split_main(&mainlist, G.main);
1865
1866         wd= bgnwrite(handle, compare, current, write_flags);
1867         
1868         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1869         mywrite(wd, buf, 12);
1870
1871         write_renderinfo(wd);
1872         write_global(wd);
1873
1874         if(current==NULL)
1875                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
1876         write_scenes   (wd, &G.main->scene);
1877         write_curves   (wd, &G.main->curve);
1878         write_mballs   (wd, &G.main->mball);
1879         write_images   (wd, &G.main->image);
1880         write_cameras  (wd, &G.main->camera);
1881         write_lamps    (wd, &G.main->lamp);
1882         write_lattices (wd, &G.main->latt);
1883         write_vfonts   (wd, &G.main->vfont);
1884         write_ipos     (wd, &G.main->ipo);
1885         write_keys     (wd, &G.main->key);
1886         write_worlds   (wd, &G.main->world);
1887         write_texts    (wd, &G.main->text);
1888         write_sounds   (wd, &G.main->sound);
1889         write_groups   (wd, &G.main->group);
1890         write_armatures(wd, &G.main->armature);
1891         write_actions  (wd, &G.main->action);
1892         write_objects  (wd, &G.main->object);
1893         write_materials(wd, &G.main->mat);
1894         write_textures (wd, &G.main->tex);
1895         write_meshs    (wd, &G.main->mesh);
1896         write_nodetrees(wd, &G.main->nodetree);
1897         write_brushes  (wd, &G.main->brush);
1898         if(current==NULL)       
1899                 write_libraries(wd,  G.main->next); /* no library save in undo */
1900
1901         if (write_user_block) {
1902                 write_userdef(wd);
1903         }
1904
1905         /* dna as last, because (to be implemented) test for which structs are written */
1906         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1907
1908         /* end of file */
1909         memset(&bhead, 0, sizeof(BHead));
1910         bhead.code= ENDB;
1911         mywrite(wd, &bhead, sizeof(BHead));
1912
1913         blo_join_main(&mainlist);
1914         G.main= mainlist.first;
1915
1916         return endwrite(wd);
1917 }
1918
1919 /* return: success (1) */
1920 int BLO_write_file(char *dir, int write_flags, char **error_r)
1921 {
1922         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1923         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1924         int file, err, write_user_block;
1925
1926         sprintf(tempname, "%s@", dir);
1927
1928         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1929         if(file == -1) {
1930                 *error_r= "Unable to open";
1931                 return 0;
1932         }
1933
1934         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1935
1936         write_user_block= BLI_streq(dir, userfilename);
1937
1938         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
1939         close(file);
1940
1941         if(!err) {
1942                 if(write_flags & G_FILE_COMPRESS)
1943                 {       
1944                         // compressed files have the same ending as regular files... only from 2.4!!!
1945                         
1946                         int ret = BLI_gzip(tempname, dir);
1947                         
1948                         if(-1==ret) {
1949                                 *error_r= "Failed opening .gz file";
1950                                 return 0;
1951                         }
1952                         if(-2==ret) {
1953                                 *error_r= "Failed opening .blend file for compression";
1954                                 return 0;
1955                         }
1956                 }
1957                 else
1958                 if(BLI_rename(tempname, dir) < 0) {
1959                         *error_r= "Can't change old file. File saved with @";
1960                         return 0;
1961                 }
1962
1963                 
1964         } else {
1965                 *error_r= strerror(errno);
1966                 remove(tempname);
1967
1968                 return 0;
1969         }
1970
1971         return 1;
1972 }
1973
1974 /* return: success (1) */
1975 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
1976 {
1977         int err;
1978
1979         err= write_file_handle(0, compare, current, 0, write_flags);
1980         
1981         if(err==0) return 1;
1982         return 0;
1983 }
1984
1985
1986         /* Runtime writing */
1987
1988 #ifdef WIN32
1989 #define PATHSEPERATOR           "\\"
1990 #else
1991 #define PATHSEPERATOR           "/"
1992 #endif
1993
1994 static char *get_install_dir(void) {
1995         extern char bprogname[];
1996         char *tmpname = BLI_strdup(bprogname);
1997         char *cut;
1998
1999 #ifdef __APPLE__
2000         cut = strstr(tmpname, ".app");
2001         if (cut) cut[0] = 0;
2002 #endif
2003
2004         cut = BLI_last_slash(tmpname);
2005
2006         if (cut) {
2007                 cut[0] = 0;
2008                 return tmpname;
2009         } else {
2010                 MEM_freeN(tmpname);
2011                 return NULL;
2012         }
2013 }
2014
2015 static char *get_runtime_path(char *exename) {
2016         char *installpath= get_install_dir();
2017
2018         if (!installpath) {
2019                 return NULL;
2020         } else {
2021                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2022
2023                 if (path == NULL) {
2024                         MEM_freeN(installpath);
2025                         return NULL;
2026                 }
2027
2028                 strcpy(path, installpath);
2029                 strcat(path, PATHSEPERATOR);
2030                 strcat(path, exename);
2031
2032                 MEM_freeN(installpath);
2033
2034                 return path;
2035         }
2036 }
2037
2038 #ifdef __APPLE__
2039
2040 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2041 {
2042         char *cause = NULL, *runtime = get_runtime_path(exename);
2043         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2044         int progfd = -1;
2045
2046         if (!runtime) {
2047                 cause= "Unable to find runtime";
2048                 goto cleanup;
2049         }
2050         //printf("runtimepath %s\n", runtime);
2051                 
2052         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2053         if (progfd==-1) {
2054                 cause= "Unable to find runtime";
2055                 goto cleanup;
2056         }
2057
2058         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2059         //printf("command %s\n", command);
2060         if (system(command) == -1) {
2061                 cause = "Couldn't copy runtime";
2062         }
2063
2064 cleanup:
2065         if (progfd!=-1)
2066                 close(progfd);
2067         if (runtime)
2068                 MEM_freeN(runtime);
2069
2070         if (cause) {
2071                 *cause_r= cause;
2072                 return 0;
2073         } else
2074                 return 1;
2075 }
2076
2077 void BLO_write_runtime(char *file, char *exename) {
2078         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2079         int outfd = -1;
2080         char *cause= NULL;
2081
2082         // remove existing file / bundle
2083         //printf("Delete file %s\n", file);
2084         BLI_delete(file, 0, TRUE);
2085
2086         if (!recursive_copy_runtime(file, exename, &cause))
2087                 goto cleanup;
2088
2089         strcpy(gamename, file);
2090         strcat(gamename, "/Contents/Resources/game.blend");
2091         //printf("gamename %s\n", gamename);
2092         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2093         if (outfd != -1) {
2094
2095                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2096
2097                 if (write(outfd, " ", 1) != 1) {
2098                         cause= "Unable to write to output file";
2099                         goto cleanup;
2100                 }
2101         } else {
2102                 cause = "Unable to open blenderfile";
2103         }
2104
2105 cleanup:
2106         if (outfd!=-1)
2107                 close(outfd);
2108
2109         if (cause)
2110                 error("Unable to make runtime: %s", cause);
2111 }
2112
2113 #else /* !__APPLE__ */
2114
2115 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2116         char *cause= NULL, *runtime= get_runtime_path(exename);
2117         unsigned char buf[1024];
2118         int count, progfd= -1;
2119
2120         if (!runtime) {
2121                 cause= "Unable to find runtime";
2122                 goto cleanup;
2123         }
2124
2125         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2126         if (progfd==-1) {
2127                 cause= "Unable to find runtime";
2128                 goto cleanup;
2129         }
2130
2131         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2132                 if (write(handle, buf, count)!=count) {
2133                         cause= "Unable to write to output file";
2134                         goto cleanup;
2135                 }
2136         }
2137
2138 cleanup:
2139         if (progfd!=-1)
2140                 close(progfd);
2141         if (runtime)
2142                 MEM_freeN(runtime);
2143
2144         if (cause) {
2145                 *cause_r= cause;
2146                 return 0;
2147         } else
2148                 return 1;
2149 }
2150
2151 static int handle_write_msb_int(int handle, int i) {
2152         unsigned char buf[4];
2153         buf[0]= (i>>24)&0xFF;
2154         buf[1]= (i>>16)&0xFF;
2155         buf[2]= (i>>8)&0xFF;
2156         buf[3]= (i>>0)&0xFF;
2157
2158         return (write(handle, buf, 4)==4);
2159 }
2160
2161 void BLO_write_runtime(char *file, char *exename) {
2162         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2163         char *cause= NULL;
2164         int datastart;
2165
2166         if (!outfd) {
2167                 cause= "Unable to open output file";
2168                 goto cleanup;
2169         }
2170         if (!handle_append_runtime(outfd, exename, &cause))
2171                 goto cleanup;
2172
2173         datastart= lseek(outfd, 0, SEEK_CUR);
2174
2175         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2176
2177         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2178                 cause= "Unable to write to output file";
2179                 goto cleanup;
2180         }
2181
2182 cleanup:
2183         if (outfd!=-1)
2184                 close(outfd);
2185
2186         if (cause)
2187                 error("Unable to make runtime: %s", cause);
2188 }
2189
2190 #endif /* !__APPLE__ */