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