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