View3D: Shading Popup
[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,
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_depsgraph(depsgraph)
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_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_scene->r.frs_sec);
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_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(m_depsgraph);
301         createShapeWriters(m_depsgraph);
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(Depsgraph *depsgraph)
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(depsgraph, base, ob->parent, NULL);
377                         }
378                 }
379         }
380 }
381
382 void AbcExporter::exploreTransform(Depsgraph *depsgraph, Base *ob_base, Object *parent, Object *dupliObParent)
383 {
384         Object *ob = ob_base->object;
385
386         /* If an object isn't exported itself, its duplilist shouldn't be
387          * exported either. */
388         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
389                 return;
390         }
391
392         if (object_type_is_exportable(m_scene, ob)) {
393                 createTransformWriter(depsgraph, ob, parent, dupliObParent);
394         }
395
396         ListBase *lb = object_duplilist(depsgraph, m_scene, ob);
397
398         if (lb) {
399                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
400                 fake_base.next = fake_base.prev = NULL;
401
402                 DupliObject *link = static_cast<DupliObject *>(lb->first);
403                 Object *dupli_ob = NULL;
404                 Object *dupli_parent = NULL;
405                 
406                 for (; link; link = link->next) {
407                         /* This skips things like custom bone shapes. */
408                         if (m_settings.renderable_only && link->no_draw) {
409                                 continue;
410                         }
411
412                         if (link->type == OB_DUPLICOLLECTION) {
413                                 dupli_ob = link->ob;
414                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
415
416                                 fake_base.object = dupli_ob;
417                                 exploreTransform(depsgraph, &fake_base, dupli_parent, ob);
418                         }
419                 }
420         }
421
422         free_object_duplilist(lb);
423 }
424
425 AbcTransformWriter * AbcExporter::createTransformWriter(Depsgraph *depsgraph, Object *ob, Object *parent, Object *dupliObParent)
426 {
427         /* An object should not be its own parent, or we'll get infinite loops. */
428         BLI_assert(ob != parent);
429         BLI_assert(ob != dupliObParent);
430
431         std::string name;
432         if (m_settings.flatten_hierarchy) {
433                 name = get_id_name(ob);
434         }
435         else {
436                 name = get_object_dag_path_name(ob, dupliObParent);
437         }
438
439         /* check if we have already created a transform writer for this object */
440         AbcTransformWriter *my_writer = getXForm(name);
441         if (my_writer != NULL) {
442                 return my_writer;
443         }
444
445         AbcTransformWriter *parent_writer = NULL;
446         Alembic::Abc::OObject alembic_parent;
447
448         if (m_settings.flatten_hierarchy || parent == NULL) {
449                 /* Parentless objects still have the "top object" as parent
450                  * in Alembic. */
451                 alembic_parent = m_writer->archive().getTop();
452         }
453         else {
454                 /* Since there are so many different ways to find parents (as evident
455                  * in the number of conditions below), we can't really look up the
456                  * parent by name. We'll just call createTransformWriter(), which will
457                  * return the parent's AbcTransformWriter pointer. */
458                 if (parent->parent) {
459                         if (parent == dupliObParent) {
460                                 parent_writer = createTransformWriter(depsgraph, parent, parent->parent, NULL);
461                         }
462                         else {
463                                 parent_writer = createTransformWriter(depsgraph, parent, parent->parent, dupliObParent);
464                         }
465                 }
466                 else if (parent == dupliObParent) {
467                         if (dupliObParent->parent == NULL) {
468                                 parent_writer = createTransformWriter(depsgraph, parent, NULL, NULL);
469                         }
470                         else {
471                                 parent_writer = createTransformWriter(depsgraph, parent, dupliObParent->parent, dupliObParent->parent);
472                         }
473                 }
474                 else {
475                         parent_writer = createTransformWriter(depsgraph, parent, dupliObParent, dupliObParent);
476                 }
477
478                 BLI_assert(parent_writer);
479                 alembic_parent = parent_writer->alembicXform();
480         }
481
482         my_writer = new AbcTransformWriter(depsgraph, ob, alembic_parent, parent_writer,
483                                            m_trans_sampling_index, m_settings);
484
485         /* When flattening, the matrix of the dupliobject has to be added. */
486         if (m_settings.flatten_hierarchy && dupliObParent) {
487                 my_writer->m_proxy_from = dupliObParent;
488         }
489
490         m_xforms[name] = my_writer;
491         return my_writer;
492 }
493
494 void AbcExporter::createShapeWriters(Depsgraph *depsgraph)
495 {
496         for (Base *base = static_cast<Base *>(m_settings.view_layer->object_bases.first); base; base = base->next) {
497                 exploreObject(depsgraph, base, NULL);
498         }
499 }
500
501 void AbcExporter::exploreObject(Depsgraph *depsgraph, Base *ob_base, Object *dupliObParent)
502 {
503         /* If an object isn't exported itself, its duplilist shouldn't be
504          * exported either. */
505         if (!export_object(&m_settings, ob_base, dupliObParent != NULL)) {
506                 return;
507         }
508
509         createShapeWriter(ob_base, dupliObParent);
510         
511         Object *ob = ob_base->object;
512         ListBase *lb = object_duplilist(depsgraph, m_scene, ob);
513
514         if (lb) {
515                 Base fake_base = *ob_base;  // copy flags (like selection state) from the real object.
516                 fake_base.next = fake_base.prev = NULL;
517
518                 DupliObject *link = static_cast<DupliObject *>(lb->first);
519
520                 for (; link; link = link->next) {
521                         /* This skips things like custom bone shapes. */
522                         if (m_settings.renderable_only && link->no_draw) {
523                                 continue;
524                         }
525                         if (link->type == OB_DUPLICOLLECTION) {
526                                 fake_base.object = link->ob;
527                                 exploreObject(depsgraph, &fake_base, ob);
528                         }
529                 }
530         }
531
532         free_object_duplilist(lb);
533 }
534
535 void AbcExporter::createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform)
536 {
537         if (!m_settings.export_hair && !m_settings.export_particles) {
538                 return;
539         }
540
541         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
542
543         for (; psys; psys = psys->next) {
544                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
545                         continue;
546                 }
547
548                 if (m_settings.export_hair && psys->part->type == PART_HAIR) {
549                         m_settings.export_child_hairs = true;
550                         m_shapes.push_back(new AbcHairWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
551                 }
552                 else if (m_settings.export_particles && psys->part->type == PART_EMITTER) {
553                         m_shapes.push_back(new AbcPointsWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
554                 }
555         }
556 }
557
558 void AbcExporter::createShapeWriter(Base *ob_base, Object *dupliObParent)
559 {
560         Object *ob = ob_base->object;
561
562         if (!object_type_is_exportable(m_scene, ob)) {
563                 return;
564         }
565
566         std::string name;
567
568         if (m_settings.flatten_hierarchy) {
569                 name = get_id_name(ob);
570         }
571         else {
572                 name = get_object_dag_path_name(ob, dupliObParent);
573         }
574         
575         AbcTransformWriter *xform = getXForm(name);
576
577         if (!xform) {
578                 ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
579                 return;
580         }
581
582         createParticleSystemsWriters(ob, xform);
583
584         switch (ob->type) {
585                 case OB_MESH:
586                 {
587                         Mesh *me = static_cast<Mesh *>(ob->data);
588
589                         if (!me) {
590                                 return;
591                         }
592
593                         m_shapes.push_back(new AbcMeshWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings));
594                         break;
595                 }
596                 case OB_SURF:
597                 {
598                         Curve *cu = static_cast<Curve *>(ob->data);
599
600                         if (!cu) {
601                                 return;
602                         }
603
604                         m_shapes.push_back(new AbcNurbsWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings));
605                         break;
606                 }
607                 case OB_CURVE:
608                 {
609                         Curve *cu = static_cast<Curve *>(ob->data);
610
611                         if (!cu) {
612                                 return;
613                         }
614
615                         m_shapes.push_back(new AbcCurveWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings));
616                         break;
617                 }
618                 case OB_CAMERA:
619                 {
620                         Camera *cam = static_cast<Camera *>(ob->data);
621
622                         if (cam->type == CAM_PERSP) {
623                                 m_shapes.push_back(new AbcCameraWriter(m_depsgraph, m_scene, ob, xform, m_shape_sampling_index, m_settings));
624                         }
625
626                         break;
627                 }
628                 case OB_MBALL:
629                 {
630                         MetaBall *mball = static_cast<MetaBall *>(ob->data);
631                         if (!mball) {
632                                 return;
633                         }
634
635                         m_shapes.push_back(new AbcMBallWriter(
636                                                m_bmain, m_depsgraph, m_scene, ob, xform,
637                                                m_shape_sampling_index, m_settings));
638                         break;
639                 }
640         }
641 }
642
643 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
644 {
645         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
646
647         if (it == m_xforms.end()) {
648                 return NULL;
649         }
650
651         return it->second;
652 }
653
654 void AbcExporter::setCurrentFrame(Main *bmain, double t)
655 {
656         m_scene->r.cfra = static_cast<int>(t);
657         m_scene->r.subframe = static_cast<float>(t) - m_scene->r.cfra;
658         BKE_scene_graph_update_for_newframe(m_depsgraph, bmain);
659 }