svn merge -r 14236:14505 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /* writefile.c
2  *
3  * .blend file writing
4  *
5  * $Id$
6  *
7  * ***** BEGIN GPL 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.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL LICENSE BLOCK *****
31  */
32
33 /*
34 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
35
36 start file:
37         BLENDER_V100    12 bytes  (versie 1.00)
38                                         V = big endian, v = little endian
39                                         _ = 4 byte pointer, - = 8 byte pointer
40
41 datablocks:             also see struct BHead
42         <bh.code>                       4 chars
43         <bh.len>                        int,  len data after BHead
44         <bh.old>                        void,  old pointer
45         <bh.SDNAnr>                     int
46         <bh.nr>                         int, in case of array: amount of structs
47         data
48         ...
49         ...
50
51 Almost all data in Blender are structures. Each struct saved
52 gets a BHead header.  With BHead the struct can be linked again
53 and compared with StructDNA .
54
55 WRITE
56
57 Preferred writing order: (not really a must, but why would you do it random?)
58 Any case: direct data is ALWAYS after the lib block
59
60 (Local file data)
61 - for each LibBlock
62         - write LibBlock
63         - write associated direct data
64 (External file data)
65 - per library
66         - write library block
67         - per LibBlock
68                 - write the ID of LibBlock
69 - write FileGlobal (some global vars)
70 - write SDNA
71 - write USER if filename is ~/.B.blend
72 */
73
74 /* for version 2.2+
75 Important to know is that 'streaming' has been added to files, for Blender Publisher
76 */
77
78
79 #ifdef HAVE_CONFIG_H
80 #include <config.h>
81 #endif
82
83 #include "zlib.h"
84
85 #ifndef WIN32
86 #include <unistd.h>
87 #else
88 #include "winsock2.h"
89 #include "BLI_winstuff.h"
90 #include <io.h>
91 #include <process.h> // for getpid
92 #endif
93
94 #include <math.h>
95 #include <fcntl.h>
96 #include <stdio.h>
97 #include <string.h>
98 #include <stdlib.h>
99
100 #include "nla.h" //  __NLA is defined
101
102 #include "DNA_armature_types.h"
103 #include "DNA_action_types.h"
104 #include "DNA_actuator_types.h"
105 #include "DNA_brush_types.h"
106 #include "DNA_camera_types.h"
107 #include "DNA_cloth_types.h"
108 #include "DNA_color_types.h"
109 #include "DNA_constraint_types.h"
110 #include "DNA_controller_types.h"
111 #include "DNA_curve_types.h"
112 #include "DNA_customdata_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_particle_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_blender.h"
156 #include "BKE_cloth.h"
157 #include "BKE_curve.h"
158 #include "BKE_customdata.h"
159 #include "BKE_constraint.h"
160 #include "BKE_global.h" // for G
161 #include "BKE_library.h" // for  set_listbasepointers
162 #include "BKE_main.h" // G.main
163 #include "BKE_node.h"
164 #include "BKE_packedFile.h" // for packAll
165 #include "BKE_screen.h" // for waitcursor
166 #include "BKE_scene.h" // for do_seq
167 #include "BKE_sound.h" /* ... and for samples */
168 #include "BKE_utildefines.h" // for defines
169 #include "BKE_modifier.h"
170 #include "BKE_idprop.h"
171 #ifdef WITH_VERSE
172 #include "BKE_verse.h"
173 #include "BIF_verse.h"
174 #endif
175
176 #include "GEN_messaging.h"
177
178 #include "BLO_writefile.h"
179 #include "BLO_readfile.h"
180 #include "BLO_undofile.h"
181
182 #include "readfile.h"
183 #include "genfile.h"
184
185 #include <errno.h>
186
187 /* ********* my write, buffered writing with minimum size chunks ************ */
188
189 #define MYWRITE_BUFFER_SIZE     100000
190 #define MYWRITE_MAX_CHUNK       32768
191
192 typedef struct {
193         struct SDNA *sdna;
194
195         int file;
196         unsigned char *buf;
197         MemFile *compare, *current;
198         
199         int tot, count, error, memsize;
200 } WriteData;
201
202 static WriteData *writedata_new(int file)
203 {
204         extern unsigned char DNAstr[];  /* DNA.c */
205         extern int DNAlen;
206
207         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
208
209                 /* XXX, see note about this in readfile.c, remove
210                  * once we have an xp lock - zr
211                  */
212
213         if (wd == NULL) return NULL;
214
215         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
216
217         wd->file= file;
218
219         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
220
221         return wd;
222 }
223
224 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
225 {
226         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
227         if (wd->error) return;
228
229         /* memory based save */
230         if(wd->current) {
231                 add_memfilechunk(NULL, wd->current, mem, memlen);
232         }
233         else {
234                 if (write(wd->file, mem, memlen) != memlen)
235                         wd->error= 1;
236                 
237         }
238 }
239
240 static void writedata_free(WriteData *wd)
241 {
242         dna_freestructDNA(wd->sdna);
243
244         MEM_freeN(wd->buf);
245         MEM_freeN(wd);
246 }
247
248 /***/
249
250 int mywfile;
251
252 /**
253  * Low level WRITE(2) wrapper that buffers data
254  * @param adr Pointer to new chunk of data
255  * @param len Length of new chunk of data
256  * @warning Talks to other functions with global parameters
257  */
258  
259 #define MYWRITE_FLUSH           NULL
260
261 static void mywrite( WriteData *wd, void *adr, int len)
262 {
263         if (wd->error) return;
264
265         /* flush helps compression for undo-save */
266         if(adr==MYWRITE_FLUSH) {
267                 if(wd->count) {
268                         writedata_do_write(wd, wd->buf, wd->count);
269                         wd->count= 0;
270                 }
271                 return;
272         }
273
274         wd->tot+= len;
275         
276         /* if we have a single big chunk, write existing data in
277          * buffer and write out big chunk in smaller pieces */
278         if(len>MYWRITE_MAX_CHUNK) {
279                 if(wd->count) {
280                         writedata_do_write(wd, wd->buf, wd->count);
281                         wd->count= 0;
282                 }
283
284                 do {
285                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
286                         writedata_do_write(wd, adr, writelen);
287                         adr = (char*)adr + writelen;
288                         len -= writelen;
289                 } while(len > 0);
290
291                 return;
292         }
293
294         /* if data would overflow buffer, write out the buffer */
295         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
296                 writedata_do_write(wd, wd->buf, wd->count);
297                 wd->count= 0;
298         }
299
300         /* append data at end of buffer */
301         memcpy(&wd->buf[wd->count], adr, len);
302         wd->count+= len;
303 }
304
305 /**
306  * BeGiN initializer for mywrite
307  * @param file File descriptor
308  * @param write_flags Write parameters
309  * @warning Talks to other functions with global parameters
310  */
311 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
312 {
313         WriteData *wd= writedata_new(file);
314
315         if (wd == NULL) return NULL;
316
317         wd->compare= compare;
318         wd->current= current;
319         /* this inits comparing */
320         add_memfilechunk(compare, NULL, NULL, 0);
321         
322         return wd;
323 }
324
325 /**
326  * END the mywrite wrapper
327  * @return 1 if write failed
328  * @return unknown global variable otherwise
329  * @warning Talks to other functions with global parameters
330  */
331 static int endwrite(WriteData *wd)
332 {
333         int err;
334
335         if (wd->count) {
336                 writedata_do_write(wd, wd->buf, wd->count);
337                 wd->count= 0;
338         }
339         
340         err= wd->error;
341         writedata_free(wd);
342
343         return err;
344 }
345
346 /* ********** WRITE FILE ****************** */
347
348 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
349 {
350         BHead bh;
351         short *sp;
352
353         if(adr==NULL || nr==0) return;
354
355         /* init BHead */
356         bh.code= filecode;
357         bh.old= adr;
358         bh.nr= nr;
359
360         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
361         if(bh.SDNAnr== -1) {
362                 printf("error: can't find SDNA code <%s>\n", structname);
363                 return;
364         }
365         sp= wd->sdna->structs[bh.SDNAnr];
366
367         bh.len= nr*wd->sdna->typelens[sp[0]];
368
369         if(bh.len==0) return;
370
371         mywrite(wd, &bh, sizeof(BHead));
372         mywrite(wd, adr, bh.len);
373 }
374
375 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
376 {
377         BHead bh;
378
379         if(adr==0) return;
380         if(len==0) return;
381
382         len+= 3;
383         len-= ( len % 4);
384
385         /* init BHead */
386         bh.code= filecode;
387         bh.old= adr;
388         bh.nr= 1;
389         bh.SDNAnr= 0;
390         bh.len= len;
391
392         mywrite(wd, &bh, sizeof(BHead));
393         if(len) mywrite(wd, adr, len);
394 }
395
396 /* *************** writing some direct data structs used in more code parts **************** */
397 /*These functions are used by blender's .blend system for file saving/loading.*/
398 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
399 void IDP_WriteProperty(IDProperty *prop, void *wd);
400
401 void IDP_WriteArray(IDProperty *prop, void *wd)
402 {
403         /*REMEMBER to set totalen to len in the linking code!!*/
404         if (prop->data.pointer) {
405                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
406         }
407 }
408
409 void IDP_WriteString(IDProperty *prop, void *wd)
410 {
411         /*REMEMBER to set totalen to len in the linking code!!*/
412         writedata(wd, DATA, prop->len+1, prop->data.pointer);
413 }
414
415 void IDP_WriteGroup(IDProperty *prop, void *wd)
416 {
417         IDProperty *loop;
418
419         for (loop=prop->data.group.first; loop; loop=loop->next) {
420                 IDP_WriteProperty(loop, wd);
421         }
422 }
423
424 /* Functions to read/write ID Properties */
425 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
426 {
427         switch (prop->type) {
428                 case IDP_GROUP:
429                         IDP_WriteGroup(prop, wd);
430                         break;
431                 case IDP_STRING:
432                         IDP_WriteString(prop, wd);
433                         break;
434                 case IDP_ARRAY:
435                         IDP_WriteArray(prop, wd);
436                         break;
437         }
438 }
439
440 void IDP_WriteProperty(IDProperty *prop, void *wd)
441 {
442         writestruct(wd, DATA, "IDProperty", 1, prop);
443         IDP_WriteProperty_OnlyData(prop, wd);
444 }
445
446 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
447 {
448         int a;
449         
450         writestruct(wd, DATA, "CurveMapping", 1, cumap);
451         for(a=0; a<CM_TOT; a++)
452                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
453 }
454
455 /* this is only direct data, tree itself should have been written */
456 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
457 {
458         bNode *node;
459         bNodeSocket *sock;
460         bNodeLink *link;
461         
462         /* for link_list() speed, we write per list */
463         
464         for(node= ntree->nodes.first; node; node= node->next)
465                 writestruct(wd, DATA, "bNode", 1, node);
466
467         for(node= ntree->nodes.first; node; node= node->next) {
468                 if(node->storage && node->type!=NODE_DYNAMIC) {
469                         /* could be handlerized at some point, now only 1 exception still */
470                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
471                                 write_curvemapping(wd, node->storage);
472                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
473                                 write_curvemapping(wd, node->storage);
474                         else 
475                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
476                 }
477                 for(sock= node->inputs.first; sock; sock= sock->next)
478                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
479                 for(sock= node->outputs.first; sock; sock= sock->next)
480                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
481         }
482         
483         for(link= ntree->links.first; link; link= link->next)
484                 writestruct(wd, DATA, "bNodeLink", 1, link);
485 }
486
487 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
488 {
489         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);
490         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);
491 }
492
493 static void write_renderinfo(WriteData *wd)             /* for renderdeamon */
494 {
495         Scene *sce;
496         int data[8];
497
498         sce= G.main->scene.first;
499         while(sce) {
500                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
501                         data[0]= sce->r.sfra;
502                         data[1]= sce->r.efra;
503
504                         memset(data+2, 0, sizeof(int)*6);
505                         strncpy((char *)(data+2), sce->id.name+2, 21);
506
507                         writedata(wd, REND, 32, data);
508                 }
509                 sce= sce->id.next;
510         }
511 }
512
513 static void write_userdef(WriteData *wd)
514 {
515         bTheme *btheme;
516
517         writestruct(wd, USER, "UserDef", 1, &U);
518
519         btheme= U.themes.first;
520         while(btheme) {
521                 writestruct(wd, DATA, "bTheme", 1, btheme);
522                 btheme= btheme->next;
523         }
524 }
525
526 static void write_effects(WriteData *wd, ListBase *lb)
527 {
528         Effect *eff;
529
530         eff= lb->first;
531         while(eff) {
532
533                 switch(eff->type) {
534                 case EFF_PARTICLE:
535                         writestruct(wd, DATA, "PartEff", 1, eff);
536                         break;
537                 default:
538                         writedata(wd, DATA, MEM_allocN_len(eff), eff);
539                 }
540
541                 eff= eff->next;
542         }
543 }
544
545 static void write_particlesettings(WriteData *wd, ListBase *idbase)
546 {
547         ParticleSettings *part;
548
549         part= idbase->first;
550         while(part) {
551                 if(part->id.us>0 || wd->current) {
552                         /* write LibData */
553                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
554                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
555                 }
556                 part= part->id.next;
557         }
558 }
559 static void write_particlesystems(WriteData *wd, ListBase *particles)
560 {
561         ParticleSystem *psys= particles->first;
562         int a;
563
564         for(; psys; psys=psys->next) {
565                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
566
567                 if(psys->particles) {
568                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
569
570                         if(psys->particles->hair) {
571                                 ParticleData *pa = psys->particles;
572
573                                 for(a=0; a<psys->totpart; a++, pa++)
574                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
575                         }
576                 }
577                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
578                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
579                 if(psys->soft) writestruct(wd, DATA, "PointCache", 1, psys->soft->pointcache);
580                 writestruct(wd, DATA, "PointCache", 1, psys->pointcache);
581         }
582 }
583
584 static void write_properties(WriteData *wd, ListBase *lb)
585 {
586         bProperty *prop;
587
588         prop= lb->first;
589         while(prop) {
590                 writestruct(wd, DATA, "bProperty", 1, prop);
591
592                 if(prop->poin && prop->poin != &prop->data)
593                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
594
595                 prop= prop->next;
596         }
597 }
598
599 static void write_sensors(WriteData *wd, ListBase *lb)
600 {
601         bSensor *sens;
602
603         sens= lb->first;
604         while(sens) {
605                 writestruct(wd, DATA, "bSensor", 1, sens);
606
607                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
608
609                 switch(sens->type) {
610                 case SENS_NEAR:
611                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
612                         break;
613                 case SENS_MOUSE:
614                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
615                         break;
616                 case SENS_TOUCH:
617                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
618                         break;
619                 case SENS_KEYBOARD:
620                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
621                         break;
622                 case SENS_PROPERTY:
623                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
624                         break;
625                 case SENS_COLLISION:
626                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
627                         break;
628                 case SENS_RADAR:
629                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
630                         break;
631                 case SENS_RANDOM:
632                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
633                         break;
634                 case SENS_RAY:
635                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
636                         break;
637                 case SENS_MESSAGE:
638                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
639                         break;
640                 case SENS_JOYSTICK:
641                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
642                         break;
643                 default:
644                         ; /* error: don't know how to write this file */
645                 }
646
647                 sens= sens->next;
648         }
649 }
650
651 static void write_controllers(WriteData *wd, ListBase *lb)
652 {
653         bController *cont;
654
655         cont= lb->first;
656         while(cont) {
657                 writestruct(wd, DATA, "bController", 1, cont);
658
659                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
660
661                 switch(cont->type) {
662                 case CONT_EXPRESSION:
663                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
664                         break;
665                 case CONT_PYTHON:
666                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
667                         break;
668                 default:
669                         ; /* error: don't know how to write this file */
670                 }
671
672                 cont= cont->next;
673         }
674 }
675
676 static void write_actuators(WriteData *wd, ListBase *lb)
677 {
678         bActuator *act;
679
680         act= lb->first;
681         while(act) {
682                 writestruct(wd, DATA, "bActuator", 1, act);
683
684                 switch(act->type) {
685                 case ACT_ACTION:
686                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
687                         break;
688                 case ACT_SOUND:
689                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
690                         break;
691                 case ACT_CD:
692                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
693                         break;
694                 case ACT_OBJECT:
695                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
696                         break;
697                 case ACT_IPO:
698                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
699                         break;
700                 case ACT_PROPERTY:
701                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
702                         break;
703                 case ACT_CAMERA:
704                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
705                         break;
706                 case ACT_CONSTRAINT:
707                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
708                         break;
709                 case ACT_EDIT_OBJECT:
710                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
711                         break;
712                 case ACT_SCENE:
713                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
714                         break;
715                 case ACT_GROUP:
716                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
717                         break;
718                 case ACT_RANDOM:
719                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
720                         break;
721                 case ACT_MESSAGE:
722                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
723                         break;
724                 case ACT_GAME:
725                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
726                         break;
727                 case ACT_VISIBILITY:
728                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
729                         break;
730                 case ACT_2DFILTER:
731                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
732                         break;
733                 case ACT_PARENT:
734                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
735                         break;
736                 default:
737                         ; /* error: don't know how to write this file */
738                 }
739
740                 act= act->next;
741         }
742 }
743
744 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
745 {
746         bActionStrip *strip;
747         bActionModifier *amod;
748         
749         for (strip=nlabase->first; strip; strip=strip->next)
750                 writestruct(wd, DATA, "bActionStrip", 1, strip);
751         for (strip=nlabase->first; strip; strip=strip->next) {
752                 for(amod= strip->modifiers.first; amod; amod= amod->next)
753                         writestruct(wd, DATA, "bActionModifier", 1, amod);
754         }
755 }
756
757 static void write_constraints(WriteData *wd, ListBase *conlist)
758 {
759         bConstraint *con;
760
761         for (con=conlist->first; con; con=con->next) {
762                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
763                 
764                 /* Write the specific data */
765                 if (cti && con->data) {
766                         /* firstly, just write the plain con->data struct */
767                         writestruct(wd, DATA, cti->structName, 1, con->data);
768                         
769                         /* do any constraint specific stuff */
770                         switch (con->type) {
771                                 case CONSTRAINT_TYPE_PYTHON:
772                                 {
773                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
774                                         bConstraintTarget *ct;
775                                         
776                                         /* write targets */
777                                         for (ct= data->targets.first; ct; ct= ct->next)
778                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
779                                         
780                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
781                                          of library blocks that implement this.*/
782                                         IDP_WriteProperty(data->prop, wd);
783                                 }
784                                 break;
785                         }
786                 }
787                 
788                 /* Write the constraint */
789                 writestruct(wd, DATA, "bConstraint", 1, con);
790         }
791 }
792
793 static void write_pose(WriteData *wd, bPose *pose)
794 {
795         bPoseChannel *chan;
796         bActionGroup *grp;
797
798         /* Write each channel */
799         if (!pose)
800                 return;
801
802         /* Write channels */
803         for (chan=pose->chanbase.first; chan; chan=chan->next) {
804                 write_constraints(wd, &chan->constraints);
805                 
806                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
807                 if (chan->bone) 
808                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
809                 
810                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
811         }
812         
813         /* Write groups */
814         for (grp=pose->agroups.first; grp; grp=grp->next) 
815                 writestruct(wd, DATA, "bActionGroup", 1, grp);
816
817         /* Write this pose */
818         writestruct(wd, DATA, "bPose", 1, pose);
819 }
820
821 static void write_defgroups(WriteData *wd, ListBase *defbase)
822 {
823         bDeformGroup    *defgroup;
824
825         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
826                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
827 }
828
829 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
830 {
831         bConstraintChannel *chan;
832
833         for (chan = chanbase->first; chan; chan=chan->next)
834                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
835
836 }
837
838 static void write_modifiers(WriteData *wd, ListBase *modbase)
839 {
840         ModifierData *md;
841
842         if (modbase == NULL) return;
843         for (md=modbase->first; md; md= md->next) {
844                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
845                 if (mti == NULL) return;
846                 
847                 writestruct(wd, DATA, mti->structName, 1, md);
848                         
849                 if (md->type==eModifierType_Hook) {
850                         HookModifierData *hmd = (HookModifierData*) md;
851                         
852                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
853                 }
854                 else if(md->type==eModifierType_Cloth) {
855                         ClothModifierData *clmd = (ClothModifierData*) md;
856                         
857                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
858                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
859                         writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
860                 } 
861                 else if (md->type==eModifierType_Collision) {
862                         
863                         /*
864                         CollisionModifierData *collmd = (CollisionModifierData*) md;
865                         // TODO: CollisionModifier should use pointcache 
866                         // + have proper reset events before enabling this
867                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
868                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
869                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
870                         */
871                 }
872                 else if (md->type==eModifierType_MeshDeform) {
873                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
874                         int size = mmd->dyngridsize;
875
876                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
877                                 mmd->bindweights);
878                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
879                                 mmd->bindcos);
880                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
881                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
882                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
883                 }
884         }
885 }
886
887 static void write_objects(WriteData *wd, ListBase *idbase)
888 {
889         Object *ob;
890         
891         ob= idbase->first;
892         while(ob) {
893                 if(ob->id.us>0 || wd->current) {
894                         /* write LibData */
895 #ifdef WITH_VERSE
896                         /* pointer at vnode stored in file have to be NULL */
897                         struct VNode *vnode = (VNode*)ob->vnode;
898                         if(vnode) ob->vnode = NULL;
899 #endif
900                         writestruct(wd, ID_OB, "Object", 1, ob);
901 #ifdef WITH_VERSE
902                         if(vnode) ob->vnode = (void*)vnode;
903 #endif
904
905                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
906                           of library blocks that implement this.*/
907                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
908
909                         /* direct data */
910                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
911                         write_effects(wd, &ob->effect);
912                         write_properties(wd, &ob->prop);
913                         write_sensors(wd, &ob->sensors);
914                         write_controllers(wd, &ob->controllers);
915                         write_actuators(wd, &ob->actuators);
916                         write_scriptlink(wd, &ob->scriptlink);
917                         write_pose(wd, ob->pose);
918                         write_defgroups(wd, &ob->defbase);
919                         write_constraints(wd, &ob->constraints);
920                         write_constraint_channels(wd, &ob->constraintChannels);
921                         write_nlastrips(wd, &ob->nlastrips);
922                         
923                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
924                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
925                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
926                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
927                         
928                         write_particlesystems(wd, &ob->particlesystem);
929                         write_modifiers(wd, &ob->modifiers);
930                 }
931                 ob= ob->id.next;
932         }
933
934         /* flush helps the compression for undo-save */
935         mywrite(wd, MYWRITE_FLUSH, 0);
936 }
937
938
939 static void write_vfonts(WriteData *wd, ListBase *idbase)
940 {
941         VFont *vf;
942         PackedFile * pf;
943
944         vf= idbase->first;
945         while(vf) {
946                 if(vf->id.us>0 || wd->current) {
947                         /* write LibData */
948                         writestruct(wd, ID_VF, "VFont", 1, vf);
949                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
950
951                         /* direct data */
952
953                         if (vf->packedfile) {
954                                 pf = vf->packedfile;
955                                 writestruct(wd, DATA, "PackedFile", 1, pf);
956                                 writedata(wd, DATA, pf->size, pf->data);
957                         }
958                 }
959
960                 vf= vf->id.next;
961         }
962 }
963
964 static void write_ipos(WriteData *wd, ListBase *idbase)
965 {
966         Ipo *ipo;
967         IpoCurve *icu;
968
969         ipo= idbase->first;
970         while(ipo) {
971                 if(ipo->id.us>0 || wd->current) {
972                         /* write LibData */
973                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
974                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
975
976                         /* direct data */
977                         icu= ipo->curve.first;
978                         while(icu) {
979                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
980                                 icu= icu->next;
981                         }
982
983                         icu= ipo->curve.first;
984                         while(icu) {
985                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
986                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
987                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
988                                 icu= icu->next;
989                         }
990                 }
991
992                 ipo= ipo->id.next;
993         }
994
995         /* flush helps the compression for undo-save */
996         mywrite(wd, MYWRITE_FLUSH, 0);
997 }
998
999 static void write_keys(WriteData *wd, ListBase *idbase)
1000 {
1001         Key *key;
1002         KeyBlock *kb;
1003
1004         key= idbase->first;
1005         while(key) {
1006                 if(key->id.us>0 || wd->current) {
1007                         /* write LibData */
1008                         writestruct(wd, ID_KE, "Key", 1, key);
1009                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1010
1011                         /* direct data */
1012                         kb= key->block.first;
1013                         while(kb) {
1014                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1015                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1016                                 kb= kb->next;
1017                         }
1018                 }
1019
1020                 key= key->id.next;
1021         }
1022         /* flush helps the compression for undo-save */
1023         mywrite(wd, MYWRITE_FLUSH, 0);
1024 }
1025
1026 static void write_cameras(WriteData *wd, ListBase *idbase)
1027 {
1028         Camera *cam;
1029
1030         cam= idbase->first;
1031         while(cam) {
1032                 if(cam->id.us>0 || wd->current) {
1033                         /* write LibData */
1034                         writestruct(wd, ID_CA, "Camera", 1, cam);
1035                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1036
1037                         /* direct data */
1038                         write_scriptlink(wd, &cam->scriptlink);
1039                 }
1040
1041                 cam= cam->id.next;
1042         }
1043 }
1044
1045 static void write_mballs(WriteData *wd, ListBase *idbase)
1046 {
1047         MetaBall *mb;
1048         MetaElem *ml;
1049
1050         mb= idbase->first;
1051         while(mb) {
1052                 if(mb->id.us>0 || wd->current) {
1053                         /* write LibData */
1054                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1055                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1056
1057                         /* direct data */
1058                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1059
1060                         ml= mb->elems.first;
1061                         while(ml) {
1062                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1063                                 ml= ml->next;
1064                         }
1065                 }
1066                 mb= mb->id.next;
1067         }
1068 }
1069
1070 int amount_of_chars(char *str)
1071 {
1072         // Since the data is saved as UTF-8 to the cu->str
1073         // The cu->len is not same as the strlen(cu->str)
1074         return strlen(str);
1075 }
1076
1077 static void write_curves(WriteData *wd, ListBase *idbase)
1078 {
1079         Curve *cu;
1080         Nurb *nu;
1081
1082         cu= idbase->first;
1083         while(cu) {
1084                 if(cu->id.us>0 || wd->current) {
1085                         /* write LibData */
1086                         writestruct(wd, ID_CU, "Curve", 1, cu);
1087
1088                         /* direct data */
1089                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1090                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1091
1092                         if(cu->vfont) {
1093                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1094                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1095                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1096                         }
1097                         else {
1098                                 /* is also the order of reading */
1099                                 nu= cu->nurb.first;
1100                                 while(nu) {
1101                                         writestruct(wd, DATA, "Nurb", 1, nu);
1102                                         nu= nu->next;
1103                                 }
1104                                 nu= cu->nurb.first;
1105                                 while(nu) {
1106                                         if( (nu->type & 7)==CU_BEZIER)
1107                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1108                                         else {
1109                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1110                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1111                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1112                                         }
1113                                         nu= nu->next;
1114                                 }
1115                         }
1116                 }
1117                 cu= cu->id.next;
1118         }
1119
1120         /* flush helps the compression for undo-save */
1121         mywrite(wd, MYWRITE_FLUSH, 0);
1122 }
1123
1124 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1125 {
1126         if (dvlist) {
1127                 int     i;
1128                 
1129                 /* Write the dvert list */
1130                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1131                 
1132                 /* Write deformation data for each dvert */
1133                 for (i=0; i<count; i++) {
1134                         if (dvlist[i].dw)
1135                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1136                 }
1137         }
1138 }
1139
1140 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1141 {
1142         int i;
1143
1144         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1145
1146         for (i=0; i<data->totlayer; i++) {
1147                 CustomDataLayer *layer= &data->layers[i];
1148                 char *structname;
1149                 int structnum, datasize;
1150
1151                 if (layer->type == CD_MDEFORMVERT) {
1152                         /* layer types that allocate own memory need special handling */
1153                         write_dverts(wd, count, layer->data);
1154                 }
1155                 else {
1156                         CustomData_file_write_info(layer->type, &structname, &structnum);
1157                         if (structnum) {
1158                                 /* when using partial visibility, the MEdge and MFace layers
1159                                    are smaller than the original, so their type and count is
1160                                    passed to make this work */
1161                                 if (layer->type != partial_type) datasize= structnum*count;
1162                                 else datasize= structnum*partial_count;
1163
1164                                 writestruct(wd, DATA, structname, datasize, layer->data);
1165                         }
1166                         else
1167                                 printf("error: this CustomDataLayer must not be written to file\n");
1168                 }
1169         }
1170 }
1171
1172 static void write_meshs(WriteData *wd, ListBase *idbase)
1173 {
1174         Mesh *mesh;
1175         MultiresLevel *lvl;
1176
1177         mesh= idbase->first;
1178         while(mesh) {
1179                 if(mesh->id.us>0 || wd->current) {
1180                         /* write LibData */
1181 #ifdef WITH_VERSE
1182                         struct VNode *vnode = (VNode*)mesh->vnode;
1183                         if(vnode) {
1184                                 /* mesh has to be created from verse geometry node*/
1185                                 create_meshdata_from_geom_node(mesh, vnode);
1186                                 /* pointer at verse node can't be stored in file */
1187                                 mesh->vnode = NULL;
1188                         }
1189 #endif
1190
1191                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1192 #ifdef WITH_VERSE
1193                         if(vnode) mesh->vnode = (void*)vnode;
1194 #endif
1195
1196                         /* direct data */
1197                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1198
1199                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1200
1201                         if(mesh->pv) {
1202                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1203                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1204                                         CD_MEDGE, mesh->totedge);
1205                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1206                                         CD_MFACE, mesh->totface);
1207                         }
1208                         else {
1209                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1210                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1211                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1212                         }
1213
1214                         /* Multires data */
1215                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1216                         if(mesh->mr) {
1217                                 lvl= mesh->mr->levels.first;
1218                                 if(lvl) {
1219                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1220                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1221                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1222                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1223                                 }
1224
1225                                 for(; lvl; lvl= lvl->next) {
1226                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1227                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1228                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1229                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1230                                 }
1231
1232                                 lvl= mesh->mr->levels.last;
1233                                 if(lvl)
1234                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1235                         }
1236
1237                         /* PMV data */
1238                         if(mesh->pv) {
1239                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1240                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1241                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1242                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1243                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1244                         }
1245                 }
1246                 mesh= mesh->id.next;
1247         }
1248 }
1249
1250 static void write_lattices(WriteData *wd, ListBase *idbase)
1251 {
1252         Lattice *lt;
1253         
1254         lt= idbase->first;
1255         while(lt) {
1256                 if(lt->id.us>0 || wd->current) {
1257                         /* write LibData */
1258                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1259                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1260
1261                         /* direct data */
1262                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1263                         
1264                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1265                         
1266                 }
1267                 lt= lt->id.next;
1268         }
1269 }
1270
1271 static void write_previews(WriteData *wd, PreviewImage *prv)
1272 {
1273         if (prv) {
1274                 short w = prv->w[1];
1275                 short h = prv->h[1];
1276                 unsigned int *rect = prv->rect[1];
1277                 /* don't write out large previews if not requested */
1278                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1279                         prv->w[1] = 0;
1280                         prv->h[1] = 0;
1281                         prv->rect[1] = NULL;
1282                 }
1283                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1284                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1285                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1286
1287                 /* restore preview, we still want to keep it in memory even if not saved to file */
1288                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1289                         prv->w[1] = w;
1290                         prv->h[1] = h;
1291                         prv->rect[1] = rect;
1292                 }
1293         }
1294 }
1295
1296 static void write_images(WriteData *wd, ListBase *idbase)
1297 {
1298         Image *ima;
1299         PackedFile * pf;
1300
1301
1302         ima= idbase->first;
1303         while(ima) {
1304                 if(ima->id.us>0 || wd->current) {
1305                         /* write LibData */
1306                         writestruct(wd, ID_IM, "Image", 1, ima);
1307                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1308
1309                         if (ima->packedfile) {
1310                                 pf = ima->packedfile;
1311                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1312                                 writedata(wd, DATA, pf->size, pf->data);
1313                         }
1314
1315                         write_previews(wd, ima->preview);
1316
1317                         }
1318                 ima= ima->id.next;
1319         }
1320         /* flush helps the compression for undo-save */
1321         mywrite(wd, MYWRITE_FLUSH, 0);
1322 }
1323
1324 static void write_textures(WriteData *wd, ListBase *idbase)
1325 {
1326         Tex *tex;
1327
1328         tex= idbase->first;
1329         while(tex) {
1330                 if(tex->id.us>0 || wd->current) {
1331                         /* write LibData */
1332                         writestruct(wd, ID_TE, "Tex", 1, tex);
1333                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1334
1335                         /* direct data */
1336                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1337                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1338                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1339                         
1340                         write_previews(wd, tex->preview);
1341                 }
1342                 tex= tex->id.next;
1343         }
1344
1345         /* flush helps the compression for undo-save */
1346         mywrite(wd, MYWRITE_FLUSH, 0);
1347 }
1348
1349 static void write_materials(WriteData *wd, ListBase *idbase)
1350 {
1351         Material *ma;
1352         int a;
1353
1354         ma= idbase->first;
1355         while(ma) {
1356                 if(ma->id.us>0 || wd->current) {
1357                         /* write LibData */
1358                         writestruct(wd, ID_MA, "Material", 1, ma);
1359                         
1360                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1361                           of library blocks that implement this.*/
1362                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1363                           set yet :) */
1364                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1365
1366                         for(a=0; a<MAX_MTEX; a++) {
1367                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1368                         }
1369                         
1370                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1371                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1372                         
1373                         write_scriptlink(wd, &ma->scriptlink);
1374                         
1375                         /* nodetree is integral part of material, no libdata */
1376                         if(ma->nodetree) {
1377                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1378                                 write_nodetree(wd, ma->nodetree);
1379                         }
1380
1381                         write_previews(wd, ma->preview);                        
1382                 }
1383                 ma= ma->id.next;
1384         }
1385 }
1386
1387 static void write_worlds(WriteData *wd, ListBase *idbase)
1388 {
1389         World *wrld;
1390         int a;
1391
1392         wrld= idbase->first;
1393         while(wrld) {
1394                 if(wrld->id.us>0 || wd->current) {
1395                         /* write LibData */
1396                         writestruct(wd, ID_WO, "World", 1, wrld);
1397                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1398
1399                         for(a=0; a<MAX_MTEX; a++) {
1400                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1401                         }
1402
1403                         write_scriptlink(wd, &wrld->scriptlink);
1404
1405                         write_previews(wd, wrld->preview);
1406
1407                 }
1408                 wrld= wrld->id.next;
1409         }
1410 }
1411
1412 static void write_lamps(WriteData *wd, ListBase *idbase)
1413 {
1414         Lamp *la;
1415         int a;
1416
1417         la= idbase->first;
1418         while(la) {
1419                 if(la->id.us>0 || wd->current) {
1420                         /* write LibData */
1421                         writestruct(wd, ID_LA, "Lamp", 1, la);
1422                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1423
1424                         /* direct data */
1425                         for(a=0; a<MAX_MTEX; a++) {
1426                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1427                         }
1428
1429                         if(la->curfalloff)
1430                                 write_curvemapping(wd, la->curfalloff); 
1431                         
1432                         write_scriptlink(wd, &la->scriptlink);
1433
1434                         write_previews(wd, la->preview);
1435
1436                 }
1437                 la= la->id.next;
1438         }
1439 }
1440
1441
1442 static void write_scenes(WriteData *wd, ListBase *scebase)
1443 {
1444         Scene *sce;
1445         Base *base;
1446         Editing *ed;
1447         Sequence *seq;
1448         MetaStack *ms;
1449         Strip *strip;
1450         TimeMarker *marker;
1451         TransformOrientation *ts;
1452         SceneRenderLayer *srl;
1453         int a;
1454         
1455         sce= scebase->first;
1456         while(sce) {
1457                 /* write LibData */
1458                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1459                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1460
1461                 /* direct data */
1462                 base= sce->base.first;
1463                 while(base) {
1464                         writestruct(wd, DATA, "Base", 1, base);
1465                         base= base->next;
1466                 }
1467
1468                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1469                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1470
1471                 for(a=0; a<MAX_MTEX; ++a)
1472                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1473                 if(sce->sculptdata.cumap)
1474                         write_curvemapping(wd, sce->sculptdata.cumap);
1475
1476                 ed= sce->ed;
1477                 if(ed) {
1478                         writestruct(wd, DATA, "Editing", 1, ed);
1479
1480                         /* reset write flags too */
1481                         WHILE_SEQ(&ed->seqbase) {
1482                                 if(seq->strip) seq->strip->done= 0;
1483                                 writestruct(wd, DATA, "Sequence", 1, seq);
1484                         }
1485                         END_SEQ
1486
1487                         WHILE_SEQ(&ed->seqbase) {
1488                                 if(seq->strip && seq->strip->done==0) {
1489                                         /* write strip with 'done' at 0 because readfile */
1490
1491                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1492                                         if(seq->effectdata) {
1493                                                 switch(seq->type){
1494                                                 case SEQ_COLOR:
1495                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1496                                                         break;
1497                                                 case SEQ_SPEED:
1498                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1499                                                         break;
1500                                                 case SEQ_WIPE:
1501                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1502                                                         break;
1503                                                 case SEQ_GLOW:
1504                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1505                                                         break;
1506                                                 case SEQ_TRANSFORM:
1507                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1508                                                         break;
1509                                                 }
1510                                         }
1511
1512                                         strip= seq->strip;
1513                                         writestruct(wd, DATA, "Strip", 1, strip);
1514                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1515                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1516                                         }
1517                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1518                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1519                                         }
1520                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1521                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1522                                         }
1523                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1524                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1525                                         }
1526                                         if(seq->type==SEQ_IMAGE)
1527                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1528                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1529                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1530
1531                                         strip->done= 1;
1532                                 }
1533                         }
1534                         END_SEQ
1535                                 
1536                         /* new; meta stack too, even when its nasty restore code */
1537                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1538                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1539                         }
1540                 }
1541
1542                 write_scriptlink(wd, &sce->scriptlink);
1543
1544                 if (sce->r.avicodecdata) {
1545                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1546                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1547                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1548                 }
1549
1550                 if (sce->r.qtcodecdata) {
1551                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1552                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1553                 }
1554
1555                 /* writing dynamic list of TimeMarkers to the blend file */
1556                 for(marker= sce->markers.first; marker; marker= marker->next)
1557                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1558                 
1559                 /* writing dynamic list of TransformOrientations to the blend file */
1560                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1561                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1562                 
1563                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1564                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1565                 
1566                 if(sce->nodetree) {
1567                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1568                         write_nodetree(wd, sce->nodetree);
1569                 }
1570                 
1571                 sce= sce->id.next;
1572         }
1573         /* flush helps the compression for undo-save */
1574         mywrite(wd, MYWRITE_FLUSH, 0);
1575 }
1576
1577 static void write_screens(WriteData *wd, ListBase *scrbase)
1578 {
1579         bScreen *sc;
1580         ScrArea *sa;
1581         ScrVert *sv;
1582         ScrEdge *se;
1583
1584         sc= scrbase->first;
1585         while(sc) {
1586                 /* write LibData */
1587                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1588                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1589
1590                 /* direct data */
1591                 sv= sc->vertbase.first;
1592                 while(sv) {
1593                         writestruct(wd, DATA, "ScrVert", 1, sv);
1594                         sv= sv->next;
1595                 }
1596
1597                 se= sc->edgebase.first;
1598                 while(se) {
1599                         writestruct(wd, DATA, "ScrEdge", 1, se);
1600                         se= se->next;
1601                 }
1602
1603                 sa= sc->areabase.first;
1604                 while(sa) {
1605                         SpaceLink *sl;
1606                         Panel *pa;
1607
1608                         writestruct(wd, DATA, "ScrArea", 1, sa);
1609
1610                         pa= sa->panels.first;
1611                         while(pa) {
1612                                 writestruct(wd, DATA, "Panel", 1, pa);
1613                                 pa= pa->next;
1614                         }
1615
1616                         /* space handler scriptlinks */
1617                         write_scriptlink(wd, &sa->scriptlink);
1618
1619                         sl= sa->spacedata.first;
1620                         while(sl) {
1621                                 if(sl->spacetype==SPACE_VIEW3D) {
1622                                         View3D *v3d= (View3D*) sl;
1623                                         writestruct(wd, DATA, "View3D", 1, v3d);
1624                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1625                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1626                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1627                                 }
1628                                 else if(sl->spacetype==SPACE_IPO) {
1629                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1630                                 }
1631                                 else if(sl->spacetype==SPACE_BUTS) {
1632                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1633                                 }
1634                                 else if(sl->spacetype==SPACE_FILE) {
1635                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1636                                 }
1637                                 else if(sl->spacetype==SPACE_SEQ) {
1638                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1639                                 }
1640                                 else if(sl->spacetype==SPACE_OOPS) {
1641                                         SpaceOops *so= (SpaceOops *)sl;
1642                                         Oops *oops;
1643
1644                                         /* cleanup */
1645                                         oops= so->oops.first;
1646                                         while(oops) {
1647                                                 Oops *oopsn= oops->next;
1648                                                 if(oops->id==0) {
1649                                                         BLI_remlink(&so->oops, oops);
1650                                                         free_oops(oops);
1651                                                 }
1652                                                 oops= oopsn;
1653                                         }
1654
1655                                         /* ater cleanup, because of listbase! */
1656                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1657
1658                                         oops= so->oops.first;
1659                                         while(oops) {
1660                                                 writestruct(wd, DATA, "Oops", 1, oops);
1661                                                 oops= oops->next;
1662                                         }
1663                                         /* outliner */
1664                                         if(so->treestore) {
1665                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1666                                                 if(so->treestore->data)
1667                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1668                                         }
1669                                 }
1670                                 else if(sl->spacetype==SPACE_IMAGE) {
1671                                         SpaceImage *sima= (SpaceImage *)sl;
1672                                         
1673                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1674                                         if(sima->cumap)
1675                                                 write_curvemapping(wd, sima->cumap);                                    
1676                                 }
1677                                 else if(sl->spacetype==SPACE_IMASEL) {
1678                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1679                                 }
1680                                 else if(sl->spacetype==SPACE_TEXT) {
1681                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1682                                 }
1683                                 else if(sl->spacetype==SPACE_SCRIPT) {
1684                                         SpaceScript *sc = (SpaceScript*)sl;
1685                                         sc->but_refs = NULL;
1686                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1687                                 }
1688                                 else if(sl->spacetype==SPACE_ACTION) {
1689                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1690                                 }
1691                                 else if(sl->spacetype==SPACE_SOUND) {
1692                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1693                                 }
1694                                 else if(sl->spacetype==SPACE_NLA){
1695                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1696                                 }
1697                                 else if(sl->spacetype==SPACE_TIME){
1698                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1699                                 }
1700                                 else if(sl->spacetype==SPACE_NODE){
1701                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1702                                 }
1703                                 sl= sl->next;
1704                         }
1705
1706                         sa= sa->next;
1707                 }
1708
1709                 sc= sc->id.next;
1710         }
1711 }
1712
1713 static void write_libraries(WriteData *wd, Main *main)
1714 {
1715         ListBase *lbarray[30];
1716         ID *id;
1717         int a, tot, foundone;
1718
1719         for(; main; main= main->next) {
1720
1721                 a=tot= set_listbasepointers(main, lbarray);
1722
1723                 /* test: is lib being used */
1724                 foundone= 0;
1725                 while(tot--) {
1726                         for(id= lbarray[tot]->first; id; id= id->next) {
1727                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1728                                         foundone= 1;
1729                                         break;
1730                                 }
1731                         }
1732                         if(foundone) break;
1733                 }
1734
1735                 if(foundone) {
1736                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1737
1738                         while(a--) {
1739                                 for(id= lbarray[a]->first; id; id= id->next) {
1740                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1741                                                 writestruct(wd, ID_ID, "ID", 1, id);
1742                                         }
1743                                 }
1744                         }
1745                 }
1746         }
1747 }
1748
1749 static void write_bone(WriteData *wd, Bone* bone)
1750 {
1751         Bone*   cbone;
1752
1753         // PATCH for upward compatibility after 2.37+ armature recode
1754         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1755                 
1756         // Write this bone
1757         writestruct(wd, DATA, "Bone", 1, bone);
1758         
1759         // Write Children
1760         cbone= bone->childbase.first;
1761         while(cbone) {
1762                 write_bone(wd, cbone);
1763                 cbone= cbone->next;
1764         }
1765 }
1766
1767 static void write_armatures(WriteData *wd, ListBase *idbase)
1768 {
1769         bArmature       *arm;
1770         Bone            *bone;
1771
1772         arm=idbase->first;
1773         while (arm) {
1774                 if (arm->id.us>0 || wd->current) {
1775                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1776                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1777
1778                         /* Direct data */
1779                         bone= arm->bonebase.first;
1780                         while(bone) {
1781                                 write_bone(wd, bone);
1782                                 bone=bone->next;
1783                         }
1784                 }
1785                 arm=arm->id.next;
1786         }
1787
1788         /* flush helps the compression for undo-save */
1789         mywrite(wd, MYWRITE_FLUSH, 0);
1790 }
1791
1792 static void write_actions(WriteData *wd, ListBase *idbase)
1793 {
1794         bAction                 *act;
1795         bActionChannel  *chan;
1796         bActionGroup    *grp;
1797         TimeMarker *marker;
1798         
1799         for(act=idbase->first; act; act= act->id.next) {
1800                 if (act->id.us>0 || wd->current) {
1801                         writestruct(wd, ID_AC, "bAction", 1, act);
1802                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1803                         
1804                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1805                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1806                                 write_constraint_channels(wd, &chan->constraintChannels);
1807                         }
1808                         
1809                         for (grp=act->groups.first; grp; grp=grp->next) {
1810                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1811                         }
1812                         
1813                         for (marker=act->markers.first; marker; marker=marker->next) {
1814                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
1815                         }
1816                 }
1817         }
1818 }
1819
1820 static void write_texts(WriteData *wd, ListBase *idbase)
1821 {
1822         Text *text;
1823         TextLine *tmp;
1824
1825         text= idbase->first;
1826         while(text) {
1827                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1828
1829                 /* write LibData */
1830                 writestruct(wd, ID_TXT, "Text", 1, text);
1831                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1832                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1833
1834                 if(!(text->flags & TXT_ISEXT)) {
1835                         /* now write the text data, in two steps for optimization in the readfunction */
1836                         tmp= text->lines.first;
1837                         while (tmp) {
1838                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1839                                 tmp= tmp->next;
1840                         }
1841
1842                         tmp= text->lines.first;
1843                         while (tmp) {
1844                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1845                                 tmp= tmp->next;
1846                         }
1847                 }
1848                 text= text->id.next;
1849         }
1850
1851         /* flush helps the compression for undo-save */
1852         mywrite(wd, MYWRITE_FLUSH, 0);
1853 }
1854
1855 static void write_sounds(WriteData *wd, ListBase *idbase)
1856 {
1857         bSound *sound;
1858         bSample *sample;
1859
1860         PackedFile * pf;
1861
1862         // set all samples to unsaved status
1863
1864         sample = samples->first; // samples is a global defined in sound.c
1865         while (sample) {
1866                 sample->flags |= SAMPLE_NEEDS_SAVE;
1867                 sample = sample->id.next;
1868         }
1869
1870         sound= idbase->first;
1871         while(sound) {
1872                 if(sound->id.us>0 || wd->current) {
1873                         // do we need to save the packedfile as well ?
1874                         sample = sound->sample;
1875                         if (sample) {
1876                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1877                                         sound->newpackedfile = sample->packedfile;
1878                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1879                                 } else {
1880                                         sound->newpackedfile = NULL;
1881                                 }
1882                         }
1883
1884                         /* write LibData */
1885                         writestruct(wd, ID_SO, "bSound", 1, sound);
1886                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1887
1888                         if (sound->newpackedfile) {
1889                                 pf = sound->newpackedfile;
1890                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1891                                 writedata(wd, DATA, pf->size, pf->data);
1892                         }
1893
1894                         if (sample) {
1895                                 sound->newpackedfile = sample->packedfile;
1896                         }
1897                 }
1898                 sound= sound->id.next;
1899         }
1900
1901         /* flush helps the compression for undo-save */
1902         mywrite(wd, MYWRITE_FLUSH, 0);
1903 }
1904
1905 static void write_groups(WriteData *wd, ListBase *idbase)
1906 {
1907         Group *group;
1908         GroupObject *go;
1909
1910         for(group= idbase->first; group; group= group->id.next) {
1911                 if(group->id.us>0 || wd->current) {
1912                         /* write LibData */
1913                         writestruct(wd, ID_GR, "Group", 1, group);
1914                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1915
1916                         go= group->gobject.first;
1917                         while(go) {
1918                                 writestruct(wd, DATA, "GroupObject", 1, go);
1919                                 go= go->next;
1920                         }
1921                 }
1922         }
1923 }
1924
1925 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1926 {
1927         bNodeTree *ntree;
1928         
1929         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1930                 if (ntree->id.us>0 || wd->current) {
1931                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1932                         write_nodetree(wd, ntree);
1933                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1934                 }
1935         }
1936 }
1937
1938 static void write_brushes(WriteData *wd, ListBase *idbase)
1939 {
1940         Brush *brush;
1941         int a;
1942         
1943         for(brush=idbase->first; brush; brush= brush->id.next) {
1944                 if(brush->id.us>0 || wd->current) {
1945                         writestruct(wd, ID_BR, "Brush", 1, brush);
1946                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1947                         for(a=0; a<MAX_MTEX; a++)
1948                                 if(brush->mtex[a])
1949                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1950                 }
1951         }
1952 }
1953
1954 static void write_scripts(WriteData *wd, ListBase *idbase)
1955 {
1956         Script *script;
1957         
1958         for(script=idbase->first; script; script= script->id.next) {
1959                 if(script->id.us>0 || wd->current) {
1960                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
1961                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
1962                 }
1963         }
1964 }
1965
1966 static void write_global(WriteData *wd)
1967 {
1968         FileGlobal fg;
1969         char subvstr[8];
1970         
1971         fg.curscreen= G.curscreen;
1972         fg.curscene= G.scene;
1973         fg.displaymode= G.displaymode;
1974         fg.winpos= G.winpos;
1975         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
1976         fg.globalf= G.f;
1977
1978         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
1979         memcpy(fg.subvstr, subvstr, 4);
1980         
1981         fg.subversion= BLENDER_SUBVERSION;
1982         fg.minversion= BLENDER_MINVERSION;
1983         fg.minsubversion= BLENDER_MINSUBVERSION;
1984         
1985         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
1986 }
1987
1988 /* if MemFile * there's filesave to memory */
1989 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
1990 {
1991         BHead bhead;
1992         ListBase mainlist;
1993         char buf[16];
1994         WriteData *wd;
1995
1996         blo_split_main(&mainlist, G.main);
1997
1998         wd= bgnwrite(handle, compare, current, write_flags);
1999         
2000         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
2001         mywrite(wd, buf, 12);
2002
2003         write_renderinfo(wd);
2004         write_global(wd);
2005
2006         if(current==NULL)
2007                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
2008         write_scenes   (wd, &G.main->scene);
2009         write_curves   (wd, &G.main->curve);
2010         write_mballs   (wd, &G.main->mball);
2011         write_images   (wd, &G.main->image);
2012         write_cameras  (wd, &G.main->camera);
2013         write_lamps    (wd, &G.main->lamp);
2014         write_lattices (wd, &G.main->latt);
2015         write_vfonts   (wd, &G.main->vfont);
2016         write_ipos     (wd, &G.main->ipo);
2017         write_keys     (wd, &G.main->key);
2018         write_worlds   (wd, &G.main->world);
2019         write_texts    (wd, &G.main->text);
2020         write_sounds   (wd, &G.main->sound);
2021         write_groups   (wd, &G.main->group);
2022         write_armatures(wd, &G.main->armature);
2023         write_actions  (wd, &G.main->action);
2024         write_objects  (wd, &G.main->object);
2025         write_materials(wd, &G.main->mat);
2026         write_textures (wd, &G.main->tex);
2027         write_meshs    (wd, &G.main->mesh);
2028         write_particlesettings(wd, &G.main->particle);
2029         write_nodetrees(wd, &G.main->nodetree);
2030         write_brushes  (wd, &G.main->brush);
2031         write_scripts  (wd, &G.main->script);
2032         if(current==NULL)       
2033                 write_libraries(wd,  G.main->next); /* no library save in undo */
2034
2035         if (write_user_block) {
2036                 write_userdef(wd);
2037         }
2038
2039         /* dna as last, because (to be implemented) test for which structs are written */
2040         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2041
2042         /* end of file */
2043         memset(&bhead, 0, sizeof(BHead));
2044         bhead.code= ENDB;
2045         mywrite(wd, &bhead, sizeof(BHead));
2046
2047         blo_join_main(&mainlist);
2048         G.main= mainlist.first;
2049
2050         return endwrite(wd);
2051 }
2052
2053 /* return: success (1) */
2054 int BLO_write_file(char *dir, int write_flags, char **error_r)
2055 {
2056         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2057         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2058         int file, err, write_user_block;
2059
2060         sprintf(tempname, "%s@", dir);
2061
2062         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2063         if(file == -1) {
2064                 *error_r= "Unable to open";
2065                 return 0;
2066         }
2067
2068         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
2069
2070         write_user_block= BLI_streq(dir, userfilename);
2071
2072         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
2073         close(file);
2074
2075         if(!err) {
2076                 if(write_flags & G_FILE_COMPRESS)
2077                 {       
2078                         // compressed files have the same ending as regular files... only from 2.4!!!
2079                         
2080                         int ret = BLI_gzip(tempname, dir);
2081                         
2082                         if(-1==ret) {
2083                                 *error_r= "Failed opening .gz file";
2084                                 return 0;
2085                         }
2086                         if(-2==ret) {
2087                                 *error_r= "Failed opening .blend file for compression";
2088                                 return 0;
2089                         }
2090                 }
2091                 else
2092                 if(BLI_rename(tempname, dir) != 0) {
2093                         *error_r= "Can't change old file. File saved with @";
2094                         return 0;
2095                 }
2096
2097                 
2098         } else {
2099                 *error_r= strerror(errno);
2100                 remove(tempname);
2101
2102                 return 0;
2103         }
2104
2105         return 1;
2106 }
2107
2108 /* return: success (1) */
2109 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
2110 {
2111         int err;
2112
2113         err= write_file_handle(0, compare, current, 0, write_flags);
2114         
2115         if(err==0) return 1;
2116         return 0;
2117 }
2118
2119
2120         /* Runtime writing */
2121
2122 #ifdef WIN32
2123 #define PATHSEPERATOR           "\\"
2124 #else
2125 #define PATHSEPERATOR           "/"
2126 #endif
2127
2128 char *get_install_dir(void) {
2129         extern char bprogname[];
2130         char *tmpname = BLI_strdup(bprogname);
2131         char *cut;
2132
2133 #ifdef __APPLE__
2134         cut = strstr(tmpname, ".app");
2135         if (cut) cut[0] = 0;
2136 #endif
2137
2138         cut = BLI_last_slash(tmpname);
2139
2140         if (cut) {
2141                 cut[0] = 0;
2142                 return tmpname;
2143         } else {
2144                 MEM_freeN(tmpname);
2145                 return NULL;
2146         }
2147 }
2148
2149 static char *get_runtime_path(char *exename) {
2150         char *installpath= get_install_dir();
2151
2152         if (!installpath) {
2153                 return NULL;
2154         } else {
2155                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2156
2157                 if (path == NULL) {
2158                         MEM_freeN(installpath);
2159                         return NULL;
2160                 }
2161
2162                 strcpy(path, installpath);
2163                 strcat(path, PATHSEPERATOR);
2164                 strcat(path, exename);
2165
2166                 MEM_freeN(installpath);
2167
2168                 return path;
2169         }
2170 }
2171
2172 #ifdef __APPLE__
2173
2174 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2175 {
2176         char *cause = NULL, *runtime = get_runtime_path(exename);
2177         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2178         int progfd = -1;
2179
2180         if (!runtime) {
2181                 cause= "Unable to find runtime";
2182                 goto cleanup;
2183         }
2184         //printf("runtimepath %s\n", runtime);
2185                 
2186         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2187         if (progfd==-1) {
2188                 cause= "Unable to find runtime";
2189                 goto cleanup;
2190         }
2191
2192         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2193         //printf("command %s\n", command);
2194         if (system(command) == -1) {
2195                 cause = "Couldn't copy runtime";
2196         }
2197
2198 cleanup:
2199         if (progfd!=-1)
2200                 close(progfd);
2201         if (runtime)
2202                 MEM_freeN(runtime);
2203
2204         if (cause) {
2205                 *cause_r= cause;
2206                 return 0;
2207         } else
2208                 return 1;
2209 }
2210
2211 void BLO_write_runtime(char *file, char *exename) {
2212         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2213         int outfd = -1;
2214         char *cause= NULL;
2215
2216         // remove existing file / bundle
2217         //printf("Delete file %s\n", file);
2218         BLI_delete(file, 0, TRUE);
2219
2220         if (!recursive_copy_runtime(file, exename, &cause))
2221                 goto cleanup;
2222
2223         strcpy(gamename, file);
2224         strcat(gamename, "/Contents/Resources/game.blend");
2225         //printf("gamename %s\n", gamename);
2226         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2227         if (outfd != -1) {
2228
2229                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2230
2231                 if (write(outfd, " ", 1) != 1) {
2232                         cause= "Unable to write to output file";
2233                         goto cleanup;
2234                 }
2235         } else {
2236                 cause = "Unable to open blenderfile";
2237         }
2238
2239 cleanup:
2240         if (outfd!=-1)
2241                 close(outfd);
2242
2243         if (cause)
2244                 error("Unable to make runtime: %s", cause);
2245 }
2246
2247 #else /* !__APPLE__ */
2248
2249 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2250         char *cause= NULL, *runtime= get_runtime_path(exename);
2251         unsigned char buf[1024];
2252         int count, progfd= -1;
2253
2254         if (!runtime) {
2255                 cause= "Unable to find runtime";
2256                 goto cleanup;
2257         }
2258
2259         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2260         if (progfd==-1) {
2261                 cause= "Unable to find runtime";
2262                 goto cleanup;
2263         }
2264
2265         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2266                 if (write(handle, buf, count)!=count) {
2267                         cause= "Unable to write to output file";
2268                         goto cleanup;
2269                 }
2270         }
2271
2272 cleanup:
2273         if (progfd!=-1)
2274                 close(progfd);
2275         if (runtime)
2276                 MEM_freeN(runtime);
2277
2278         if (cause) {
2279                 *cause_r= cause;
2280                 return 0;
2281         } else
2282                 return 1;
2283 }
2284
2285 static int handle_write_msb_int(int handle, int i) {
2286         unsigned char buf[4];
2287         buf[0]= (i>>24)&0xFF;
2288         buf[1]= (i>>16)&0xFF;
2289         buf[2]= (i>>8)&0xFF;
2290         buf[3]= (i>>0)&0xFF;
2291
2292         return (write(handle, buf, 4)==4);
2293 }
2294
2295 void BLO_write_runtime(char *file, char *exename) {
2296         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2297         char *cause= NULL;
2298         int datastart;
2299
2300         if (!outfd) {
2301                 cause= "Unable to open output file";
2302                 goto cleanup;
2303         }
2304         if (!handle_append_runtime(outfd, exename, &cause))
2305                 goto cleanup;
2306
2307         datastart= lseek(outfd, 0, SEEK_CUR);
2308
2309         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2310
2311         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2312                 cause= "Unable to write to output file";
2313                 goto cleanup;
2314         }
2315
2316 cleanup:
2317         if (outfd!=-1)
2318                 close(outfd);
2319
2320         if (cause)
2321                 error("Unable to make runtime: %s", cause);
2322 }
2323
2324 #endif /* !__APPLE__ */