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