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