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