Alembic import: select imported objects
[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(), PATH_MAX);
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(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_step_xform = params->frame_step_xform;
336         job->settings.frame_step_shape = params->frame_step_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         if (as_background_job) {
363                 wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
364                                             CTX_wm_window(C),
365                                             job->scene,
366                                             "Alembic Export",
367                                             WM_JOB_PROGRESS,
368                                             WM_JOB_TYPE_ALEMBIC);
369
370                 /* setup job */
371                 WM_jobs_customdata_set(wm_job, job, MEM_freeN);
372                 WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
373                 WM_jobs_callbacks(wm_job, export_startjob, NULL, NULL, export_endjob);
374
375                 WM_jobs_start(CTX_wm_manager(C), wm_job);
376         }
377         else {
378                 /* Fake a job context, so that we don't need NULL pointer checks while exporting. */
379                 short stop = 0, do_update = 0;
380                 float progress = 0.f;
381
382                 export_startjob(job, &stop, &do_update, &progress);
383                 export_endjob(job);
384         }
385
386         return job->export_ok;
387 }
388
389 /* ********************** Import file ********************** */
390
391 /**
392  * Generates an AbcObjectReader for this Alembic object and its children.
393  *
394  * \param object The Alembic IObject to visit.
395  * \param readers The created AbcObjectReader * will be appended to this vector.
396  * \param settings Import settings, not used directly but passed to the
397  *                 AbcObjectReader subclass constructors.
398  * \param r_assign_as_parent Return parameter, contains a list of reader
399  *                 pointers, whose parent pointer should still be set.
400  *                 This is filled when this call to visit_object() didn't create
401  *                 a reader that should be the parent.
402  * \return A pair of boolean and reader pointer. The boolean indicates whether
403  *         this IObject claims its parent as part of the same object
404  *         (for example an IPolyMesh object would claim its parent, as the mesh
405  *         is interpreted as the object's data, and the parent IXform as its
406  *         Blender object). The pointer is the AbcObjectReader that represents
407  *         the IObject parameter.
408  *
409  * NOTE: this function is similar to gather_object_paths above, need to keep
410  * them in sync. */
411 static std::pair<bool, AbcObjectReader *> visit_object(
412         const IObject &object,
413         AbcObjectReader::ptr_vector &readers,
414         ImportSettings &settings,
415         AbcObjectReader::ptr_vector &r_assign_as_parent)
416 {
417         const std::string & full_name = object.getFullName();
418
419         if (!object.valid()) {
420                 std::cerr << "  - "
421                           << full_name
422                           << ": object is invalid, skipping it and all its children.\n";
423                 return std::make_pair(false, static_cast<AbcObjectReader *>(NULL));
424         }
425
426         /* The interpretation of data by the children determine the role of this
427          * object. This is especially important for Xform objects, as they can be
428          * either part of a Blender object or a Blender object (Empty) themselves.
429          */
430         size_t children_claiming_this_object = 0;
431         size_t num_children = object.getNumChildren();
432         AbcObjectReader::ptr_vector claiming_child_readers;
433         AbcObjectReader::ptr_vector nonclaiming_child_readers;
434         AbcObjectReader::ptr_vector assign_as_parent;
435         for (size_t i = 0; i < num_children; ++i) {
436                 const IObject ichild = object.getChild(i);
437
438                 /* TODO: When we only support C++11, use std::tie() instead. */
439                 std::pair<bool, AbcObjectReader *> child_result;
440                 child_result = visit_object(ichild, readers, settings, assign_as_parent);
441
442                 bool child_claims_this_object = child_result.first;
443                 AbcObjectReader *child_reader = child_result.second;
444
445                 if (child_reader == NULL) {
446                         BLI_assert(!child_claims_this_object);
447                 }
448                 else {
449                         if (child_claims_this_object) {
450                                 claiming_child_readers.push_back(child_reader);
451                         } else {
452                                 nonclaiming_child_readers.push_back(child_reader);
453                         }
454                 }
455
456                 children_claiming_this_object += child_claims_this_object ? 1 : 0;
457         }
458         BLI_assert(children_claiming_this_object == claiming_child_readers.size());
459
460         AbcObjectReader *reader = NULL;
461         const MetaData &md = object.getMetaData();
462         bool parent_is_part_of_this_object = false;
463
464         if (!object.getParent()) {
465                 /* The root itself is not an object we should import. */
466         }
467         else if (IXform::matches(md)) {
468                 bool create_empty;
469
470                 /* An xform can either be a Blender Object (if it contains a mesh, for
471                  * example), but it can also be an Empty. Its correct translation to
472                  * Blender's data model depends on its children. */
473
474                 /* Check whether or not this object is a Maya locator, which is
475                  * similar to empties used as parent object in Blender. */
476                 if (has_property(object.getProperties(), "locator")) {
477                         create_empty = true;
478                 }
479                 else {
480                         create_empty = claiming_child_readers.empty();
481                 }
482
483                 if (create_empty) {
484                         reader = new AbcEmptyReader(object, settings);
485                 }
486         }
487         else if (IPolyMesh::matches(md)) {
488                 reader = new AbcMeshReader(object, settings);
489                 parent_is_part_of_this_object = true;
490         }
491         else if (ISubD::matches(md)) {
492                 reader = new AbcSubDReader(object, settings);
493                 parent_is_part_of_this_object = true;
494         }
495         else if (INuPatch::matches(md)) {
496 #ifdef USE_NURBS
497                 /* TODO(kevin): importing cyclic NURBS from other software crashes
498                  * at the moment. This is due to the fact that NURBS in other
499                  * software have duplicated points which causes buffer overflows in
500                  * Blender. Need to figure out exactly how these points are
501                  * duplicated, in all cases (cyclic U, cyclic V, and cyclic UV).
502                  * Until this is fixed, disabling NURBS reading. */
503                 reader = new AbcNurbsReader(object, settings);
504                 parent_is_part_of_this_object = true;
505 #endif
506         }
507         else if (ICamera::matches(md)) {
508                 reader = new AbcCameraReader(object, settings);
509                 parent_is_part_of_this_object = true;
510         }
511         else if (IPoints::matches(md)) {
512                 reader = new AbcPointsReader(object, settings);
513                 parent_is_part_of_this_object = true;
514         }
515         else if (IMaterial::matches(md)) {
516                 /* Pass for now. */
517         }
518         else if (ILight::matches(md)) {
519                 /* Pass for now. */
520         }
521         else if (IFaceSet::matches(md)) {
522                 /* Pass, those are handled in the mesh reader. */
523         }
524         else if (ICurves::matches(md)) {
525                 reader = new AbcCurveReader(object, settings);
526                 parent_is_part_of_this_object = true;
527         }
528         else {
529                 std::cerr << "Alembic object " << full_name
530                           << " is of unsupported schema type '"
531                           << object.getMetaData().get("schemaObjTitle") << "'"
532                           << std::endl;
533         }
534
535         if (reader) {
536                 /* We have created a reader, which should imply that this object is
537                  * not claimed as part of any child Alembic object. */
538                 BLI_assert(claiming_child_readers.empty());
539
540                 readers.push_back(reader);
541                 reader->incref();
542
543                 AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
544                                                   MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
545                 BLI_strncpy(abc_path->path, full_name.c_str(), PATH_MAX);
546                 BLI_addtail(&settings.cache_file->object_paths, abc_path);
547
548                 /* We can now assign this reader as parent for our children. */
549                 if (nonclaiming_child_readers.size() + assign_as_parent.size() > 0) {
550                         /* TODO: When we only support C++11, use for (a: b) instead. */
551                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
552                                 child_reader->parent_reader = reader;
553                         }
554                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
555                                 child_reader->parent_reader = reader;
556                         }
557                 }
558         }
559         else if (object.getParent()) {
560                 if (claiming_child_readers.size() > 0) {
561                         /* The first claiming child will serve just fine as parent to
562                          * our non-claiming children. Since all claiming children share
563                          * the same XForm, it doesn't really matter which one we pick. */
564                         AbcObjectReader *claiming_child = claiming_child_readers[0];
565                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
566                                 child_reader->parent_reader = claiming_child;
567                         }
568                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
569                                 child_reader->parent_reader = claiming_child;
570                         }
571                         /* Claiming children should have our parent set as their parent. */
572                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
573                                 r_assign_as_parent.push_back(child_reader);
574                         }
575                 }
576                 else {
577                         /* This object isn't claimed by any child, and didn't produce
578                          * a reader. Odd situation, could be the top Alembic object, or
579                          * an unsupported Alembic schema. Delegate to our parent. */
580                         BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
581                                 r_assign_as_parent.push_back(child_reader);
582                         }
583                         BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
584                                 r_assign_as_parent.push_back(child_reader);
585                         }
586                         BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
587                                 r_assign_as_parent.push_back(child_reader);
588                         }
589                 }
590         }
591
592         return std::make_pair(parent_is_part_of_this_object, reader);
593 }
594
595 enum {
596         ABC_NO_ERROR = 0,
597         ABC_ARCHIVE_FAIL,
598 };
599
600 struct ImportJobData {
601         Main *bmain;
602         Scene *scene;
603
604         char filename[1024];
605         ImportSettings settings;
606
607         std::vector<AbcObjectReader *> readers;
608
609         short *stop;
610         short *do_update;
611         float *progress;
612
613         char error_code;
614         bool was_cancelled;
615         bool import_ok;
616 };
617
618 ABC_INLINE bool is_mesh_and_strands(const IObject &object)
619 {
620         bool has_mesh = false;
621         bool has_curve = false;
622
623         for (int i = 0; i < object.getNumChildren(); ++i) {
624                 const IObject &child = object.getChild(i);
625
626                 if (!child.valid()) {
627                         continue;
628                 }
629
630                 const MetaData &md = child.getMetaData();
631
632                 if (IPolyMesh::matches(md)) {
633                         has_mesh = true;
634                 }
635                 else if (ISubD::matches(md)) {
636                         has_mesh = true;
637                 }
638                 else if (ICurves::matches(md)) {
639                         has_curve = true;
640                 }
641                 else if (IPoints::matches(md)) {
642                         has_curve = true;
643                 }
644         }
645
646         return has_mesh && has_curve;
647 }
648
649 static void import_startjob(void *user_data, short *stop, short *do_update, float *progress)
650 {
651         SCOPE_TIMER("Alembic import, objects reading and creation");
652
653         ImportJobData *data = static_cast<ImportJobData *>(user_data);
654
655         data->stop = stop;
656         data->do_update = do_update;
657         data->progress = progress;
658
659         ArchiveReader *archive = new ArchiveReader(data->filename);
660
661         if (!archive->valid()) {
662                 delete archive;
663                 data->error_code = ABC_ARCHIVE_FAIL;
664                 return;
665         }
666
667         CacheFile *cache_file = static_cast<CacheFile *>(BKE_cachefile_add(data->bmain, BLI_path_basename(data->filename)));
668
669         /* Decrement the ID ref-count because it is going to be incremented for each
670          * modifier and constraint that it will be attached to, so since currently
671          * it is not used by anyone, its use count will off by one. */
672         id_us_min(&cache_file->id);
673
674         cache_file->is_sequence = data->settings.is_sequence;
675         cache_file->scale = data->settings.scale;
676         cache_file->handle = handle_from_archive(archive);
677         BLI_strncpy(cache_file->filepath, data->filename, 1024);
678
679         data->settings.cache_file = cache_file;
680
681         *data->do_update = true;
682         *data->progress = 0.05f;
683
684         /* Parse Alembic Archive. */
685         AbcObjectReader::ptr_vector assign_as_parent;
686         visit_object(archive->getTop(), data->readers, data->settings, assign_as_parent);
687
688         /* There shouldn't be any orphans. */
689         BLI_assert(assign_as_parent.size() == 0);
690
691         if (G.is_break) {
692                 data->was_cancelled = true;
693                 return;
694         }
695
696         *data->do_update = true;
697         *data->progress = 0.1f;
698
699         /* Create objects and set scene frame range. */
700
701         const float size = static_cast<float>(data->readers.size());
702         size_t i = 0;
703
704         chrono_t min_time = std::numeric_limits<chrono_t>::max();
705         chrono_t max_time = std::numeric_limits<chrono_t>::min();
706
707         std::vector<AbcObjectReader *>::iterator iter;
708         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
709                 AbcObjectReader *reader = *iter;
710
711                 if (reader->valid()) {
712                         reader->readObjectData(data->bmain, 0.0f);
713
714                         min_time = std::min(min_time, reader->minTime());
715                         max_time = std::max(max_time, reader->maxTime());
716                 }
717                 else {
718                         std::cerr << "Object " << reader->name() << " in Alembic file "
719                                   << data->filename << " is invalid.\n";
720                 }
721
722                 *data->progress = 0.1f + 0.3f * (++i / size);
723                 *data->do_update = true;
724
725                 if (G.is_break) {
726                         data->was_cancelled = true;
727                         return;
728                 }
729         }
730
731         if (data->settings.set_frame_range) {
732                 Scene *scene = data->scene;
733
734                 if (data->settings.is_sequence) {
735                         SFRA = data->settings.offset;
736                         EFRA = SFRA + (data->settings.sequence_len - 1);
737                         CFRA = SFRA;
738                 }
739                 else if (min_time < max_time) {
740                         SFRA = static_cast<int>(round(min_time * FPS));
741                         EFRA = static_cast<int>(round(max_time * FPS));
742                         CFRA = SFRA;
743                 }
744         }
745
746         /* Setup parenthood. */
747         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
748                 const AbcObjectReader *reader = *iter;
749                 const AbcObjectReader *parent_reader = reader->parent_reader;
750                 Object *ob = reader->object();
751
752                 if (parent_reader == NULL) {
753                         ob->parent = NULL;
754                 }
755                 else {
756                         ob->parent = parent_reader->object();
757                 }
758         }
759
760         /* Setup transformations and constraints. */
761         i = 0;
762         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
763                 AbcObjectReader *reader = *iter;
764                 reader->setupObjectTransform(0.0f);
765
766                 *data->progress = 0.7f + 0.3f * (++i / size);
767                 *data->do_update = true;
768
769                 if (G.is_break) {
770                         data->was_cancelled = true;
771                         return;
772                 }
773         }
774 }
775
776 static void import_endjob(void *user_data)
777 {
778         SCOPE_TIMER("Alembic import, cleanup");
779
780         ImportJobData *data = static_cast<ImportJobData *>(user_data);
781
782         std::vector<AbcObjectReader *>::iterator iter;
783
784         /* Delete objects on cancelation. */
785         if (data->was_cancelled) {
786                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
787                         Object *ob = (*iter)->object();
788
789                         /* It's possible that cancellation occured between the creation of
790                          * the reader and the creation of the Blender object. */
791                         if (ob == NULL) continue;
792
793                         BKE_libblock_free_us(data->bmain, ob);
794                 }
795         }
796         else {
797                 /* Add object to scene. */
798                 Base *base;
799
800                 BKE_scene_base_deselect_all(data->scene);
801
802                 for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
803                         Object *ob = (*iter)->object();
804                         ob->lay = data->scene->lay;
805
806                         base = BKE_scene_base_add(data->scene, ob);
807                         BKE_scene_base_select(data->scene, base);
808
809                         DAG_id_tag_update_ex(data->bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
810                 }
811
812                 DAG_relations_tag_update(data->bmain);
813         }
814
815         for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
816                 AbcObjectReader *reader = *iter;
817                 reader->decref();
818
819                 if (reader->refcount() == 0) {
820                         delete reader;
821                 }
822         }
823
824         switch (data->error_code) {
825                 default:
826                 case ABC_NO_ERROR:
827                         data->import_ok = !data->was_cancelled;
828                         break;
829                 case ABC_ARCHIVE_FAIL:
830                         WM_report(RPT_ERROR, "Could not open Alembic archive for reading! See console for detail.");
831                         break;
832         }
833
834         WM_main_add_notifier(NC_SCENE | ND_FRAME, data->scene);
835 }
836
837 static void import_freejob(void *user_data)
838 {
839         ImportJobData *data = static_cast<ImportJobData *>(user_data);
840         delete data;
841 }
842
843 bool ABC_import(bContext *C, const char *filepath, float scale, bool is_sequence,
844                 bool set_frame_range, int sequence_len, int offset,
845                 bool validate_meshes, bool as_background_job)
846 {
847         /* Using new here since MEM_* funcs do not call ctor to properly initialize
848          * data. */
849         ImportJobData *job = new ImportJobData();
850         job->bmain = CTX_data_main(C);
851         job->scene = CTX_data_scene(C);
852         job->import_ok = false;
853         BLI_strncpy(job->filename, filepath, 1024);
854
855         job->settings.scale = scale;
856         job->settings.is_sequence = is_sequence;
857         job->settings.set_frame_range = set_frame_range;
858         job->settings.sequence_len = sequence_len;
859         job->settings.offset = offset;
860         job->settings.validate_meshes = validate_meshes;
861         job->error_code = ABC_NO_ERROR;
862         job->was_cancelled = false;
863
864         G.is_break = false;
865
866         if (as_background_job) {
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         else {
882                 /* Fake a job context, so that we don't need NULL pointer checks while importing. */
883                 short stop = 0, do_update = 0;
884                 float progress = 0.f;
885
886                 import_startjob(job, &stop, &do_update, &progress);
887                 import_endjob(job);
888         }
889
890         return job->import_ok;
891 }
892
893 /* ************************************************************************** */
894
895 void ABC_get_transform(CacheReader *reader, float r_mat[4][4], float time, float scale)
896 {
897         if (!reader) {
898                 return;
899         }
900
901         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
902
903         bool is_constant = false;
904         abc_reader->read_matrix(r_mat, time, scale, is_constant);
905 }
906
907 /* ************************************************************************** */
908
909 DerivedMesh *ABC_read_mesh(CacheReader *reader,
910                            Object *ob,
911                            DerivedMesh *dm,
912                            const float time,
913                            const char **err_str,
914                            int read_flag)
915 {
916         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
917         IObject iobject = abc_reader->iobject();
918
919         if (!iobject.valid()) {
920                 *err_str = "Invalid object: verify object path";
921                 return NULL;
922         }
923
924         const ObjectHeader &header = iobject.getHeader();
925
926         if (IPolyMesh::matches(header)) {
927                 if (ob->type != OB_MESH) {
928                         *err_str = "Object type mismatch: object path points to a mesh!";
929                         return NULL;
930                 }
931
932                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
933         }
934         else if (ISubD::matches(header)) {
935                 if (ob->type != OB_MESH) {
936                         *err_str = "Object type mismatch: object path points to a subdivision mesh!";
937                         return NULL;
938                 }
939
940                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
941         }
942         else if (IPoints::matches(header)) {
943                 if (ob->type != OB_MESH) {
944                         *err_str = "Object type mismatch: object path points to a point cloud (requires a mesh object)!";
945                         return NULL;
946                 }
947
948                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
949         }
950         else if (ICurves::matches(header)) {
951                 if (ob->type != OB_CURVE) {
952                         *err_str = "Object type mismatch: object path points to a curve!";
953                         return NULL;
954                 }
955
956                 return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
957         }
958
959         *err_str = "Unsupported object type: verify object path"; // or poke developer
960         return NULL;
961 }
962
963 /* ************************************************************************** */
964
965 void CacheReader_free(CacheReader *reader)
966 {
967         AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
968         abc_reader->decref();
969
970         if (abc_reader->refcount() == 0) {
971                 delete abc_reader;
972         }
973 }
974
975 CacheReader *CacheReader_open_alembic_object(AbcArchiveHandle *handle, CacheReader *reader, Object *object, const char *object_path)
976 {
977         if (object_path[0] == '\0') {
978                 return reader;
979         }
980
981         ArchiveReader *archive = archive_from_handle(handle);
982
983         if (!archive || !archive->valid()) {
984                 return reader;
985         }
986
987         IObject iobject;
988         find_iobject(archive->getTop(), iobject, object_path);
989
990         if (reader) {
991                 CacheReader_free(reader);
992         }
993
994         ImportSettings settings;
995         AbcObjectReader *abc_reader = create_reader(iobject, settings);
996         abc_reader->object(object);
997         abc_reader->incref();
998
999         return reinterpret_cast<CacheReader *>(abc_reader);
1000 }