2e882a491c35fb824895575525325eac3edb1364
[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(EvaluationContext *eval_ctx, 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(eval_ctx, 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 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, Object *ob,
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 && !parent_selected(ob)) {
154                         return false;
155                 }
156
157                 if (settings->visible_layers_only && !(settings->scene->lay & ob->lay)) {
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, const char *filename, ExportSettings &settings)
172     : m_bmain(bmain)
173     , m_settings(settings)
174     , m_filename(filename)
175     , m_trans_sampling_index(0)
176     , m_shape_sampling_index(0)
177     , m_scene(scene)
178     , m_writer(NULL)
179 {}
180
181 AbcExporter::~AbcExporter()
182 {
183         /* Free xforms map */
184         m_xforms_type::iterator it_x, e_x;
185         for (it_x = m_xforms.begin(), e_x = m_xforms.end(); it_x != e_x; ++it_x) {
186                 delete it_x->second;
187         }
188
189         /* Free shapes vector */
190         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
191                 delete m_shapes[i];
192         }
193
194         delete m_writer;
195 }
196
197 void AbcExporter::getShutterSamples(unsigned int nr_of_samples,
198                                     bool time_relative,
199                                     std::vector<double> &samples)
200 {
201         Scene *scene = m_scene; /* for use in the FPS macro */
202         samples.clear();
203
204         unsigned int frame_offset = time_relative ? m_settings.frame_start : 0;
205         double time_factor = time_relative ? FPS : 1.0;
206         double shutter_open = m_settings.shutter_open;
207         double shutter_close = m_settings.shutter_close;
208         double time_inc = (shutter_close - shutter_open) / nr_of_samples;
209
210         /* sample between shutter open & close */
211         for (int sample=0; sample < nr_of_samples; ++sample) {
212                 double sample_time = shutter_open + time_inc * sample;
213                 double time = (frame_offset + sample_time) / time_factor;
214
215                 samples.push_back(time);
216         }
217 }
218
219 Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
220 {
221         std::vector<double> samples;
222
223         if (m_settings.frame_start == m_settings.frame_end) {
224                 return TimeSamplingPtr(new Alembic::Abc::TimeSampling());
225         }
226
227         getShutterSamples(step, true, samples);
228
229         Alembic::Abc::TimeSamplingType ts(
230                     static_cast<uint32_t>(samples.size()),
231                     1.0 / m_scene->r.frs_sec);
232
233         return TimeSamplingPtr(new Alembic::Abc::TimeSampling(ts, samples));
234 }
235
236 void AbcExporter::getFrameSet(unsigned int nr_of_samples,
237                               std::set<double> &frames)
238 {
239         frames.clear();
240
241         std::vector<double> shutter_samples;
242
243         getShutterSamples(nr_of_samples, false, shutter_samples);
244
245         for (double frame = m_settings.frame_start; frame <= m_settings.frame_end; frame += 1.0) {
246                 for (size_t j = 0; j < nr_of_samples; ++j) {
247                         frames.insert(frame + shutter_samples[j]);
248                 }
249         }
250 }
251
252 void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
253 {
254         std::string scene_name;
255
256         if (bmain->name[0] != '\0') {
257                 char scene_file_name[FILE_MAX];
258                 BLI_strncpy(scene_file_name, bmain->name, FILE_MAX);
259                 scene_name = scene_file_name;
260         }
261         else {
262                 scene_name = "untitled";
263         }
264
265         Scene *scene = m_scene;
266         const double fps = FPS;
267         char buf[16];
268         snprintf(buf, 15, "%f", fps);
269         const std::string str_fps = buf;
270
271         Alembic::AbcCoreAbstract::MetaData md;
272         md.set("FramesPerTimeUnit", str_fps);
273
274         m_writer = new ArchiveWriter(m_filename, scene_name.c_str(), m_settings.export_ogawa, md);
275
276         /* Create time samplings for transforms and shapes. */
277
278         TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_samples_xform);
279
280         m_trans_sampling_index = m_writer->archive().addTimeSampling(*trans_time);
281
282         TimeSamplingPtr shape_time;
283
284         if ((m_settings.frame_samples_shape == m_settings.frame_samples_xform) ||
285             (m_settings.frame_start == m_settings.frame_end))
286         {
287                 shape_time = trans_time;
288                 m_shape_sampling_index = m_trans_sampling_index;
289         }
290         else {
291                 shape_time = createTimeSampling(m_settings.frame_samples_shape);
292                 m_shape_sampling_index = m_writer->archive().addTimeSampling(*shape_time);
293         }
294
295         OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_writer->archive(), m_trans_sampling_index);
296
297         createTransformWritersHierarchy(bmain->eval_ctx);
298         createShapeWriters(bmain->eval_ctx);
299
300         /* Make a list of frames to export. */
301
302         std::set<double> xform_frames;
303         getFrameSet(m_settings.frame_samples_xform, xform_frames);
304
305         std::set<double> shape_frames;
306         getFrameSet(m_settings.frame_samples_shape, shape_frames);
307
308         /* Merge all frames needed. */
309         std::set<double> frames(xform_frames);
310         frames.insert(shape_frames.begin(), shape_frames.end());
311
312         /* Export all frames. */
313
314         std::set<double>::const_iterator begin = frames.begin();
315         std::set<double>::const_iterator end = frames.end();
316
317         const float size = static_cast<float>(frames.size());
318         size_t i = 0;
319
320         for (; begin != end; ++begin) {
321                 progress = (++i / size);
322
323                 if (G.is_break) {
324                         was_canceled = true;
325                         break;
326                 }
327
328                 const double frame = *begin;
329
330                 /* 'frame' is offset by start frame, so need to cancel the offset. */
331                 setCurrentFrame(bmain, frame);
332
333                 if (shape_frames.count(frame) != 0) {
334                         for (int i = 0, e = m_shapes.size(); i != e; ++i) {
335                                 m_shapes[i]->write();
336                         }
337                 }
338
339                 if (xform_frames.count(frame) == 0) {
340                         continue;
341                 }
342
343                 m_xforms_type::iterator xit, xe;
344                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
345                         xit->second->write();
346                 }
347
348                 /* Save the archive 's bounding box. */
349                 Imath::Box3d bounds;
350
351                 for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
352                         Imath::Box3d box = xit->second->bounds();
353                         bounds.extendBy(box);
354                 }
355
356                 archive_bounds_prop.set(bounds);
357         }
358 }
359
360 void AbcExporter::createTransformWritersHierarchy(EvaluationContext *eval_ctx)
361 {
362         Base *base = static_cast<Base *>(m_scene->base.first);
363
364         while (base) {
365                 Object *ob = base->object;
366
367                 switch (ob->type) {
368                         case OB_LAMP:
369                         case OB_LATTICE:
370                         case OB_SPEAKER:
371                                 /* We do not export transforms for objects of these classes. */
372                                 break;
373                         default:
374                                 exploreTransform(eval_ctx, ob, ob->parent);
375                 }
376
377                 base = base->next;
378         }
379 }
380
381 void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Object *ob, Object *parent, Object *dupliObParent)
382 {
383         /* If an object isn't exported itself, its duplilist shouldn't be
384          * exported either. */
385         if (!export_object(&m_settings, ob, dupliObParent != NULL)) {
386                 return;
387         }
388
389         if (object_type_is_exportable(eval_ctx, m_scene, ob)) {
390                 createTransformWriter(ob, parent, dupliObParent);
391         }
392
393         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
394
395         if (lb) {
396                 DupliObject *link = static_cast<DupliObject *>(lb->first);
397                 Object *dupli_ob = NULL;
398                 Object *dupli_parent = NULL;
399                 
400                 for (; link; link = link->next) {
401                         /* This skips things like custom bone shapes. */
402                         if (m_settings.renderable_only && link->no_draw) {
403                                 continue;
404                         }
405
406                         if (link->type == OB_DUPLIGROUP) {
407                                 dupli_ob = link->ob;
408                                 dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
409
410                                 exploreTransform(eval_ctx, dupli_ob, dupli_parent, ob);
411                         }
412                 }
413         }
414
415         free_object_duplilist(lb);
416 }
417
418 AbcTransformWriter * AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
419 {
420         /* An object should not be its own parent, or we'll get infinite loops. */
421         BLI_assert(ob != parent);
422         BLI_assert(ob != dupliObParent);
423
424         std::string name;
425         if (m_settings.flatten_hierarchy) {
426                 name = get_id_name(ob);
427         }
428         else {
429                 name = get_object_dag_path_name(ob, dupliObParent);
430         }
431
432         /* check if we have already created a transform writer for this object */
433         AbcTransformWriter *my_writer = getXForm(name);
434         if (my_writer != NULL) {
435                 return my_writer;
436         }
437
438         AbcTransformWriter *parent_writer = NULL;
439         Alembic::Abc::OObject alembic_parent;
440
441         if (m_settings.flatten_hierarchy || parent == NULL) {
442                 /* Parentless objects still have the "top object" as parent
443                  * in Alembic. */
444                 alembic_parent = m_writer->archive().getTop();
445         }
446         else {
447                 /* Since there are so many different ways to find parents (as evident
448                  * in the number of conditions below), we can't really look up the
449                  * parent by name. We'll just call createTransformWriter(), which will
450                  * return the parent's AbcTransformWriter pointer. */
451                 if (parent->parent) {
452                         if (parent == dupliObParent) {
453                                 parent_writer = createTransformWriter(parent, parent->parent, NULL);
454                         }
455                         else {
456                                 parent_writer = createTransformWriter(parent, parent->parent, dupliObParent);
457                         }
458                 }
459                 else if (parent == dupliObParent) {
460                         if (dupliObParent->parent == NULL) {
461                                 parent_writer = createTransformWriter(parent, NULL, NULL);
462                         }
463                         else {
464                                 parent_writer = createTransformWriter(parent, dupliObParent->parent, dupliObParent->parent);
465                         }
466                 }
467                 else {
468                         parent_writer = createTransformWriter(parent, dupliObParent, dupliObParent);
469                 }
470
471                 BLI_assert(parent_writer);
472                 alembic_parent = parent_writer->alembicXform();
473         }
474
475         my_writer = new AbcTransformWriter(ob, alembic_parent, parent_writer,
476                                            m_trans_sampling_index, m_settings);
477
478         /* When flattening, the matrix of the dupliobject has to be added. */
479         if (m_settings.flatten_hierarchy && dupliObParent) {
480                 my_writer->m_proxy_from = dupliObParent;
481         }
482
483         m_xforms[name] = my_writer;
484         return my_writer;
485 }
486
487 void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
488 {
489         Base *base = static_cast<Base *>(m_scene->base.first);
490
491         while (base) {
492                 Object *ob = base->object;
493                 exploreObject(eval_ctx, ob, NULL);
494
495                 base = base->next;
496         }
497 }
498
499 void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Object *ob, Object *dupliObParent)
500 {
501         /* If an object isn't exported itself, its duplilist shouldn't be
502          * exported either. */
503         if (!export_object(&m_settings, ob, dupliObParent != NULL)) {
504                 return;
505         }
506
507         createShapeWriter(ob, dupliObParent);
508         
509         ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
510
511         if (lb) {
512                 DupliObject *link = static_cast<DupliObject *>(lb->first);
513
514                 for (; link; link = link->next) {
515                         /* This skips things like custom bone shapes. */
516                         if (m_settings.renderable_only && link->no_draw) {
517                                 continue;
518                         }
519
520                         if (link->type == OB_DUPLIGROUP) {
521                                 exploreObject(eval_ctx, link->ob, ob);
522                         }
523                 }
524         }
525
526         free_object_duplilist(lb);
527 }
528
529 void AbcExporter::createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform)
530 {
531         if (!m_settings.export_hair && !m_settings.export_particles) {
532                 return;
533         }
534
535         ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
536
537         for (; psys; psys = psys->next) {
538                 if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
539                         continue;
540                 }
541
542                 if (m_settings.export_hair && psys->part->type == PART_HAIR) {
543                         m_settings.export_child_hairs = true;
544                         m_shapes.push_back(new AbcHairWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
545                 }
546                 else if (m_settings.export_particles && psys->part->type == PART_EMITTER) {
547                         m_shapes.push_back(new AbcPointsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
548                 }
549         }
550 }
551
552 void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
553 {
554         if (!object_type_is_exportable(m_bmain->eval_ctx, m_scene, ob)) {
555                 return;
556         }
557
558         std::string name;
559
560         if (m_settings.flatten_hierarchy) {
561                 name = get_id_name(ob);
562         }
563         else {
564                 name = get_object_dag_path_name(ob, dupliObParent);
565         }
566         
567         AbcTransformWriter *xform = getXForm(name);
568
569         if (!xform) {
570                 ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
571                 return;
572         }
573
574         createParticleSystemsWriters(ob, xform);
575
576         switch (ob->type) {
577                 case OB_MESH:
578                 {
579                         Mesh *me = static_cast<Mesh *>(ob->data);
580
581                         if (!me) {
582                                 return;
583                         }
584
585                         m_shapes.push_back(new AbcMeshWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
586                         break;
587                 }
588                 case OB_SURF:
589                 {
590                         Curve *cu = static_cast<Curve *>(ob->data);
591
592                         if (!cu) {
593                                 return;
594                         }
595
596                         m_shapes.push_back(new AbcNurbsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
597                         break;
598                 }
599                 case OB_CURVE:
600                 {
601                         Curve *cu = static_cast<Curve *>(ob->data);
602
603                         if (!cu) {
604                                 return;
605                         }
606
607                         m_shapes.push_back(new AbcCurveWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
608                         break;
609                 }
610                 case OB_CAMERA:
611                 {
612                         Camera *cam = static_cast<Camera *>(ob->data);
613
614                         if (cam->type == CAM_PERSP) {
615                                 m_shapes.push_back(new AbcCameraWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings));
616                         }
617
618                         break;
619                 }
620                 case OB_MBALL:
621                 {
622                         MetaBall *mball = static_cast<MetaBall *>(ob->data);
623                         if (!mball) {
624                                 return;
625                         }
626
627                         m_shapes.push_back(new AbcMBallWriter(
628                                                m_bmain, m_scene, ob, xform,
629                                                m_shape_sampling_index, m_settings));
630                         break;
631                 }
632         }
633 }
634
635 AbcTransformWriter *AbcExporter::getXForm(const std::string &name)
636 {
637         std::map<std::string, AbcTransformWriter *>::iterator it = m_xforms.find(name);
638
639         if (it == m_xforms.end()) {
640                 return NULL;
641         }
642
643         return it->second;
644 }
645
646 void AbcExporter::setCurrentFrame(Main *bmain, double t)
647 {
648         m_scene->r.cfra = static_cast<int>(t);
649         m_scene->r.subframe = static_cast<float>(t) - m_scene->r.cfra;
650         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, m_scene, m_scene->lay);
651 }