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