-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathalembicReader.cpp
4245 lines (3697 loc) · 128 KB
/
alembicReader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2016-2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/// \file alembicReader.cpp
#include "pxr/pxr.h"
#include "pxr/usd/usdAbc/alembicReader.h"
#include "pxr/usd/usdAbc/alembicUtil.h"
#include "pxr/usd/usdGeom/tokens.h"
#include "pxr/usd/usdGeom/xformable.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/base/work/threadLimits.h"
#include "pxr/base/trace/trace.h"
#include "pxr/base/tf/envSetting.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/ostreamMethods.h"
#include <boost/type_traits/is_base_of.hpp>
#include <boost/utility/enable_if.hpp>
#include <Alembic/Abc/ArchiveInfo.h>
#include <Alembic/Abc/IArchive.h>
#include <Alembic/Abc/IObject.h>
#include <Alembic/Abc/ITypedArrayProperty.h>
#include <Alembic/Abc/ITypedScalarProperty.h>
#include <Alembic/AbcCoreAbstract/Foundation.h>
#ifdef PXR_MULTIVERSE_SUPPORT_ENABLED
#include <Alembic/AbcCoreGit/All.h>
#endif // PXR_MULTIVERSE_SUPPORT_ENABLED
#ifdef PXR_HDF5_SUPPORT_ENABLED
#include <Alembic/AbcCoreHDF5/All.h>
#endif // PXR_HDF5_SUPPORT_ENABLED
#include <Alembic/AbcCoreOgawa/All.h>
#include <Alembic/AbcGeom/GeometryScope.h>
#include <Alembic/AbcGeom/ICamera.h>
#include <Alembic/AbcGeom/ICurves.h>
#include <Alembic/AbcGeom/IPoints.h>
#include <Alembic/AbcGeom/IPolyMesh.h>
#include <Alembic/AbcGeom/ISubD.h>
#include <Alembic/AbcGeom/IXform.h>
#include <Alembic/AbcGeom/SchemaInfoDeclarations.h>
#include <Alembic/AbcGeom/Visibility.h>
#include <functional>
#include <memory>
#include <mutex>
PXR_NAMESPACE_OPEN_SCOPE
// Define this to dump the namespace hierarchy as we traverse Alembic.
//#define USDABC_ALEMBIC_DEBUG
TF_DEFINE_PRIVATE_TOKENS(
_tokens,
(transform)
((xformOpTransform, "xformOp:transform"))
);
TF_DEFINE_ENV_SETTING(
USD_ABC_WARN_ALL_UNSUPPORTED_VALUES, false,
"Issue warnings for all unsupported values encountered.");
TF_DEFINE_ENV_SETTING(
USD_ABC_NUM_OGAWA_STREAMS, 4,
"The number of threads available for reading ogawa-backed files via UsdAbc.");
TF_DEFINE_ENV_SETTING(
USD_ABC_WRITE_UV_AS_ST_TEXCOORD2FARRAY, false,
"Switch to true to enable writing Alembic uv sets as primvars:st with type "
"texCoord2fArray to USD");
TF_DEFINE_ENV_SETTING(
USD_ABC_XFORM_PRIM_COLLAPSE, true,
"Collapse Xforms containing a single geometry into a single geom Prim in USD");
#if ALEMBIC_LIBRARY_VERSION >= 10709
TF_DEFINE_ENV_SETTING(
USD_ABC_READ_ARCHIVE_USE_MMAP, false,
"Use mmap when reading from an Ogawa archive.");
#endif
namespace {
using namespace ::Alembic::AbcGeom;
using namespace UsdAbc_AlembicUtil;
static const TfToken&
_GetUVPropertyName()
{
static const TfToken uvUsdAbcPropertyName =
(TfGetEnvSetting(USD_ABC_WRITE_UV_AS_ST_TEXCOORD2FARRAY)) ?
(UsdAbcPropertyNames->st) : (UsdAbcPropertyNames->uv);
return uvUsdAbcPropertyName;
}
static const SdfValueTypeName&
_GetUVTypeName()
{
static const SdfValueTypeName uvTypeName =
(TfGetEnvSetting(USD_ABC_WRITE_UV_AS_ST_TEXCOORD2FARRAY)) ?
(SdfValueTypeNames->TexCoord2fArray) : (SdfValueTypeNames->Float2Array);
return uvTypeName;
}
static size_t
_GetNumOgawaStreams()
{
return std::min(TfGetEnvSetting(USD_ABC_NUM_OGAWA_STREAMS),
static_cast<int>(WorkGetConcurrencyLimit()));
}
#ifdef PXR_HDF5_SUPPORT_ENABLED
// A global mutex until our HDF5 library is thread safe. It has to be
// recursive to handle the case where we write an Alembic file using an
// UsdAbc_AlembicData as the source.
static TfStaticData<std::recursive_mutex> _hdf5;
#endif // PXR_HDF5_SUPPORT_ENABLED
// The SdfAbstractData time samples type.
// XXX: SdfAbstractData should typedef this.
typedef std::set<double> UsdAbc_TimeSamples;
// A vector of Alembic times.
typedef std::vector<chrono_t> _AlembicTimeSamples;
class _ReaderContext;
class _PrimReaderContext;
//
// Error / warning message helpers
//
// Helper function to produce a string representing the path
// to an Alembic property.
static std::string
_GetAlembicPath(const IScalarProperty& p)
{
std::vector<std::string> names;
names.push_back(p.getName());
for (ICompoundProperty prop = p.getParent();
prop.valid(); prop = prop.getParent()) {
names.push_back(prop.getName());
}
const std::string propName = TfStringJoin(names.rbegin(), names.rend(),".");
std::string path = p.getObject().getFullName();
if (!propName.empty() && propName[0] != '.') {
path += '.';
}
path += propName;
return path;
}
// Produce a string description of the sample selector
static std::string
_GetSampleSelectorDescription(const ISampleSelector& iss)
{
if (iss.getRequestedIndex() == -1) {
return "sample time " + TfStringify(iss.getRequestedTime());
}
return "sample index " + TfStringify(iss.getRequestedIndex());
}
enum _WarningType
{
WarningVisibility = 0,
WarningSubdivisionScheme,
WarningInterpolateBoundary,
WarningFaceVaryingInterpolateBoundary
};
static const char* _WarningNames[] =
{
"visibility",
"subdivision scheme",
"interpolate boundary",
"face varying interpolate boundary"
};
static void
_PostUnsupportedValueWarning(
const IScalarProperty& property,
const ISampleSelector& iss,
_WarningType warning,
const std::string& authoredValue,
const std::string& replacementValue)
{
const IObject object = property.getObject();
const std::string archiveName = object.getArchive().getName();
if (TfGetEnvSetting(USD_ABC_WARN_ALL_UNSUPPORTED_VALUES)) {
TF_WARN(
"Unsupported %s '%s' for <%s> at %s in archive '%s'. "
"Using '%s' instead.",
_WarningNames[warning],
authoredValue.c_str(),
_GetAlembicPath(property).c_str(),
_GetSampleSelectorDescription(iss).c_str(),
archiveName.c_str(),
replacementValue.c_str());
return;
}
typedef std::pair<_WarningType, std::string> _WarningAndArchive;
typedef std::set<_WarningAndArchive> _IssuedWarnings;
static _IssuedWarnings warnings;
static std::mutex mutex;
bool issueWarning = false;
{
std::lock_guard<std::mutex> lock(mutex);
const _WarningAndArchive newWarning(warning, archiveName);
issueWarning = warnings.insert(newWarning).second;
}
if (issueWarning) {
TF_WARN(
"Unsupported %s detected in archive '%s'. Using '%s' instead.",
_WarningNames[warning], archiveName.c_str(),
replacementValue.c_str());
}
}
//
// Name helpers
//
struct _AlembicFixName {
std::string operator()(std::string const &x) const {
return TfMakeValidIdentifier(x);
}
};
struct _AlembicFixNamespacedName {
std::string operator()(std::string const &x) const {
auto elems = TfStringSplit(x, ":");
std::transform(elems.begin(), elems.end(), elems.begin(),
TfMakeValidIdentifier);
return TfStringJoin(elems, ":");
}
};
template <class T>
static
std::string
_CleanName(
const std::string& inName,
const char* trimLeading,
const std::set<std::string>& usedNames,
T fixer,
bool (*test)(const std::string&) = &SdfPath::IsValidIdentifier)
{
// Just return the name if it doesn't need mangling. We assume the
// client has prepopulated usedNames with all Alembic names in the group.
if (test(inName)) {
return TfToken(inName);
}
// Mangle name into desired form.
// Handle empty name.
std::string name = inName;
if (name.empty()) {
name = '_';
}
else {
// Trim leading.
name = TfStringTrimLeft(name, trimLeading);
// If name is not a valid identifier then substitute characters.
if (!test(name)) {
name = fixer(name);
}
}
// Now check against usedNames.
if (usedNames.find(name) != usedNames.end()) {
// Just number the tries.
int i = 0;
std::string attempt = TfStringPrintf("%s_%d", name.c_str(), ++i);
while (usedNames.find(attempt) != usedNames.end()) {
attempt = TfStringPrintf("%s_%d", name.c_str(), ++i);
}
name = attempt;
}
return name;
}
//
// Metadata helpers
//
// A map of metadata.
typedef std::map<TfToken, VtValue> MetadataMap;
/// Returns the Alembic metadata name for a Usd metadata field name.
static
std::string
_AmdName(const std::string& name)
{
return "Usd:" + name;
}
static
void
_GetBoolMetadata(
const MetaData& alembicMetadata,
MetadataMap& usdMetadata,
const TfToken& field)
{
std::string value = alembicMetadata.get(_AmdName(field));
if (!value.empty()) {
usdMetadata[field] = VtValue(value == "true");
}
}
static
void
_GetStringMetadata(
const MetaData& alembicMetadata,
MetadataMap& usdMetadata,
const TfToken& field)
{
std::string value = alembicMetadata.get(_AmdName(field));
if (!value.empty()) {
usdMetadata[field] = VtValue(value);
}
}
static
void
_GetTokenMetadata(
const MetaData& alembicMetadata,
MetadataMap& usdMetadata,
const TfToken& field)
{
std::string value = alembicMetadata.get(_AmdName(field));
if (!value.empty()) {
usdMetadata[field] = VtValue(TfToken(value));
}
}
static
void
_GetDoubleMetadata(
const MetaData& alembicMetadata,
MetadataMap& usdMetadata,
const TfToken& field)
{
std::string value = alembicMetadata.get(_AmdName(field));
if (!value.empty()) {
char* end;
const double v = strtod(value.c_str(), &end);
if (*end == '\0') {
usdMetadata[field] = VtValue(v);
}
}
}
//
// AlembicProperty
//
// Helpers for \c AlembicProperty.
template <class T, class Enable = void>
struct _AlembicPropertyHelper {
// T operator()(const ICompoundProperty& parent, const std::string& name)const;
};
template <>
struct _AlembicPropertyHelper<ICompoundProperty> {
ICompoundProperty
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (header->isCompound()) {
return ICompoundProperty(parent, name);
}
}
return ICompoundProperty();
}
};
template <>
struct _AlembicPropertyHelper<IScalarProperty> {
IScalarProperty
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (header->isScalar()) {
return IScalarProperty(parent, name);
}
}
return IScalarProperty();
}
};
template <class T>
struct _AlembicPropertyHelper<ITypedScalarProperty<T> > {
ITypedScalarProperty<T>
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (ITypedScalarProperty<T>::matches(*header)) {
return ITypedScalarProperty<T>(parent, name);
}
}
return ITypedScalarProperty<T>();
}
};
template <>
struct _AlembicPropertyHelper<IArrayProperty> {
IArrayProperty
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (header->isArray()) {
return IArrayProperty(parent, name);
}
}
return IArrayProperty();
}
};
template <class T>
struct _AlembicPropertyHelper<ITypedArrayProperty<T> > {
ITypedArrayProperty<T>
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (ITypedArrayProperty<T>::matches(*header)) {
return ITypedArrayProperty<T>(parent, name);
}
}
return ITypedArrayProperty<T>();
}
};
template <class T>
struct _AlembicPropertyHelper<ITypedGeomParam<T> > {
ITypedGeomParam<T>
operator()(const ICompoundProperty& parent, const std::string& name) const
{
if (const PropertyHeader* header = parent.getPropertyHeader(name)) {
if (ITypedGeomParam<T>::matches(*header)) {
return ITypedGeomParam<T>(parent, name);
}
}
return ITypedGeomParam<T>();
}
};
/// \class AlembicProperty
/// \brief Wraps an Alembic property of any type.
///
/// An object of this type can hold any Alembic property but it must be
/// cast to get a concrete property object. The client must know what
/// to cast to but the client can get the property header that describes
/// the held data.
class AlembicProperty {
public:
AlembicProperty(const SdfPath& path, const std::string& name);
AlembicProperty(const SdfPath& path, const std::string& name,
const IObject& parent);
AlembicProperty(const SdfPath& path, const std::string& name,
const ICompoundProperty& parent);
/// Returns the Usd path for this property.
const SdfPath& GetPath() const;
/// Returns the parent compound property.
ICompoundProperty GetParent() const;
/// Returns the name of the property.
const std::string& GetName() const;
/// Get the property header. This returns \c NULL if the property
/// doesn't exist.
const PropertyHeader* GetHeader() const;
/// This is the only way to get an actual Alembic property object.
/// You must supply the expected type. If it's incorrect then
/// you'll get an object of the requested type but its valid()
/// method will return \c false.
template <class T>
T Cast() const
{
if (_parent.valid()) {
return _AlembicPropertyHelper<T>()(_parent, _name);
}
else {
return T();
}
}
private:
SdfPath _path;
ICompoundProperty _parent;
std::string _name;
};
AlembicProperty::AlembicProperty(
const SdfPath& path,
const std::string& name) :
_path(path), _parent(), _name(name)
{
// Do nothing
}
AlembicProperty::AlembicProperty(
const SdfPath& path,
const std::string& name,
const IObject& parent) :
_path(path), _parent(parent.getProperties()), _name(name)
{
// Do nothing
}
AlembicProperty::AlembicProperty(
const SdfPath& path,
const std::string& name,
const ICompoundProperty& parent) :
_path(path), _parent(parent), _name(name)
{
// Do nothing
}
const SdfPath&
AlembicProperty::GetPath() const
{
return _path;
}
ICompoundProperty
AlembicProperty::GetParent() const
{
return _parent;
}
const std::string&
AlembicProperty::GetName() const
{
return _name;
}
const PropertyHeader*
AlembicProperty::GetHeader() const
{
return _parent.valid() ? _parent.getPropertyHeader(_name) : NULL;
}
//
// _ReaderSchema
//
/// \class _ReaderSchema
/// \brief The Usd to Alembic schema.
///
/// This class stores functions to read a Usd prim from Alembic keyed by
/// type. Each type can have multiple readers, each affected by the
/// previous via a \c _PrimReaderContext.
class _ReaderSchema {
public:
typedef std::function<void (_PrimReaderContext*)> PrimReader;
typedef std::vector<PrimReader> PrimReaderVector;
typedef UsdAbc_AlembicDataConversion::ToUsdConverter Converter;
_ReaderSchema();
/// Returns the prim readers for the given Alembic schema. Returns an
/// empty vector if the schema isn't known.
const PrimReaderVector& GetPrimReaders(const std::string& schema) const;
// Helper for defining types.
class TypeRef {
public:
TypeRef(PrimReaderVector* readers) : _readerVector(readers) { }
TypeRef& AppendReader(const PrimReader& reader)
{
_readerVector->push_back(reader);
return *this;
}
private:
PrimReaderVector* _readerVector;
};
/// Adds a type and returns a helper for defining it.
template <class T>
TypeRef AddType(T name)
{
return TypeRef(&_readers[name]);
}
/// Adds the fallback type and returns a helper for defining it.
TypeRef AddFallbackType()
{
return AddType(std::string());
}
/// Returns the object holding the conversions registry.
const UsdAbc_AlembicDataConversion& GetConversions() const
{
return _conversions.data;
}
private:
const UsdAbc_AlembicConversions _conversions;
typedef std::map<std::string, PrimReaderVector> _ReaderMap;
_ReaderMap _readers;
};
_ReaderSchema::_ReaderSchema()
{
// Do nothing
}
const _ReaderSchema::PrimReaderVector&
_ReaderSchema::GetPrimReaders(const std::string& schema) const
{
_ReaderMap::const_iterator i = _readers.find(schema);
if (i != _readers.end()) {
return i->second;
}
i = _readers.find(std::string());
if (i != _readers.end()) {
return i->second;
}
static const PrimReaderVector empty;
return empty;
}
/// \class _ReaderContext
/// \brief The Alembic to Usd writer context.
///
/// This object holds information used by the writer for a given archive
/// and Usd data.
class _ReaderContext {
public:
/// Gets data from some property at a given sample.
typedef std::function<bool (const UsdAbc_AlembicDataAny&,
const ISampleSelector&)> Converter;
/// An optional ordering of name children or properties.
typedef boost::optional<TfTokenVector> Ordering;
/// Sample times.
typedef UsdAbc_AlembicDataReader::TimeSamples TimeSamples;
/// Sample index.
typedef UsdAbc_AlembicDataReader::Index Index;
/// Property cache.
struct Property {
SdfValueTypeName typeName;
MetadataMap metadata;
TimeSamples sampleTimes;
bool timeSampled;
bool uniform;
Converter converter;
};
typedef std::map<TfToken, Property> PropertyMap;
/// Prim cache.
struct Prim {
Prim() : instanceable(false), promoted(false) { }
TfToken typeName;
TfTokenVector children;
TfTokenVector properties;
SdfSpecifier specifier;
Ordering primOrdering;
Ordering propertyOrdering;
MetadataMap metadata;
PropertyMap propertiesCache;
SdfPath master; // Path to master; only set on instances
std::string instanceSource; // Alembic path to instance source;
// only set on master.
bool instanceable; // Instanceable; only set on master.
bool promoted; // True if a promoted instance/master
};
_ReaderContext();
/// \name Reader setup
/// @{
/// Open an archive.
bool Open(const std::string& filePath, std::string* errorLog);
/// Close the archive.
void Close();
/// Sets the reader schema.
void SetSchema(const _ReaderSchema* schema) { _schema = schema; }
/// Returns the reader schema.
const _ReaderSchema& GetSchema() const { return *_schema; }
/// Sets or resets the flag named \p flagName.
void SetFlag(const TfToken& flagName, bool set);
/// @}
/// \name Reader caching
/// @{
/// Returns \c true iff a flag is in the set.
bool IsFlagSet(const TfToken& flagName) const;
/// Creates and returns the prim cache for path \p path.
Prim& AddPrim(const SdfPath& path);
/// Returns \c true if \p object is an instance in Usd (i.e. it's an
/// instance in Alembic or is the source of an instance).
bool IsInstance(const IObject& object) const;
/// Creates and returns the prim cache for path \p path that's an
/// instance of \p object.
Prim& AddInstance(const SdfPath& path, const IObject& object);
/// Creates and returns the property cache for path \p path.
Property& FindOrCreateProperty(const SdfPath& path);
/// Returns the property cache for path \p path if it exists, otherwise
/// \c NULL.
const Property* FindProperty(const SdfPath& path);
/// Returns the sample times converted to Usd.
TimeSamples ConvertSampleTimes(const _AlembicTimeSamples&) const;
/// Add the given sample times to the global set of sample times.
void AddSampleTimes(const TimeSamples&);
/// @}
/// \name SdfAbstractData access
/// @{
/// Test for the existence of a spec at \p id.
bool HasSpec(const SdfAbstractDataSpecId& id) const;
/// Returns the spec type for the spec at \p id.
SdfSpecType GetSpecType(const SdfAbstractDataSpecId& id) const;
/// Test for the existence of and optionally return the value at
/// (\p id,\p fieldName).
bool HasField(const SdfAbstractDataSpecId& id,
const TfToken& fieldName,
const UsdAbc_AlembicDataAny& value) const;
/// Test for the existence of and optionally return the value of the
/// property at \p id at index \p index.
bool HasValue(const SdfAbstractDataSpecId& id, Index index,
const UsdAbc_AlembicDataAny& value) const;
/// Visit the specs.
void VisitSpecs(const SdfAbstractData& owner,
SdfAbstractDataSpecVisitor* visitor) const;
/// List the fields.
TfTokenVector List(const SdfAbstractDataSpecId& id) const;
/// Returns the sampled times over all properties.
const UsdAbc_TimeSamples& ListAllTimeSamples() const;
/// Returns the sampled times for the property with id \p id.
const TimeSamples&
ListTimeSamplesForPath(const SdfAbstractDataSpecId& id) const;
/// @}
private:
typedef AbcA::ObjectReaderPtr _ObjectPtr;
typedef std::set<_ObjectPtr> _ObjectReaderSet;
typedef std::map<_ObjectPtr, _ObjectReaderSet> _SourceToInstancesMap;
// Open an archive of different formats.
bool _OpenHDF5(const std::string& filePath, IArchive*,
std::string* format, std::recursive_mutex** mutex) const;
bool _OpenOgawa(const std::string& filePath, IArchive*,
std::string* format, std::recursive_mutex** mutex) const;
bool _OpenGit(const std::string& filePath, IArchive*,
std::string* format, std::recursive_mutex** mutex) const;
// Walk the object hierarchy looking for instances and instance sources.
static void _FindInstances(const IObject& parent,
_SourceToInstancesMap* instances);
// Add to promotable those instance sources that are promotable.
static void _FindPromotable(const _SourceToInstancesMap& instances,
_ObjectReaderSet* promotable);
// Store instancing state.
void _SetupInstancing(const _SourceToInstancesMap& instances,
const _ObjectReaderSet& promotable,
std::set<std::string>* usedNames);
// Clear caches.
void _Clear();
const Prim* _GetPrim(const SdfAbstractDataSpecId& id) const;
const Property* _GetProperty(const Prim&,
const SdfAbstractDataSpecId& id) const;
bool _HasField(const Prim* prim,
const TfToken& fieldName,
const UsdAbc_AlembicDataAny& value) const;
bool _HasField(const Property* property,
const TfToken& fieldName,
const UsdAbc_AlembicDataAny& value) const;
bool _HasValue(const Property* property,
const ISampleSelector& selector,
const UsdAbc_AlembicDataAny& value) const;
// Custom auto-lock that safely ignores a NULL pointer.
class _Lock : boost::noncopyable {
public:
_Lock(std::recursive_mutex* mutex) : _mutex(mutex) {
if (_mutex) _mutex->lock();
}
~_Lock() { if (_mutex) _mutex->unlock(); }
private:
std::recursive_mutex* _mutex;
};
private:
// The mutex to lock when reading the archive. This is NULL except
// for HDF5.
mutable std::recursive_mutex* _mutex;
// Conversion options.
double _timeScale; // Scale Alembic time by this factor.
double _timeOffset; // Offset Alembic->Usd time (after scale).
std::set<TfToken, TfTokenFastArbitraryLessThan> _flags;
// Input state.
IArchive _archive;
const _ReaderSchema* _schema;
// A map of the full names of known instance sources. The mapped
// value has the Usd master path and whether we're using the actual
// instance source or its parent. We use the parent in some cases
// in order to get more sharing in the Usd world.
struct _MasterInfo {
SdfPath path;
bool promoted;
};
typedef std::map<std::string, _MasterInfo> _SourceToMasterMap;
_SourceToMasterMap _instanceSources;
// A map of full name of instance to full name of source. If we're
// using the parent of the source as the master then the source path
// is the parent of the actual source and the instance path is the
// parent of the actual instance.
typedef std::map<std::string, std::string> _InstanceToSourceMap;
_InstanceToSourceMap _instances;
// Caches.
typedef std::map<SdfPath, Prim> _PrimMap;
_PrimMap _prims;
Prim* _pseudoRoot;
UsdAbc_TimeSamples _allTimeSamples;
};
static
void
_ReadPrimChildren(
_ReaderContext& context,
const IObject& object,
const SdfPath& path,
_ReaderContext::Prim& prim);
_ReaderContext::_ReaderContext() :
_mutex(NULL),
_timeScale(24.0), // Usd is frames, Alembic is seconds.
_timeOffset(0.0), // Time 0.0 to frame 0.
_schema(NULL)
{
// Do nothing
}
bool
_ReaderContext::Open(const std::string& filePath, std::string* errorLog)
{
Close();
IArchive archive;
std::string format;
if (!(_OpenOgawa(filePath, &archive, &format, &_mutex) ||
_OpenHDF5(filePath, &archive, &format, &_mutex) ||
_OpenGit(filePath, &archive, &format, &_mutex))) {
*errorLog = "Unsupported format";
return false;
}
// Lock _mutex if it exists for remainder of this method.
_Lock lock(_mutex);
// Get info.
uint32_t apiVersion;
std::string writer, version, date, comment;
GetArchiveInfo(archive, writer, version, apiVersion, date, comment);
// Report.
if (IsFlagSet(UsdAbc_AlembicContextFlagNames->verbose)) {
TF_STATUS("Opened %s file written by Alembic %s",
format.c_str(),
UsdAbc_FormatAlembicVersion(apiVersion).c_str());
}
// Cut over.
_archive = archive;
// Fill pseudo-root in the cache.
const SdfPath rootPath = SdfPath::AbsoluteRootPath();
_pseudoRoot = &_prims[rootPath];
_pseudoRoot->metadata[SdfFieldKeys->Documentation] = comment;
// Gather the names of the root prims. Instancing will want to create
// new root prims. Those must have unique names that don't modify the
// names of existing root prims. So we have to have the existing names
// first.
IObject root = _archive.getTop();
std::set<std::string> usedRootNames;
for (size_t i = 0, n = root.getNumChildren(); i != n; ++i) {
IObject child(root, root.getChildHeader(i).getName());
std::string name = _CleanName(child.getName(), " _", usedRootNames,
_AlembicFixName(),
&SdfPath::IsValidIdentifier);
usedRootNames.insert(name);
}
// Fetch authored timeCodesPerSecond early so that we can use it
// for rescaling timeSamples.
if (const PropertyHeader* property =
root.getProperties().getPropertyHeader("Usd")) {
const MetaData& metadata = property->getMetaData();
_pseudoRoot->metadata[SdfFieldKeys->TimeCodesPerSecond] = 24.0;
_GetDoubleMetadata(metadata, _pseudoRoot->metadata,
SdfFieldKeys->TimeCodesPerSecond);
_timeScale = _pseudoRoot->metadata[SdfFieldKeys->TimeCodesPerSecond].Get<double>();
}
// Collect instancing information.
// Skipping this step makes later code expand instances.
if (!IsFlagSet(UsdAbc_AlembicContextFlagNames->expandInstances)) {
// Find the instance sources and their instances.
_SourceToInstancesMap instances;
_FindInstances(root, &instances);
// If we're allowing instance promotion find the candidates.
_ObjectReaderSet promotable;
if (IsFlagSet(UsdAbc_AlembicContextFlagNames->promoteInstances)) {
_FindPromotable(instances, &promotable);
}
// Save instancing info to lookup during main traversal, including
// choosing paths for the masters.
_SetupInstancing(instances, promotable, &usedRootNames);
}
// Fill rest of the cache.
_ReadPrimChildren(*this, root, rootPath, *_pseudoRoot);
// Append the masters to the pseudo-root. We use lexicographical order
// but the order doesn't really matter. We also note here the Alembic
// source path for each master and whether it's instanceable or not
// (which is chosen simply by the disableInstancing flag).
if (!_instanceSources.empty()) {
const bool instanceable =
!IsFlagSet(UsdAbc_AlembicContextFlagNames->disableInstancing);
std::map<SdfPath, std::string> masters;
for (const _SourceToMasterMap::value_type& v: _instanceSources) {
masters[v.second.path] = v.first;
}
for (const auto& master: masters) {
const SdfPath& name = master.first;