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