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