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