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