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