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