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