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