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