Merge branch 'master' into blender2.8
[blender.git] / source / blender / alembic / intern / abc_exporter.cc
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  * Contributor(s): Esteban Tovagliari, Cedric Paille, Kevin Dietrich
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 #include "abc_exporter.h"
24
25 #include <cmath>
26
27 #include "abc_archive.h"
28 #include "abc_camera.h"
29 #include "abc_curves.h"
30 #include "abc_hair.h"
31 #include "abc_mball.h"
32 #include "abc_mesh.h"
33 #include "abc_nurbs.h"
34 #include "abc_points.h"
35 #include "abc_transform.h"
36 #include "abc_util.h"
37
38 extern "C" {
39 #include "DNA_camera_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_meta_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_space_types.h"  /* for FILE_MAX */
47
48 #include "BLI_string.h"
49
50 #ifdef WIN32
51 /* needed for MSCV because of snprintf from BLI_string */
52 #  include "BLI_winstuff.h"
53 #endif
54
55 #include "BKE_anim.h"
56 #include "BKE_global.h"
57 #include "BKE_idprop.h"
58 #include "BKE_main.h"
59 #include "BKE_mball.h"
60 #include "BKE_modifier.h"
61 #include "BKE_particle.h"
62 #include "BKE_scene.h"
63
64 #include "DEG_depsgraph_query.h"
65 }
66
67 using Alembic::Abc::TimeSamplingPtr;
68 using Alembic::Abc::OBox3dProperty;
69
70 /* ************************************************************************** */
71
72 ExportSettings::ExportSettings()
73     : scene(NULL)
74     , view_layer(NULL)
75     , depsgraph(NULL)
76         , logger()
77     , selected_only(false)
78     , visible_layers_only(false)
79     , renderable_only(false)
80     , frame_start(1)
81     , frame_end(1)
82     , frame_samples_xform(1)
83     , frame_samples_shape(1)
84     , shutter_open(0.0)
85     , shutter_close(1.0)
86     , global_scale(1.0f)
87     , flatten_hierarchy(false)
88     , export_normals(false)
89     , export_uvs(false)
90     , export_vcols(false)
91     , export_face_sets(false)
92     , export_vweigths(false)
93     , export_hair(true)
94     , export_particles(true)
95     , apply_subdiv(false)
96     , use_subdiv_schema(false)
97     , export_child_hairs(true)
98     , export_ogawa(true)
99     , pack_uv(false)
100     , triangulate(false)
101     , quad_method(0)
102     , ngon_method(0)
103     , do_convert_axis(false)
104 {}
105
106 static bool object_is_smoke_sim(Object *ob)
107 {
108         ModifierData *md = modifiers_findByType(ob, eModifierType_Smoke);
109
110         if (md) {
111                 SmokeModifierData *smd = reinterpret_cast<SmokeModifierData *>(md);
112                 return (smd->type == MOD_SMOKE_TYPE_DOMAIN);
113         }
114
115         return false;
116 }
117
118 static bool object_type_is_exportable(Scene *scene, Object *ob)
119 {
120         switch (ob->type) {
121                 case OB_MESH:
122                         if (object_is_smoke_sim(ob)) {
123                                 return false;
124                         }
125
126                         return true;
127                 case OB_EMPTY:
128                 case OB_CURVE:
129                 case OB_SURF:
130                 case OB_CAMERA:
131                         return true;
132                 case OB_MBALL:
133                         return AbcMBallWriter::isBasisBall(scene, ob);
134                 default:
135                         return false;
136         }
137 }
138
139
140 /**
141  * Returns whether this object should be exported into the Alembic file.
142  *
143  * \param settings export settings, used for options like 'selected only'.
144  * \param ob the object's base in question.
145  * \param is_duplicated: Normally false; true when the object is instanced
146  * into the scene by a dupli-object (e.g. part of a dupligroup).
147  * This ignores selection and layer visibility,
148  * and assumes that the dupli-object itself (e.g. the group-instantiating empty) is exported.
149  */
150 static bool export_object(const ExportSettings * const settings, const Base * const ob_base,
151                           bool is_duplicated)
152 {
153         if (!is_duplicated) {
154                 /* These two tests only make sense when the object isn't being instanced
155                  * into the scene. When it is, its exportability is determined by
156                  * its dupli-object and the DupliObject::no_draw property. */
157                 if (settings->selected_only && !object_selected(ob_base)) {
158                         return false;
159                 }
160                 // FIXME Sybren: handle these cleanly (maybe just remove code), now using active scene layer instead.
161                 if (settings->visible_layers_only && (ob_base->flag & BASE_VISIBLE) == 0) {
162                         return false;
163                 }
164         }
165
166         //      if (settings->renderable_only && (ob->restrictflag & OB_RESTRICT_RENDER)) {
167         //              return false;
168         //      }
169
170         return true;
171 }
172
173 /* ************************************************************************** */
174
175 AbcExporter::AbcExporter(Main *bmain, const char *filename, ExportSettings &settings)
176     : m_bmain(bmain)
177     , m_settings(settings)
178     , m_filename(filename)
179     , m_trans_sampling_index(0)
180     , m_shape_sampling_index(0)
181     , m_writer(NULL)
182 {}
183
184 AbcExporter::~AbcExporter()
185 {
186         /* Free xforms map */
187         m_xforms_type::iterator it_x, e_x;
188         for (it_x = m_xforms.begin(), e_x = m_xforms.end(); it_x != e_x; ++it_x) {
189                 delete it_x->second;
190         }
191
192         /* Free shapes vector */
193         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
194                 delete m_shapes[i];
195         }
196
197         delete m_writer;
198 }
199
200 void AbcExporter::getShutterSamples(unsigned int nr_of_samples,
201                                     bool time_relative,
202                                     std::vector<double> &samples)
203 {
204         Scene *scene = m_settings.scene; /* for use in the FPS macro */
205         samples.clear();
206
207         unsigned int frame_offset = time_relative ? m_settings.frame_start : 0;
208         double time_factor = time_relative ? FPS : 1.0;
209         double shutter_open = m_settings.shutter_open;
210         double shutter_close = m_settings.shutter_close;
211         double time_inc = (shutter_close - shutter_open) / nr_of_samples;
212
213         /* sample between shutter open & close */
214         for (int sample=0; sample < nr_of_samples; ++sample) {
215                 double sample_time = shutter_open + time_inc * sample;
216                 double time = (frame_offset + sample_time) / time_factor;
217
218                 samples.push_back(time);
219         }
220 }
221
222 Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
223 {
224         std::vector<double> samples;
225
226         if (m_settings.frame_start == m_settings.frame_end) {
227                 return TimeSamplingPtr(new Alembic::Abc::TimeSampling());
228         }
229
230         getShutterSamples(step, true, samples);
231
232         Alembic::Abc::TimeSamplingType ts(
233                     static_cast<uint32_t>(samples.size()),
234                     1.0 / m_settings.scene->r.frs_sec); /* TODO(Sybren): shouldn't we use the FPS macro here? */
235
236         return TimeSamplingPtr(new Alembic::Abc::TimeSampling(ts, samples));
237 }
238
239 void AbcExporter::getFrameSet(unsigned int nr_of_samples,
240                               std::set<double> &frames)
241 {
242         frames.clear();
243
244         std::vector<double> shutter_samples;
245
246         getShutterSamples(nr_of_samples, false, shutter_samples);
247
248         for (double frame = m_settings.frame_start; frame <= m_settings.frame_end; frame += 1.0) {
249                 for (size_t j = 0; j < nr_of_samples; ++j) {
250                         frames.insert(frame + shutter_samples[j]);
251                 }
252         }
253 }
254
255 void AbcExporter::operator()(float &progress, bool &was_canceled)
256 {
257         std::string scene_name;
258
259         if (m_bmain->name[0] != '\0') {
260                 char scene_file_name[FILE_MAX];
261                 BLI_strncpy(scene_file_name, m_bmain->name, FILE_MAX);
262                 scene_name = scene_file_name;
263         }
264         else {
265                 scene_name = "untitled";
266         }
267
268         Scene *scene = m_settings.scene;
269         const double fps = FPS;
270         char buf[16];
271         snprintf(buf, 15, "%f", fps);
272         const std::string str_fps = buf;
273
274         Alembic::AbcCoreAbstract::MetaData md;
275         md.set("FramesPerTimeUnit", str_fps);
276
277         m_writer = new ArchiveWriter(m_filename, scene_name.c_str(), m_settings.export_ogawa, md);
278
279         /* Create time samplings for transforms and shapes. */
280
281         TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_samples_xform);
282
283         m_trans_sampling_index = m_writer->archive().addTimeSampling(*trans_time);
284
285         TimeSamplingPtr shape_time;
286
287         if ((m_settings.frame_samples_shape == m_settings.frame_samples_xform) ||
288             (m_settings.frame_start == m_settings.frame_end))
289         {
290                 shape_time = trans_time;
291                 m_shape_sampling_index = m_trans_sampling_index;
292         }
293         else {
294                 shape_time = createTimeSampling(m_settings.frame_samples_shape);
295                 m_shape_sampling_index = m_writer->archive().addTimeSampling(*shape_time);
296         }
297
298         OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_writer->archive(), m_trans_sampling_index);
299
300         createTransformWritersHierarchy();
301         createShapeWriters();
302
303         /* Make a list of frames to export. */
304
305         std::set<double> xform_frames;
306         getFrameSet(m_settings.frame_samples_xform, xform_frames);
307
308         std::set<double> shape_frames;
309         getFrameSet(m_settings.frame_samples_shape, shape_frames);
310
311         /* Merge all frames needed. */
312         std::set<double> frames(xform_frames);
313         frames.insert(shape_frames.begin(), shape_frames.end());
314
315         /* Export all frames. */
316
317         std::set<double>::const_iterator begin = frames.begin();
318         std::set<double>::const_iterator end = frames.end();
319
320         const float size = static_cast<float>(frames.size());
321         size_t i = 0;
322
323         for (; begin != end; ++begin) {
324                 progress = (++i / size);
325
326                 if (G.is_break) {
327                         was_canceled = true;
328                         break;
329                 }
330
331                 const double frame = *begin;
332
333                 /* 'frame' is offset by start frame, so need to cancel the offset. */
334                 setCurrentFrame(m_bmain, frame);
335
336                 if (shape_frames.count(frame) != 0) {
337                         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
338                                 m_shapes[i]->write();
339                         }
340                 }
341
342                 if (xform_frames.count(frame) == 0) {
343                         continue;
344                 }
345
346                 m_xforms_type::iterator xit, xe;
347                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
348                         xit->second->write();
349                 }
350
351                 /* Save the archive 's bounding box. */
352                 Imath::Box3d bounds;
353
354                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
355                         Imath::Box3d box = xit->second->bounds();
356                         bounds.extendBy(box);
357                 }
358
359                 archive_bounds_prop.set(bounds);
360         }
361 }
362
363 void AbcExporter::createTransformWritersHierarchy()
364 {
365         for (Base *base = static_cast<Base *>(m_settings.view_layer->object_bases.first); base; base = base->next) {
366                 Object *ob = base->object;
367
368                 if (export_object(&m_settings, base, false)) {
369                         switch (ob->type) {
370                                 case OB_LAMP:
371                                 case OB_LATTICE:
372                                 case OB_SPEAKER:
373                                         /* We do not export transforms for objects of these classes. */
374                                         break;
375                                 default:
376                                         exploreTransform(base, ob->parent, NULL);
377                         }
378                 }
379         }
380 }
381
382 void AbcExporter::exploreTransform(Base *ob_base, Object *parent, Object *dupliObParent)
383 {
384         /* If an object isn't exported itself, its duplilist shouldn't be
385          * exported either. */
386         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
387                 return;
388         }
389
390         Object *ob = DEG_get_evaluated_object(m_settings.depsgraph, ob_base->object);
391         if (object_type_is_exportable(m_settings.scene, ob)) {
392                 createTransformWriter(ob, parent, dupliObParent);
393         }
394
395         ListBase *lb = object_duplilist(m_settings.depsgraph, m_settings.scene, ob);
396
397         if (lb) {
398                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
399                 fake_base.next = fake_base.prev = NULL;
400
401                 DupliObject *link = static_cast<DupliObject *>(lb->first);
402                 Object *dupli_ob = NULL;
403                 Object *dupli_parent = NULL;
404
405                 for (; link; link = link->next) {
406                         /* This skips things like custom bone shapes. */
407                         if (m_settings.renderable_only && link->no_draw) {
408                                 continue;
409                         }
410
411                         if (link->type == OB_DUPLICOLLECTION) {
412                                 dupli_ob = link->ob;
413                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
414
415                                 fake_base.object = dupli_ob;
416                                 exploreTransform(&fake_base, dupli_parent, ob);
417                         }
418                 }
419
420                 free_object_duplilist(lb);
421         }
422 }
423
424 AbcTransformWriter * AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
425 {
426         /* An object should not be its own parent, or we'll get infinite loops. */
427         BLI_assert(ob != parent);
428         BLI_assert(ob != dupliObParent);
429
430         std::string name;
431         if (m_settings.flatten_hierarchy) {
432                 name = get_id_name(ob);
433         }
434         else {
435                 name = get_object_dag_path_name(ob, dupliObParent);
436         }
437
438         /* check if we have already created a transform writer for this object */
439         AbcTransformWriter *my_writer = getXForm(name);
440         if (my_writer != NULL) {
441                 return my_writer;
442         }
443
444         AbcTransformWriter *parent_writer = NULL;
445         Alembic::Abc::OObject alembic_parent;
446
447         if (m_settings.flatten_hierarchy || parent == NULL) {
448                 /* Parentless objects still have the "top object" as parent
449                  * in Alembic. */
450                 alembic_parent = m_writer->archive().getTop();
451         }
452         else {
453                 /* Since there are so many different ways to find parents (as evident
454                  * in the number of conditions below), we can't really look up the
455                  * parent by name. We'll just call createTransformWriter(), which will
456                  * return the parent's AbcTransformWriter pointer. */
457                 if (parent->parent) {
458                         if (parent == dupliObParent) {
459                                 parent_writer = createTransformWriter(parent, parent->parent, NULL);
460                         }
461                         else {
462                                 parent_writer = createTransformWriter(parent, parent->parent, dupliObParent);
463                         }
464                 }
465                 else if (parent == dupliObParent) {
466                         if (dupliObParent->parent == NULL) {
467                                 parent_writer = createTransformWriter(parent, NULL, NULL);
468                         }
469                         else {
470                                 parent_writer = createTransformWriter(parent, dupliObParent->parent, dupliObParent->parent);
471                         }
472                 }
473                 else {
474                         parent_writer = createTransformWriter(parent, dupliObParent, dupliObParent);
475                 }
476
477                 BLI_assert(parent_writer);
478                 alembic_parent = parent_writer->alembicXform();
479         }
480
481         my_writer = new AbcTransformWriter(ob, alembic_parent, parent_writer,
482                                            m_trans_sampling_index, m_settings);
483
484         /* When flattening, the matrix of the dupliobject has to be added. */
485         if (m_settings.flatten_hierarchy && dupliObParent) {
486                 my_writer->m_proxy_from = dupliObParent;
487         }
488
489         m_xforms[name] = my_writer;
490         return my_writer;
491 }
492
493 void AbcExporter::createShapeWriters()
494 {
495         for (Base *base = static_cast<Base *>(m_settings.view_layer->object_bases.first); base; base = base->next) {
496                 exploreObject(base, NULL);
497         }
498 }
499
500 void AbcExporter::exploreObject(Base *ob_base, Object *dupliObParent)
501 {
502         /* If an object isn't exported itself, its duplilist shouldn't be
503          * exported either. */
504         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
505                 return;
506         }
507
508         Object *ob = DEG_get_evaluated_object(m_settings.depsgraph, ob_base->object);
509         createShapeWriter(ob, dupliObParent);
510
511         ListBase *lb = object_duplilist(m_settings.depsgraph, m_settings.scene, ob);
512
513         if (lb) {
514                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
515                 fake_base.next = fake_base.prev = NULL;
516
517                 DupliObject *link = static_cast<DupliObject *>(lb->first);
518
519                 for (; link; link = link->next) {
520                         /* This skips things like custom bone shapes. */
521                         if (m_settings.renderable_only && link->no_draw) {
522                                 continue;
523                         }
524                         if (link->type == OB_DUPLICOLLECTION) {
525                                 fake_base.object = link->ob;
526                                 exploreObject(&fake_base, ob);
527                         }
528                 }
529
530                 free_object_duplilist(lb);
531         }
532 }
533
534 void AbcExporter::createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform)
535 {
536         if (!m_settings.export_hair && !m_settings.export_particles) {
537                 return;
538         }
539
540         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
541
542         for (; psys; psys = psys->next) {
543                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
544                         continue;
545                 }
546
547                 if (m_settings.export_hair && psys->part->type == PART_HAIR) {
548                         m_settings.export_child_hairs = true;
549                         m_shapes.push_back(new AbcHairWriter(ob, xform, m_shape_sampling_index, m_settings, psys));
550                 }
551                 else if (m_settings.export_particles && psys->part->type == PART_EMITTER) {
552                         m_shapes.push_back(new AbcPointsWriter(ob, xform, m_shape_sampling_index, m_settings, psys));
553                 }
554         }
555 }
556
557 void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
558 {
559         if (!object_type_is_exportable(m_settings.scene, ob)) {
560                 return;
561         }
562
563         std::string name;
564
565         if (m_settings.flatten_hierarchy) {
566                 name = get_id_name(ob);
567         }
568         else {
569                 name = get_object_dag_path_name(ob, dupliObParent);
570         }
571
572         AbcTransformWriter *xform = getXForm(name);
573
574         if (!xform) {
575                 ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
576                 return;
577         }
578
579         createParticleSystemsWriters(ob, xform);
580
581         switch (ob->type) {
582                 case OB_MESH:
583                 {
584                         Mesh *me = static_cast<Mesh *>(ob->data);
585
586                         if (!me) {
587                                 return;
588                         }
589
590                         m_shapes.push_back(new AbcMeshWriter(ob, xform, m_shape_sampling_index, m_settings));
591                         break;
592                 }
593                 case OB_SURF:
594                 {
595                         Curve *cu = static_cast<Curve *>(ob->data);
596
597                         if (!cu) {
598                                 return;
599                         }
600
601                         m_shapes.push_back(new AbcNurbsWriter(ob, xform, m_shape_sampling_index, m_settings));
602                         break;
603                 }
604                 case OB_CURVE:
605                 {
606                         Curve *cu = static_cast<Curve *>(ob->data);
607
608                         if (!cu) {
609                                 return;
610                         }
611
612                         m_shapes.push_back(new AbcCurveWriter(ob, xform, m_shape_sampling_index, m_settings));
613                         break;
614                 }
615                 case OB_CAMERA:
616                 {
617                         Camera *cam = static_cast<Camera *>(ob->data);
618
619                         if (cam->type == CAM_PERSP) {
620                                 m_shapes.push_back(new AbcCameraWriter(ob, xform, m_shape_sampling_index, m_settings));
621                         }
622
623                         break;
624                 }
625                 case OB_MBALL:
626                 {
627                         MetaBall *mball = static_cast<MetaBall *>(ob->data);
628                         if (!mball) {
629                                 return;
630                         }
631
632                         m_shapes.push_back(new AbcMBallWriter(
633                                                m_bmain, ob, xform,
634                                                m_shape_sampling_index, m_settings));
635                         break;
636                 }
637         }
638 }
639
640 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
641 {
642         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
643
644         if (it == m_xforms.end()) {
645                 return NULL;
646         }
647
648         return it->second;
649 }
650
651 void AbcExporter::setCurrentFrame(Main *bmain, double t)
652 {
653         m_settings.scene->r.cfra = static_cast<int>(t);
654         m_settings.scene->r.subframe = static_cast<float>(t) - m_settings.scene->r.cfra;
655         BKE_scene_graph_update_for_newframe(m_settings.depsgraph, bmain);
656 }