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