b7e510834aaa99b9daba29f210570c2d1a1fac8f
[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 #ifndef WIN32 
87 #include <unistd.h>
88 #else
89 #include "winsock2.h"
90 #include "BLI_winstuff.h"
91 #include <io.h>
92 #include <process.h> // for getpid
93 #endif
94
95 #include <math.h>
96 #include <fcntl.h>
97 #include <stdio.h>
98 #include <string.h>
99 #include <stdlib.h>
100
101 #include "nla.h" //  __NLA is defined
102
103 #include "DNA_packedFile_types.h"
104 #include "DNA_sdna_types.h"
105 #include "DNA_property_types.h"
106 #include "DNA_sensor_types.h"
107 #include "DNA_controller_types.h"
108 #include "DNA_actuator_types.h"
109 #include "DNA_effect_types.h"
110 #include "DNA_object_types.h"
111 #include "DNA_userdef_types.h"
112 #include "DNA_vfont_types.h"
113 #include "DNA_ipo_types.h"
114 #include "DNA_curve_types.h"
115 #include "DNA_camera_types.h"
116 #include "DNA_meta_types.h"
117 #include "DNA_mesh_types.h"
118 #include "DNA_meshdata_types.h"
119 #include "DNA_material_types.h"
120 #include "DNA_lattice_types.h"
121 #include "DNA_armature_types.h"
122 #include "DNA_sequence_types.h"
123 #include "DNA_ika_types.h"
124 #include "DNA_group_types.h"
125 #include "DNA_oops_types.h"
126 #include "DNA_space_types.h"
127 #include "DNA_screen_types.h"
128 #include "DNA_view3d_types.h"
129 #include "DNA_lamp_types.h"
130 #include "DNA_fileglobal_types.h"
131 #include "DNA_sound_types.h"
132 #include "DNA_texture_types.h"
133 #include "DNA_text_types.h"
134 #include "DNA_image_types.h"
135 #include "DNA_key_types.h"
136 #include "DNA_scene_types.h"
137 #include "DNA_constraint_types.h"
138 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
139 #include "DNA_action_types.h"
140 #include "DNA_nla_types.h"
141
142 #include "MEM_guardedalloc.h" // MEM_freeN 
143 #include "BLI_blenlib.h"
144 #include "BLI_linklist.h"
145
146 #include "BKE_action.h"
147 #include "BKE_utildefines.h" // for KNOTSU KNOTSV WHILE_SEQ END_SEQ defines
148 #include "BKE_bad_level_calls.h" // build_seqar (from WHILE_SEQ) free_oops error
149 #include "BKE_constraint.h"
150 #include "BKE_main.h" // G.main
151 #include "BKE_global.h" // for G
152 #include "BKE_screen.h" // for waitcursor
153 #include "BKE_packedFile.h" // for packAll
154 #include "BKE_library.h" // for  set_listbasepointers
155 #include "BKE_sound.h" /* ... and for samples */
156
157 #include "GEN_messaging.h"
158
159 #include "BLO_writefile.h"
160 #include "BLO_readfile.h"
161
162 #include "readfile.h"
163 #include "genfile.h"
164
165 /* *******  MYWRITE ********* */
166
167 #include "BLO_writeStreamGlue.h"
168
169 /***/
170
171 typedef struct {
172         struct SDNA *sdna;
173
174         int file;
175         unsigned char *buf;
176         
177         int tot, count, error;
178         
179         int is_publisher;
180         struct writeStreamGlueStruct *streamGlue;
181 } WriteData;
182
183 static WriteData *writedata_new(int file, int is_publisher)
184 {
185         extern char DNAstr[];   /* DNA.c */
186         extern int DNAlen;
187         
188         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
189
190                 /* XXX, see note about this in readfile.c, remove
191                  * once we have an xp lock - zr
192                  */
193         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
194         
195         wd->file= file;
196         wd->is_publisher= is_publisher;
197
198         wd->buf= MEM_mallocN(100000, "wd->buf");
199         
200         return wd;
201 }
202
203 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
204 {
205         if (wd->error) return;
206         
207         if (wd->is_publisher) {
208                 wd->error = writeStreamGlue(Global_streamGlueControl, &wd->streamGlue, mem, memlen, 0);
209         } else {
210                 if (write(wd->file, mem, memlen) != memlen)
211                         wd->error= 1;
212         }       
213 }
214
215 static void writedata_free(WriteData *wd) 
216 {
217         dna_freestructDNA(wd->sdna);
218
219         MEM_freeN(wd->buf);
220         MEM_freeN(wd);
221 }
222
223 /***/
224
225 struct streamGlueControlStruct *Global_streamGlueControl;
226 int mywfile;
227
228 /**
229  * Low level WRITE(2) wrapper that buffers data
230  * @param adr Pointer to new chunk of data
231  * @param len Length of new chunk of data
232  * @warning Talks to other functions with global parameters
233  */
234         static void
235 mywrite(
236         WriteData *wd, 
237         void *adr,
238         int len)
239 {
240         if (wd->error) return;
241
242         wd->tot+= len;
243
244         if(len>50000) {
245                 if(wd->count) {
246                         writedata_do_write(wd, wd->buf, wd->count);
247                         wd->count= 0;
248                 }
249                 writedata_do_write(wd, adr, len);
250                 return;
251         }
252         if(len+wd->count>99999) {
253                 writedata_do_write(wd, wd->buf, wd->count);
254                 wd->count= 0; 
255         }
256         memcpy(&wd->buf[wd->count], adr, len);
257         wd->count+= len;
258 }
259
260 /**
261  * BeGiN initializer for mywrite
262  * @param file File descriptor
263  * @param write_flags Write parameters
264  * @warning Talks to other functions with global parameters
265  */
266         static WriteData *
267 bgnwrite(
268         int file, 
269         int write_flags)
270 {
271         int is_publisher= (write_flags & (G_FILE_COMPRESS | G_FILE_LOCK | G_FILE_SIGN | G_FILE_PUBLISH));
272         WriteData *wd= writedata_new(file, is_publisher);
273         
274         if (is_publisher) {
275                 mywfile= file;
276                 wd->streamGlue = NULL;
277                 Global_streamGlueControl = streamGlueControlConstructor();
278                 streamGlueControlAppendAction(Global_streamGlueControl, DUMPFROMMEMORY);
279                 if (write_flags & G_FILE_COMPRESS) {
280                         streamGlueControlAppendAction(Global_streamGlueControl, DEFLATE);
281                 }
282                 if (write_flags & G_FILE_LOCK) {
283                         streamGlueControlAppendAction(Global_streamGlueControl, ENCRYPT);
284                 }
285                 if (write_flags & G_FILE_SIGN) {
286                         streamGlueControlAppendAction(Global_streamGlueControl, SIGN);
287                 }
288                 streamGlueControlAppendAction(Global_streamGlueControl, WRITEBLENFILE);
289         }
290         
291         return wd;
292 }
293
294 /**
295  * END the mywrite wrapper
296  * @return 1 if write failed
297  * @return unknown global variable otherwise
298  * @warning Talks to other functions with global parameters
299  */
300         static int
301 endwrite(
302         WriteData *wd)
303 {
304         int err;
305         
306         if (wd->count) {
307                 writedata_do_write(wd, wd->buf, wd->count);
308                 wd->count= 0; 
309         }
310         if (wd->is_publisher) {
311                 writeStreamGlue(Global_streamGlueControl, &wd->streamGlue, NULL, 0, 1);
312                 streamGlueControlDestructor(Global_streamGlueControl);
313                 // final writestream error handling goes here
314                 if (wd->error) {
315                         int err = wd->error;
316                         int errFunction = BWS_GETFUNCTION(err);
317                         int errGeneric =  BWS_GETGENERR(err);
318                         int errSpecific = BWS_GETSPECERR(err);
319                         char *errFunctionStrings[] = {
320                                 "",
321                                 "The write stream",
322                                 "The deflation",
323                                 "The encryption",
324                                 "The signing",
325                                 "Writing the blendfile"
326                         };
327                         char *errGenericStrings[] = {
328                                 "",
329                                 "generated an out of memory error",
330                                 "is not allowed in this version",
331                                 "has problems with your key"
332                         };
333                         char *errWriteStreamGlueStrings[] = {
334                                 "",
335                                 "does not know how to proceed"
336                         };
337                         char *errDeflateStrings[] = {
338                                 "",
339                                 "bumped on a compress error"
340                         };
341                         char *errEncryptStrings[] = {
342                                 "",
343                                 "could not write the key",
344                                 "bumped on an encrypt error"
345                         };
346                         char *errSignStrings[] = {
347                                 "",
348                                 "could not write the key",
349                                 "failed"
350                         };
351                         char *errWriteBlenFileStrings[] = {
352                                 "",
353                                 "encountered problems writing the filedescription",
354                                 "encountered problems writing the blendfile",
355                                 "encountered problems writing one (or more) parameters"
356                         };
357                         char *errFunctionString= errFunctionStrings[errFunction];
358                         char *errExtraString= "";
359                         
360                         if (errGeneric)
361                         {
362                                 errExtraString= errGenericStrings[errGeneric];
363                         }
364                         else if (errSpecific)
365                         {
366                                 switch (errFunction)
367                                 {
368                                 case BWS_WRITESTREAMGLUE:
369                                         errExtraString= errWriteStreamGlueStrings[errSpecific];
370                                         break;
371                                 case BWS_DEFLATE:
372                                         errExtraString= errDeflateStrings[errSpecific];
373                                         break;
374                                 case BWS_ENCRYPT:
375                                         errExtraString= errEncryptStrings[errSpecific];
376                                         break;
377                                 case BWS_SIGN:
378                                         errExtraString= errSignStrings[errSpecific];
379                                         break;
380                                 case BWS_WRITEBLENFILE:
381                                         errExtraString= errWriteBlenFileStrings[errSpecific];
382                                         break;
383                                 default:
384                                         break;
385                                 }
386                         }
387                         
388                                 // call Blender error popup window
389                         error("%s %s", errFunctionString, errExtraString);
390                 }
391         }
392         
393         err= wd->error;
394         writedata_free(wd);
395         
396         return err;
397 }
398
399 /* ********** WRITE FILE ****************** */
400
401 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
402 {
403         BHead bh;
404         short *sp;
405         
406         if(adr==0 || nr==0) return;
407         
408         /* init BHead */
409         bh.code= filecode;
410         bh.old= adr;
411         bh.nr= nr;
412         
413         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
414         if(bh.SDNAnr== -1) {
415                 printf("error: can't find SDNA code %s\n", structname);
416                 return;
417         }
418         sp= wd->sdna->structs[bh.SDNAnr];
419         
420         bh.len= nr*wd->sdna->typelens[sp[0]];
421         
422         if(bh.len==0) return;
423                 
424         mywrite(wd, &bh, sizeof(BHead));
425         mywrite(wd, adr, bh.len);
426 }
427
428 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
429 {
430         BHead bh;
431         
432         if(adr==0) return;
433         if(len==0) return;
434         
435         len+= 3;
436         len-= ( len % 4);
437         
438         /* init BHead */
439         bh.code= filecode;
440         bh.old= adr;
441         bh.nr= 1;
442         bh.SDNAnr= 0;   
443         bh.len= len;
444         
445         mywrite(wd, &bh, sizeof(BHead));
446         if(len) mywrite(wd, adr, len);
447 }
448
449 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
450 {
451         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);   
452         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);       
453 }
454
455 static void write_renderinfo(WriteData *wd)             /* for renderdaemon */
456 {
457         Scene *sce;
458         int data[8];
459         
460         sce= G.main->scene.first;
461         while(sce) {
462                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
463                         data[0]= sce->r.sfra;
464                         data[1]= sce->r.efra;
465                         
466                         strncpy((char *)(data+2), sce->id.name+2, 23);
467                         
468                         writedata(wd, REND, 32, data);
469                 }
470                 sce= sce->id.next;
471         }
472 }
473
474 static void write_userdef(WriteData *wd)
475 {
476         bTheme *btheme;
477         
478         writestruct(wd, USER, "UserDef", 1, &U);
479         
480         btheme= U.themes.first;
481         while(btheme) {
482                 writestruct(wd, DATA, "bTheme", 1, btheme);
483                 btheme= btheme->next;
484         }
485 }
486
487 static void write_effects(WriteData *wd, ListBase *lb)
488 {
489         Effect *eff;
490         
491         eff= lb->first;
492         while(eff) {
493                 
494                 switch(eff->type) {
495                 case EFF_BUILD:
496                         writestruct(wd, DATA, "BuildEff", 1, eff);
497                         break;  
498                 case EFF_PARTICLE:
499                         writestruct(wd, DATA, "PartEff", 1, eff);
500                         break;  
501                 case EFF_WAVE:
502                         writestruct(wd, DATA, "WaveEff", 1, eff);
503                         break;  
504                 default:
505                         writedata(wd, DATA, MEM_allocN_len(eff), eff);
506                 }
507                 
508                 eff= eff->next;
509         }
510 }
511
512 static void write_properties(WriteData *wd, ListBase *lb)
513 {
514         bProperty *prop;
515         
516         prop= lb->first;
517         while(prop) {
518                 writestruct(wd, DATA, "bProperty", 1, prop);
519         
520                 if(prop->poin && prop->poin != &prop->data) 
521                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
522         
523                 prop= prop->next;
524         }
525 }
526
527 static void write_sensors(WriteData *wd, ListBase *lb)
528 {
529         bSensor *sens;
530         
531         sens= lb->first;
532         while(sens) {
533                 writestruct(wd, DATA, "bSensor", 1, sens);
534                 
535                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
536                 
537                 switch(sens->type) {
538                 case SENS_NEAR:
539                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
540                         break;
541                 case SENS_MOUSE:
542                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
543                         break;
544                 case SENS_TOUCH:
545                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
546                         break;
547                 case SENS_KEYBOARD:
548                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
549                         break;
550                 case SENS_PROPERTY:
551                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
552                         break;
553                 case SENS_COLLISION:
554                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
555                         break;
556                 case SENS_RADAR:
557                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
558                         break;
559                 case SENS_RANDOM:
560                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
561                         break;
562                 case SENS_RAY:
563                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
564                         break;
565                 case SENS_MESSAGE:
566                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
567                         break;
568                 default:
569                         ; /* error: don't know how to write this file */
570                 }
571         
572                 sens= sens->next;
573         }
574 }
575
576 static void write_controllers(WriteData *wd, ListBase *lb)
577 {
578         bController *cont;
579         
580         cont= lb->first;
581         while(cont) {
582                 writestruct(wd, DATA, "bController", 1, cont);
583         
584                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
585         
586                 switch(cont->type) {
587                 case CONT_EXPRESSION:
588                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
589                         break;
590                 case CONT_PYTHON:
591                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
592                         break;
593                 default:
594                         ; /* error: don't know how to write this file */
595                 }
596         
597                 cont= cont->next;
598         }
599 }
600
601 static void write_actuators(WriteData *wd, ListBase *lb)
602 {
603         bActuator *act;
604         
605         act= lb->first;
606         while(act) {
607                 writestruct(wd, DATA, "bActuator", 1, act);
608         
609                 switch(act->type) {
610                 case ACT_ACTION:
611                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
612                         break;
613                 case ACT_SOUND:
614                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
615                         break;
616                 case ACT_CD:
617                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
618                         break;
619                 case ACT_OBJECT:
620                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
621                         break;
622                 case ACT_IPO:
623                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
624                         break;
625                 case ACT_PROPERTY:
626                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
627                         break;
628                 case ACT_CAMERA:
629                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
630                         break;
631                 case ACT_CONSTRAINT:
632                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
633                         break;
634                 case ACT_EDIT_OBJECT:
635                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
636                         break;
637                 case ACT_SCENE:
638                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
639                         break;
640                 case ACT_GROUP:
641                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
642                         break;
643                 case ACT_RANDOM:
644                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
645                         break;
646                 case ACT_MESSAGE:
647                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
648                         break;
649                 case ACT_GAME:
650                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
651                         break;
652                 case ACT_VISIBILITY:
653                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
654                         break;
655                 default:
656                         ; /* error: don't know how to write this file */
657                 }
658         
659                 act= act->next;
660         }
661 }
662
663 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
664 {
665         bActionStrip *strip;
666
667         for (strip=nlabase->first; strip; strip=strip->next)
668                 writestruct(wd, DATA, "bActionStrip", 1, strip);
669 }
670
671 static void write_constraints(WriteData *wd, ListBase *conlist)
672 {
673         bConstraint *con;
674         
675         for (con=conlist->first; con; con=con->next) {
676                 /* Write the specific data */
677                 switch (con->type) {
678                 case CONSTRAINT_TYPE_NULL:
679                         break;
680                 case CONSTRAINT_TYPE_TRACKTO:
681                         writestruct(wd, DATA, "bTrackToConstraint", 1, con->data);
682                         break;
683                 case CONSTRAINT_TYPE_KINEMATIC:
684                         writestruct(wd, DATA, "bKinematicConstraint", 1, con->data);
685                         break;
686                 case CONSTRAINT_TYPE_ROTLIKE:
687                         writestruct(wd, DATA, "bRotateLikeConstraint", 1, con->data);
688                         break;
689                 case CONSTRAINT_TYPE_LOCLIKE:
690                         writestruct(wd, DATA, "bLocateLikeConstraint", 1, con->data);
691                         break;
692                 case CONSTRAINT_TYPE_ACTION:
693                         writestruct(wd, DATA, "bActionConstraint", 1, con->data);
694                         break;
695                 case CONSTRAINT_TYPE_LOCKTRACK:
696                         writestruct(wd, DATA, "bLockTrackConstraint", 1, con->data);
697                         break;
698                 case CONSTRAINT_TYPE_FOLLOWPATH:
699                         writestruct(wd, DATA, "bFollowPathConstraint", 1, con->data);
700                         break;
701                 default:
702                         break;
703                 }
704                 /* Write the constraint */
705                 writestruct(wd, DATA, "bConstraint", 1, con);
706         }
707 }
708
709 static void write_pose(WriteData *wd, bPose *pose)
710 {
711         bPoseChannel    *chan;
712         
713         /* Write each channel */
714         
715         if (!pose)
716                 return;
717         
718         // Write channels
719         for (chan=pose->chanbase.first; chan; chan=chan->next) {
720                 write_constraints(wd, &chan->constraints);
721                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
722         }
723         
724         // Write this pose 
725         writestruct(wd, DATA, "bPose", 1, pose);
726 }
727
728 static void write_defgroups(WriteData *wd, ListBase *defbase)
729 {
730         bDeformGroup    *defgroup;
731         
732         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
733                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
734 }
735
736 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
737 {
738         bConstraintChannel *chan;
739
740         for (chan = chanbase->first; chan; chan=chan->next)
741                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
742         
743 }
744
745 static void write_objects(WriteData *wd, ListBase *idbase)
746 {
747         Object *ob;
748         
749         ob= idbase->first;
750         while(ob) {
751                 if(ob->id.us>0) {
752                         /* write LibData */
753                         writestruct(wd, ID_OB, "Object", 1, ob);
754                         
755                         /* direct data */
756                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
757                         write_effects(wd, &ob->effect);
758                         write_properties(wd, &ob->prop);
759                         write_sensors(wd, &ob->sensors);
760                         write_controllers(wd, &ob->controllers);
761                         write_actuators(wd, &ob->actuators);
762                         write_scriptlink(wd, &ob->scriptlink);
763                         write_pose(wd, ob->pose);
764                         write_defgroups(wd, &ob->defbase);
765                         write_constraints(wd, &ob->constraints);
766                         write_constraint_channels(wd, &ob->constraintChannels);
767                         write_nlastrips(wd, &ob->nlastrips);
768                 }
769                 ob= ob->id.next;
770         }
771 }
772
773
774 static void write_vfonts(WriteData *wd, ListBase *idbase)
775 {
776         VFont *vf;
777         PackedFile * pf;
778         
779         vf= idbase->first;
780         while(vf) {
781                 if(vf->id.us>0) {
782                         /* write LibData */
783                         writestruct(wd, ID_VF, "VFont", 1, vf);
784                 
785                         /* direct data */
786                         
787                         if (vf->packedfile) {
788                                 pf = vf->packedfile;
789                                 writestruct(wd, DATA, "PackedFile", 1, pf);
790                                 writedata(wd, DATA, pf->size, pf->data);
791                         }
792                 }
793                 
794                 vf= vf->id.next;
795         }
796 }
797
798 static void write_ipos(WriteData *wd, ListBase *idbase)
799 {
800         Ipo *ipo;
801         IpoCurve *icu;
802         
803         ipo= idbase->first;
804         while(ipo) {
805                 if(ipo->id.us>0) {
806                         /* write LibData */
807                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
808                 
809                         /* direct data */
810                         icu= ipo->curve.first;
811                         while(icu) {
812                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
813                                 icu= icu->next;
814                         }
815         
816                         icu= ipo->curve.first;
817                         while(icu) {
818                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
819                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
820                                 icu= icu->next;
821                         }
822                 }
823                 
824                 ipo= ipo->id.next;
825         }
826 }
827
828 static void write_keys(WriteData *wd, ListBase *idbase)
829 {
830         Key *key;
831         KeyBlock *kb;
832         
833         key= idbase->first;
834         while(key) {
835                 if(key->id.us>0) {
836                         /* write LibData */
837                         writestruct(wd, ID_KE, "Key", 1, key);
838                 
839                         /* direct data */
840                         kb= key->block.first;
841                         while(kb) {
842                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
843                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
844                                 kb= kb->next;
845                         }
846                 }
847                 
848                 key= key->id.next;
849         }
850 }
851
852 static void write_cameras(WriteData *wd, ListBase *idbase)
853 {
854         Camera *cam;
855         
856         cam= idbase->first;
857         while(cam) {
858                 if(cam->id.us>0) {
859                         /* write LibData */
860                         writestruct(wd, ID_CA, "Camera", 1, cam);
861                 
862                         /* direct data */
863                         write_scriptlink(wd, &cam->scriptlink);
864                 }
865                 
866                 cam= cam->id.next;
867         }
868 }
869
870 static void write_mballs(WriteData *wd, ListBase *idbase)
871 {
872         MetaBall *mb;
873         MetaElem *ml;
874         
875         mb= idbase->first;
876         while(mb) {
877                 if(mb->id.us>0) {
878                         /* write LibData */
879                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
880                         
881                         /* direct data */
882                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
883                         
884                         ml= mb->elems.first;
885                         while(ml) {
886                                 writestruct(wd, DATA, "MetaElem", 1, ml);
887                                 ml= ml->next;
888                         }
889                 }
890                 mb= mb->id.next;
891         }
892 }
893
894 static void write_curves(WriteData *wd, ListBase *idbase)
895 {
896         Curve *cu;
897         Nurb *nu;
898         
899         cu= idbase->first;
900         while(cu) {
901                 if(cu->id.us>0) {
902                         /* write LibData */
903                         writestruct(wd, ID_CU, "Curve", 1, cu);
904                         
905                         /* direct data */
906                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
907                         
908                         if(cu->vfont) {
909                                 writedata(wd, DATA, cu->len+1, cu->str);
910                         }
911                         else {
912                                 /* is also the order of reading */
913                                 nu= cu->nurb.first;
914                                 while(nu) {
915                                         writestruct(wd, DATA, "Nurb", 1, nu);
916                                         nu= nu->next;
917                                 }
918                                 nu= cu->nurb.first;
919                                 while(nu) {
920                                         if( (nu->type & 7)==CU_BEZIER) 
921                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
922                                         else {
923                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
924                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
925                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
926                                         }
927                                         nu= nu->next;
928                                 }
929                         }
930                 }
931                 cu= cu->id.next;
932         }
933 }
934
935 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
936 {
937         int     i;
938                 
939         /* Write the dvert list */
940         writestruct(wd, DATA, "MDeformVert", count, dvlist);
941         
942         /* Write deformation data for each dvert */
943         if (dvlist) {
944                 for (i=0; i<count; i++) {
945                         if (dvlist[i].dw)
946                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw); 
947                 }
948         }
949 }
950
951 static void write_meshs(WriteData *wd, ListBase *idbase)
952 {
953         Mesh *mesh;
954         
955         mesh= idbase->first;
956         while(mesh) {
957                 if(mesh->id.us>0) {
958                         /* write LibData */
959                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
960                         
961                         /* direct data */
962                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
963                         writestruct(wd, DATA, "MVert", mesh->totvert, mesh->mvert);
964                         write_dverts(wd, mesh->totvert, mesh->dvert);
965                         writestruct(wd, DATA, "MFace", mesh->totface, mesh->mface);
966                         writestruct(wd, DATA, "TFace", mesh->totface, mesh->tface);
967                         writestruct(wd, DATA, "MCol", 4*mesh->totface, mesh->mcol);
968                         writestruct(wd, DATA, "MSticky", mesh->totvert, mesh->msticky);
969         
970                 }
971                 mesh= mesh->id.next;
972         }
973 }
974
975 static void write_images(WriteData *wd, ListBase *idbase)
976 {
977         Image *ima;
978         PackedFile * pf;
979         
980         ima= idbase->first;
981         while(ima) {
982                 if(ima->id.us>0) {
983                         /* write LibData */
984                         writestruct(wd, ID_IM, "Image", 1, ima);
985         
986                         if (ima->packedfile) {
987                                 pf = ima->packedfile;
988                                 writestruct(wd, DATA, "PackedFile", 1, pf);
989                                 writedata(wd, DATA, pf->size, pf->data);
990                         }
991                 }
992                 ima= ima->id.next;
993         }
994 }
995
996 static void write_textures(WriteData *wd, ListBase *idbase)
997 {
998         Tex *tex;
999         
1000         tex= idbase->first;
1001         while(tex) {
1002                 if(tex->id.us>0) {
1003                         /* write LibData */
1004                         writestruct(wd, ID_TE, "Tex", 1, tex);
1005                         
1006                         /* direct data */
1007                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1008                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1009                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1010                 }
1011                 tex= tex->id.next;
1012         }
1013 }
1014
1015 static void write_materials(WriteData *wd, ListBase *idbase)
1016 {
1017         Material *ma;
1018         int a;
1019         
1020         ma= idbase->first;
1021         while(ma) {
1022                 if(ma->id.us>0) {
1023                         /* write LibData */
1024                         writestruct(wd, ID_MA, "Material", 1, ma);
1025                         
1026                         for(a=0; a<8; a++) {
1027                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1028                         }
1029         
1030                         write_scriptlink(wd, &ma->scriptlink);
1031                 }
1032                 ma= ma->id.next;
1033         }
1034 }
1035
1036 static void write_worlds(WriteData *wd, ListBase *idbase)
1037 {
1038         World *wrld;
1039         int a;
1040         
1041         wrld= idbase->first;
1042         while(wrld) {
1043                 if(wrld->id.us>0) {
1044                         /* write LibData */
1045                         writestruct(wd, ID_WO, "World", 1, wrld);
1046         
1047                         for(a=0; a<8; a++) {
1048                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1049                         }
1050         
1051                         write_scriptlink(wd, &wrld->scriptlink);
1052                 }
1053                 wrld= wrld->id.next;
1054         }
1055 }
1056
1057 static void write_lamps(WriteData *wd, ListBase *idbase)
1058 {
1059         Lamp *la;
1060         int a;
1061         
1062         la= idbase->first;
1063         while(la) {
1064                 if(la->id.us>0) {
1065                         /* write LibData */
1066                         writestruct(wd, ID_LA, "Lamp", 1, la);
1067                 
1068                         /* direct data */
1069                         for(a=0; a<8; a++) {
1070                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1071                         }
1072         
1073                         write_scriptlink(wd, &la->scriptlink);
1074                 }
1075                 la= la->id.next;
1076         }
1077 }
1078
1079 static void write_lattices(WriteData *wd, ListBase *idbase)
1080 {
1081         Lattice *lt;
1082         
1083         lt= idbase->first;
1084         while(lt) {
1085                 if(lt->id.us>0) {
1086                         /* write LibData */
1087                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1088                 
1089                         /* direct data */
1090                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1091                 }
1092                 lt= lt->id.next;
1093         }
1094 }
1095
1096 static void write_ikas(WriteData *wd, ListBase *idbase)
1097 {
1098         Ika *ika;
1099         Limb *li;
1100         
1101         ika= idbase->first;
1102         while(ika) {
1103                 if(ika->id.us>0) {
1104                         /* write LibData */
1105                         writestruct(wd, ID_IK, "Ika", 1, ika);
1106                         
1107                         /* direct data */
1108                         li= ika->limbbase.first;
1109                         while(li) {
1110                                 writestruct(wd, DATA, "Limb", 1, li);
1111                                 li= li->next;
1112                         }
1113                         
1114                         writestruct(wd, DATA, "Deform", ika->totdef, ika->def);
1115                 }
1116                 ika= ika->id.next;
1117         }
1118 }
1119
1120 static void write_scenes(WriteData *wd, ListBase *scebase)
1121 {
1122         Scene *sce;
1123         Base *base;
1124         Editing *ed;
1125         Sequence *seq;
1126         Strip *strip;
1127         
1128         sce= scebase->first;
1129         while(sce) {
1130                 /* write LibData */
1131                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1132                 
1133                 /* direct data */
1134                 base= sce->base.first;
1135                 while(base) {
1136                         writestruct(wd, DATA, "Base", 1, base);
1137                         base= base->next;
1138                 }
1139                 
1140                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1141                 writestruct(wd, DATA, "FreeCamera", 1, sce->fcam);
1142                 
1143                 ed= sce->ed;
1144                 if(ed) {
1145                         writestruct(wd, DATA, "Editing", 1, ed);
1146         
1147                         /* reset write flags too */
1148                         WHILE_SEQ(&ed->seqbase) {
1149                                 if(seq->strip) seq->strip->done= 0;
1150                                 writestruct(wd, DATA, "Sequence", 1, seq);
1151                         }
1152                         END_SEQ
1153                         
1154                         WHILE_SEQ(&ed->seqbase) {
1155                                 if(seq->strip && seq->strip->done==0) {
1156                                         /* write strip with 'done' at 0 because readfile */
1157                                         
1158                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1159                                         
1160                                         strip= seq->strip;
1161                                         writestruct(wd, DATA, "Strip", 1, strip);
1162                                         
1163                                         if(seq->type==SEQ_IMAGE) 
1164                                                 writestruct(wd, DATA, "StripElem", strip->len, strip->stripdata);
1165                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_SOUND)
1166                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1167                                                 
1168                                         strip->done= 1;
1169                                 }
1170                         }
1171                         END_SEQ
1172                 }
1173         
1174                 write_scriptlink(wd, &sce->scriptlink);
1175
1176                 if (sce->r.avicodecdata) {
1177                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1178                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1179                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1180                 }
1181                 
1182                 if (sce->r.qtcodecdata) {
1183                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1184                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1185                 }
1186
1187                 sce= sce->id.next;
1188         }
1189 }
1190
1191 static void write_screens(WriteData *wd, ListBase *scrbase)
1192 {
1193         bScreen *sc;
1194         ScrArea *sa;
1195         ScrVert *sv;
1196         ScrEdge *se;
1197         
1198         sc= scrbase->first;
1199         while(sc) {
1200                 /* write LibData */
1201                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1202                 
1203                 /* direct data */
1204                 sv= sc->vertbase.first;
1205                 while(sv) {
1206                         writestruct(wd, DATA, "ScrVert", 1, sv);
1207                         sv= sv->next;
1208                 }
1209         
1210                 se= sc->edgebase.first;
1211                 while(se) {
1212                         writestruct(wd, DATA, "ScrEdge", 1, se);
1213                         se= se->next;
1214                 }
1215         
1216                 sa= sc->areabase.first;
1217                 while(sa) {
1218                         SpaceLink *sl;
1219                         Panel *pa;
1220
1221                         writestruct(wd, DATA, "ScrArea", 1, sa);
1222                         
1223                         pa= sa->panels.first;
1224                         while(pa) {
1225                                 writestruct(wd, DATA, "Panel", 1, pa);
1226                                 pa= pa->next;
1227                         }
1228                         
1229                         sl= sa->spacedata.first;
1230                         while(sl) {
1231                                 if(sl->spacetype==SPACE_VIEW3D) {
1232                                         View3D *v3d= (View3D*) sl;
1233                                         writestruct(wd, DATA, "View3D", 1, v3d);
1234                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1235                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1236                                 }
1237                                 else if(sl->spacetype==SPACE_IPO) {
1238                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1239                                 }
1240                                 else if(sl->spacetype==SPACE_BUTS) {
1241                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1242                                 }
1243                                 else if(sl->spacetype==SPACE_FILE) {
1244                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1245                                 }
1246                                 else if(sl->spacetype==SPACE_SEQ) {
1247                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1248                                 }
1249                                 else if(sl->spacetype==SPACE_OOPS) {
1250                                         SpaceOops *so= (SpaceOops *)sl;
1251                                         Oops *oops;
1252                                         
1253                                         /* cleanup */
1254                                         oops= so->oops.first;
1255                                         while(oops) {
1256                                                 Oops *oopsn= oops->next;
1257                                                 if(oops->id==0) {
1258                                                         BLI_remlink(&so->oops, oops);
1259                                                         free_oops(oops);
1260                                                 }
1261                                                 oops= oopsn;
1262                                         }
1263         
1264                                         /* ater cleanup, because of listbase! */
1265                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1266         
1267                                         oops= so->oops.first;
1268                                         while(oops) {
1269                                                 writestruct(wd, DATA, "Oops", 1, oops);
1270                                                 oops= oops->next;
1271                                         }
1272                                 }
1273                                 else if(sl->spacetype==SPACE_IMAGE) {
1274                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1275                                 }
1276                                 else if(sl->spacetype==SPACE_IMASEL) {
1277                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1278                                 }
1279                                 else if(sl->spacetype==SPACE_TEXT) {
1280                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1281                                 }
1282                                 else if(sl->spacetype==SPACE_SCRIPT) {
1283                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1284                                 }
1285                                 else if(sl->spacetype==SPACE_ACTION) {
1286                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1287                                 }
1288                                 else if(sl->spacetype==SPACE_SOUND) {
1289                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1290                                 }
1291                                 else if(sl->spacetype==SPACE_NLA){
1292                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1293                                 }
1294                                 sl= sl->next;
1295                         }
1296                         
1297                         sa= sa->next;
1298                 }
1299         
1300                 sc= sc->id.next;
1301         }
1302 }
1303
1304 static void write_libraries(WriteData *wd, Main *main)
1305 {
1306         ListBase *lbarray[30];
1307         ID *id;
1308         int a, tot, foundone;
1309         
1310         while(main) {
1311         
1312                 a=tot= set_listbasepointers(main, lbarray);
1313         
1314                 /* test: is lib being used */
1315                 foundone= 0;
1316                 while(tot--) {
1317                         id= lbarray[tot]->first;
1318                         while(id) {
1319                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1320                                         foundone= 1;
1321                                         break;
1322                                 }
1323                                 id= id->next;
1324                         }
1325                         if(foundone) break;
1326                 }
1327                 
1328                 if(foundone) {  
1329                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1330         
1331                         while(a--) {
1332                                 id= lbarray[a]->first;
1333                                 while(id) {
1334                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1335                                                 
1336                                                 writestruct(wd, ID_ID, "ID", 1, id);
1337                                         }
1338                                         id= id->next;
1339                                 }
1340                         }
1341                 }
1342                 
1343                 main= main->next;
1344         }
1345 }
1346
1347 static void write_bone(WriteData *wd, Bone* bone)
1348 {
1349         Bone*   cbone;
1350         
1351 //      write_constraints(wd, &bone->constraints);      
1352         
1353         // Write this bone 
1354         writestruct(wd, DATA, "Bone", 1, bone);
1355         
1356         // Write Children 
1357         cbone= bone->childbase.first;
1358         while(cbone) {
1359                 write_bone(wd, cbone);
1360                 cbone= cbone->next;
1361         }
1362 }
1363
1364 static void write_armatures(WriteData *wd, ListBase *idbase)
1365 {
1366         bArmature       *arm;
1367         Bone            *bone;
1368         
1369         arm=idbase->first;
1370         while (arm) {
1371                 if (arm->id.us>0) {
1372                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1373         
1374                         /* Direct data */
1375                         bone= arm->bonebase.first;
1376                         while(bone) {
1377                                 write_bone(wd, bone);
1378                                 bone=bone->next;
1379                         }
1380                 }
1381                 arm=arm->id.next;
1382         }
1383 }
1384
1385 static void write_actions(WriteData *wd, ListBase *idbase)
1386 {
1387         bAction                 *act;
1388         bActionChannel  *chan;
1389         act=idbase->first;
1390         while (act) {
1391                 if (act->id.us>0) {
1392                         writestruct(wd, ID_AC, "bAction", 1, act);
1393                         
1394                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1395                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1396                                 write_constraint_channels(wd, &chan->constraintChannels);
1397                         }
1398                 }
1399                 act=act->id.next;
1400         }
1401 }
1402
1403 static void write_texts(WriteData *wd, ListBase *idbase)
1404 {
1405         Text *text;
1406         TextLine *tmp;
1407         
1408         text= idbase->first;
1409         while(text) {
1410                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1411                 
1412                 /* write LibData */
1413                 writestruct(wd, ID_TXT, "Text", 1, text);
1414                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1415         
1416                 if(!(text->flags & TXT_ISEXT)) {                        
1417                         /* now write the text data, in two steps for optimization in the readfunction */
1418                         tmp= text->lines.first;
1419                         while (tmp) {
1420                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1421                                 tmp= tmp->next;
1422                         }
1423         
1424                         tmp= text->lines.first;
1425                         while (tmp) {
1426                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1427                                 tmp= tmp->next;
1428                         }
1429                 }
1430                 text= text->id.next;
1431         }
1432 }
1433
1434 static void write_sounds(WriteData *wd, ListBase *idbase)
1435 {
1436         bSound *sound;
1437         bSample *sample;
1438         
1439         PackedFile * pf;
1440         
1441         // set all samples to unsaved status
1442         
1443         sample = samples->first;
1444         while (sample) {
1445                 sample->flags |= SAMPLE_NEEDS_SAVE;
1446                 sample = sample->id.next;
1447         }
1448         
1449         sound= idbase->first;
1450         while(sound) {
1451                 if(sound->id.us>0) {
1452                         // do we need to save the packedfile as well ?
1453                         sample = sound->sample;
1454                         if (sample) {
1455                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1456                                         sound->newpackedfile = sample->packedfile;
1457                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1458                                 } else {
1459                                         sound->newpackedfile = NULL;
1460                                 }
1461                         }
1462         
1463                         /* write LibData */
1464                         writestruct(wd, ID_SO, "bSound", 1, sound);
1465         
1466                         if (sound->newpackedfile) {
1467                                 pf = sound->newpackedfile;
1468                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1469                                 writedata(wd, DATA, pf->size, pf->data);
1470                         }
1471         
1472                         if (sample) {
1473                                 sound->newpackedfile = sample->packedfile;
1474                         }
1475                 }
1476                 sound= sound->id.next;
1477         }
1478 }
1479
1480 static void write_groups(WriteData *wd, ListBase *idbase)
1481 {
1482         Group *group;
1483         GroupKey *gk;
1484         GroupObject *go;
1485         ObjectKey *ok;
1486         
1487         group= idbase->first;
1488         while(group) {
1489                 if(group->id.us>0) {
1490                         /* write LibData */
1491                         writestruct(wd, ID_GR, "Group", 1, group);
1492                         
1493                         gk= group->gkey.first;
1494                         while(gk) {
1495                                 writestruct(wd, DATA, "GroupKey", 1, gk);
1496                                 gk= gk->next;
1497                         }
1498         
1499                         go= group->gobject.first;
1500                         while(go) {
1501                                 writestruct(wd, DATA, "GroupObject", 1, go);
1502                                 go= go->next;
1503                         }
1504                         go= group->gobject.first;
1505                         while(go) {
1506                                 ok= go->okey.first;
1507                                 while(ok) {
1508                                         writestruct(wd, DATA, "ObjectKey", 1, ok);
1509                                         ok= ok->next;
1510                                 }
1511                                 go= go->next;
1512                         }
1513                         
1514                 }
1515                 group= group->id.next;
1516         }
1517 }
1518
1519 static void write_global(WriteData *wd)
1520 {
1521         FileGlobal fg;
1522         
1523         fg.curscreen= G.curscreen;
1524         fg.displaymode= R.displaymode;
1525         fg.winpos= R.winpos;
1526         fg.fileflags= G.fileflags;
1527         fg.globalf= G.f;
1528         
1529         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1530 }
1531
1532 static int write_file_handle(int handle, int write_user_block, int write_flags) 
1533 {
1534         ListBase mainlist;
1535         char buf[13];
1536         WriteData *wd;
1537         int data;
1538         
1539         mainlist.first= mainlist.last= G.main;
1540         G.main->next= NULL;
1541         
1542         blo_split_main(&mainlist);
1543         
1544         wd= bgnwrite(handle, write_flags);
1545
1546         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
1547         mywrite(wd, buf, 12);
1548         
1549         write_renderinfo(wd);
1550         
1551         write_screens  (wd, &G.main->screen);
1552         write_scenes   (wd, &G.main->scene);
1553         write_objects  (wd, &G.main->object);
1554         write_meshs    (wd, &G.main->mesh);
1555         write_curves   (wd, &G.main->curve);
1556         write_mballs   (wd, &G.main->mball);
1557         write_materials(wd, &G.main->mat);
1558         write_textures (wd, &G.main->tex);
1559         write_images   (wd, &G.main->image);
1560         write_cameras  (wd, &G.main->camera);
1561         write_lamps    (wd, &G.main->lamp);
1562         write_lattices (wd, &G.main->latt);
1563         write_ikas     (wd, &G.main->ika);
1564         write_vfonts   (wd, &G.main->vfont);
1565         write_ipos     (wd, &G.main->ipo);
1566         write_keys     (wd, &G.main->key);
1567         write_worlds   (wd, &G.main->world);
1568         write_texts    (wd, &G.main->text);
1569         write_sounds   (wd, &G.main->sound);
1570         write_groups   (wd, &G.main->group);
1571         write_armatures(wd, &G.main->armature);
1572         write_actions  (wd, &G.main->action);
1573         write_libraries(wd,  G.main->next);
1574
1575         write_global(wd);
1576         if (write_user_block) {
1577                 write_userdef(wd);
1578         }
1579         
1580         /* dna as last, because (to be implemented) test for which structs are written */
1581         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
1582         
1583         data= ENDB;
1584         mywrite(wd, &data, 4);
1585         
1586         data= 0;
1587         mywrite(wd, &data, 4);
1588         
1589         blo_join_main(&mainlist);
1590         G.main= mainlist.first;
1591         
1592         return endwrite(wd);
1593 }
1594
1595 int BLO_write_file(char *dir, int write_flags, char **error_r)
1596 {
1597         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
1598         char tempname[FILE_MAXDIR+FILE_MAXFILE];
1599         int file, fout, write_user_block;
1600 #ifdef WIN32
1601         char tmpdir[FILE_MAXDIR+FILE_MAXFILE];
1602 #endif
1603         
1604         sprintf(tempname, "%s@", dir);
1605
1606         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
1607         if(file == -1) {
1608                 *error_r= "Unable to open";
1609                 return 0;
1610         }
1611         
1612 #if 0
1613         BLI_getInstallationDir(tmpdir);
1614
1615         if(BLI_exists(tmpdir))
1616                 strcat(tmpdir,"/.blender/");
1617
1618         BLI_make_file_string(G.sce, userfilename, tmpdir, ".B.blend");
1619 #else
1620         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
1621 #endif
1622
1623         write_user_block= BLI_streq(dir, userfilename);
1624
1625         fout= write_file_handle(file, write_user_block, write_flags);
1626         close(file);
1627         
1628         if(!fout) {
1629                 if(BLI_rename(tempname, dir) < 0) {
1630                         *error_r= "Can't change old file. File saved with @";
1631                         return 0;
1632                 }
1633         } else {
1634                 remove(tempname);
1635
1636                 *error_r= "Not enough diskspace";
1637                 return 0;
1638         }
1639         
1640         return 1;
1641 }
1642
1643         /* Runtime writing */
1644
1645 #ifdef WIN32
1646 #define PATHSEPERATOR           "\\"
1647 #else
1648 #define PATHSEPERATOR           "/"
1649 #endif  
1650
1651 static char *get_install_dir(void) {
1652         extern char bprogname[];
1653         char *tmpname = BLI_strdup(bprogname);
1654         char *cut;
1655
1656 #ifdef __APPLE__
1657         cut = strstr(tmpname, ".app");
1658         if (cut) cut[0] = 0;
1659 #endif
1660
1661         cut = BLI_last_slash(tmpname);
1662         
1663         if (cut) {
1664                 cut[0] = 0;
1665                 return tmpname;
1666         } else {
1667                 MEM_freeN(tmpname);
1668                 return NULL;
1669         }
1670 }
1671
1672 static char *get_runtime_path(char *exename) {
1673         char *installpath= get_install_dir();
1674         
1675         if (!installpath) {
1676                 return NULL;
1677         } else {
1678                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
1679                 strcpy(path, installpath);
1680                 strcat(path, PATHSEPERATOR);
1681                 strcat(path, exename);
1682         
1683                 MEM_freeN(installpath);
1684         
1685                 return path;
1686         }
1687 }
1688
1689 #ifdef __APPLE__
1690
1691 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) {
1692         char *cause = NULL, *runtime = get_runtime_path(exename);
1693         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
1694         int progfd = -1;
1695         
1696         if (!runtime) {
1697                 cause= "Unable to find runtime";
1698                 goto cleanup;
1699         }
1700         
1701         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1702         if (progfd==-1) {
1703                 cause= "Unable to find runtime";
1704                 goto cleanup;
1705         }
1706
1707         sprintf(command, "/bin/cp -R %s %s", runtime, outname);
1708         if (system(command) == -1) {
1709                 cause = "Couldn't copy runtime";
1710         }
1711
1712 cleanup:
1713         if (progfd!=-1)
1714                 close(progfd);
1715         if (runtime)
1716                 MEM_freeN(runtime);
1717         
1718         if (cause) {
1719                 *cause_r= cause;
1720                 return 0;
1721         } else
1722                 return 1;
1723 }
1724
1725 void BLO_write_runtime(char *file, char *exename) {
1726         char gamename[FILE_MAXDIR+FILE_MAXFILE];
1727         int outfd = -1;
1728         char *cause= NULL;
1729         
1730         // remove existing file / bundle
1731         BLI_delete(file, NULL, TRUE);
1732         
1733         if (!recursive_copy_runtime(file, exename, &cause))
1734                 goto cleanup;
1735                 
1736         strcpy(gamename, file);
1737         strcat(gamename, "/Contents/Resources/game.blend");
1738         
1739         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1740         if (outfd != -1) {
1741
1742                 /* Ensure runtime's are built with Publisher files */
1743                 write_file_handle(outfd, 0, G.fileflags|G_FILE_PUBLISH);
1744                 
1745                 if (write(outfd, " ", 1) != 1) {
1746                         cause= "Unable to write to output file";
1747                         goto cleanup;
1748                 }
1749         } else {
1750                 cause = "Unable to open blenderfile";
1751         }
1752         
1753 cleanup:
1754         if (outfd!=-1)
1755                 close(outfd);
1756         
1757         if (cause)
1758                 error("Unable to make runtime: %s", cause);
1759 }
1760
1761 #else /* !__APPLE__ */
1762
1763 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
1764         char *cause= NULL, *runtime= get_runtime_path(exename);
1765         unsigned char buf[1024];
1766         int count, progfd= -1;
1767         
1768         if (!runtime) {
1769                 cause= "Unable to find runtime";
1770                 goto cleanup;
1771         }
1772         
1773         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
1774         if (progfd==-1) {
1775                 cause= "Unable to find runtime";
1776                 goto cleanup;
1777         }
1778
1779         while ((count= read(progfd, buf, sizeof(buf)))>0) {
1780                 if (write(handle, buf, count)!=count) {
1781                         cause= "Unable to write to output file";
1782                         goto cleanup;
1783                 }
1784         }
1785         
1786 cleanup:
1787         if (progfd!=-1)
1788                 close(progfd);
1789         if (runtime)
1790                 MEM_freeN(runtime);
1791         
1792         if (cause) {
1793                 *cause_r= cause;
1794                 return 0;
1795         } else
1796                 return 1;
1797 }
1798
1799 static int handle_write_msb_int(int handle, int i) {
1800         unsigned char buf[4];
1801         buf[0]= (i>>24)&0xFF;
1802         buf[1]= (i>>16)&0xFF;
1803         buf[2]= (i>>8)&0xFF;
1804         buf[3]= (i>>0)&0xFF;
1805         
1806         return (write(handle, buf, 4)==4);
1807 }
1808
1809 void BLO_write_runtime(char *file, char *exename) {
1810         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
1811         char *cause= NULL;
1812         int datastart;
1813         
1814         if (!outfd) {
1815                 cause= "Unable to open output file";
1816                 goto cleanup;
1817         }
1818         if (!handle_append_runtime(outfd, exename, &cause))
1819                 goto cleanup;
1820                 
1821         datastart= lseek(outfd, 0, SEEK_CUR);
1822
1823                 /* Ensure runtime's are built with Publisher files */
1824         write_file_handle(outfd, 0, G.fileflags|G_FILE_PUBLISH);
1825         
1826         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
1827                 cause= "Unable to write to output file";
1828                 goto cleanup;
1829         }
1830         
1831 cleanup:
1832         if (outfd!=-1)
1833                 close(outfd);
1834         
1835         if (cause)
1836                 error("Unable to make runtime: %s", cause);
1837 }
1838
1839 #endif /* !__APPLE__ */