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