Alembic: exporting MetaBalls as mesh
[blender.git] / source / blender / alembic / intern / alembic_capi.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_alembic.h"
24 #include <boost/foreach.hpp>
25
26 #include <Alembic/AbcMaterial/IMaterial.h>
27
28 #include "abc_archive.h"
29 #include "abc_camera.h"
30 #include "abc_curves.h"
31 #include "abc_hair.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 "MEM_guardedalloc.h"
40
41 #include "DNA_cachefile_types.h"
42 #include "DNA_curve_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46
47 #include "BKE_cachefile.h"
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_context.h"
50 #include "BKE_curve.h"
51 #include "BKE_depsgraph.h"
52 #include "BKE_global.h"
53 #include "BKE_library.h"
54 #include "BKE_main.h"
55 #include "BKE_scene.h"
56
57 /* SpaceType struct has a member called 'new' which obviously conflicts with C++
58  * so temporarily redefining the new keyword to make it compile. */
59 #define new extern_new
60 #include "BKE_screen.h"
61 #undef new
62
63 #include "BLI_fileops.h"
64 #include "BLI_ghash.h"
65 #include "BLI_listbase.h"
66 #include "BLI_math.h"
67 #include "BLI_path_util.h"
68 #include "BLI_string.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72 }
73
74 using Alembic::Abc::Int32ArraySamplePtr;
75 using Alembic::Abc::ObjectHeader;
76
77 using Alembic::AbcGeom::MetaData;
78 using Alembic::AbcGeom::P3fArraySamplePtr;
79 using Alembic::AbcGeom::kWrapExisting;
80
81 using Alembic::AbcGeom::ICamera;
82 using Alembic::AbcGeom::ICurves;
83 using Alembic::AbcGeom::ICurvesSchema;
84 using Alembic::AbcGeom::IFaceSet;
85 using Alembic::AbcGeom::ILight;
86 using Alembic::AbcGeom::INuPatch;
87 using Alembic::AbcGeom::IObject;
88 using Alembic::AbcGeom::IPoints;
89 using Alembic::AbcGeom::IPointsSchema;
90 using Alembic::AbcGeom::IPolyMesh;
91 using Alembic::AbcGeom::IPolyMeshSchema;
92 using Alembic::AbcGeom::ISampleSelector;
93 using Alembic::AbcGeom::ISubD;
94 using Alembic::AbcGeom::IV2fGeomParam;
95 using Alembic::AbcGeom::IXform;
96 using Alembic::AbcGeom::IXformSchema;
97 using Alembic::AbcGeom::N3fArraySamplePtr;
98 using Alembic::AbcGeom::XformSample;
99 using Alembic::AbcGeom::ICompoundProperty;
100 using Alembic::AbcGeom::IN3fArrayProperty;
101 using Alembic::AbcGeom::IN3fGeomParam;
102 using Alembic::AbcGeom::V3fArraySamplePtr;
103
104 using Alembic::AbcMaterial::IMaterial;
105
106 struct AbcArchiveHandle {
107         int unused;
108 };
109
110 ABC_INLINE ArchiveReader *archive_from_handle(AbcArchiveHandle *handle)
111 {
112         return reinterpret_cast<ArchiveReader *>(handle);
113 }
114
115 ABC_INLINE AbcArchiveHandle *handle_from_archive(ArchiveReader *archive)
116 {
117         return reinterpret_cast<AbcArchiveHandle *>(archive);
118 }
119
120 //#define USE_NURBS
121
122 /* NOTE: this function is similar to visit_objects below, need to keep them in
123  * sync. */
124 static bool gather_objects_paths(const IObject &object, ListBase *object_paths)
125 {
126         if (!object.valid()) {
127                 return false;
128         }
129
130
131         size_t children_claiming_this_object = 0;
132         size_t num_children = object.getNumChildren();
133
134         for (size_t i = 0; i < num_children; ++i) {
135                 bool child_claims_this_object = gather_objects_paths(object.getChild(i), object_paths);
136                 children_claiming_this_object += child_claims_this_object ? 1 : 0;
137         }
138
139         const MetaData &md = object.getMetaData();
140         bool get_path = false;
141         bool parent_is_part_of_this_object = false;
142
143         if (!object.getParent()) {
144                 /* The root itself is not an object we should import. */
145         }
146         else if (IXform::matches(md)) {
147                 if (has_property(object.getProperties(), "locator")) {
148                         get_path = true;
149                 }
150                 else {
151                         get_path = children_claiming_this_object == 0;
152                 }
153
154                 /* Transforms are never "data" for their parent. */
155                 parent_is_part_of_this_object = false;
156         }
157         else {
158                 /* These types are "data" for their parent. */
159                 get_path =
160                         IPolyMesh::matches(md) ||
161                         ISubD::matches(md) ||
162 #ifdef USE_NURBS
163                         INuPatch::matches(md) ||
164 #endif
165                         ICamera::matches(md) ||
166                         IPoints::matches(md) ||
167                         ICurves::matches(md);
168                 parent_is_part_of_this_object = get_path;
169         }
170
171         if (get_path) {
172                 void *abc_path_void = MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath");
173                 AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(abc_path_void);
174
175                 BLI_strncpy(abc_path->path, object.getFullName().c_str(), sizeof(abc_path->path));
176                 BLI_addtail(object_paths, abc_path);
177         }
178
179         return parent_is_part_of_this_object;
180 }
181
182 AbcArchiveHandle *ABC_create_handle(const char *filename, ListBase *object_paths)
183 {
184         ArchiveReader *archive = new ArchiveReader(filename);
185
186         if (!archive->valid()) {
187                 delete archive;
188                 return NULL;
189         }
190
191         if (object_paths) {
192                 gather_objects_paths(archive->getTop(), object_paths);
193         }
194
195         return handle_from_archive(archive);
196 }
197
198 void ABC_free_handle(AbcArchiveHandle *handle)
199 {
200         delete archive_from_handle(handle);
201 }
202
203 int ABC_get_version()
204 {
205         return ALEMBIC_LIBRARY_VERSION;
206 }
207
208 static void find_iobject(const IObject &object, IObject &ret,
209                          const std::string &path)
210 {
211         if (!object.valid()) {
212                 return;
213         }
214
215         std::vector<std::string> tokens;
216         split(path, '/', tokens);
217
218         IObject tmp = object;
219
220         std::vector<std::string>::iterator iter;
221         for (iter = tokens.begin(); iter != tokens.end(); ++iter) {
222                 IObject child = tmp.getChild(*iter);
223                 tmp = child;
224         }
225
226         ret = tmp;
227 }
228
229 struct ExportJobData {
230         Scene *scene;
231         Main *bmain;
232
233         char filename[1024];
234         ExportSettings settings;
235
236         short *stop;
237         short *do_update;
238         float *progress;
239
240         bool was_canceled;
241         bool export_ok;
242 };
243
244 static void export_startjob(void *customdata, short *stop, short *do_update, float *progress)
245 {
246         ExportJobData *data = static_cast<ExportJobData *>(customdata);
247
248         data->stop = stop;
249         data->do_update = do_update;
250         data->progress = progress;
251
252         /* XXX annoying hack: needed to prevent data corruption when changing
253          * scene frame in separate threads
254          */
255         G.is_rendering = true;
256         BKE_spacedata_draw_locks(true);
257
258         G.is_break = false;
259
260         try {
261                 Scene *scene = data->scene;
262                 AbcExporter exporter(data->bmain, scene, data->filename, data->settings);
263
264                 const int orig_frame = CFRA;
265
266                 data->was_canceled = false;
267                 exporter(data->bmain, *data->progress, data->was_canceled);
268
269                 if (CFRA != orig_frame) {
270                         CFRA = orig_frame;
271
272                         BKE_scene_update_for_newframe(data->bmain->eval_ctx, data->bmain,
273                                                       scene, scene->lay);
274                 }
275
276                 data->export_ok = !data->was_canceled;
277         }
278         catch (const std::exception &e) {
279                 ABC_LOG(data->settings.logger) << "Abc Export error: " << e.what() << '\n';
280         }
281         catch (...) {
282                 ABC_LOG(data->settings.logger) << "Abc Export: unknown error...\n";
283         }
284 }
285
286 static void export_endjob(void *customdata)
287 {
288         ExportJobData *data = static_cast<ExportJobData *>(customdata);
289
290         if (data->was_canceled && BLI_exists(data->filename)) {
291                 BLI_delete(data->filename, false, false);
292         }
293
294         if (!data->settings.logger.empty()) {
295                 std::cerr << data->settings.logger;
296                 WM_report(RPT_ERROR, "Errors occured during the export, look in the console to know more...");
297         }
298
299         G.is_rendering = false;
300         BKE_spacedata_draw_locks(false);
301 }
302
303 bool ABC_export(
304         Scene *scene,
305         bContext *C,
306         const char *filepath,
307         const struct AlembicExportParams *params,
308         bool as_background_job)
309 {
310         ExportJobData *job = static_cast<ExportJobData *>(MEM_mallocN(sizeof(ExportJobData), "ExportJobData"));
311         job->scene = scene;
312         job->bmain = CTX_data_main(C);
313         job->export_ok = false;
314         BLI_strncpy(job->filename, filepath, 1024);
315
316         /* Alright, alright, alright....
317          *
318          * ExportJobData contains an ExportSettings containing a SimpleLogger.
319          *
320          * Since ExportJobData is a C-style struct dynamically allocated with
321          * MEM_mallocN (see above), its construtor is never called, therefore the
322          * ExportSettings constructor is not called which implies that the
323          * SimpleLogger one is not called either. SimpleLogger in turn does not call
324          * the constructor of its data members which ultimately means that its
325          * std::ostringstream member has a NULL pointer. To be able to properly use
326          * the stream's operator<<, the pointer needs to be set, therefore we have
327          * to properly construct everything. And this is done using the placement
328          * new operator as here below. It seems hackish, but I'm too lazy to
329          * do bigger refactor and maybe there is a better way which does not involve
330          * hardcore refactoring. */
331         new (&job->settings) ExportSettings();
332         job->settings.scene = job->scene;
333         job->settings.frame_start = params->frame_start;
334         job->settings.frame_end = params->frame_end;
335         job->settings.frame_samples_xform = params->frame_samples_xform;
336         job->settings.frame_samples_shape = params->frame_samples_shape;
337         job->settings.shutter_open = params->shutter_open;
338         job->settings.shutter_close = params->shutter_close;
339         job->settings.selected_only = params->selected_only;
340         job->settings.export_face_sets = params->face_sets;
341         job->settings.export_normals = params->normals;
342         job->settings.export_uvs = params->uvs;
343         job->settings.export_vcols = params->vcolors;
344         job->settings.export_hair = params->export_hair;
345         job->settings.export_particles = params->export_particles;
346         job->settings.apply_subdiv = params->apply_subdiv;
347         job->settings.flatten_hierarchy = params->flatten_hierarchy;
348         job->settings.visible_layers_only = params->visible_layers_only;
349         job->settings.renderable_only = params->renderable_only;
350         job->settings.use_subdiv_schema = params->use_subdiv_schema;
351         job->settings.export_ogawa = (params->compression_type == ABC_ARCHIVE_OGAWA);
352         job->settings.pack_uv = params->packuv;
353         job->settings.global_scale = params->global_scale;
354         job->settings.triangulate = params->triangulate;
355         job->settings.quad_method = params->quad_method;
356         job->settings.ngon_method = params->ngon_method;
357
358         if (job->settings.frame_start > job->settings.frame_end) {
359                 std::swap(job->settings.frame_start, job->settings.frame_end);
360         }
361
362         bool export_ok = false;
363         if (as_background_job) {
364                 wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
365                                             CTX_wm_window(C),
366                                             job->scene,
367                                             "Alembic Export",
368                                             WM_JOB_PROGRESS,
369                                             WM_JOB_TYPE_ALEMBIC);
370
371                 /* setup job */
372                 WM_jobs_customdata_set(wm_job, job, MEM_freeN);
373                 WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
374                 WM_jobs_callbacks(wm_job, export_startjob, NULL, NULL, export_endjob);
375
376                 WM_jobs_start(CTX_wm_manager(C), wm_job);
377         }
378         else {
379                 /* Fake a job context, so that we don't need NULL pointer checks while exporting. */
380                 short stop = 0, do_update = 0;
381                 float progress = 0.f;
382
383                 export_startjob(job, &stop, &do_update, &progress);
384                 export_endjob(job);
385                 export_ok = job->export_ok;
386
387                 MEM_freeN(job);
388         }
389
390         return export_ok;
391 }
392
393 /* ********************** Import file ********************** */
394
395 /**
396  * Generates an AbcObjectReader for this Alembic object and its children.
397  *
398  * \param object The Alembic IObject to visit.
399  * \param readers The created AbcObjectReader * will be appended to this vector.
400  * \param settings Import settings, not used directly but passed to the
401  *                 AbcObjectReader subclass constructors.
402  * \param r_assign_as_parent Return parameter, contains a list of reader
403  *                 pointers, whose parent pointer should still be set.
404  *                 This is filled when this call to visit_object() didn't create
405  *                 a reader that should be the parent.
406  * \return A pair of boolean and reader pointer. The boolean indicates whether
407  *         this IObject claims its parent as part of the same object
408  *         (for example an IPolyMesh object would claim its parent, as the mesh
409  *         is interpreted as the object's data, and the parent IXform as its
410  *         Blender object). The pointer is the AbcObjectReader that represents
411  *         the IObject parameter.
412  *
413  * NOTE: this function is similar to gather_object_paths above, need to keep
414  * them in sync. */
415 static std::pair<bool, AbcObjectReader *> visit_object(
416         const IObject &object,
417         AbcObjectReader::ptr_vector &readers,
418         ImportSettings &settings,
419         AbcObjectReader::ptr_vector &r_assign_as_parent)
420 {
421         const std::string & full_name = object.getFullName();
422
423         if (!object.valid()) {
424                 std::cerr << "  - "
425                           << full_name
426                           << ": object is invalid, skipping it and all its children.\n";
427                 return std::make_pair(false, static_cast<AbcObjectReader *>(NULL));
428         }
429
430         /* The interpretation of data by the children determine the role of this
431          * object. This is especially important for Xform objects, as they can be
432          * either part of a Blender object or a Blender object (Empty) themselves.
433          */
434         size_t children_claiming_this_object = 0;
435         size_t num_children = object.getNumChildren();
436         AbcObjectReader::ptr_vector claiming_child_readers;
437         AbcObjectReader::ptr_vector nonclaiming_child_readers;
438         AbcObjectReader::ptr_vector assign_as_parent;
439         for (size_t i = 0; i < num_children; ++i) {
440                 const IObject ichild = object.getChild(i);
441
442                 /* TODO: When we only support C++11, use std::tie() instead. */
443                 std::pair<bool, AbcObjectReader *> child_result;
444                 child_result = visit_object(ichild, readers, settings, assign_as_parent);
445
446                 bool child_claims_this_object = child_result.first;
447                 AbcObjectReader *child_reader = child_result.second;
448
449                 if (child_reader == NULL) {
450                         BLI_assert(!child_claims_this_object);
451                 }
452                 else {
453                         if (child_claims_this_object) {
454                                 claiming_child_readers.push_back(child_reader);
455                         }
456                         else {
457                                 nonclaiming_child_readers.push_back(child_reader);
458                         }
459                 }
460
461                 children_claiming_this_object += child_claims_this_object ? 1 : 0;
462         }
463         BLI_assert(children_claiming_this_object == claiming_child_readers.size());
464
465         AbcObjectReader *reader = NULL;
466         const MetaData &md = object.getMetaData();
467         bool parent_is_part_of_this_object = false;
468
469         if (!object.getParent()) {
470                 /* The root itself is not an object we should import. */
471         }
472         else if (IXform::matches(md)) {
473                 bool create_empty;
474
475                 /* An xform can either be a Blender Object (if it contains a mesh, for
476                  * example), but it can also be an Empty. Its correct translation to
477                  * Blender's data model depends on its children. */
478
479                 /* Check whether or not this object is a Maya locator, which is
480                  * similar to empties used as parent object in Blender. */
481                 if (has_property(object.getProperties(), "locator")) {
482                         create_empty = true;
483                 }
484                 else {
485                         create_empty = claiming_child_readers.empty();
486                 }
487
488                 if (create_empty) {
489                         reader = new AbcEmptyReader(object, settings);
490                 }
491         }
492         else if (IPolyMesh::matches(md)) {
493                 reader = new AbcMeshReader(object, settings);
494                 parent_is_part_of_this_object = true;
495         }
496         else if (ISubD::matches(md)) {
497                 reader = new AbcSubDReader(object, settings);
498                 parent_is_part_of_this_object = true;
499         }
500         else if (INuPatch::matches(md)) {
501 #ifdef USE_NURBS
502                 /* TODO(kevin): importing cyclic NURBS from other software crashes
503                  * at the moment. This is due to the fact that NURBS in other
504                  * software have duplicated points which causes buffer overflows in
505                  * Blender. Need to figure out exactly how these points are
506                  * duplicated, in all cases (cyclic U, cyclic V, and cyclic UV).
507                  * Until this is fixed, disabling NURBS reading. */
508                 reader = new AbcNurbsReader(object, settings);
509                 parent_is_part_of_this_object = true;
510 #endif
511         }
512         else if (ICamera::matches(md)) {
513                 reader = new AbcCameraReader(object, settings);
514                 parent_is_part_of_this_object = true;
515         }
516         else if (IPoints::matches(md)) {
517                 reader = new AbcPointsReader(object, settings);
518                 parent_is_part_of_this_object = true;
519         }
520         else if (IMaterial::matches(md)) {
521                 /* Pass for now. */
522         }
523         else if (ILight::matches(md)) {
524                 /* Pass for now. */
525         }
526         else if (IFaceSet::matches(md)) {
527                 /* Pass, those are handled in the mesh reader. */
528         }
529         else if (ICurves::matches(md)) {
530                 reader = new AbcCurveReader(object, settings);
531                 parent_is_part_of_this_object = true;
532         }
533         else {
534                 std::cerr << "Alembic object " << full_name
535                           << " is of unsupported schema type '"
536                           << object.getMetaData().get("schemaObjTitle") << "'"
537                           << std::endl;
538         }
539
540         if (reader) {
541                 /* We have created a reader, which should imply that this object is
542                  * not claimed as part of any child Alembic object. */
543                 BLI_assert(claiming_child_readers.empty());
544
545                 readers.push_back(reader);
546                 reader->incref();
547
548                 AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
549                                                   MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
550                 BLI_strncpy(abc_path->path, full_name.c_str(), sizeof(abc_path->path));
551                 BLI_addtail(&settings.cache_file->object_paths, abc_path);
552
553                 /* We can now assign this reader as parent for our children. */
554                 if (nonclaiming_child_readers.size() + assign_as_parent.size() > 0) {
555                         /* TODO: When we only support C++11, use for (a: b) instead. */
556                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
557                                 child_reader->parent_reader = reader;
558                         }
559                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
560                                 child_reader->parent_reader = reader;
561                         }
562                 }
563         }
564         else if (object.getParent()) {
565                 if (claiming_child_readers.size() > 0) {
566                         /* The first claiming child will serve just fine as parent to
567                          * our non-claiming children. Since all claiming children share
568                          * the same XForm, it doesn't really matter which one we pick. */
569                         AbcObjectReader *claiming_child = claiming_child_readers[0];
570                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
571                                 child_reader->parent_reader = claiming_child;
572                         }
573                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
574                                 child_reader->parent_reader = claiming_child;
575                         }
576                         /* Claiming children should have our parent set as their parent. */
577                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
578                                 r_assign_as_parent.push_back(child_reader);
579                         }
580                 }
581                 else {
582                         /* This object isn't claimed by any child, and didn't produce
583                          * a reader. Odd situation, could be the top Alembic object, or
584                          * an unsupported Alembic schema. Delegate to our parent. */
585                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
586                                 r_assign_as_parent.push_back(child_reader);
587                         }
588                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
589                                 r_assign_as_parent.push_back(child_reader);
590                         }
591                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
592                                 r_assign_as_parent.push_back(child_reader);
593                         }
594                 }
595         }
596
597         return std::make_pair(parent_is_part_of_this_object, reader);
598 }
599
600 enum {
601         ABC_NO_ERROR = 0,
602         ABC_ARCHIVE_FAIL,
603         ABC_UNSUPPORTED_HDF5,
604 };
605
606 struct ImportJobData {
607         Main *bmain;
608         Scene *scene;
609
610         char filename[1024];
611         ImportSettings settings;
612
613         std::vector<AbcObjectReader *> readers;
614
615         short *stop;
616         short *do_update;
617         float *progress;
618
619         char error_code;
620         bool was_cancelled;
621         bool import_ok;
622 };
623
624 ABC_INLINE bool is_mesh_and_strands(const IObject &object)
625 {
626         bool has_mesh = false;
627         bool has_curve = false;
628
629         for (int i = 0; i < object.getNumChildren(); ++i) {
630                 const IObject &child = object.getChild(i);
631
632                 if (!child.valid()) {
633                         continue;
634                 }
635
636                 const MetaData &md = child.getMetaData();
637
638                 if (IPolyMesh::matches(md)) {
639                         has_mesh = true;
640                 }
641                 else if (ISubD::matches(md)) {
642                         has_mesh = true;
643                 }
644                 else if (ICurves::matches(md)) {
645                         has_curve = true;
646                 }
647                 else if (IPoints::matches(md)) {
648                         has_curve = true;
649                 }
650         }
651
652         return has_mesh && has_curve;
653 }
654
655 static void import_startjob(void *user_data, short *stop, short *do_update, float *progress)
656 {
657         SCOPE_TIMER("Alembic import, objects reading and creation");
658
659         ImportJobData *data = static_cast<ImportJobData *>(user_data);
660
661         data->stop = stop;
662         data->do_update = do_update;
663         data->progress = progress;
664
665         ArchiveReader *archive = new ArchiveReader(data->filename);
666
667         if (!archive->valid()) {
668 #ifndef WITH_ALEMBIC_HDF5
669                 data->error_code = archive->is_hdf5() ? ABC_UNSUPPORTED_HDF5 : ABC_ARCHIVE_FAIL;
670 #else
671                 data->error_code = ABC_ARCHIVE_FAIL;
672 #endif
673                 delete archive;
674                 return;
675         }
676
677         CacheFile *cache_file = static_cast<CacheFile *>(BKE_cachefile_add(data->bmain, BLI_path_basename(data->filename)));
678
679         /* Decrement the ID ref-count because it is going to be incremented for each
680          * modifier and constraint that it will be attached to, so since currently
681          * it is not used by anyone, its use count will off by one. */
682         id_us_min(&cache_file->id);
683
684         cache_file->is_sequence = data->settings.is_sequence;
685         cache_file->scale = data->settings.scale;
686         cache_file->handle = handle_from_archive(archive);
687         BLI_strncpy(cache_file->filepath, data->filename, 1024);
688
689         data->settings.cache_file = cache_file;
690
691         *data->do_update = true;
692         *data->progress = 0.05f;
693
694         /* Parse Alembic Archive. */
695         AbcObjectReader::ptr_vector assign_as_parent;
696         visit_object(archive->getTop(), data->readers, data->settings, assign_as_parent);
697
698         /* There shouldn't be any orphans. */
699         BLI_assert(assign_as_parent.size() == 0);
700
701         if (G.is_break) {
702                 data->was_cancelled = true;
703                 return;
704         }
705
706         *data->do_update = true;
707         *data->progress = 0.1f;
708
709         /* Create objects and set scene frame range. */
710
711         const float size = static_cast<float>(data->readers.size());
712         size_t i = 0;
713
714         chrono_t min_time = std::numeric_limits<chrono_t>::max();
715         chrono_t max_time = std::numeric_limits<chrono_t>::min();
716
717         ISampleSelector sample_sel(0.0f);
718         std::vector<AbcObjectReader *>::iterator iter;
719         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
720                 AbcObjectReader *reader = *iter;
721
722                 if (reader->valid()) {
723                         reader->readObjectData(data->bmain, sample_sel);
724
725                         min_time = std::min(min_time, reader->minTime());
726                         max_time = std::max(max_time, reader->maxTime());
727                 }
728                 else {
729                         std::cerr << "Object " << reader->name() << " in Alembic file "
730                                   << data->filename << " is invalid.\n";
731                 }
732
733                 *data->progress = 0.1f + 0.3f * (++i / size);
734                 *data->do_update = true;
735
736                 if (G.is_break) {
737                         data->was_cancelled = true;
738                         return;
739                 }
740         }
741
742         if (data->settings.set_frame_range) {
743                 Scene *scene = data->scene;
744
745                 if (data->settings.is_sequence) {
746                         SFRA = data->settings.sequence_offset;
747                         EFRA = SFRA + (data->settings.sequence_len - 1);
748                         CFRA = SFRA;
749                 }
750                 else if (min_time < max_time) {
751                         SFRA = static_cast<int>(round(min_time * FPS));
752                         EFRA = static_cast<int>(round(max_time * FPS));
753                         CFRA = SFRA;
754                 }
755         }
756
757         /* Setup parenthood. */
758         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
759                 const AbcObjectReader *reader = *iter;
760                 const AbcObjectReader *parent_reader = reader->parent_reader;
761                 Object *ob = reader->object();
762
763                 if (parent_reader == NULL || !reader->inherits_xform()) {
764                         ob->parent = NULL;
765                 }
766                 else {
767                         ob->parent = parent_reader->object();
768                 }
769         }
770
771         /* Setup transformations and constraints. */
772         i = 0;
773         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
774                 AbcObjectReader *reader = *iter;
775                 reader->setupObjectTransform(0.0f);
776
777                 *data->progress = 0.7f + 0.3f * (++i / size);
778                 *data->do_update = true;
779
780                 if (G.is_break) {
781                         data->was_cancelled = true;
782                         return;
783                 }
784         }
785 }
786
787 static void import_endjob(void *user_data)
788 {
789         SCOPE_TIMER("Alembic import, cleanup");
790
791         ImportJobData *data = static_cast<ImportJobData *>(user_data);
792
793         std::vector<AbcObjectReader *>::iterator iter;
794
795         /* Delete objects on cancelation. */
796         if (data->was_cancelled) {
797                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
798                         Object *ob = (*iter)->object();
799
800                         /* It's possible that cancellation occured between the creation of
801                          * the reader and the creation of the Blender object. */
802                         if (ob == NULL) continue;
803
804                         BKE_libblock_free_us(data->bmain, ob);
805                 }
806         }
807         else {
808                 /* Add object to scene. */
809                 Base *base;
810
811                 BKE_scene_base_deselect_all(data->scene);
812
813                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
814                         Object *ob = (*iter)->object();
815                         ob->lay = data->scene->lay;
816
817                         base = BKE_scene_base_add(data->scene, ob);
818                         BKE_scene_base_select(data->scene, base);
819
820                         DAG_id_tag_update_ex(data->bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
821                 }
822
823                 DAG_relations_tag_update(data->bmain);
824         }
825
826         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
827                 AbcObjectReader *reader = *iter;
828                 reader->decref();
829
830                 if (reader->refcount() == 0) {
831                         delete reader;
832                 }
833         }
834
835         switch (data->error_code) {
836                 default:
837                 case ABC_NO_ERROR:
838                         data->import_ok = !data->was_cancelled;
839                         break;
840                 case ABC_ARCHIVE_FAIL:
841                         WM_report(RPT_ERROR, "Could not open Alembic archive for reading! See console for detail.");
842                         break;
843                 case ABC_UNSUPPORTED_HDF5:
844                         WM_report(RPT_ERROR, "Alembic archive in obsolete HDF5 format is not supported.");
845                         break;
846         }
847
848         WM_main_add_notifier(NC_SCENE | ND_FRAME, data->scene);
849 }
850
851 static void import_freejob(void *user_data)
852 {
853         ImportJobData *data = static_cast<ImportJobData *>(user_data);
854         delete data;
855 }
856
857 bool ABC_import(bContext *C, const char *filepath, float scale, bool is_sequence,
858                 bool set_frame_range, int sequence_len, int offset,
859                 bool validate_meshes, bool as_background_job)
860 {
861         /* Using new here since MEM_* funcs do not call ctor to properly initialize
862          * data. */
863         ImportJobData *job = new ImportJobData();
864         job->bmain = CTX_data_main(C);
865         job->scene = CTX_data_scene(C);
866         job->import_ok = false;
867         BLI_strncpy(job->filename, filepath, 1024);
868
869         job->settings.scale = scale;
870         job->settings.is_sequence = is_sequence;
871         job->settings.set_frame_range = set_frame_range;
872         job->settings.sequence_len = sequence_len;
873         job->settings.sequence_offset = offset;
874         job->settings.validate_meshes = validate_meshes;
875         job->error_code = ABC_NO_ERROR;
876         job->was_cancelled = false;
877
878         G.is_break = false;
879
880         bool import_ok = false;
881         if (as_background_job) {
882                 wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
883                                             CTX_wm_window(C),
884                                             job->scene,
885                                             "Alembic Import",
886                                             WM_JOB_PROGRESS,
887                                             WM_JOB_TYPE_ALEMBIC);
888
889                 /* setup job */
890                 WM_jobs_customdata_set(wm_job, job, import_freejob);
891                 WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
892                 WM_jobs_callbacks(wm_job, import_startjob, NULL, NULL, import_endjob);
893
894                 WM_jobs_start(CTX_wm_manager(C), wm_job);
895         }
896         else {
897                 /* Fake a job context, so that we don't need NULL pointer checks while importing. */
898                 short stop = 0, do_update = 0;
899                 float progress = 0.f;
900
901                 import_startjob(job, &stop, &do_update, &progress);
902                 import_endjob(job);
903                 import_ok = job->import_ok;
904
905                 import_freejob(job);
906         }
907
908         return import_ok;
909 }
910
911 /* ************************************************************************** */
912
913 void ABC_get_transform(CacheReader *reader, float r_mat[4][4], float time, float scale)
914 {
915         if (!reader) {
916                 return;
917         }
918
919         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
920
921         bool is_constant = false;
922         abc_reader->read_matrix(r_mat, time, scale, is_constant);
923 }
924
925 /* ************************************************************************** */
926
927 DerivedMesh *ABC_read_mesh(CacheReader *reader,
928                            Object *ob,
929                            DerivedMesh *dm,
930                            const float time,
931                            const char **err_str,
932                            int read_flag)
933 {
934         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
935         IObject iobject = abc_reader->iobject();
936
937         if (!iobject.valid()) {
938                 *err_str = "Invalid object: verify object path";
939                 return NULL;
940         }
941
942         const ObjectHeader &header = iobject.getHeader();
943         if (!abc_reader->accepts_object_type(header, ob, err_str)) {
944                 /* err_str is set by acceptsObjectType() */
945                 return NULL;
946         }
947
948         /* kFloorIndex is used to be compatible with non-interpolating
949          * properties; they use the floor. */
950         ISampleSelector sample_sel(time, ISampleSelector::kFloorIndex);
951         return abc_reader->read_derivedmesh(dm, sample_sel, read_flag, err_str);
952 }
953
954 /* ************************************************************************** */
955
956 void CacheReader_free(CacheReader *reader)
957 {
958         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
959         abc_reader->decref();
960
961         if (abc_reader->refcount() == 0) {
962                 delete abc_reader;
963         }
964 }
965
966 void CacheReader_incref(CacheReader *reader)
967 {
968         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
969         abc_reader->incref();
970 }
971
972 CacheReader *CacheReader_open_alembic_object(AbcArchiveHandle *handle, CacheReader *reader, Object *object, const char *object_path)
973 {
974         if (object_path[0] == '\0') {
975                 return reader;
976         }
977
978         ArchiveReader *archive = archive_from_handle(handle);
979
980         if (!archive || !archive->valid()) {
981                 return reader;
982         }
983
984         IObject iobject;
985         find_iobject(archive->getTop(), iobject, object_path);
986
987         if (reader) {
988                 CacheReader_free(reader);
989         }
990
991         ImportSettings settings;
992         AbcObjectReader *abc_reader = create_reader(iobject, settings);
993         if (abc_reader == NULL) {
994                 /* This object is not supported */
995                 return NULL;
996         }
997         abc_reader->object(object);
998         abc_reader->incref();
999
1000         return reinterpret_cast<CacheReader *>(abc_reader);
1001 }