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