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