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