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