Fluid physics for particles by Raul Fernandez Hernandez (Farsthary) and Stephen Swhit...
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <math.h>
76 #include <fcntl.h>
77 #include <stdio.h>
78 #include <string.h>
79 #include <stdlib.h>
80
81 #include "zlib.h"
82
83 #ifndef WIN32
84 #include <unistd.h>
85 #else
86 #include "winsock2.h"
87 #include <io.h>
88 #include <process.h> // for getpid
89 #include "BLI_winstuff.h"
90 #endif
91
92 #include "DNA_anim_types.h"
93 #include "DNA_armature_types.h"
94 #include "DNA_action_types.h"
95 #include "DNA_actuator_types.h"
96 #include "DNA_boid_types.h"
97 #include "DNA_brush_types.h"
98 #include "DNA_camera_types.h"
99 #include "DNA_cloth_types.h"
100 #include "DNA_color_types.h"
101 #include "DNA_constraint_types.h"
102 #include "DNA_controller_types.h"
103 #include "DNA_curve_types.h"
104 #include "DNA_customdata_types.h"
105 #include "DNA_effect_types.h"
106 #include "DNA_genfile.h"
107 #include "DNA_group_types.h"
108 #include "DNA_gpencil_types.h"
109 #include "DNA_image_types.h"
110 #include "DNA_ipo_types.h"      // XXX depreceated - animsys
111 #include "DNA_fileglobal_types.h"
112 #include "DNA_key_types.h"
113 #include "DNA_lattice_types.h"
114 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
115 #include "DNA_lamp_types.h"
116 #include "DNA_meta_types.h"
117 #include "DNA_mesh_types.h"
118 #include "DNA_meshdata_types.h"
119 #include "DNA_material_types.h"
120 #include "DNA_modifier_types.h"
121 #include "DNA_nla_types.h"
122 #include "DNA_node_types.h"
123 #include "DNA_object_types.h"
124 #include "DNA_object_force.h"
125 #include "DNA_outliner_types.h"
126 #include "DNA_packedFile_types.h"
127 #include "DNA_particle_types.h"
128 #include "DNA_property_types.h"
129 #include "DNA_scene_types.h"
130 #include "DNA_sdna_types.h"
131 #include "DNA_sequence_types.h"
132 #include "DNA_sensor_types.h"
133 #include "DNA_smoke_types.h"
134 #include "DNA_space_types.h"
135 #include "DNA_screen_types.h"
136 #include "DNA_sound_types.h"
137 #include "DNA_texture_types.h"
138 #include "DNA_text_types.h"
139 #include "DNA_view3d_types.h"
140 #include "DNA_vfont_types.h"
141 #include "DNA_userdef_types.h"
142 #include "DNA_world_types.h"
143 #include "DNA_windowmanager_types.h"
144
145 #include "MEM_guardedalloc.h" // MEM_freeN
146 #include "BLI_blenlib.h"
147 #include "BLI_linklist.h"
148 #include "BLI_bpath.h"
149
150 #include "BKE_action.h"
151 #include "BKE_blender.h"
152 #include "BKE_cloth.h"
153 #include "BKE_curve.h"
154 #include "BKE_customdata.h"
155 #include "BKE_constraint.h"
156 #include "BKE_global.h" // for G
157 #include "BKE_library.h" // for  set_listbasepointers
158 #include "BKE_main.h"
159 #include "BKE_node.h"
160 #include "BKE_packedFile.h" // for packAll
161 #include "BKE_pointcache.h"
162 #include "BKE_report.h"
163 #include "BKE_screen.h" // for waitcursor
164 #include "BKE_sequencer.h"
165 #include "BKE_sound.h" /* ... and for samples */
166 #include "BKE_utildefines.h" // for defines
167 #include "BKE_modifier.h"
168 #include "BKE_idprop.h"
169 #include "BKE_fcurve.h"
170
171 #include "BLO_writefile.h"
172 #include "BLO_readfile.h"
173 #include "BLO_undofile.h"
174
175 #include "readfile.h"
176
177 #include <errno.h>
178
179 /* ********* my write, buffered writing with minimum size chunks ************ */
180
181 #define MYWRITE_BUFFER_SIZE     100000
182 #define MYWRITE_MAX_CHUNK       32768
183
184 typedef struct {
185         struct SDNA *sdna;
186
187         int file;
188         unsigned char *buf;
189         MemFile *compare, *current;
190         
191         int tot, count, error, memsize;
192 } WriteData;
193
194 static WriteData *writedata_new(int file)
195 {
196         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
197
198                 /* XXX, see note about this in readfile.c, remove
199                  * once we have an xp lock - zr
200                  */
201
202         if (wd == NULL) return NULL;
203
204         wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
205
206         wd->file= file;
207
208         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
209
210         return wd;
211 }
212
213 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
214 {
215         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
216         if (wd->error) return;
217
218         /* memory based save */
219         if(wd->current) {
220                 add_memfilechunk(NULL, wd->current, mem, memlen);
221         }
222         else {
223                 if (write(wd->file, mem, memlen) != memlen)
224                         wd->error= 1;
225                 
226         }
227 }
228
229 static void writedata_free(WriteData *wd)
230 {
231         DNA_sdna_free(wd->sdna);
232
233         MEM_freeN(wd->buf);
234         MEM_freeN(wd);
235 }
236
237 /***/
238
239 int mywfile;
240
241 /**
242  * Low level WRITE(2) wrapper that buffers data
243  * @param adr Pointer to new chunk of data
244  * @param len Length of new chunk of data
245  * @warning Talks to other functions with global parameters
246  */
247  
248 #define MYWRITE_FLUSH           NULL
249
250 static void mywrite( WriteData *wd, void *adr, int len)
251 {
252         if (wd->error) return;
253
254         /* flush helps compression for undo-save */
255         if(adr==MYWRITE_FLUSH) {
256                 if(wd->count) {
257                         writedata_do_write(wd, wd->buf, wd->count);
258                         wd->count= 0;
259                 }
260                 return;
261         }
262
263         wd->tot+= len;
264         
265         /* if we have a single big chunk, write existing data in
266          * buffer and write out big chunk in smaller pieces */
267         if(len>MYWRITE_MAX_CHUNK) {
268                 if(wd->count) {
269                         writedata_do_write(wd, wd->buf, wd->count);
270                         wd->count= 0;
271                 }
272
273                 do {
274                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
275                         writedata_do_write(wd, adr, writelen);
276                         adr = (char*)adr + writelen;
277                         len -= writelen;
278                 } while(len > 0);
279
280                 return;
281         }
282
283         /* if data would overflow buffer, write out the buffer */
284         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
285                 writedata_do_write(wd, wd->buf, wd->count);
286                 wd->count= 0;
287         }
288
289         /* append data at end of buffer */
290         memcpy(&wd->buf[wd->count], adr, len);
291         wd->count+= len;
292 }
293
294 /**
295  * BeGiN initializer for mywrite
296  * @param file File descriptor
297  * @param write_flags Write parameters
298  * @warning Talks to other functions with global parameters
299  */
300 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
301 {
302         WriteData *wd= writedata_new(file);
303
304         if (wd == NULL) return NULL;
305
306         wd->compare= compare;
307         wd->current= current;
308         /* this inits comparing */
309         add_memfilechunk(compare, NULL, NULL, 0);
310         
311         return wd;
312 }
313
314 /**
315  * END the mywrite wrapper
316  * @return 1 if write failed
317  * @return unknown global variable otherwise
318  * @warning Talks to other functions with global parameters
319  */
320 static int endwrite(WriteData *wd)
321 {
322         int err;
323
324         if (wd->count) {
325                 writedata_do_write(wd, wd->buf, wd->count);
326                 wd->count= 0;
327         }
328         
329         err= wd->error;
330         writedata_free(wd);
331
332         return err;
333 }
334
335 /* ********** WRITE FILE ****************** */
336
337 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
338 {
339         BHead bh;
340         short *sp;
341
342         if(adr==NULL || nr==0) return;
343
344         /* init BHead */
345         bh.code= filecode;
346         bh.old= adr;
347         bh.nr= nr;
348
349         bh.SDNAnr= DNA_struct_find_nr(wd->sdna, structname);
350         if(bh.SDNAnr== -1) {
351                 printf("error: can't find SDNA code <%s>\n", structname);
352                 return;
353         }
354         sp= wd->sdna->structs[bh.SDNAnr];
355
356         bh.len= nr*wd->sdna->typelens[sp[0]];
357
358         if(bh.len==0) return;
359
360         mywrite(wd, &bh, sizeof(BHead));
361         mywrite(wd, adr, bh.len);
362 }
363
364 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
365 {
366         BHead bh;
367
368         if(adr==0) return;
369         if(len==0) return;
370
371         len+= 3;
372         len-= ( len % 4);
373
374         /* init BHead */
375         bh.code= filecode;
376         bh.old= adr;
377         bh.nr= 1;
378         bh.SDNAnr= 0;
379         bh.len= len;
380
381         mywrite(wd, &bh, sizeof(BHead));
382         if(len) mywrite(wd, adr, len);
383 }
384
385 /* *************** writing some direct data structs used in more code parts **************** */
386 /*These functions are used by blender's .blend system for file saving/loading.*/
387 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
388 void IDP_WriteProperty(IDProperty *prop, void *wd);
389 static void write_animdata(WriteData *wd, AnimData *adt); // XXX code needs reshuffling, but not before NLA SoC is merged back into 2.5
390
391 static void IDP_WriteArray(IDProperty *prop, void *wd)
392 {
393         /*REMEMBER to set totalen to len in the linking code!!*/
394         if (prop->data.pointer) {
395                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
396
397                 if(prop->subtype == IDP_GROUP) {
398                         IDProperty **array= prop->data.pointer;
399                         int a;
400
401                         for(a=0; a<prop->len; a++)
402                                 IDP_WriteProperty(array[a], wd);
403                 }
404         }
405 }
406
407 static void IDP_WriteIDPArray(IDProperty *prop, void *wd)
408 {
409         /*REMEMBER to set totalen to len in the linking code!!*/
410         if (prop->data.pointer) {
411                 IDProperty *array = prop->data.pointer;
412                 int a;
413
414                 writestruct(wd, DATA, "IDProperty", prop->len, array);
415
416                 for(a=0; a<prop->len; a++)
417                         IDP_WriteProperty_OnlyData(&array[a], wd);
418         }
419 }
420
421 static void IDP_WriteString(IDProperty *prop, void *wd)
422 {
423         /*REMEMBER to set totalen to len in the linking code!!*/
424         writedata(wd, DATA, prop->len+1, prop->data.pointer);
425 }
426
427 static void IDP_WriteGroup(IDProperty *prop, void *wd)
428 {
429         IDProperty *loop;
430
431         for (loop=prop->data.group.first; loop; loop=loop->next) {
432                 IDP_WriteProperty(loop, wd);
433         }
434 }
435
436 /* Functions to read/write ID Properties */
437 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
438 {
439         switch (prop->type) {
440                 case IDP_GROUP:
441                         IDP_WriteGroup(prop, wd);
442                         break;
443                 case IDP_STRING:
444                         IDP_WriteString(prop, wd);
445                         break;
446                 case IDP_ARRAY:
447                         IDP_WriteArray(prop, wd);
448                         break;
449                 case IDP_IDPARRAY:
450                         IDP_WriteIDPArray(prop, wd);
451                         break;
452         }
453 }
454
455 void IDP_WriteProperty(IDProperty *prop, void *wd)
456 {
457         writestruct(wd, DATA, "IDProperty", 1, prop);
458         IDP_WriteProperty_OnlyData(prop, wd);
459 }
460
461 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
462 {
463         int a;
464         
465         writestruct(wd, DATA, "CurveMapping", 1, cumap);
466         for(a=0; a<CM_TOT; a++)
467                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
468 }
469
470 /* this is only direct data, tree itself should have been written */
471 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
472 {
473         bNode *node;
474         bNodeSocket *sock;
475         bNodeLink *link;
476         
477         /* for link_list() speed, we write per list */
478         
479         if(ntree->adt) write_animdata(wd, ntree->adt);
480         
481         for(node= ntree->nodes.first; node; node= node->next)
482                 writestruct(wd, DATA, "bNode", 1, node);
483
484         for(node= ntree->nodes.first; node; node= node->next) {
485                 if(node->storage && node->type!=NODE_DYNAMIC) {
486                         /* could be handlerized at some point, now only 1 exception still */
487                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
488                                 write_curvemapping(wd, node->storage);
489                         else if(ntree->type==NTREE_COMPOSIT && ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
490                                 write_curvemapping(wd, node->storage);
491                         else if(ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) )
492                                 write_curvemapping(wd, node->storage);
493                         else 
494                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
495                 }
496                 for(sock= node->inputs.first; sock; sock= sock->next)
497                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
498                 for(sock= node->outputs.first; sock; sock= sock->next)
499                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
500         }
501         
502         for(link= ntree->links.first; link; link= link->next)
503                 writestruct(wd, DATA, "bNodeLink", 1, link);
504 }
505
506 static void current_screen_compat(Main *mainvar, bScreen **screen)
507 {
508         wmWindowManager *wm;
509         wmWindow *window;
510
511         /* find a global current screen in the first open window, to have
512          * a reasonable default for reading in older versions */
513         wm= mainvar->wm.first;
514         window= (wm)? wm->windows.first: NULL;
515         *screen= (window)? window->screen: NULL;
516 }
517
518 static void write_renderinfo(WriteData *wd, Main *mainvar)              /* for renderdeamon */
519 {
520         bScreen *curscreen;
521         Scene *sce;
522         int data[8];
523
524         /* XXX in future, handle multiple windows with multiple screnes? */
525         current_screen_compat(mainvar, &curscreen);
526
527         for(sce= mainvar->scene.first; sce; sce= sce->id.next) {
528                 if(sce->id.lib==NULL  && ( sce==curscreen->scene || (sce->r.scemode & R_BG_RENDER)) ) {
529                         data[0]= sce->r.sfra;
530                         data[1]= sce->r.efra;
531
532                         memset(data+2, 0, sizeof(int)*6);
533                         strncpy((char *)(data+2), sce->id.name+2, 21);
534
535                         writedata(wd, REND, 32, data);
536                 }
537         }
538 }
539
540 static void write_userdef(WriteData *wd)
541 {
542         bTheme *btheme;
543         wmKeyMap *keymap;
544         wmKeyMapItem *kmi;
545         bAddon *bext;
546
547         writestruct(wd, USER, "UserDef", 1, &U);
548
549         for(btheme= U.themes.first; btheme; btheme=btheme->next)
550                 writestruct(wd, DATA, "bTheme", 1, btheme);
551
552         for(keymap= U.keymaps.first; keymap; keymap=keymap->next) {
553                 writestruct(wd, DATA, "wmKeyMap", 1, keymap);
554
555                 for(kmi=keymap->items.first; kmi; kmi=kmi->next) {
556                         writestruct(wd, DATA, "wmKeyMapItem", 1, kmi);
557
558                         if(kmi->properties)
559                                 IDP_WriteProperty(kmi->properties, wd);
560                 }
561         }
562
563         for(bext= U.addons.first; bext; bext=bext->next)
564                 writestruct(wd, DATA, "bAddon", 1, bext);
565 }
566
567 static void write_boid_state(WriteData *wd, BoidState *state)
568 {
569         BoidRule *rule = state->rules.first;
570         //BoidCondition *cond = state->conditions.first;
571
572         writestruct(wd, DATA, "BoidState", 1, state);
573
574         for(; rule; rule=rule->next) {
575                 switch(rule->type) {
576                         case eBoidRuleType_Goal:
577                         case eBoidRuleType_Avoid:
578                                 writestruct(wd, DATA, "BoidRuleGoalAvoid", 1, rule);
579                                 break;
580                         case eBoidRuleType_AvoidCollision:
581                                 writestruct(wd, DATA, "BoidRuleAvoidCollision", 1, rule);
582                                 break;
583                         case eBoidRuleType_FollowLeader:
584                                 writestruct(wd, DATA, "BoidRuleFollowLeader", 1, rule);
585                                 break;
586                         case eBoidRuleType_AverageSpeed:
587                                 writestruct(wd, DATA, "BoidRuleAverageSpeed", 1, rule);
588                                 break;
589                         case eBoidRuleType_Fight:
590                                 writestruct(wd, DATA, "BoidRuleFight", 1, rule);
591                                 break;
592                         default:
593                                 writestruct(wd, DATA, "BoidRule", 1, rule);
594                                 break;
595                 }
596         }
597         //for(; cond; cond=cond->next)
598         //      writestruct(wd, DATA, "BoidCondition", 1, cond);
599 }
600 /* TODO: replace *cache with *cachelist once it's coded */
601 #define PTCACHE_WRITE_PSYS      0
602 #define PTCACHE_WRITE_CLOTH     1
603 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
604 {
605         PointCache *cache = ptcaches->first;
606         int i;
607
608         for(; cache; cache=cache->next) {
609                 writestruct(wd, DATA, "PointCache", 1, cache);
610
611                 if((cache->flag & PTCACHE_DISK_CACHE)==0) {
612                         PTCacheMem *pm = cache->mem_cache.first;
613
614                         for(; pm; pm=pm->next) {
615                                 writestruct(wd, DATA, "PTCacheMem", 1, pm);
616                                 if(pm->index_array)
617                                         writedata(wd, DATA, MEM_allocN_len(pm->index_array), pm->index_array);
618                                 
619                                 for(i=0; i<BPHYS_TOT_DATA; i++) {
620                                         if(pm->data[i] && pm->data_types & (1<<i))
621                                                 writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
622                                 }
623                         }
624                 }
625         }
626 }
627 static void write_particlesettings(WriteData *wd, ListBase *idbase)
628 {
629         ParticleSettings *part;
630         ParticleDupliWeight *dw;
631
632         part= idbase->first;
633         while(part) {
634                 if(part->id.us>0 || wd->current) {
635                         /* write LibData */
636                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
637                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
638                         if (part->adt) write_animdata(wd, part->adt);
639                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
640                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
641                         writestruct(wd, DATA, "EffectorWeights", 1, part->effector_weights);
642
643                         dw = part->dupliweights.first;
644                         for(; dw; dw=dw->next)
645                                 writestruct(wd, DATA, "ParticleDupliWeight", 1, dw);
646
647                         if(part->boids && part->phystype == PART_PHYS_BOIDS) {
648                                 BoidState *state = part->boids->states.first;
649
650                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
651
652                                 for(; state; state=state->next)
653                                         write_boid_state(wd, state);
654                         }
655                         if(part->fluid && part->phystype == PART_PHYS_FLUID){
656                                 writestruct(wd, DATA, "SPHFluidSettings", 1, part->fluid); 
657                         }
658                 }
659                 part= part->id.next;
660         }
661 }
662 static void write_particlesystems(WriteData *wd, ListBase *particles)
663 {
664         ParticleSystem *psys= particles->first;
665         ParticleTarget *pt;
666         int a;
667
668         for(; psys; psys=psys->next) {
669                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
670
671                 if(psys->particles) {
672                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
673
674                         if(psys->particles->hair) {
675                                 ParticleData *pa = psys->particles;
676
677                                 for(a=0; a<psys->totpart; a++, pa++)
678                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
679                         }
680
681                         if(psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
682                                 writestruct(wd, DATA, "BoidParticle", psys->totpart, psys->particles->boid);
683                 }
684                 pt = psys->targets.first;
685                 for(; pt; pt=pt->next)
686                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
687
688                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
689
690                 if(psys->clmd) {
691                         writestruct(wd, DATA, "ClothModifierData", 1, psys->clmd);
692                         writestruct(wd, DATA, "ClothSimSettings", 1, psys->clmd->sim_parms);
693                         writestruct(wd, DATA, "ClothCollSettings", 1, psys->clmd->coll_parms);
694                 }
695                 
696                 write_pointcaches(wd, &psys->ptcaches);
697         }
698 }
699
700 static void write_properties(WriteData *wd, ListBase *lb)
701 {
702         bProperty *prop;
703
704         prop= lb->first;
705         while(prop) {
706                 writestruct(wd, DATA, "bProperty", 1, prop);
707
708                 if(prop->poin && prop->poin != &prop->data)
709                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
710
711                 prop= prop->next;
712         }
713 }
714
715 static void write_sensors(WriteData *wd, ListBase *lb)
716 {
717         bSensor *sens;
718
719         sens= lb->first;
720         while(sens) {
721                 writestruct(wd, DATA, "bSensor", 1, sens);
722
723                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
724
725                 switch(sens->type) {
726                 case SENS_NEAR:
727                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
728                         break;
729                 case SENS_MOUSE:
730                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
731                         break;
732                 case SENS_TOUCH:
733                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
734                         break;
735                 case SENS_KEYBOARD:
736                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
737                         break;
738                 case SENS_PROPERTY:
739                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
740                         break;
741                 case SENS_ARMATURE:
742                         writestruct(wd, DATA, "bArmatureSensor", 1, sens->data);
743                         break;
744                 case SENS_ACTUATOR:
745                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
746                         break;
747                 case SENS_DELAY:
748                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
749                         break;
750                 case SENS_COLLISION:
751                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
752                         break;
753                 case SENS_RADAR:
754                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
755                         break;
756                 case SENS_RANDOM:
757                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
758                         break;
759                 case SENS_RAY:
760                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
761                         break;
762                 case SENS_MESSAGE:
763                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
764                         break;
765                 case SENS_JOYSTICK:
766                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
767                         break;
768                 default:
769                         ; /* error: don't know how to write this file */
770                 }
771
772                 sens= sens->next;
773         }
774 }
775
776 static void write_controllers(WriteData *wd, ListBase *lb)
777 {
778         bController *cont;
779
780         cont= lb->first;
781         while(cont) {
782                 writestruct(wd, DATA, "bController", 1, cont);
783
784                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
785
786                 switch(cont->type) {
787                 case CONT_EXPRESSION:
788                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
789                         break;
790                 case CONT_PYTHON:
791                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
792                         break;
793                 default:
794                         ; /* error: don't know how to write this file */
795                 }
796
797                 cont= cont->next;
798         }
799 }
800
801 static void write_actuators(WriteData *wd, ListBase *lb)
802 {
803         bActuator *act;
804
805         act= lb->first;
806         while(act) {
807                 writestruct(wd, DATA, "bActuator", 1, act);
808
809                 switch(act->type) {
810                 case ACT_ACTION:
811                 case ACT_SHAPEACTION:
812                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
813                         break;
814                 case ACT_SOUND:
815                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
816                         break;
817                 case ACT_OBJECT:
818                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
819                         break;
820                 case ACT_IPO:
821                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
822                         break;
823                 case ACT_PROPERTY:
824                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
825                         break;
826                 case ACT_CAMERA:
827                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
828                         break;
829                 case ACT_CONSTRAINT:
830                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
831                         break;
832                 case ACT_EDIT_OBJECT:
833                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
834                         break;
835                 case ACT_SCENE:
836                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
837                         break;
838                 case ACT_GROUP:
839                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
840                         break;
841                 case ACT_RANDOM:
842                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
843                         break;
844                 case ACT_MESSAGE:
845                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
846                         break;
847                 case ACT_GAME:
848                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
849                         break;
850                 case ACT_VISIBILITY:
851                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
852                         break;
853                 case ACT_2DFILTER:
854                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
855                         break;
856                 case ACT_PARENT:
857                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
858                         break;
859                 case ACT_STATE:
860                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
861                         break;
862                 case ACT_ARMATURE:
863                         writestruct(wd, DATA, "bArmatureActuator", 1, act->data);
864                         break;
865                 default:
866                         ; /* error: don't know how to write this file */
867                 }
868
869                 act= act->next;
870         }
871 }
872
873 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
874 {
875         FModifier *fcm;
876         
877         /* Modifiers */
878         for (fcm= fmodifiers->first; fcm; fcm= fcm->next) {
879                 FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
880                 
881                 /* Write the specific data */
882                 if (fmi && fcm->data) {
883                         /* firstly, just write the plain fmi->data struct */
884                         writestruct(wd, DATA, fmi->structName, 1, fcm->data);
885                         
886                         /* do any modifier specific stuff */
887                         switch (fcm->type) {
888                                 case FMODIFIER_TYPE_GENERATOR:
889                                 {
890                                         FMod_Generator *data= (FMod_Generator *)fcm->data;
891                                         
892                                         /* write coefficients array */
893                                         if (data->coefficients)
894                                                 writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
895                                 }
896                                         break;
897                                 case FMODIFIER_TYPE_ENVELOPE:
898                                 {
899                                         FMod_Envelope *data= (FMod_Envelope *)fcm->data;
900                                         
901                                         /* write envelope data */
902                                         if (data->data)
903                                                 writedata(wd, DATA, sizeof(FCM_EnvelopeData)*(data->totvert), data->data);
904                                 }
905                                         break;
906                                 case FMODIFIER_TYPE_PYTHON:
907                                 {
908                                         FMod_Python *data = (FMod_Python *)fcm->data;
909                                         
910                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
911                                          of library blocks that implement this.*/
912                                         IDP_WriteProperty(data->prop, wd);
913                                 }
914                                         break;
915                         }
916                 }
917                 
918                 /* Write the modifier */
919                 writestruct(wd, DATA, "FModifier", 1, fcm);
920         }
921 }
922
923 static void write_fcurves(WriteData *wd, ListBase *fcurves)
924 {
925         FCurve *fcu;
926         
927         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
928                 /* F-Curve */
929                 writestruct(wd, DATA, "FCurve", 1, fcu);
930                 
931                 /* curve data */
932                 if (fcu->bezt)          
933                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
934                 if (fcu->fpt)
935                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
936                         
937                 if (fcu->rna_path)
938                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
939                 
940                 /* driver data */
941                 if (fcu->driver) {
942                         ChannelDriver *driver= fcu->driver;
943                         DriverVar *dvar;
944                         
945                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
946                         
947                         /* variables */
948                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
949                                 writestruct(wd, DATA, "DriverVar", 1, dvar);
950                                 
951                                 DRIVER_TARGETS_USED_LOOPER(dvar)
952                                 {
953                                         if (dtar->rna_path)
954                                                 writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
955                                 }
956                                 DRIVER_TARGETS_LOOPER_END
957                         }
958                 }
959                 
960                 /* write F-Modifiers */
961                 write_fmodifiers(wd, &fcu->modifiers);
962         }
963 }
964
965 static void write_actions(WriteData *wd, ListBase *idbase)
966 {
967         bAction *act;
968         bActionGroup *grp;
969         TimeMarker *marker;
970         
971         for(act=idbase->first; act; act= act->id.next) {
972                 if (act->id.us>0 || wd->current) {
973                         writestruct(wd, ID_AC, "bAction", 1, act);
974                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
975                         
976                         write_fcurves(wd, &act->curves);
977                         
978                         for (grp=act->groups.first; grp; grp=grp->next) {
979                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
980                         }
981                         
982                         for (marker=act->markers.first; marker; marker=marker->next) {
983                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
984                         }
985                 }
986         }
987         
988         /* flush helps the compression for undo-save */
989         mywrite(wd, MYWRITE_FLUSH, 0);
990 }
991
992 static void write_keyingsets(WriteData *wd, ListBase *list)
993 {
994         KeyingSet *ks;
995         KS_Path *ksp;
996         
997         for (ks= list->first; ks; ks= ks->next) {
998                 /* KeyingSet */
999                 writestruct(wd, DATA, "KeyingSet", 1, ks);
1000                 
1001                 /* Paths */
1002                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1003                         /* Path */
1004                         writestruct(wd, DATA, "KS_Path", 1, ksp);
1005                         
1006                         if (ksp->rna_path)
1007                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
1008                 }
1009         }
1010 }
1011
1012 static void write_nlastrips(WriteData *wd, ListBase *strips)
1013 {
1014         NlaStrip *strip;
1015         
1016         for (strip= strips->first; strip; strip= strip->next) {
1017                 /* write the strip first */
1018                 writestruct(wd, DATA, "NlaStrip", 1, strip);
1019                 
1020                 /* write the strip's F-Curves and modifiers */
1021                 write_fcurves(wd, &strip->fcurves);
1022                 write_fmodifiers(wd, &strip->modifiers);
1023                 
1024                 /* write the strip's children */
1025                 write_nlastrips(wd, &strip->strips);
1026         }
1027 }
1028
1029 static void write_nladata(WriteData *wd, ListBase *nlabase)
1030 {
1031         NlaTrack *nlt;
1032         
1033         /* write all the tracks */
1034         for (nlt= nlabase->first; nlt; nlt= nlt->next) {
1035                 /* write the track first */
1036                 writestruct(wd, DATA, "NlaTrack", 1, nlt);
1037                 
1038                 /* write the track's strips */
1039                 write_nlastrips(wd, &nlt->strips);
1040         }
1041 }
1042
1043 static void write_animdata(WriteData *wd, AnimData *adt)
1044 {
1045         AnimOverride *aor;
1046         
1047         /* firstly, just write the AnimData block */
1048         writestruct(wd, DATA, "AnimData", 1, adt);
1049         
1050         /* write drivers */
1051         write_fcurves(wd, &adt->drivers);
1052         
1053         /* write overrides */
1054         // FIXME: are these needed?
1055         for (aor= adt->overrides.first; aor; aor= aor->next) {
1056                 /* overrides consist of base data + rna_path */
1057                 writestruct(wd, DATA, "AnimOverride", 1, aor);
1058                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
1059         }
1060         
1061         // TODO write the remaps (if they are needed)
1062         
1063         /* write NLA data */
1064         write_nladata(wd, &adt->nla_tracks);
1065 }
1066
1067 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1068 {
1069         /* sanity checks */
1070         if (mpath == NULL)
1071                 return;
1072         
1073         /* firstly, just write the motionpath struct */
1074         writestruct(wd, DATA, "bMotionPath", 1, mpath);
1075         
1076         /* now write the array of data */
1077         writestruct(wd, DATA, "bMotionPathVert", mpath->length, mpath->points);
1078 }
1079
1080 static void write_constraints(WriteData *wd, ListBase *conlist)
1081 {
1082         bConstraint *con;
1083
1084         for (con=conlist->first; con; con=con->next) {
1085                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1086                 
1087                 /* Write the specific data */
1088                 if (cti && con->data) {
1089                         /* firstly, just write the plain con->data struct */
1090                         writestruct(wd, DATA, cti->structName, 1, con->data);
1091                         
1092                         /* do any constraint specific stuff */
1093                         switch (con->type) {
1094                                 case CONSTRAINT_TYPE_PYTHON:
1095                                 {
1096                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1097                                         bConstraintTarget *ct;
1098                                         
1099                                         /* write targets */
1100                                         for (ct= data->targets.first; ct; ct= ct->next)
1101                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1102                                         
1103                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1104                                          of library blocks that implement this.*/
1105                                         IDP_WriteProperty(data->prop, wd);
1106                                 }
1107                                         break;
1108                                 case CONSTRAINT_TYPE_SPLINEIK: 
1109                                 {
1110                                         bSplineIKConstraint *data= (bSplineIKConstraint*)con->data;
1111                                         
1112                                         /* write points array */
1113                                         writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
1114                                 }
1115                                         break;
1116                         }
1117                 }
1118                 
1119                 /* Write the constraint */
1120                 writestruct(wd, DATA, "bConstraint", 1, con);
1121         }
1122 }
1123
1124 static void write_pose(WriteData *wd, bPose *pose)
1125 {
1126         bPoseChannel *chan;
1127         bActionGroup *grp;
1128
1129         /* Write each channel */
1130         if (!pose)
1131                 return;
1132
1133         /* Write channels */
1134         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1135                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1136                  of library blocks that implement this.*/
1137                 if (chan->prop)
1138                         IDP_WriteProperty(chan->prop, wd);
1139                 
1140                 write_constraints(wd, &chan->constraints);
1141                 
1142                 write_motionpath(wd, chan->mpath);
1143                 
1144                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1145                 if (chan->bone) 
1146                         chan->selectflag= chan->bone->flag & BONE_SELECTED; /* gets restored on read, for library armatures */
1147                 
1148                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1149         }
1150         
1151         /* Write groups */
1152         for (grp=pose->agroups.first; grp; grp=grp->next) 
1153                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1154
1155         /* write IK param */
1156         if (pose->ikparam) {
1157                 char *structname = (char *)get_ikparam_name(pose);
1158                 if (structname)
1159                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1160         }
1161
1162         /* Write this pose */
1163         writestruct(wd, DATA, "bPose", 1, pose);
1164
1165 }
1166
1167 static void write_defgroups(WriteData *wd, ListBase *defbase)
1168 {
1169         bDeformGroup    *defgroup;
1170
1171         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1172                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1173 }
1174
1175 static void write_modifiers(WriteData *wd, ListBase *modbase)
1176 {
1177         ModifierData *md;
1178
1179         if (modbase == NULL) return;
1180         for (md=modbase->first; md; md= md->next) {
1181                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1182                 if (mti == NULL) return;
1183                 
1184                 writestruct(wd, DATA, mti->structName, 1, md);
1185                         
1186                 if (md->type==eModifierType_Hook) {
1187                         HookModifierData *hmd = (HookModifierData*) md;
1188                         
1189                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1190                 }
1191                 else if(md->type==eModifierType_Cloth) {
1192                         ClothModifierData *clmd = (ClothModifierData*) md;
1193                         
1194                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1195                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1196                         writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
1197                         write_pointcaches(wd, &clmd->ptcaches);
1198                 } 
1199                 else if(md->type==eModifierType_Smoke) {
1200                         SmokeModifierData *smd = (SmokeModifierData*) md;
1201                         
1202                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1203                         {
1204                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1205                                 writestruct(wd, DATA, "EffectorWeights", 1, smd->domain->effector_weights);
1206                         }
1207                         else if(smd->type & MOD_SMOKE_TYPE_FLOW)
1208                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1209                         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1210                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1211
1212                         if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain)
1213                         {
1214                                 write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1215                                 write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1216                         }
1217                 } 
1218                 else if(md->type==eModifierType_Fluidsim) {
1219                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1220                         
1221                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1222                 } 
1223                 else if (md->type==eModifierType_Collision) {
1224                         
1225                         /*
1226                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1227                         // TODO: CollisionModifier should use pointcache 
1228                         // + have proper reset events before enabling this
1229                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1230                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1231                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1232                         */
1233                 }
1234                 else if (md->type==eModifierType_MeshDeform) {
1235                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1236                         int size = mmd->dyngridsize;
1237
1238                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
1239                                 mmd->bindweights);
1240                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1241                                 mmd->bindcos);
1242                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1243                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1244                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1245                 }
1246         }
1247 }
1248
1249 static void write_objects(WriteData *wd, ListBase *idbase)
1250 {
1251         Object *ob;
1252         
1253         ob= idbase->first;
1254         while(ob) {
1255                 if(ob->id.us>0 || wd->current) {
1256                         /* write LibData */
1257                         writestruct(wd, ID_OB, "Object", 1, ob);
1258                         
1259                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1260                           of library blocks that implement this.*/
1261                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1262                         
1263                         if (ob->adt) write_animdata(wd, ob->adt);
1264                         
1265                         /* direct data */
1266                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1267                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1268                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1269                         write_properties(wd, &ob->prop);
1270                         write_sensors(wd, &ob->sensors);
1271                         write_controllers(wd, &ob->controllers);
1272                         write_actuators(wd, &ob->actuators);
1273                         write_pose(wd, ob->pose);
1274                         write_defgroups(wd, &ob->defbase);
1275                         write_constraints(wd, &ob->constraints);
1276                         write_motionpath(wd, ob->mpath);
1277                         
1278                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1279                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1280                         if(ob->soft) {
1281                                 write_pointcaches(wd, &ob->soft->ptcaches);
1282                                 writestruct(wd, DATA, "EffectorWeights", 1, ob->soft->effector_weights);
1283                         }
1284                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1285                         
1286                         write_particlesystems(wd, &ob->particlesystem);
1287                         write_modifiers(wd, &ob->modifiers);
1288                 }
1289                 ob= ob->id.next;
1290         }
1291
1292         /* flush helps the compression for undo-save */
1293         mywrite(wd, MYWRITE_FLUSH, 0);
1294 }
1295
1296
1297 static void write_vfonts(WriteData *wd, ListBase *idbase)
1298 {
1299         VFont *vf;
1300         PackedFile * pf;
1301
1302         vf= idbase->first;
1303         while(vf) {
1304                 if(vf->id.us>0 || wd->current) {
1305                         /* write LibData */
1306                         writestruct(wd, ID_VF, "VFont", 1, vf);
1307                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1308
1309                         /* direct data */
1310
1311                         if (vf->packedfile) {
1312                                 pf = vf->packedfile;
1313                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1314                                 writedata(wd, DATA, pf->size, pf->data);
1315                         }
1316                 }
1317
1318                 vf= vf->id.next;
1319         }
1320 }
1321
1322
1323 static void write_keys(WriteData *wd, ListBase *idbase)
1324 {
1325         Key *key;
1326         KeyBlock *kb;
1327
1328         key= idbase->first;
1329         while(key) {
1330                 if(key->id.us>0 || wd->current) {
1331                         /* write LibData */
1332                         writestruct(wd, ID_KE, "Key", 1, key);
1333                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1334                         
1335                         if (key->adt) write_animdata(wd, key->adt);
1336                         
1337                         /* direct data */
1338                         kb= key->block.first;
1339                         while(kb) {
1340                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1341                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1342                                 kb= kb->next;
1343                         }
1344                 }
1345
1346                 key= key->id.next;
1347         }
1348         /* flush helps the compression for undo-save */
1349         mywrite(wd, MYWRITE_FLUSH, 0);
1350 }
1351
1352 static void write_cameras(WriteData *wd, ListBase *idbase)
1353 {
1354         Camera *cam;
1355
1356         cam= idbase->first;
1357         while(cam) {
1358                 if(cam->id.us>0 || wd->current) {
1359                         /* write LibData */
1360                         writestruct(wd, ID_CA, "Camera", 1, cam);
1361                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1362                         
1363                         if (cam->adt) write_animdata(wd, cam->adt);
1364                 }
1365
1366                 cam= cam->id.next;
1367         }
1368 }
1369
1370 static void write_mballs(WriteData *wd, ListBase *idbase)
1371 {
1372         MetaBall *mb;
1373         MetaElem *ml;
1374
1375         mb= idbase->first;
1376         while(mb) {
1377                 if(mb->id.us>0 || wd->current) {
1378                         /* write LibData */
1379                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1380                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1381
1382                         /* direct data */
1383                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1384                         if (mb->adt) write_animdata(wd, mb->adt);
1385
1386                         ml= mb->elems.first;
1387                         while(ml) {
1388                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1389                                 ml= ml->next;
1390                         }
1391                 }
1392                 mb= mb->id.next;
1393         }
1394 }
1395
1396 static int amount_of_chars(char *str)
1397 {
1398         // Since the data is saved as UTF-8 to the cu->str
1399         // The cu->len is not same as the strlen(cu->str)
1400         return strlen(str);
1401 }
1402
1403 static void write_curves(WriteData *wd, ListBase *idbase)
1404 {
1405         Curve *cu;
1406         Nurb *nu;
1407
1408         cu= idbase->first;
1409         while(cu) {
1410                 if(cu->id.us>0 || wd->current) {
1411                         /* write LibData */
1412                         writestruct(wd, ID_CU, "Curve", 1, cu);
1413                         
1414                         /* direct data */
1415                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1416                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1417                         if (cu->adt) write_animdata(wd, cu->adt);
1418                         
1419                         if(cu->vfont) {
1420                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1421                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1422                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1423                         }
1424                         else {
1425                                 /* is also the order of reading */
1426                                 nu= cu->nurb.first;
1427                                 while(nu) {
1428                                         writestruct(wd, DATA, "Nurb", 1, nu);
1429                                         nu= nu->next;
1430                                 }
1431                                 nu= cu->nurb.first;
1432                                 while(nu) {
1433                                         if(nu->type == CU_BEZIER)
1434                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1435                                         else {
1436                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1437                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1438                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1439                                         }
1440                                         nu= nu->next;
1441                                 }
1442                         }
1443                 }
1444                 cu= cu->id.next;
1445         }
1446
1447         /* flush helps the compression for undo-save */
1448         mywrite(wd, MYWRITE_FLUSH, 0);
1449 }
1450
1451 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1452 {
1453         if (dvlist) {
1454                 int i;
1455                 
1456                 /* Write the dvert list */
1457                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1458                 
1459                 /* Write deformation data for each dvert */
1460                 for (i=0; i<count; i++) {
1461                         if (dvlist[i].dw)
1462                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1463                 }
1464         }
1465 }
1466
1467 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1468 {
1469         if(mdlist) {
1470                 int i;
1471                 
1472                 writestruct(wd, DATA, "MDisps", count, mdlist);
1473                 if(!external) {
1474                         for(i = 0; i < count; ++i) {
1475                                 if(mdlist[i].disps)
1476                                         writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1477                         }
1478                 }
1479         }
1480 }
1481
1482 static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data, int partial_type, int partial_count)
1483 {
1484         int i;
1485
1486         /* write external customdata (not for undo) */
1487         if(data->external && !wd->current)
1488                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1489
1490         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1491
1492         for (i=0; i<data->totlayer; i++) {
1493                 CustomDataLayer *layer= &data->layers[i];
1494                 char *structname;
1495                 int structnum, datasize;
1496
1497                 if (layer->type == CD_MDEFORMVERT) {
1498                         /* layer types that allocate own memory need special handling */
1499                         write_dverts(wd, count, layer->data);
1500                 }
1501                 else if (layer->type == CD_MDISPS) {
1502                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1503                 }
1504                 else {
1505                         CustomData_file_write_info(layer->type, &structname, &structnum);
1506                         if (structnum) {
1507                                 /* when using partial visibility, the MEdge and MFace layers
1508                                    are smaller than the original, so their type and count is
1509                                    passed to make this work */
1510                                 if (layer->type != partial_type) datasize= structnum*count;
1511                                 else datasize= structnum*partial_count;
1512
1513                                 writestruct(wd, DATA, structname, datasize, layer->data);
1514                         }
1515                         else
1516                                 printf("error: this CustomDataLayer must not be written to file\n");
1517                 }
1518         }
1519
1520         if(data->external)
1521                 writestruct(wd, DATA, "CustomDataExternal", 1, data->external);
1522 }
1523
1524 static void write_meshs(WriteData *wd, ListBase *idbase)
1525 {
1526         Mesh *mesh;
1527
1528         mesh= idbase->first;
1529         while(mesh) {
1530                 if(mesh->id.us>0 || wd->current) {
1531                         /* write LibData */
1532                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1533
1534                         /* direct data */
1535                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1536
1537                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1538
1539                         if(mesh->pv) {
1540                                 write_customdata(wd, &mesh->id, mesh->pv->totvert, &mesh->vdata, -1, 0);
1541                                 write_customdata(wd, &mesh->id, mesh->pv->totedge, &mesh->edata,
1542                                         CD_MEDGE, mesh->totedge);
1543                                 write_customdata(wd, &mesh->id, mesh->pv->totface, &mesh->fdata,
1544                                         CD_MFACE, mesh->totface);
1545                         }
1546                         else {
1547                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1548                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1549                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1550                         }
1551
1552                         /* PMV data */
1553                         if(mesh->pv) {
1554                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1555                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1556                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1557                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1558                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1559                         }
1560                 }
1561                 mesh= mesh->id.next;
1562         }
1563 }
1564
1565 static void write_lattices(WriteData *wd, ListBase *idbase)
1566 {
1567         Lattice *lt;
1568         
1569         lt= idbase->first;
1570         while(lt) {
1571                 if(lt->id.us>0 || wd->current) {
1572                         /* write LibData */
1573                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1574                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1575
1576                         /* direct data */
1577                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1578                         
1579                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1580                         
1581                 }
1582                 lt= lt->id.next;
1583         }
1584 }
1585
1586 static void write_previews(WriteData *wd, PreviewImage *prv)
1587 {
1588         if (prv) {
1589                 short w = prv->w[1];
1590                 short h = prv->h[1];
1591                 unsigned int *rect = prv->rect[1];
1592                 /* don't write out large previews if not requested */
1593                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1594                         prv->w[1] = 0;
1595                         prv->h[1] = 0;
1596                         prv->rect[1] = NULL;
1597                 }
1598                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1599                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1600                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1601
1602                 /* restore preview, we still want to keep it in memory even if not saved to file */
1603                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1604                         prv->w[1] = w;
1605                         prv->h[1] = h;
1606                         prv->rect[1] = rect;
1607                 }
1608         }
1609 }
1610
1611 static void write_images(WriteData *wd, ListBase *idbase)
1612 {
1613         Image *ima;
1614         PackedFile * pf;
1615
1616
1617         ima= idbase->first;
1618         while(ima) {
1619                 if(ima->id.us>0 || wd->current) {
1620                         /* write LibData */
1621                         writestruct(wd, ID_IM, "Image", 1, ima);
1622                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1623
1624                         if (ima->packedfile) {
1625                                 pf = ima->packedfile;
1626                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1627                                 writedata(wd, DATA, pf->size, pf->data);
1628                         }
1629
1630                         write_previews(wd, ima->preview);
1631                 }
1632                 ima= ima->id.next;
1633         }
1634         /* flush helps the compression for undo-save */
1635         mywrite(wd, MYWRITE_FLUSH, 0);
1636 }
1637
1638 static void write_textures(WriteData *wd, ListBase *idbase)
1639 {
1640         Tex *tex;
1641
1642         tex= idbase->first;
1643         while(tex) {
1644                 if(tex->id.us>0 || wd->current) {
1645                         /* write LibData */
1646                         writestruct(wd, ID_TE, "Tex", 1, tex);
1647                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1648
1649                         if (tex->adt) write_animdata(wd, tex->adt);
1650
1651                         /* direct data */
1652                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1653                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1654                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1655                         if(tex->type == TEX_POINTDENSITY && tex->pd) {
1656                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
1657                                 if(tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
1658                         }
1659                         if(tex->type == TEX_VOXELDATA && tex->vd) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
1660                         
1661                         /* nodetree is integral part of texture, no libdata */
1662                         if(tex->nodetree) {
1663                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1664                                 write_nodetree(wd, tex->nodetree);
1665                         }
1666                         
1667                         write_previews(wd, tex->preview);
1668                 }
1669                 tex= tex->id.next;
1670         }
1671
1672         /* flush helps the compression for undo-save */
1673         mywrite(wd, MYWRITE_FLUSH, 0);
1674 }
1675
1676 static void write_materials(WriteData *wd, ListBase *idbase)
1677 {
1678         Material *ma;
1679         int a;
1680
1681         ma= idbase->first;
1682         while(ma) {
1683                 if(ma->id.us>0 || wd->current) {
1684                         /* write LibData */
1685                         writestruct(wd, ID_MA, "Material", 1, ma);
1686                         
1687                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1688                           of library blocks that implement this.*/
1689                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1690                           set yet :) */
1691                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1692                         
1693                         if (ma->adt) write_animdata(wd, ma->adt);
1694
1695                         for(a=0; a<MAX_MTEX; a++) {
1696                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1697                         }
1698                         
1699                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1700                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1701                         
1702                         /* nodetree is integral part of material, no libdata */
1703                         if(ma->nodetree) {
1704                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1705                                 write_nodetree(wd, ma->nodetree);
1706                         }
1707
1708                         write_previews(wd, ma->preview);                        
1709                 }
1710                 ma= ma->id.next;
1711         }
1712 }
1713
1714 static void write_worlds(WriteData *wd, ListBase *idbase)
1715 {
1716         World *wrld;
1717         int a;
1718
1719         wrld= idbase->first;
1720         while(wrld) {
1721                 if(wrld->id.us>0 || wd->current) {
1722                         /* write LibData */
1723                         writestruct(wd, ID_WO, "World", 1, wrld);
1724                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1725                         
1726                         if (wrld->adt) write_animdata(wd, wrld->adt);
1727                         
1728                         for(a=0; a<MAX_MTEX; a++) {
1729                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1730                         }
1731                         
1732                         write_previews(wd, wrld->preview);
1733                 }
1734                 wrld= wrld->id.next;
1735         }
1736 }
1737
1738 static void write_lamps(WriteData *wd, ListBase *idbase)
1739 {
1740         Lamp *la;
1741         int a;
1742
1743         la= idbase->first;
1744         while(la) {
1745                 if(la->id.us>0 || wd->current) {
1746                         /* write LibData */
1747                         writestruct(wd, ID_LA, "Lamp", 1, la);
1748                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1749                         
1750                         if (la->adt) write_animdata(wd, la->adt);
1751                         
1752                         /* direct data */
1753                         for(a=0; a<MAX_MTEX; a++) {
1754                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1755                         }
1756                         
1757                         if(la->curfalloff)
1758                                 write_curvemapping(wd, la->curfalloff); 
1759                         
1760                         write_previews(wd, la->preview);
1761                         
1762                 }
1763                 la= la->id.next;
1764         }
1765 }
1766
1767 static void write_paint(WriteData *wd, Paint *p)
1768 {
1769         if(p && p->brushes)
1770                 writedata(wd, DATA, p->brush_count * sizeof(Brush*), p->brushes);
1771 }
1772
1773 static void write_scenes(WriteData *wd, ListBase *scebase)
1774 {
1775         Scene *sce;
1776         Base *base;
1777         Editing *ed;
1778         Sequence *seq;
1779         MetaStack *ms;
1780         Strip *strip;
1781         TimeMarker *marker;
1782         TransformOrientation *ts;
1783         SceneRenderLayer *srl;
1784         ToolSettings *tos;
1785         
1786         sce= scebase->first;
1787         while(sce) {
1788                 /* write LibData */
1789                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1790                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1791                 
1792                 if (sce->adt) write_animdata(wd, sce->adt);
1793                 write_keyingsets(wd, &sce->keyingsets);
1794                 
1795                 /* direct data */
1796                 base= sce->base.first;
1797                 while(base) {
1798                         writestruct(wd, DATA, "Base", 1, base);
1799                         base= base->next;
1800                 }
1801                 
1802                 tos = sce->toolsettings;
1803                 writestruct(wd, DATA, "ToolSettings", 1, tos);
1804                 if(tos->vpaint) {
1805                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
1806                         write_paint(wd, &tos->vpaint->paint);
1807                 }
1808                 if(tos->wpaint) {
1809                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
1810                         write_paint(wd, &tos->wpaint->paint);
1811                 }
1812                 if(tos->sculpt) {
1813                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
1814                         write_paint(wd, &tos->sculpt->paint);
1815                 }
1816
1817                 write_paint(wd, &tos->imapaint.paint);
1818
1819                 ed= sce->ed;
1820                 if(ed) {
1821                         writestruct(wd, DATA, "Editing", 1, ed);
1822                         
1823                         /* reset write flags too */
1824                         
1825                         SEQ_BEGIN(ed, seq) {
1826                                 if(seq->strip) seq->strip->done= 0;
1827                                 writestruct(wd, DATA, "Sequence", 1, seq);
1828                         }
1829                         SEQ_END
1830                         
1831                         SEQ_BEGIN(ed, seq) {
1832                                 if(seq->strip && seq->strip->done==0) {
1833                                         /* write strip with 'done' at 0 because readfile */
1834                                         
1835                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1836                                         if(seq->effectdata) {
1837                                                 switch(seq->type){
1838                                                 case SEQ_COLOR:
1839                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1840                                                         break;
1841                                                 case SEQ_SPEED:
1842                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1843                                                         break;
1844                                                 case SEQ_WIPE:
1845                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1846                                                         break;
1847                                                 case SEQ_GLOW:
1848                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1849                                                         break;
1850                                                 case SEQ_TRANSFORM:
1851                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1852                                                         break;
1853                                                 }
1854                                         }
1855                                         
1856                                         strip= seq->strip;
1857                                         writestruct(wd, DATA, "Strip", 1, strip);
1858                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1859                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1860                                         }
1861                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1862                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1863                                         }
1864                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1865                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1866                                         }
1867                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1868                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1869                                         }
1870                                         if(seq->type==SEQ_IMAGE)
1871                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1872                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1873                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1874                                         
1875                                         strip->done= 1;
1876                                 }
1877                         }
1878                         SEQ_END
1879                                 
1880                         /* new; meta stack too, even when its nasty restore code */
1881                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1882                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1883                         }
1884                 }
1885                 
1886                 if (sce->r.avicodecdata) {
1887                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1888                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1889                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1890                 }
1891
1892                 if (sce->r.qtcodecdata) {
1893                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1894                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1895                 }
1896                 if (sce->r.ffcodecdata.properties) {
1897                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1898                 }
1899
1900                 /* writing dynamic list of TimeMarkers to the blend file */
1901                 for(marker= sce->markers.first; marker; marker= marker->next)
1902                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1903                 
1904                 /* writing dynamic list of TransformOrientations to the blend file */
1905                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1906                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1907                 
1908                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1909                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1910                 
1911                 if(sce->nodetree) {
1912                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1913                         write_nodetree(wd, sce->nodetree);
1914                 }
1915                 
1916                 sce= sce->id.next;
1917         }
1918         /* flush helps the compression for undo-save */
1919         mywrite(wd, MYWRITE_FLUSH, 0);
1920 }
1921
1922 static void write_gpencils(WriteData *wd, ListBase *lb)
1923 {
1924         bGPdata *gpd;
1925         bGPDlayer *gpl;
1926         bGPDframe *gpf;
1927         bGPDstroke *gps;
1928         
1929         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
1930                 /* write gpd data block to file */
1931                 writestruct(wd, ID_GD, "bGPdata", 1, gpd);
1932                 
1933                 /* write grease-pencil layers to file */
1934                 for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1935                         writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1936                         
1937                         /* write this layer's frames to file */
1938                         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1939                                 writestruct(wd, DATA, "bGPDframe", 1, gpf);
1940                                 
1941                                 /* write strokes */
1942                                 for (gps= gpf->strokes.first; gps; gps= gps->next) {
1943                                         writestruct(wd, DATA, "bGPDstroke", 1, gps);
1944                                         writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1945                                 }
1946                         }
1947                 }
1948         }
1949 }
1950
1951 static void write_windowmanagers(WriteData *wd, ListBase *lb)
1952 {
1953         wmWindowManager *wm;
1954         wmWindow *win;
1955         
1956         for(wm= lb->first; wm; wm= wm->id.next) {
1957                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
1958                 
1959                 for(win= wm->windows.first; win; win= win->next)
1960                         writestruct(wd, DATA, "wmWindow", 1, win);
1961         }
1962 }
1963
1964 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
1965 {       
1966         writestruct(wd, DATA, "ARegion", 1, ar);
1967         
1968         if(ar->regiondata) {
1969                 switch(spacetype) {
1970                         case SPACE_VIEW3D:
1971                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
1972                                         RegionView3D *rv3d= ar->regiondata;
1973                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
1974                                         
1975                                         if(rv3d->localvd)
1976                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
1977                                         if(rv3d->clipbb) 
1978                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
1979
1980                                 }
1981                                 else
1982                                         printf("regiondata write missing!\n");
1983                                 break;
1984                         default:
1985                                 printf("regiondata write missing!\n");
1986                 }
1987         }
1988 }
1989
1990 static void write_screens(WriteData *wd, ListBase *scrbase)
1991 {
1992         bScreen *sc;
1993         ScrArea *sa;
1994         ScrVert *sv;
1995         ScrEdge *se;
1996
1997         sc= scrbase->first;
1998         while(sc) {
1999                 
2000                 /* write LibData */
2001                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2002                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2003                 if (sc->id.properties) 
2004                         IDP_WriteProperty(sc->id.properties, wd);
2005                 
2006                 /* direct data */
2007                 for(sv= sc->vertbase.first; sv; sv= sv->next)
2008                         writestruct(wd, DATA, "ScrVert", 1, sv);
2009                 
2010                 for(se= sc->edgebase.first; se; se= se->next) 
2011                         writestruct(wd, DATA, "ScrEdge", 1, se);
2012                 
2013                 for(sa= sc->areabase.first; sa; sa= sa->next) {
2014                         SpaceLink *sl;
2015                         Panel *pa;
2016                         ARegion *ar;
2017                         
2018                         writestruct(wd, DATA, "ScrArea", 1, sa);
2019                         
2020                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
2021                                 write_region(wd, ar, sa->spacetype);
2022                                 
2023                                 for(pa= ar->panels.first; pa; pa= pa->next)
2024                                         writestruct(wd, DATA, "Panel", 1, pa);
2025                         }
2026                         
2027                         sl= sa->spacedata.first;
2028                         while(sl) {
2029                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
2030                                         write_region(wd, ar, sl->spacetype);
2031                                 
2032                                 if(sl->spacetype==SPACE_VIEW3D) {
2033                                         View3D *v3d= (View3D *) sl;
2034                                         BGpic *bgpic;
2035                                         writestruct(wd, DATA, "View3D", 1, v3d);
2036                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2037                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2038                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2039                                 }
2040                                 else if(sl->spacetype==SPACE_IPO) {
2041                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2042                                         ListBase tmpGhosts = sipo->ghostCurves;
2043                                         
2044                                         /* temporarily disable ghost curves when saving */
2045                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2046                                         
2047                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2048                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2049                                         
2050                                         /* reenable ghost curves */
2051                                         sipo->ghostCurves= tmpGhosts;
2052                                 }
2053                                 else if(sl->spacetype==SPACE_BUTS) {
2054                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2055                                 }
2056                                 else if(sl->spacetype==SPACE_FILE) {
2057                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2058                                 }
2059                                 else if(sl->spacetype==SPACE_SEQ) {
2060                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2061                                 }
2062                                 else if(sl->spacetype==SPACE_OUTLINER) {
2063                                         SpaceOops *so= (SpaceOops *)sl;
2064                                         
2065                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2066
2067                                         /* outliner */
2068                                         if(so->treestore) {
2069                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2070                                                 if(so->treestore->data)
2071                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2072                                         }
2073                                 }
2074                                 else if(sl->spacetype==SPACE_IMAGE) {
2075                                         SpaceImage *sima= (SpaceImage *)sl;
2076                                         
2077                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2078                                         if(sima->cumap)
2079                                                 write_curvemapping(wd, sima->cumap);
2080                                 }
2081                                 else if(sl->spacetype==SPACE_IMASEL) {
2082                                         // XXX: depreceated... do we still want to keep this?
2083                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
2084                                 }
2085                                 else if(sl->spacetype==SPACE_TEXT) {
2086                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2087                                 }
2088                                 else if(sl->spacetype==SPACE_SCRIPT) {
2089                                         SpaceScript *sc = (SpaceScript*)sl;
2090                                         sc->but_refs = NULL;
2091                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2092                                 }
2093                                 else if(sl->spacetype==SPACE_ACTION) {
2094                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2095                                 }
2096                                 else if(sl->spacetype==SPACE_SOUND) {
2097                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
2098                                 }
2099                                 else if(sl->spacetype==SPACE_NLA){
2100                                         SpaceNla *snla= (SpaceNla *)sl;
2101                                         
2102                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2103                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2104                                 }
2105                                 else if(sl->spacetype==SPACE_TIME){
2106                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2107                                 }
2108                                 else if(sl->spacetype==SPACE_NODE){
2109                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2110                                 }
2111                                 else if(sl->spacetype==SPACE_LOGIC){
2112                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2113                                 }
2114                                 else if(sl->spacetype==SPACE_CONSOLE) {
2115                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2116                                 }
2117                                 else if(sl->spacetype==SPACE_USERPREF) {
2118                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2119                                 }
2120
2121                                 sl= sl->next;
2122                         }
2123                 }
2124
2125                 sc= sc->id.next;
2126         }
2127 }
2128
2129 static void write_libraries(WriteData *wd, Main *main)
2130 {
2131         ListBase *lbarray[30];
2132         ID *id;
2133         int a, tot, foundone;
2134
2135         for(; main; main= main->next) {
2136
2137                 a=tot= set_listbasepointers(main, lbarray);
2138
2139                 /* test: is lib being used */
2140                 foundone= 0;
2141                 while(tot--) {
2142                         for(id= lbarray[tot]->first; id; id= id->next) {
2143                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2144                                         foundone= 1;
2145                                         break;
2146                                 }
2147                         }
2148                         if(foundone) break;
2149                 }
2150
2151                 if(foundone) {
2152                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2153
2154                         while(a--) {
2155                                 for(id= lbarray[a]->first; id; id= id->next) {
2156                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2157                                                 writestruct(wd, ID_ID, "ID", 1, id);
2158                                         }
2159                                 }
2160                         }
2161                 }
2162         }
2163 }
2164
2165 static void write_bone(WriteData *wd, Bone* bone)
2166 {
2167         Bone*   cbone;
2168
2169         // PATCH for upward compatibility after 2.37+ armature recode
2170         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2171                 
2172         // Write this bone
2173         writestruct(wd, DATA, "Bone", 1, bone);
2174
2175         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2176          of library blocks that implement this.*/
2177         if (bone->prop)
2178                 IDP_WriteProperty(bone->prop, wd);
2179         
2180         // Write Children
2181         cbone= bone->childbase.first;
2182         while(cbone) {
2183                 write_bone(wd, cbone);
2184                 cbone= cbone->next;
2185         }
2186 }
2187
2188 static void write_armatures(WriteData *wd, ListBase *idbase)
2189 {
2190         bArmature       *arm;
2191         Bone            *bone;
2192
2193         arm=idbase->first;
2194         while (arm) {
2195                 if (arm->id.us>0 || wd->current) {
2196                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2197                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2198
2199                         if (arm->adt) write_animdata(wd, arm->adt);
2200
2201                         /* Direct data */
2202                         bone= arm->bonebase.first;
2203                         while(bone) {
2204                                 write_bone(wd, bone);
2205                                 bone=bone->next;
2206                         }
2207                 }
2208                 arm=arm->id.next;
2209         }
2210
2211         /* flush helps the compression for undo-save */
2212         mywrite(wd, MYWRITE_FLUSH, 0);
2213 }
2214
2215 static void write_texts(WriteData *wd, ListBase *idbase)
2216 {
2217         Text *text;
2218         TextLine *tmp;
2219         TextMarker *mrk;
2220
2221         text= idbase->first;
2222         while(text) {
2223                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2224
2225                 /* write LibData */
2226                 writestruct(wd, ID_TXT, "Text", 1, text);
2227                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2228                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2229
2230                 if(!(text->flags & TXT_ISEXT)) {
2231                         /* now write the text data, in two steps for optimization in the readfunction */
2232                         tmp= text->lines.first;
2233                         while (tmp) {
2234                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2235                                 tmp= tmp->next;
2236                         }
2237
2238                         tmp= text->lines.first;
2239                         while (tmp) {
2240                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2241                                 tmp= tmp->next;
2242                         }
2243
2244                         /* write markers */
2245                         mrk= text->markers.first;
2246                         while (mrk) {
2247                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2248                                 mrk= mrk->next;
2249                         }
2250                 }
2251
2252
2253                 text= text->id.next;
2254         }
2255
2256         /* flush helps the compression for undo-save */
2257         mywrite(wd, MYWRITE_FLUSH, 0);
2258 }
2259
2260 static void write_sounds(WriteData *wd, ListBase *idbase)
2261 {
2262         bSound *sound;
2263
2264         PackedFile * pf;
2265
2266         sound= idbase->first;
2267         while(sound) {
2268                 if(sound->id.us>0 || wd->current) {
2269                         /* write LibData */
2270                         writestruct(wd, ID_SO, "bSound", 1, sound);
2271                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2272
2273                         if (sound->packedfile) {
2274                                 pf = sound->packedfile;
2275                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2276                                 writedata(wd, DATA, pf->size, pf->data);
2277                         }
2278                 }
2279                 sound= sound->id.next;
2280         }
2281
2282         /* flush helps the compression for undo-save */
2283         mywrite(wd, MYWRITE_FLUSH, 0);
2284 }
2285
2286 static void write_groups(WriteData *wd, ListBase *idbase)
2287 {
2288         Group *group;
2289         GroupObject *go;
2290
2291         for(group= idbase->first; group; group= group->id.next) {
2292                 if(group->id.us>0 || wd->current) {
2293                         /* write LibData */
2294                         writestruct(wd, ID_GR, "Group", 1, group);
2295                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2296
2297                         go= group->gobject.first;
2298                         while(go) {
2299                                 writestruct(wd, DATA, "GroupObject", 1, go);
2300                                 go= go->next;
2301                         }
2302                 }
2303         }
2304 }
2305
2306 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2307 {
2308         bNodeTree *ntree;
2309         
2310         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2311                 if (ntree->id.us>0 || wd->current) {
2312                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2313                         write_nodetree(wd, ntree);
2314                         
2315                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2316                         
2317                         if (ntree->adt) write_animdata(wd, ntree->adt);
2318                 }
2319         }
2320 }
2321
2322 static void write_brushes(WriteData *wd, ListBase *idbase)
2323 {
2324         Brush *brush;
2325         
2326         for(brush=idbase->first; brush; brush= brush->id.next) {
2327                 if(brush->id.us>0 || wd->current) {
2328                         writestruct(wd, ID_BR, "Brush", 1, brush);
2329                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2330                         
2331                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2332                         
2333                         if(brush->curve)
2334                                 write_curvemapping(wd, brush->curve);
2335                 }
2336         }
2337 }
2338
2339 static void write_scripts(WriteData *wd, ListBase *idbase)
2340 {
2341         Script *script;
2342         
2343         for(script=idbase->first; script; script= script->id.next) {
2344                 if(script->id.us>0 || wd->current) {
2345                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2346                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2347                 }
2348         }
2349 }
2350
2351 /* context is usually defined by WM, two cases where no WM is available:
2352  * - for forward compatibility, curscreen has to be saved
2353  * - for undofile, curscene needs to be saved */
2354 static void write_global(WriteData *wd, int fileflags, Main *mainvar)
2355 {
2356         FileGlobal fg;
2357         bScreen *screen;
2358         char subvstr[8];
2359         
2360         current_screen_compat(mainvar, &screen);
2361
2362         /* XXX still remap G */
2363         fg.curscreen= screen;
2364         fg.curscene= screen->scene;
2365         fg.displaymode= G.displaymode;
2366         fg.winpos= G.winpos;
2367         fg.fileflags= (fileflags & ~G_FILE_NO_UI);      // prevent to save this, is not good convention, and feature with concerns...
2368         fg.globalf= G.f;
2369         BLI_strncpy(fg.filename, mainvar->name, sizeof(fg.filename));
2370
2371         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2372         memcpy(fg.subvstr, subvstr, 4);
2373         
2374         fg.subversion= BLENDER_SUBVERSION;
2375         fg.minversion= BLENDER_MINVERSION;
2376         fg.minsubversion= BLENDER_MINSUBVERSION;
2377         fg.pads= 0; /* prevent mem checkers from complaining */
2378         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2379 }
2380
2381 /* if MemFile * there's filesave to memory */
2382 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2383                                                          int write_user_block, int write_flags)
2384 {
2385         BHead bhead;
2386         ListBase mainlist;
2387         char buf[16];
2388         WriteData *wd;
2389
2390         blo_split_main(&mainlist, mainvar);
2391
2392         wd= bgnwrite(handle, compare, current, write_flags);
2393         
2394         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2395         mywrite(wd, buf, 12);
2396
2397         write_renderinfo(wd, mainvar);
2398         write_global(wd, write_flags, mainvar);
2399
2400         /* no UI save in undo */
2401         if(current==NULL) {
2402                 write_windowmanagers(wd, &mainvar->wm);
2403                 write_screens  (wd, &mainvar->screen);
2404         }
2405         write_scenes   (wd, &mainvar->scene);
2406         write_curves   (wd, &mainvar->curve);
2407         write_mballs   (wd, &mainvar->mball);
2408         write_images   (wd, &mainvar->image);
2409         write_cameras  (wd, &mainvar->camera);
2410         write_lamps    (wd, &mainvar->lamp);
2411         write_lattices (wd, &mainvar->latt);
2412         write_vfonts   (wd, &mainvar->vfont);
2413         write_keys     (wd, &mainvar->key);
2414         write_worlds   (wd, &mainvar->world);
2415         write_texts    (wd, &mainvar->text);
2416         write_sounds   (wd, &mainvar->sound);
2417         write_groups   (wd, &mainvar->group);
2418         write_armatures(wd, &mainvar->armature);
2419         write_actions  (wd, &mainvar->action);
2420         write_objects  (wd, &mainvar->object);
2421         write_materials(wd, &mainvar->mat);
2422         write_textures (wd, &mainvar->tex);
2423         write_meshs    (wd, &mainvar->mesh);
2424         write_particlesettings(wd, &mainvar->particle);
2425         write_nodetrees(wd, &mainvar->nodetree);
2426         write_brushes  (wd, &mainvar->brush);
2427         write_scripts  (wd, &mainvar->script);
2428         write_gpencils (wd, &mainvar->gpencil);
2429         write_libraries(wd,  mainvar->next);
2430
2431         if (write_user_block) {
2432                 write_userdef(wd);
2433         }
2434                                                         
2435         /* dna as last, because (to be implemented) test for which structs are written */
2436         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2437
2438         /* end of file */
2439         memset(&bhead, 0, sizeof(BHead));
2440         bhead.code= ENDB;
2441         mywrite(wd, &bhead, sizeof(BHead));
2442
2443         blo_join_main(&mainlist);
2444
2445         return endwrite(wd);
2446 }
2447
2448 /* return: success (1) */
2449 int BLO_write_file(Main *mainvar, char *dir, int write_flags, ReportList *reports)
2450 {
2451         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2452         char tempname[FILE_MAXDIR+FILE_MAXFILE+1];
2453         int file, err, write_user_block;
2454
2455         /* open temporary file, so we preserve the original in case we crash */
2456         BLI_snprintf(tempname, sizeof(tempname), "%s@", dir);
2457
2458         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2459         if(file == -1) {
2460                 BKE_report(reports, RPT_ERROR, "Unable to open file for writing.");
2461                 return 0;
2462         }
2463
2464         /* remapping of relative paths to new file location */
2465         if(write_flags & G_FILE_RELATIVE_REMAP) {
2466                 char dir1[FILE_MAXDIR+FILE_MAXFILE];
2467                 char dir2[FILE_MAXDIR+FILE_MAXFILE];
2468                 BLI_split_dirfile(dir, dir1, NULL);
2469                 BLI_split_dirfile(mainvar->name, dir2, NULL);
2470
2471                 /* just incase there is some subtle difference */
2472                 BLI_cleanup_dir(mainvar->name, dir1);
2473                 BLI_cleanup_dir(mainvar->name, dir2);
2474
2475                 if(strcmp(dir1, dir2)==0)
2476                         write_flags &= ~G_FILE_RELATIVE_REMAP;
2477                 else
2478                         makeFilesAbsolute(G.sce, NULL);
2479         }
2480
2481         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B25.blend");
2482         write_user_block= BLI_streq(dir, userfilename);
2483
2484         if(write_flags & G_FILE_RELATIVE_REMAP)
2485                 makeFilesRelative(dir, NULL); /* note, making relative to something OTHER then G.sce */
2486
2487         /* actual file writing */
2488         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags);
2489         close(file);
2490
2491         /* rename/compress */
2492         if(!err) {
2493                 if(write_flags & G_FILE_COMPRESS) {
2494                         /* compressed files have the same ending as regular files... only from 2.4!!! */
2495                         char gzname[FILE_MAXDIR+FILE_MAXFILE+4];
2496                         int ret;
2497
2498                         /* first write compressed to separate @.gz */
2499                         BLI_snprintf(gzname, sizeof(gzname), "%s@.gz", dir);
2500                         ret = BLI_gzip(tempname, gzname);
2501                         
2502                         if(0==ret) {
2503                                 /* now rename to real file name, and delete temp @ file too */
2504                                 if(BLI_rename(gzname, dir) != 0) {
2505                                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @.");
2506                                         return 0;
2507                                 }
2508
2509                                 BLI_delete(tempname, 0, 0);
2510                         }
2511                         else if(-1==ret) {
2512                                 BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2513                                 return 0;
2514                         }
2515                         else if(-2==ret) {
2516                                 BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2517                                 return 0;
2518                         }
2519                 }
2520                 else if(BLI_rename(tempname, dir) != 0) {
2521                         BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2522                         return 0;
2523                 }
2524                 
2525         }
2526         else {
2527                 BKE_report(reports, RPT_ERROR, strerror(errno));
2528                 remove(tempname);
2529
2530                 return 0;
2531         }
2532
2533         return 1;
2534 }
2535
2536 /* return: success (1) */
2537 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags, ReportList *reports)
2538 {
2539         int err;
2540
2541         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags);
2542         
2543         if(err==0) return 1;
2544         return 0;
2545 }
2546
2547
2548         /* Runtime writing */
2549
2550 #ifdef WIN32
2551 #define PATHSEPERATOR           "\\"
2552 #else
2553 #define PATHSEPERATOR           "/"
2554 #endif
2555
2556 static char *get_runtime_path(char *exename) {
2557         char *installpath= get_install_dir();
2558
2559         if (!installpath) {
2560                 return NULL;
2561         } else {
2562                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2563
2564                 if (path == NULL) {
2565                         MEM_freeN(installpath);
2566                         return NULL;
2567                 }
2568
2569                 strcpy(path, installpath);
2570                 strcat(path, PATHSEPERATOR);
2571                 strcat(path, exename);
2572
2573                 MEM_freeN(installpath);
2574
2575                 return path;
2576         }
2577 }
2578
2579 #ifdef __APPLE__
2580
2581 static int recursive_copy_runtime(char *outname, char *exename, ReportList *reports)
2582 {
2583         char *runtime = get_runtime_path(exename);
2584         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2585         int progfd = -1, error= 0;
2586
2587         if (!runtime) {
2588                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2589                 error= 1;
2590                 goto cleanup;
2591         }
2592         //printf("runtimepath %s\n", runtime);
2593                 
2594         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2595         if (progfd==-1) {
2596                 BKE_report(reports, RPT_ERROR, "Unable to find runtime");
2597                 error= 1;
2598                 goto cleanup;
2599         }
2600
2601         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2602         //printf("command %s\n", command);
2603         if (system(command) == -1) {
2604                 BKE_report(reports, RPT_ERROR, "Couldn't copy runtime");
2605                 error= 1;
2606         }
2607
2608 cleanup:
2609         if (progfd!=-1)
2610                 close(progfd);
2611         if (runtime)
2612                 MEM_freeN(runtime);
2613
2614         return !error;
2615 }
2616
2617 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports) 
2618 {
2619         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2620         int outfd = -1, error= 0;
2621
2622         // remove existing file / bundle
2623         //printf("Delete file %s\n", file);
2624         BLI_delete(file, 0, TRUE);
2625
2626         if (!recursive_copy_runtime(file, exename, reports)) {
2627                 error= 1;
2628                 goto cleanup;
2629         }
2630
2631         strcpy(gamename, file);
2632         strcat(gamename, "/Contents/Resources/game.blend");
2633         //printf("gamename %s\n", gamename);
2634         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2635         if (outfd != -1) {
2636
2637                 write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2638
2639                 if (write(outfd, " ", 1) != 1) {
2640                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2641                         error= 1;
2642                         goto cleanup;
2643                 }
2644         } else {
2645                 BKE_report(reports, RPT_ERROR, "Unable to open blenderfile.");
2646                 error= 1;
2647         }
2648
2649 cleanup:
2650         if (outfd!=-1)
2651                 close(outfd);
2652
2653         BKE_reports_prepend(reports, "Unable to make runtime: ");
2654         return !error;
2655 }
2656
2657 #else /* !__APPLE__ */
2658
2659 static int handle_append_runtime(int handle, char *exename, ReportList *reports)
2660 {
2661         char *runtime= get_runtime_path(exename);
2662         unsigned char buf[1024];
2663         int count, progfd= -1, error= 0;
2664
2665         if (!BLI_exists(runtime)) {
2666                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.");
2667                 error= 1;
2668                 goto cleanup;
2669         }
2670
2671         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2672         if (progfd==-1) {
2673                 BKE_report(reports, RPT_ERROR, "Unable to find runtime.@");
2674                 error= 1;
2675                 goto cleanup;
2676         }
2677
2678         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2679                 if (write(handle, buf, count)!=count) {
2680                         BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2681                         error= 1;
2682                         goto cleanup;
2683                 }
2684         }
2685
2686 cleanup:
2687         if (progfd!=-1)
2688                 close(progfd);
2689         if (runtime)
2690                 MEM_freeN(runtime);
2691
2692         return !error;
2693 }
2694
2695 static int handle_write_msb_int(int handle, int i) 
2696 {
2697         unsigned char buf[4];
2698         buf[0]= (i>>24)&0xFF;
2699         buf[1]= (i>>16)&0xFF;
2700         buf[2]= (i>>8)&0xFF;
2701         buf[3]= (i>>0)&0xFF;
2702
2703         return (write(handle, buf, 4)==4);
2704 }
2705
2706 int BLO_write_runtime(Main *mainvar, char *file, char *exename, ReportList *reports)
2707 {
2708         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2709         int datastart, error= 0;
2710
2711         if (!outfd) {
2712                 BKE_report(reports, RPT_ERROR, "Unable to open output file.");
2713                 error= 1;
2714                 goto cleanup;
2715         }
2716         if (!handle_append_runtime(outfd, exename, reports)) {
2717                 error= 1;
2718                 goto cleanup;
2719         }
2720
2721         datastart= lseek(outfd, 0, SEEK_CUR);
2722
2723         write_file_handle(mainvar, outfd, NULL,NULL, 0, G.fileflags);
2724
2725         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2726                 BKE_report(reports, RPT_ERROR, "Unable to write to output file.");
2727                 error= 1;
2728                 goto cleanup;
2729         }
2730
2731 cleanup:
2732         if (outfd!=-1)
2733                 close(outfd);
2734
2735         BKE_reports_prepend(reports, "Unable to make runtime: ");
2736         return !error;
2737 }
2738
2739 #endif /* !__APPLE__ */