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