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