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