forked from PixarAnimationStudios/OpenUSD
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlayer.cpp
3824 lines (3281 loc) · 115 KB
/
layer.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 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 Sdf/layer.cpp
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/assetPathResolver.h"
#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/changeManager.h"
#include "pxr/usd/sdf/childrenPolicies.h"
#include "pxr/usd/sdf/childrenUtils.h"
#include "pxr/usd/sdf/debugCodes.h"
#include "pxr/usd/sdf/fileFormat.h"
#include "pxr/usd/sdf/layerRegistry.h"
#include "pxr/usd/sdf/layerStateDelegate.h"
#include "pxr/usd/sdf/notice.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/sdf/reference.h"
#include "pxr/usd/sdf/relationshipSpec.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/specType.h"
#include "pxr/usd/sdf/textFileFormat.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/subLayerListEditor.h"
#include "pxr/usd/sdf/variantSetSpec.h"
#include "pxr/usd/sdf/variantSpec.h"
#include "pxr/base/tracelite/trace.h"
#include "pxr/usd/ar/resolver.h"
#include "pxr/usd/ar/resolverContextBinder.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/tf/fileUtils.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/mallocTag.h"
#include "pxr/base/tf/ostreamMethods.h"
#include "pxr/base/tf/pathUtils.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/scopeDescription.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/stackTrace.h"
#include <boost/bind.hpp>
#include <atomic>
#include <fstream>
#include <set>
#include <vector>
using boost::bind;
using std::map;
using std::set;
using std::string;
using std::vector;
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define< SdfLayer, TfType::Bases<SdfLayerBase> >();
}
// Muted Layers stores the paths of layers that should be muted. The stored
// paths should be asset paths, when applicable, or identifiers if no asset
// path exists for the desired layers.
typedef set<string> _MutedLayers;
typedef std::map<std::string, SdfAbstractDataRefPtr> _MutedLayerDataMap;
static TfStaticData<_MutedLayers> _mutedLayers;
static TfStaticData<_MutedLayerDataMap> _mutedLayerData;
// Global mutex protecting _mutedLayers and _mutedLayerData
static TfStaticData<std::mutex> _mutedLayersMutex;
// This is a global revision number that tracks changes to _mutedLayers. Since
// we seldom mute and unmute layers, this lets layers cache their muteness and
// do quick validity checks without taking a lock and looking themselves up in
// _mutedLayers.
static std::atomic_size_t _mutedLayersRevision { 1 };
// A registry for loaded layers.
static TfStaticData<Sdf_LayerRegistry> _layerRegistry;
// Global mutex protecting _layerRegistry.
static TfStaticData<std::mutex> _layerRegistryMutex;
SdfLayer::SdfLayer(
const SdfFileFormatConstPtr &fileFormat,
const string &identifier,
const string &realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args) :
SdfLayerBase(fileFormat, args),
_idRegistry(SdfLayerHandle(this)),
_data(fileFormat->InitData(args)),
_stateDelegate(SdfSimpleLayerStateDelegate::New()),
_lastDirtyState(false),
_assetInfo(new Sdf_AssetInfo),
_mutedLayersRevisionCache(0),
_isMutedCache(false),
_permissionToEdit(true),
_permissionToSave(true)
{
TF_DEBUG(SDF_LAYER).Msg("SdfLayer::SdfLayer('%s', '%s')\n",
identifier.c_str(), realPath.c_str());
// If the identifier has the anonymous layer identifier prefix, it is a
// template into which the layer address must be inserted. This ensures
// that anonymous layers have unique identifiers, and can be referenced by
// Sd object reprs.
string layerIdentifier = Sdf_IsAnonLayerIdentifier(identifier) ?
Sdf_ComputeAnonLayerIdentifier(identifier, this) : identifier;
// Lock the initialization mutex before we publish this object
// (i.e. add it to the registry in _InitializeFromIdentifier).
// This ensures that other threads looking for this layer will
// block until it is fully initialized.
_initializationMutex.lock();
// Initialize layer asset information.
_InitializeFromIdentifier(layerIdentifier, realPath, std::string(), assetInfo);
// A new layer is not dirty.
_MarkCurrentStateAsClean();
}
// CODE_COVERAGE_OFF
SdfLayer::~SdfLayer()
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::~SdfLayer('%s')\n", GetIdentifier().c_str());
if (IsMuted()) {
std::string mutedPath = _GetMutedPath();
SdfAbstractDataRefPtr mutedData;
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
// Drop any in-memory edits we may have been holding for this layer.
// To minimize time holding the lock, swap the data out and
// erase the entry, then release the lock before proceeding
// to drop the refcount.
_MutedLayerDataMap::iterator i = _mutedLayerData->find(mutedPath);
if (i != _mutedLayerData->end()) {
std::swap(mutedData, i->second);
_mutedLayerData->erase(i);
}
}
}
std::lock_guard<std::mutex> lock(*_layerRegistryMutex);
// Note that FindOrOpen may have already removed this layer from
// the registry, so we count on this API not emitting errors in that
// case.
_layerRegistry->Erase(SdfCreateHandle(this));
}
// CODE_COVERAGE_ON
// ---
// SdfLayer static functions and data
// ---
SdfLayerRefPtr
SdfLayer::_CreateNewWithFormat(
const SdfFileFormatConstPtr &fileFormat,
const string& identifier,
const string& realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments& args)
{
// This method should be called with _layerRegistryMutex already held.
// Create and return a new layer with _initializationMutex locked.
return fileFormat->NewLayer<SdfLayer>(
fileFormat, identifier, realPath, assetInfo, args);
}
void
SdfLayer::_FinishInitialization(bool success)
{
_initializationWasSuccessful = success;
_initializationMutex.unlock();
}
bool
SdfLayer::_WaitForInitializationAndCheckIfSuccessful()
{
// Note: the caller is responsible for holding a reference to this
// layer, to keep it from being destroyed out from under us while
// blocked on the mutex.
// Drop the GIL in case we might have it -- if the layer load happening in
// another thread needs the GIL, we'd deadlock here.
TF_PY_ALLOW_THREADS_IN_SCOPE();
// Try to acquire and then release _initializationMutex. If the
// layer is still being initialized, this will be locked, blocking
// progress until initialization completes and the mutex unlocks.
_initializationMutex.lock();
_initializationMutex.unlock();
// For various reasons, initialization may have failed.
// For example, the menva parser may have hit a syntax error,
// or transfering content from a source layer may have failed.
// In this case _initializationWasSuccessful will be set to false.
// The callers of this method are responsible for checking the result
// and dropping any references they hold. As a convenience to them,
// we return the value here.
return _initializationWasSuccessful.get();
}
SdfLayerRefPtr
SdfLayer::CreateAnonymous(const string& tag)
{
// XXX:
// It would be nice to use the _GetFileFormatForPath helper function
// from below, but that function expects a layer identifier and the
// tag is supposed to be just a helpful debugging aid; the fact that
// one can specify an underlying layer file format by specifying an
// extension was unintended.
SdfFileFormatConstPtr fileFormat;
const string suffix = TfStringGetSuffix(tag);
if (not suffix.empty()) {
fileFormat = SdfFileFormat::FindById(TfToken(suffix));
}
if (not fileFormat) {
fileFormat = SdfFileFormat::FindById(SdfTextFileFormatTokens->Id);
}
if (not fileFormat) {
TF_CODING_ERROR("Cannot determine file format for anonymous SdfLayer");
return SdfLayerRefPtr();
}
return _CreateAnonymousWithFormat(fileFormat, tag);
}
SdfLayerRefPtr
SdfLayer::_CreateAnonymousWithFormat(
const SdfFileFormatConstPtr &fileFormat, const std::string& tag)
{
std::lock_guard<std::mutex> lock(*_layerRegistryMutex);
SdfLayerRefPtr layer =
_CreateNewWithFormat(
fileFormat, Sdf_GetAnonLayerIdentifierTemplate(tag), string());
// No layer initialization required, so initialization is complete.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
bool
SdfLayer::IsAnonymous() const
{
return Sdf_IsAnonLayerIdentifier(GetIdentifier());
}
bool
SdfLayer::IsAnonymousLayerIdentifier(const string& identifier)
{
return Sdf_IsAnonLayerIdentifier(identifier);
}
string
SdfLayer::GetDisplayNameFromIdentifier(const string& identifier)
{
return Sdf_GetLayerDisplayName(identifier);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const string& identifier,
const string& realPath,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s', '%s')\n",
identifier.c_str(), realPath.c_str(), TfStringify(args).c_str());
return _CreateNew(TfNullPtr, identifier, realPath, ArAssetInfo(), args);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const string& realPath,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s', '%s', '%s')\n",
fileFormat->GetFormatId().GetText(),
identifier.c_str(), realPath.c_str(), TfStringify(args).c_str());
return _CreateNew(fileFormat, identifier, realPath, ArAssetInfo(), args);
}
static SdfFileFormatConstPtr
_GetFileFormatForPath(const std::string &filePath,
const SdfLayer::FileFormatArguments &args)
{
// Determine which file extension to use.
const string ext = ArGetResolver().GetExtension(filePath);
if (ext.empty()) {
return TfNullPtr;
}
// Find a file format that can handle this extension and the
// specified target (if any).
const std::string* target =
TfMapLookupPtr(args, SdfFileFormatTokens->TargetArg);
return SdfFileFormat::FindByExtension(
ext, (target ? *target : std::string()));
}
SdfLayerRefPtr
SdfLayer::_CreateNew(
SdfFileFormatConstPtr fileFormat,
const string& identifier,
const string& realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args)
{
if (Sdf_IsAnonLayerIdentifier(identifier)) {
TF_CODING_ERROR("Cannot create a new layer with anonymous "
"layer identifier '%s'.", identifier.c_str());
return TfNullPtr;
}
string whyNot;
if (not Sdf_CanCreateNewLayerWithIdentifier(identifier, &whyNot)) {
TF_CODING_ERROR("Cannot create new layer '%s': %s",
identifier.c_str(),
whyNot.c_str());
return TfNullPtr;
}
ArResolver& resolver = ArGetResolver();
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const bool isRelativePath = resolver.IsRelativePath(identifier);
const string absIdentifier =
isRelativePath ? TfAbsPath(identifier) : identifier;
// In case of failure below, we want to release the layer
// registry mutex lock before destroying the layer.
SdfLayerRefPtr layer;
{
std::lock_guard<std::mutex> lock(*_layerRegistryMutex);
// Check for existing layer with this identifier.
if (_layerRegistry->Find(absIdentifier)) {
TF_CODING_ERROR("A layer already exists with identifier '%s'",
absIdentifier.c_str());
return TfNullPtr;
}
// Direct newly created layers to a local path.
const string localPath = realPath.empty() ?
resolver.ComputeLocalPath(absIdentifier) : realPath;
if (localPath.empty()) {
TF_CODING_ERROR(
"Failed to compute local path for new layer with "
"identifier '%s'", absIdentifier.c_str());
return TfNullPtr;
}
// If not explicitly supplied one, try to determine the fileFormat
// based on the identifier suffix,
if (not fileFormat) {
fileFormat = _GetFileFormatForPath(absIdentifier, args);
if (not TF_VERIFY(fileFormat))
return TfNullPtr;
}
layer = _CreateNewWithFormat(
fileFormat, absIdentifier, localPath, assetInfo, args);
// XXX 2011-08-19 Newly created layers should not be
// saved to disk automatically.
//
// Force the save here to ensure this new layer overwrites any
// existing layer on disk.
if (not TF_VERIFY(layer) or not layer->_Save(/* force = */ true)) {
// Dropping the layer reference will destroy it, and
// the destructor will remove it from the registry.
return TfNullPtr;
}
// Once we have saved the layer, initialization is complete.
layer->_FinishInitialization(/* success = */ true);
}
// Return loaded layer or special-cased in-memory layer.
return layer;
}
// Creates a new empty layer with the given identifier for a given file
// format class. This is so that Python File Format classes can create
// layers (CreateNew(); doesn't work, because it already saves during
// construction of the layer. That is something specific (python generated)
// layer types may choose to not do.)
SdfLayerRefPtr
SdfLayer::New(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const string& realPath,
const FileFormatArguments& args)
{
// No layer identifier or realPath policies can be applied at this point.
// This method is called by the file format implementation to create new
// layer objects. Policy is applied in CreateNew.
if (not fileFormat) {
TF_CODING_ERROR("Invalid file format");
return TfNullPtr;
}
if (identifier.empty()) {
TF_CODING_ERROR("Cannot construct a layer with an empty identifier.");
return TfNullPtr;
}
std::lock_guard<std::mutex> lock(*_layerRegistryMutex);
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const string absIdentifier = ArGetResolver().IsRelativePath(identifier) ?
TfAbsPath(identifier) : identifier;
SdfLayerRefPtr layer = _CreateNewWithFormat(
fileFormat, absIdentifier, realPath, ArAssetInfo(), args);
// No further initialization required.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
/* static */
string
SdfLayer::ComputeRealPath(const string &layerPath)
{
return Sdf_ComputeFilePath(layerPath);
}
static SdfLayer::FileFormatArguments&
_CanonicalizeFileFormatArguments(const std::string& filePath,
const SdfFileFormatConstPtr& fileFormat,
SdfLayer::FileFormatArguments& args)
{
// Nothing to do if there isn't an associated file format.
// This is expected by _ComputeInfoToFindOrOpenLayer and isn't an error.
if (not fileFormat) {
// XXX:
// Sdf is unable to determine a file format for layers that are created
// without a file extension (which includes anonymous layers). The keys
// for these layers in the registry will never include a 'target'
// argument -- the API doesn't give you a way to do that.
//
// So, if a 'target' is specified here, we want to strip it out
// so Find and FindOrOpen will search the registry and find these
// layers. If we didn't, we would search the registry for an
// identifier with the 'target' arg embedded, and we'd never find
// it.
//
// This is a hack. I think the right thing is to either:
// a) Ensure that a layer's identifier always encodes its file format
// b) Do this target argument stripping in Find / FindOrOpen, find
// the layer, then verify that the layer's target is the one that
// was specified.
//
// These are larger changes that require updating some clients, so
// I don't want to do this yet.
if (ArGetResolver().GetExtension(filePath).empty()) {
args.erase(SdfFileFormatTokens->TargetArg);
}
return args;
}
// If the file format plugin being used to open the indicated layer
// is the primary plugin for layers of that type, it means the 'target'
// argument (if any) had no effect and can be stripped from the arguments.
if (fileFormat->IsPrimaryFormatForExtensions()) {
args.erase(SdfFileFormatTokens->TargetArg);
}
// If there aren't any more args to canonicalize, we can exit early.
if (args.empty()) {
return args;
}
// Strip out any arguments that match the file format's published
// default arguments. A layer opened without any arguments should
// be considered equivalent to a layer opened with only default
// arguments specified.
const SdfLayer::FileFormatArguments defaultArgs =
fileFormat->GetDefaultFileFormatArguments();
TF_FOR_ALL(it, defaultArgs) {
SdfLayer::FileFormatArguments::iterator argIt = args.find(it->first);
if (argIt != args.end() and argIt->second == it->second) {
args.erase(argIt);
}
}
return args;
}
struct SdfLayer::_FindOrOpenLayerInfo
{
// File format plugin for the layer. This may be NULL if
// the file format could not be identified.
SdfFileFormatConstPtr fileFormat;
// Canonical file format arguments.
SdfLayer::FileFormatArguments fileFormatArgs;
// Path to the layer.
string layerPath;
// Identifier for the layer, combining both the layer path and
// file format arguments.
string identifier;
};
bool
SdfLayer::_ComputeInfoToFindOrOpenLayer(
const string& identifier,
const SdfLayer::FileFormatArguments& args,
_FindOrOpenLayerInfo* info)
{
TRACE_FUNCTION();
if (identifier.empty()) {
return false;
}
string layerPath;
SdfLayer::FileFormatArguments layerArgs;
if (not Sdf_SplitIdentifier(identifier, &layerPath, &layerArgs) or
layerPath.empty()) {
return false;
}
// Merge explicitly-specified arguments over any arguments
// embedded in the given identifier.
if (layerArgs.empty()) {
layerArgs = args;
}
else {
TF_FOR_ALL(it, args) {
layerArgs[it->first] = it->second;
}
}
info->fileFormat = _GetFileFormatForPath(layerPath, layerArgs);
info->fileFormatArgs.swap(_CanonicalizeFileFormatArguments(
layerPath, info->fileFormat, layerArgs));
info->layerPath.swap(layerPath);
info->identifier = Sdf_CreateIdentifier(
info->layerPath, info->fileFormatArgs);
return true;
}
SdfLayerRefPtr
SdfLayer::_TryToFindLayer(const string &identifier,
const string &resolvedPath)
{
if (SdfLayerHandle layer = _layerRegistry->Find(identifier, resolvedPath)) {
// Try to acquire a TfRefPtr to this layer. Since we have
// _layerRegistryMutex locked, we guarantee that the layer's
// TfRefBase will not be destroyed until we unlock.
SdfLayerRefPtr layerRef = TfCreateRefPtrFromProtectedWeakPtr(layer);
if (layerRef) {
return layerRef;
}
// The layer is expiring.
// Leave _layerRegistryMutex locked and continue below to
// re-open the layer as a new object. Remove the soon-to-vanish
// layer from the registry to pre-empt errors about adding a
// duplicate entry for the same asset path.
_layerRegistry->Erase(layer);
}
return TfNullPtr;
}
/* static */
SdfLayerRefPtr
SdfLayer::FindOrOpen(const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::FindOrOpen('%s', '%s')\n",
identifier.c_str(), TfStringify(args).c_str());
// Drop the GIL, since if we hold it and another thread that has the
// _layerRegistryMutex needs it (if its opening code invokes python, for
// instance), we'll deadlock.
TF_PY_ALLOW_THREADS_IN_SCOPE();
_FindOrOpenLayerInfo layerInfo;
if (not _ComputeInfoToFindOrOpenLayer(identifier, args, &layerInfo))
return TfNullPtr;
// Resolve the path before we take the lock, since doing the resolution is
// slow.
bool isAnonymous = IsAnonymousLayerIdentifier(layerInfo.layerPath);
// If we're trying to open an anonymous layer, do not try to compute the
// real path for it.
ArAssetInfo assetInfo;
const string resolvedPath = isAnonymous ? layerInfo.layerPath :
Sdf_ResolvePath(layerInfo.layerPath, &assetInfo);
// First see if this layer is already present.
_layerRegistryMutex->lock();
if (SdfLayerRefPtr layer =
_TryToFindLayer(layerInfo.identifier, resolvedPath)) {
// Unlock the mutex so other threads trying to access
// unrelated layers can proceed while this thread waits
// for this layer to be ready.
_layerRegistryMutex->unlock();
return layer->_WaitForInitializationAndCheckIfSuccessful()
? layer
: TfNullPtr;
}
if (resolvedPath.empty()) {
_layerRegistryMutex->unlock();
return TfNullPtr;
}
// Otherwise we create the layer and insert it into the registry.
return _OpenLayerAndUnlockRegistry(layerInfo, /* metadataOnly */ false,
resolvedPath, assetInfo, isAnonymous);
}
/* static */
SdfLayerRefPtr
SdfLayer::OpenAsAnonymous(
const std::string &layerPath,
bool metadataOnly)
{
// Find a file format that can handle this extension.
const SdfFileFormatConstPtr format =
_GetFileFormatForPath(layerPath, FileFormatArguments());
if (not format) {
TF_CODING_ERROR("Cannot locate file format plugin for reading @%s@",
layerPath.c_str());
return TfNullPtr;
}
// Resolve the file path.
const string resolvedPath = Sdf_ResolvePath(layerPath);
if (resolvedPath.empty()) {
return TfNullPtr;
}
// Create a new anonymous layer.
SdfLayerRefPtr layer;
{
std::lock_guard<std::mutex> lock(*_layerRegistryMutex);
layer = _CreateNewWithFormat(
format, Sdf_GetAnonLayerIdentifierTemplate(string()),
string());
// From this point, we must call _FinishInitialization() on
// either success or failure in order to unblock other
// threads waiting for initialization to finish.
}
// Run the file parser to read in the file contents.
if (not layer->_ReadFromFile(layerPath, resolvedPath, metadataOnly)) {
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
layer->_MarkCurrentStateAsClean();
layer->_FinishInitialization(/* success = */ true);
return layer;
}
const SdfSchemaBase&
SdfLayer::GetSchema() const
{
return SdfSchema::GetInstance();
}
SdfLayer::_ReloadResult
SdfLayer::_Reload(bool force)
{
TRACE_FUNCTION();
string identifier = GetIdentifier();
if (identifier.empty()) {
TF_CODING_ERROR("Can't reload a layer with no identifier");
return _ReloadFailed;
}
SdfChangeBlock block;
if (IsAnonymous() and GetFileFormat()->ShouldSkipAnonymousReload()) {
// Different file formats have different policies for reloading
// anonymous layers. Some want to treat it as a noop, others want to
// treat it as 'Clear'.
//
// XXX: in the future, I think we want FileFormat plugins to
// have a Reload function. The plugin can manage when it needs to
// reload data appropriately.
return _ReloadSkipped;
}
else if (IsMuted() or IsAnonymous()) {
// Reloading a muted layer leaves it with the initialized contents.
SdfAbstractDataRefPtr initialData =
GetFileFormat()->InitData(GetFileFormatArguments());
if (_data->Equals(initialData)) {
return _ReloadSkipped;
}
_SetData(initialData);
} else {
// The physical location of the file may have changed since
// the last load, so re-resolve the identifier.
string oldRealPath = GetRealPath();
UpdateAssetInfo();
string realPath = GetRealPath();
// If path resolution in UpdateAssetInfo failed, we may end
// up with an empty real path, and cannot reload the layer.
if (realPath.empty()) {
TF_RUNTIME_ERROR(
"Cannot determine real path for '%s', skipping reload.",
identifier.c_str());
return _ReloadFailed;
}
// If this layer's modification timestamp is empty, this is a
// new layer that has never been serialized. This could happen
// if a layer were created with SdfLayer::New, for instance.
// In such cases we can skip the reload since there's nowhere
// to reload data from.
//
// This ensures we don't ask for the modification timestamp for
// unserialized new layers below, which would result in errors.
//
// XXX 2014-09-02 Reset layer to initial data?
if (_assetModificationTime.IsEmpty()) {
return _ReloadSkipped;
}
// Get the layer's modification timestamp.
VtValue timestamp = ArGetResolver().GetModificationTimestamp(
GetIdentifier(), realPath);
if (timestamp.IsEmpty()) {
TF_CODING_ERROR(
"Unable to get modification time for '%s (%s)'",
GetIdentifier().c_str(), realPath.c_str());
return _ReloadFailed;
}
// See if we can skip reloading.
if (not force and not IsDirty()
and (realPath == oldRealPath)
and (timestamp == _assetModificationTime)) {
return _ReloadSkipped;
}
if (not _ReadFromFile(
GetIdentifier(), realPath, /* metadataOnly = */ false)) {
return _ReloadFailed;
}
_assetModificationTime.Swap(timestamp);
}
_MarkCurrentStateAsClean();
Sdf_ChangeManager::Get().DidReloadLayerContent(SdfLayerHandle(this));
return _ReloadSucceeded;
}
bool
SdfLayer::Reload(bool force)
{
return _Reload(force) == _ReloadSucceeded;
}
bool
SdfLayer::ReloadLayers(
const set<SdfLayerHandle>& layers,
bool force)
{
TF_DESCRIBE_SCOPE("Reloading %zu layer(s)", layers.size());
// Block re-composition until we've finished reloading layers.
SdfChangeBlock block;
bool status = true;
TF_FOR_ALL(layer, layers) {
if (*layer) {
if ((*layer)->_Reload(force) == _ReloadFailed) {
status = false;
TF_WARN("Unable to re-read @%s@",
(*layer)->GetIdentifier().c_str());
}
}
}
return status;
}
bool
SdfLayer::Import(const string &layerPath)
{
string filePath = Sdf_ComputeFilePath(layerPath);
if (filePath.empty())
return false;
return _ReadFromFile(layerPath, filePath, /* metadataOnly = */ false);
}
bool
SdfLayer::ImportFromString(const std::string &s)
{
return GetFileFormat()->ReadFromString(SdfLayerBasePtr(this), s);
}
bool
SdfLayer::_ReadFromFile(
const string& identifier,
const string& resolvedPath,
bool metadataOnly)
{
TRACE_FUNCTION();
TfAutoMallocTag tag("SdfLayer::_ReadFromFile");
TF_DESCRIBE_SCOPE("Loading layer '%s'", resolvedPath.c_str());
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_ReadFromFile('%s', '%s', metadataOnly=%s)\n",
identifier.c_str(), resolvedPath.c_str(),
TfStringify(metadataOnly).c_str());
SdfFileFormatConstPtr format = GetFileFormat();
if (format->LayersAreFileBased()) {
if (not ArGetResolver().FetchToLocalResolvedPath(
identifier, resolvedPath)) {
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_ReadFromFile - unable to fetch '%s' to "
"local path '%s'\n",
identifier.c_str(), resolvedPath.c_str());
return false;
}
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::_ReadFromFile - fetched '%s' to local path '%s'\n",
identifier.c_str(), resolvedPath.c_str());
}
return format->ReadFromFile(
SdfLayerBasePtr(this), resolvedPath, metadataOnly);
}
/*static*/
SdfLayerHandle
SdfLayer::Find(const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
// We don't need to drop the GIL here, since _TryToFindLayer() doesn't
// invoke any plugin code, and if we do wind up calling
// _WaitForInitializationAndCheckIfSuccessful() then we'll drop the GIL in
// there.
_FindOrOpenLayerInfo layerInfo;
if (not _ComputeInfoToFindOrOpenLayer(identifier, args, &layerInfo))
return TfNullPtr;
// Resolve the path before we take the lock, since doing the resolution is
// slow.
bool isAnonymous = IsAnonymousLayerIdentifier(layerInfo.layerPath);
// If we're trying to open an anonymous layer, do not try to compute the
// real path for it.
const string resolvedPath = isAnonymous ? layerInfo.layerPath :
Sdf_ResolvePath(layerInfo.layerPath);
// First see if this layer is already present.
_layerRegistryMutex->lock();
if (SdfLayerRefPtr layer =
_TryToFindLayer(layerInfo.identifier, resolvedPath)) {
// Unlock the mutex so other threads trying to access
// unrelated layers can proceed while this thread waits
// for this layer to be ready.
_layerRegistryMutex->unlock();
return layer->_WaitForInitializationAndCheckIfSuccessful()
? layer
: TfNullPtr;
}
_layerRegistryMutex->unlock();
return TfNullPtr;
}
/* static */
SdfLayerHandle
SdfLayer::FindRelativeToLayer(
const SdfLayerHandle &anchor,
const string &layerPath,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
if (not anchor) {
TF_CODING_ERROR("Anchor layer is invalid");
return TfNullPtr;
}
return Find(anchor->ComputeAbsolutePath(layerPath), args);
}
std::set<double>
SdfLayer::ListAllTimeSamples() const
{
return _data->ListAllTimeSamples();
}
std::set<double>
SdfLayer::ListTimeSamplesForPath(const SdfAbstractDataSpecId& id) const
{
return _data->ListTimeSamplesForPath(id);
}
bool
SdfLayer::GetBracketingTimeSamples(double time, double* tLower, double* tUpper)
{
return _data->GetBracketingTimeSamples(time, tLower, tUpper);
}
size_t
SdfLayer::GetNumTimeSamplesForPath(const SdfAbstractDataSpecId& id) const
{
return _data->GetNumTimeSamplesForPath(id);
}
bool
SdfLayer::GetBracketingTimeSamplesForPath(const SdfAbstractDataSpecId& id,
double time,
double* tLower, double* tUpper)
{
return _data->GetBracketingTimeSamplesForPath(id, time, tLower, tUpper);
}
bool
SdfLayer::QueryTimeSample(const SdfAbstractDataSpecId& id, double time,
VtValue *value) const
{
return _data->QueryTimeSample(id, time, value);
}
bool
SdfLayer::QueryTimeSample(const SdfAbstractDataSpecId& id, double time,
SdfAbstractDataValue *value) const
{
return _data->QueryTimeSample(id, time, value);
}
static TfType
_GetExpectedTimeSampleValueType(
const SdfLayer& layer, const SdfAbstractDataSpecId& id)
{
const SdfSpecType specType = layer.GetSpecType(id);
if (specType == SdfSpecTypeUnknown) {
TF_CODING_ERROR("Cannot set time sample at <%s> since spec does "