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