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