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