HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
stage.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 #ifndef PXR_USD_USD_STAGE_H
25 #define PXR_USD_USD_STAGE_H
26 
27 /// \file usd/stage.h
28 
29 #include "pxr/pxr.h"
30 #include "pxr/usd/usd/api.h"
31 #include "pxr/usd/usd/common.h"
32 #include "pxr/usd/usd/editTarget.h"
38 #include "pxr/usd/usd/primFlags.h"
39 
41 #include "pxr/base/tf/hashmap.h"
42 #include "pxr/base/tf/weakBase.h"
43 
44 #include "pxr/usd/ar/ar.h"
45 #include "pxr/usd/ar/notice.h"
47 #include "pxr/usd/sdf/notice.h"
48 #include "pxr/usd/sdf/path.h"
49 #include "pxr/usd/sdf/types.h"
50 #include "pxr/usd/pcp/cache.h"
51 #include "pxr/base/vt/value.h"
53 
54 #include <tbb/concurrent_vector.h>
55 #include <tbb/concurrent_unordered_set.h>
56 #include <tbb/concurrent_hash_map.h>
57 #include <tbb/spin_rw_mutex.h>
58 
59 #include <functional>
60 #include <string>
61 #include <memory>
62 #include <optional>
63 #include <unordered_map>
64 #include <utility>
65 
67 
68 class ArResolverContext;
69 class GfInterval;
71 class Usd_AssetPathContext;
72 class Usd_ClipCache;
73 class Usd_InstanceCache;
74 class Usd_InstanceChanges;
75 class Usd_InterpolatorBase;
76 class Usd_Resolver;
77 class UsdResolveInfo;
78 class UsdResolveTarget;
79 class UsdPrim;
80 class UsdPrimRange;
81 
83 
84 /// \class UsdStage
85 ///
86 /// The outermost container for scene description, which owns and presents
87 /// composed prims as a scenegraph, following the composition recipe
88 /// recursively described in its associated "root layer".
89 ///
90 /// USD derives its persistent-storage scalability by combining and reusing
91 /// simple compositions into richer aggregates using referencing and layering
92 /// with sparse overrides. Ultimately, every composition (i.e. "scene") is
93 /// identifiable by its root layer, i.e. the <tt>.usd</tt> file, and a scene
94 /// is instantiated in an application on a UsdStage that presents a composed
95 /// view of the scene's root layer. Each simple composition referenced into
96 /// a larger composition could be presented on its own UsdStage, at the same
97 /// (or not) time that it is participating in the larger composition on its
98 /// own UsdStage; all of the underlying layers will be shared by the two
99 /// stages, while each maintains its own scenegraph of composed prims.
100 ///
101 /// A UsdStage has sole ownership over the UsdPrim 's with which it is populated,
102 /// and retains \em shared ownership (with other stages and direct clients of
103 /// SdfLayer's, via the Sdf_LayerRegistry that underlies all SdfLayer creation
104 /// methods) of layers. It provides roughly five categories of API that
105 /// address different aspects of scene management:
106 ///
107 /// - \ref Usd_lifetimeManagement "Stage lifetime management" methods for
108 /// constructing and initially populating a UsdStage from an existing layer
109 /// file, or one that will be created as a result, in memory or on the
110 /// filesystem.
111 /// - \ref Usd_workingSetManagement "Load/unload working set management" methods
112 /// that allow you to specify which \ref Usd_Payloads "payloads" should be
113 /// included and excluded from the stage's composition.
114 /// - \ref Usd_variantManagement "Variant management" methods to manage
115 /// policy for which variant to use when composing prims that provide
116 /// a named variant set, but do not specify a selection.
117 /// - \ref Usd_primManagement "Prim access, creation, and mutation" methods
118 /// that allow you to find, create, or remove a prim identified by a path on
119 /// the stage. This group also provides methods for efficiently traversing the
120 /// prims on the stage.
121 /// - \ref Usd_layerManagement "Layers and EditTargets" methods provide access
122 /// to the layers in the stage's <em>root LayerStack</em> (i.e. the root layer
123 /// and all of its recursive sublayers), and the ability to set a UsdEditTarget
124 /// into which all subsequent mutations to objects associated with the stage
125 /// (e.g. prims, properties, etc) will go.
126 /// - \ref Usd_stageSerialization "Serialization" methods for "flattening" a
127 /// composition (to varying degrees), and exporting a completely flattened
128 /// view of the stage to a string or file. These methods can be very useful
129 /// for targeted asset optimization and debugging, though care should be
130 /// exercized with large scenes, as flattening defeats some of the benefits of
131 /// referenced scene description, and may produce very large results,
132 /// especially in file formats that do not support data de-duplication, like
133 /// the usda text format!
134 ///
135 /// \section Usd_SessionLayer Stage Session Layers
136 ///
137 /// Each UsdStage can possess an optional "session layer". The purpose of
138 /// a session layer is to hold ephemeral edits that modify a UsdStage's contents
139 /// or behavior in a way that is useful to the client, but should not be
140 /// considered as permanent mutations to be recorded upon export. A very
141 /// common use of session layers is to make variant selections, to pick a
142 /// specific LOD or shading variation, for example. The session layer is
143 /// also frequently used to override the visibility of geometry
144 /// and assets in the scene. A session layer, if present, contributes to a
145 /// UsdStage's identity, for purposes of stage-caching, etc.
146 ///
147 /// To edit content in a session layer, get the layer's edit target using
148 /// stage->GetEditTargetForLocalLayer(stage->GetSessionLayer()) and set that
149 /// target in the stage by calling SetEditTarget() or creating a UsdEditContext.
150 ///
151 class UsdStage : public TfRefBase, public TfWeakBase {
152 public:
153 
154  // --------------------------------------------------------------------- //
155  /// \anchor Usd_lifetimeManagement
156  /// \name Lifetime Management
157  /// @{
158  // --------------------------------------------------------------------- //
159 
160  /// \enum InitialLoadSet
161  ///
162  /// Specifies the initial set of prims to load when opening a UsdStage.
163  ///
165  {
166  LoadAll, ///< Load all loadable prims
167  LoadNone ///< Load no loadable prims
168  };
169 
170  /// Create a new stage with root layer \p identifier, destroying
171  /// potentially existing files with that identifier; it is considered an
172  /// error if an existing, open layer is present with this identifier.
173  ///
174  /// \sa SdfLayer::CreateNew()
175  ///
176  /// Invoking an overload that does not take a \p sessionLayer argument will
177  /// create a stage with an anonymous in-memory session layer. To create a
178  /// stage without a session layer, pass TfNullPtr (or None in python) as the
179  /// \p sessionLayer argument.
180  //
181  /// The initial set of prims to load on the stage can be specified
182  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
183  ///
184  /// If \p pathResolverContext is provided it will be bound when creating the
185  /// root layer at \p identifier and whenever asset path resolution is done
186  /// for this stage, regardless of what other context may be bound at that
187  /// time. Otherwise Usd will create the root layer with no context bound,
188  /// then create a context for all future asset path resolution for the stage
189  /// by calling ArResolver::CreateDefaultContextForAsset with the root
190  /// layer's repository path if the layer has one, otherwise its resolved
191  /// path.
192  USD_API
193  static UsdStageRefPtr
194  CreateNew(const std::string& identifier,
195  InitialLoadSet load = LoadAll);
196  /// \overload
197  USD_API
198  static UsdStageRefPtr
199  CreateNew(const std::string& identifier,
200  const SdfLayerHandle& sessionLayer,
201  InitialLoadSet load = LoadAll);
202  /// \overload
203  USD_API
204  static UsdStageRefPtr
205  CreateNew(const std::string& identifier,
206  const SdfLayerHandle& sessionLayer,
207  const ArResolverContext& pathResolverContext,
208  InitialLoadSet load = LoadAll);
209  /// \overload
210  USD_API
211  static UsdStageRefPtr
212  CreateNew(const std::string& identifier,
213  const ArResolverContext& pathResolverContext,
214  InitialLoadSet load = LoadAll);
215 
216  /// Creates a new stage only in memory, analogous to creating an
217  /// anonymous SdfLayer.
218  ///
219  /// If \p pathResolverContext is provided it will be bound when creating the
220  /// root layer at \p identifier and whenever asset path resolution is done
221  /// for this stage, regardless of what other context may be bound at that
222  /// time. Otherwise Usd will create the root layer with no context bound,
223  /// then create a context for all future asset path resolution for the stage
224  /// by calling ArResolver::CreateDefaultContext.
225  ///
226  /// The initial set of prims to load on the stage can be specified
227  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
228  ///
229  /// Invoking an overload that does not take a \p sessionLayer argument will
230  /// create a stage with an anonymous in-memory session layer. To create a
231  /// stage without a session layer, pass TfNullPtr (or None in python) as the
232  /// \p sessionLayer argument.
233  USD_API
234  static UsdStageRefPtr
236  /// \overload
237  USD_API
238  static UsdStageRefPtr
239  CreateInMemory(const std::string& identifier,
240  InitialLoadSet load = LoadAll);
241  /// \overload
242  USD_API
243  static UsdStageRefPtr
244  CreateInMemory(const std::string& identifier,
245  const ArResolverContext& pathResolverContext,
246  InitialLoadSet load = LoadAll);
247  /// \overload
248  USD_API
249  static UsdStageRefPtr
250  CreateInMemory(const std::string& identifier,
251  const SdfLayerHandle &sessionLayer,
252  InitialLoadSet load = LoadAll);
253  /// \overload
254  USD_API
255  static UsdStageRefPtr
256  CreateInMemory(const std::string& identifier,
257  const SdfLayerHandle &sessionLayer,
258  const ArResolverContext& pathResolverContext,
259  InitialLoadSet load = LoadAll);
260 
261  /// Attempt to find a matching existing stage in a cache if
262  /// UsdStageCacheContext objects exist on the stack. Failing that, create a
263  /// new stage and recursively compose prims defined within and referenced by
264  /// the layer at \p filePath, which must already exist.
265  ///
266  /// The initial set of prims to load on the stage can be specified
267  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
268  ///
269  /// If \p pathResolverContext is provided it will be bound when opening the
270  /// root layer at \p filePath and whenever asset path resolution is done for
271  /// this stage, regardless of what other context may be bound at that
272  /// time. Otherwise Usd will open the root layer with no context bound, then
273  /// create a context for all future asset path resolution for the stage by
274  /// calling ArResolver::CreateDefaultContextForAsset with the layer's
275  /// repository path if the layer has one, otherwise its resolved path.
276  USD_API
277  static UsdStageRefPtr
278  Open(const std::string& filePath, InitialLoadSet load = LoadAll);
279  /// \overload
280  USD_API
281  static UsdStageRefPtr
282  Open(const std::string& filePath,
283  const ArResolverContext& pathResolverContext,
284  InitialLoadSet load = LoadAll);
285 
286  /// Create a new stage and recursively compose prims defined within and
287  /// referenced by the layer at \p filePath which must already exist, subject
288  /// to \p mask.
289  ///
290  /// These OpenMasked() methods do not automatically consult or populate
291  /// UsdStageCache s.
292  ///
293  /// The initial set of prims to load on the stage can be specified
294  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
295  ///
296  /// If \p pathResolverContext is provided it will be bound when opening the
297  /// root layer at \p filePath and whenever asset path resolution is done for
298  /// this stage, regardless of what other context may be bound at that
299  /// time. Otherwise Usd will open the root layer with no context bound, then
300  /// create a context for all future asset path resolution for the stage by
301  /// calling ArResolver::CreateDefaultContextForAsset with the layer's
302  /// repository path if the layer has one, otherwise its resolved path.
303  USD_API
304  static UsdStageRefPtr
305  OpenMasked(const std::string &filePath,
307  InitialLoadSet load = LoadAll);
308  /// \overload
309  USD_API
310  static UsdStageRefPtr
311  OpenMasked(const std::string &filePath,
312  const ArResolverContext &pathResolverContext,
314  InitialLoadSet load = LoadAll);
315 
316  /// Open a stage rooted at \p rootLayer.
317  ///
318  /// Attempt to find a stage that matches the passed arguments in a
319  /// UsdStageCache if UsdStageCacheContext objects exist on the calling
320  /// stack. If a matching stage is found, return that stage. Otherwise,
321  /// create a new stage rooted at \p rootLayer.
322  ///
323  /// Invoking an overload that does not take a \p sessionLayer argument will
324  /// create a stage with an anonymous in-memory session layer. To create a
325  /// stage without a session layer, pass TfNullPtr (or None in python) as the
326  /// \p sessionLayer argument.
327  ///
328  /// The initial set of prims to load on the stage can be specified
329  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
330  ///
331  /// If \p pathResolverContext is provided it will be bound when whenever
332  /// asset path resolution is done for this stage, regardless of what other
333  /// context may be bound at that time. Otherwise Usd will create a context
334  /// for all future asset path resolution for the stage by calling
335  /// ArResolver::CreateDefaultContextForAsset with the layer's repository
336  /// path if the layer has one, otherwise its resolved path.
337  ///
338  /// When searching for a matching stage in bound UsdStageCache s, only the
339  /// provided arguments matter for cache lookup. For example, if only a root
340  /// layer (or a root layer file path) is provided, the first stage found in
341  /// any cache that has that root layer is returned. So, for example if you
342  /// require that the stage have no session layer, you must explicitly
343  /// specify TfNullPtr (or None in python) for the sessionLayer argument.
344  USD_API
345  static UsdStageRefPtr
346  Open(const SdfLayerHandle& rootLayer,
347  InitialLoadSet load=LoadAll);
348  /// \overload
349  USD_API
350  static UsdStageRefPtr
351  Open(const SdfLayerHandle& rootLayer,
352  const SdfLayerHandle& sessionLayer,
353  InitialLoadSet load=LoadAll);
354  /// \overload
355  USD_API
356  static UsdStageRefPtr
357  Open(const SdfLayerHandle& rootLayer,
358  const ArResolverContext& pathResolverContext,
359  InitialLoadSet load=LoadAll);
360  /// \overload
361  USD_API
362  static UsdStageRefPtr
363  Open(const SdfLayerHandle& rootLayer,
364  const SdfLayerHandle& sessionLayer,
365  const ArResolverContext& pathResolverContext,
366  InitialLoadSet load=LoadAll);
367 
368  /// Open a stage rooted at \p rootLayer and with limited population subject
369  /// to \p mask.
370  ///
371  /// These OpenMasked() methods do not automatically consult or populate
372  /// UsdStageCache s.
373  ///
374  /// Invoking an overload that does not take a \p sessionLayer argument will
375  /// create a stage with an anonymous in-memory session layer. To create a
376  /// stage without a session layer, pass TfNullPtr (or None in python) as the
377  /// \p sessionLayer argument.
378  ///
379  /// The initial set of prims to load on the stage can be specified
380  /// using the \p load parameter. \sa UsdStage::InitialLoadSet.
381  ///
382  /// If \p pathResolverContext is provided it will be bound when whenever
383  /// asset path resolution is done for this stage, regardless of what other
384  /// context may be bound at that time. Otherwise Usd will create a context
385  /// for all future asset path resolution for the stage by calling
386  /// ArResolver::CreateDefaultContextForAsset with the layer's repository
387  /// path if the layer has one, otherwise its resolved path.
388  USD_API
389  static UsdStageRefPtr
390  OpenMasked(const SdfLayerHandle& rootLayer,
392  InitialLoadSet load=LoadAll);
393  /// \overload
394  USD_API
395  static UsdStageRefPtr
396  OpenMasked(const SdfLayerHandle& rootLayer,
397  const SdfLayerHandle& sessionLayer,
399  InitialLoadSet load=LoadAll);
400  /// \overload
401  USD_API
402  static UsdStageRefPtr
403  OpenMasked(const SdfLayerHandle& rootLayer,
404  const ArResolverContext& pathResolverContext,
406  InitialLoadSet load=LoadAll);
407  /// \overload
408  USD_API
409  static UsdStageRefPtr
410  OpenMasked(const SdfLayerHandle& rootLayer,
411  const SdfLayerHandle& sessionLayer,
412  const ArResolverContext& pathResolverContext,
414  InitialLoadSet load=LoadAll);
415 
416  USD_API
417  virtual ~UsdStage();
418 
419  /// Calls SdfLayer::Reload on all layers contributing to this stage,
420  /// except session layers and sublayers of session layers.
421  ///
422  /// This includes non-session sublayers, references and payloads.
423  /// Note that reloading anonymous layers clears their content, so
424  /// invoking Reload() on a stage constructed via CreateInMemory()
425  /// will clear its root layer.
426  ///
427  /// \note This method is considered a mutation, which has potentially
428  /// global effect! Unlike the various Load() methods whose actions
429  /// affect only **this stage**, Reload() may cause layers to change their
430  /// contents, and because layers are global resources shared by
431  /// potentially many Stages, calling Reload() on one stage may result in
432  /// a mutation to any number of stages. In general, unless you are
433  /// highly confident your stage is the only consumer of its layers, you
434  /// should only call Reload() when you are assured no other threads may
435  /// be reading from any Stages.
436  USD_API
437  void Reload();
438 
439  /// Indicates whether the specified file is supported by UsdStage.
440  ///
441  /// This function is a cheap way to determine whether a
442  /// file might be open-able with UsdStage::Open. It is
443  /// purely based on the given \p filePath and does not
444  /// open the file or perform analysis on the contents.
445  /// As such, UsdStage::Open may still fail even if this
446  /// function returns true.
447  USD_API
448  static bool
449  IsSupportedFile(const std::string& filePath);
450 
451  /// @}
452 
453  // --------------------------------------------------------------------- //
454  /// \anchor Usd_layerSerialization
455  /// \name Layer Serialization
456  ///
457  /// Functions for saving changes to layers that contribute opinions to
458  /// this stage. Layers may also be saved by calling SdfLayer::Save or
459  /// exported to a new file by calling SdfLayer::Export.
460  ///
461  /// @{
462 
463  /// Calls SdfLayer::Save on all dirty layers contributing to this stage
464  /// except session layers and sublayers of session layers.
465  ///
466  /// This function will emit a warning and skip each dirty anonymous
467  /// layer it encounters, since anonymous layers cannot be saved with
468  /// SdfLayer::Save. These layers must be manually exported by calling
469  /// SdfLayer::Export.
470  USD_API
471  void Save();
472 
473  /// Calls SdfLayer::Save on all dirty session layers and sublayers of
474  /// session layers contributing to this stage.
475  ///
476  /// This function will emit a warning and skip each dirty anonymous
477  /// layer it encounters, since anonymous layers cannot be saved with
478  /// SdfLayer::Save. These layers must be manually exported by calling
479  /// SdfLayer::Export.
480  USD_API
481  void SaveSessionLayers();
482 
483  /// @}
484 
485  // --------------------------------------------------------------------- //
486  /// \anchor Usd_variantManagement
487  /// \name Variant Management
488  ///
489  /// These methods provide control over the policy to use when composing
490  /// prims that specify a variant set but do not specify a selection.
491  ///
492  /// The first is to declare a list of preferences in plugInfo.json
493  /// metadata on a plugin using this structure:
494  ///
495  /// \code{.json}
496  /// "UsdVariantFallbacks": { # top level key
497  /// "shadingComplexity": [ # example variant set
498  /// "full", # example fallback #1
499  /// "light" # example fallback #2
500  /// ]
501  /// },
502  /// \endcode
503  ///
504  /// This example ensures that we will get the "full" shadingComplexity
505  /// for any prim with a shadingComplexity VariantSet that doesn't
506  /// otherwise specify a selection, \em and has a "full" variant; if its
507  /// shadingComplexity does not have a "full" variant, but \em does have
508  /// a "light" variant, then the selection will be "light". In other
509  /// words, the entries in the "shadingComplexity" list in the plugInfo.json
510  /// represent a priority-ordered list of fallback selections.
511  ///
512  /// The plugin metadata is discovered and applied before the first
513  /// UsdStage is constructed in a given process. It can be defined
514  /// in any plugin. However, if multiple plugins express contrary
515  /// lists for the same named variant set, the result is undefined.
516  ///
517  /// The plugin metadata approach is useful for ensuring that sensible
518  /// default behavior applies across a pipeline without requiring
519  /// every script and binary to explicitly configure every VariantSet
520  /// that subscribes to fallback in the pipeline.
521  /// There may be times when you want to override this behavior in a
522  /// particular script -- for example, a pipeline script that knows
523  /// it wants to entirely ignore shading in order to minimize
524  /// processing time -- which motivates the second approach.
525  ///
526  /// SetGlobalVariantFallbacks() provides a way to override, for
527  /// the entire process, which fallbacks to use in subsequently
528  /// constructed UsdStage instances.
529  ///
530  /// @{
531 
532  /// Get the global variant fallback preferences used in new UsdStages.
533  USD_API
535 
536  /// Set the global variant fallback preferences used in new
537  /// UsdStages. This overrides any fallbacks configured in plugin
538  /// metadata, and only affects stages created after this call.
539  ///
540  /// \note This does not affect existing UsdStages.
541  USD_API
542  static void
544 
545  /// @}
546 
547  // --------------------------------------------------------------------- //
548  /// \anchor Usd_workingSetManagement
549  /// \name Working Set Management
550  ///
551  /// The following rules apply to all Load/Unload methods:
552  ///
553  /// - Loading an already loaded prim is legal, though may result in
554  /// some recomposition cost. Similarly, unloading an unloaded prim
555  /// is legal.
556  /// - Specifying a path that does not target a prim is legal as long it
557  /// has an ancestor present in the scene graph (other than the
558  /// absolute root). If the given path has no such ancestor, it is an
559  /// error.
560  /// - Specifying a path to an inactive prim is an error.
561  /// - Specifying a path to a prototype prim or a prim within a
562  /// prototype is an error.
563  ///
564  /// If an instance prim (or a path identifying a prim descendant to an
565  /// instance) is encountered during a Load/Unload operation, these functions
566  /// may cause instancing to change on the stage in order to ensure that no
567  /// other instances are affected. The load/unload rules that affect a given
568  /// prim hierarchy are considered when determining which prims can be
569  /// instanced together. Instance sharing occurs when different instances
570  /// have equivalent load rules.
571  ///
572  /// The GetLoadRules() and SetLoadRules() provide direct low-level access to
573  /// the UsdStageLoadRules that govern payload inclusion on a stage.
574  ///
575  /// @{
576  // --------------------------------------------------------------------- //
577 
578  /// Modify this stage's load rules to load the prim at \p path, its
579  /// ancestors, and all of its descendants if \p policy is
580  /// UsdLoadWithDescendants. If \p policy is UsdLoadWithoutDescendants, then
581  /// payloads on descendant prims are not loaded.
582  ///
583  /// See \ref Usd_workingSetManagement "Working Set Management" for more
584  /// information.
585  USD_API
588 
589  /// Modify this stage's load rules to unload the prim and its descendants
590  /// specified by \p path.
591  ///
592  /// See \ref Usd_workingSetManagement "Working Set Management" for more
593  /// information.
594  USD_API
596 
597  /// Unload and load the given path sets. The effect is as if the unload set
598  /// were processed first followed by the load set.
599  ///
600  /// This is equivalent to calling UsdStage::Unload for each item in the
601  /// unloadSet followed by UsdStage::Load for each item in the loadSet,
602  /// however this method is more efficient as all operations are committed in
603  /// a single batch. The \p policy argument is described in the
604  /// documentation for Load().
605  ///
606  /// See \ref Usd_workingSetManagement "Working Set Management" for more
607  /// information.
608  USD_API
609  void LoadAndUnload(const SdfPathSet &loadSet, const SdfPathSet &unloadSet,
611 
612  /// Returns a set of all loaded paths.
613  ///
614  /// The paths returned are both those that have been explicitly loaded and
615  /// those that were loaded as a result of dependencies, ancestors or
616  /// descendants of explicitly loaded paths.
617  ///
618  /// This method does not return paths to inactive prims.
619  ///
620  /// See \ref Usd_workingSetManagement "Working Set Management" for more
621  /// information.
622  USD_API
624 
625  /// Returns an SdfPathSet of all paths that can be loaded.
626  ///
627  /// Note that this method does not return paths to inactive prims as they
628  /// cannot be loaded.
629  ///
630  /// The set returned includes loaded and unloaded paths. To determine the
631  /// set of unloaded paths, one can diff this set with the current load set,
632  /// for example:
633  /// \code
634  /// SdfPathSet loaded = stage->GetLoadSet(),
635  /// all = stage->FindLoadable(),
636  /// result;
637  /// std::set_difference(loaded.begin(), loaded.end(),
638  /// all.begin(), all.end(),
639  /// std::inserter(result, result.end()));
640  /// \endcode
641  ///
642  /// See \ref Usd_workingSetManagement "Working Set Management" for more
643  /// information.
644  USD_API
646  const SdfPath& rootPath = SdfPath::AbsoluteRootPath());
647 
648  /// Return the stage's current UsdStageLoadRules governing payload
649  /// inclusion.
650  ///
651  /// See \ref Usd_workingSetManagement "Working Set Management" for more
652  /// information.
654  return _loadRules;
655  }
656 
657  /// Set the UsdStageLoadRules to govern payload inclusion on this stage.
658  /// This rebuilds the stage's entire prim hierarchy to follow \p rules.
659  ///
660  /// Note that subsequent calls to Load(), Unload(), LoadAndUnload() will
661  /// modify this stages load rules as described in the documentation for
662  /// those member functions.
663  ///
664  /// See \ref Usd_workingSetManagement "Working Set Management" for more
665  /// information.
666  USD_API
667  void SetLoadRules(UsdStageLoadRules const &rules);
668 
669  /// Return this stage's population mask.
671  return _populationMask;
672  }
673 
674  /// Set this stage's population mask and recompose the stage.
675  USD_API
677 
678  /// Expand this stage's population mask to include the targets of all
679  /// relationships that pass \p relPred and connections to all attributes
680  /// that pass \p attrPred recursively. The attributes and relationships are
681  /// those on all the prims found by traversing the stage according to \p
682  /// traversalPredicate. If \p relPred is null, include all relationship
683  /// targets; if \p attrPred is null, include all connections.
684  ///
685  /// This function can be used, for example, to expand a population mask for
686  /// a given prim to include bound materials, if those bound materials are
687  /// expressed as relationships or attribute connections.
688  ///
689  /// See also UsdPrim::FindAllRelationshipTargetPaths() and
690  /// UsdPrim::FindAllAttributeConnectionPaths().
691  USD_API
693  Usd_PrimFlagsPredicate const &traversalPredicate,
694  std::function<bool (UsdRelationship const &)> const &relPred = nullptr,
695  std::function<bool (UsdAttribute const &)> const &attrPred = nullptr);
696 
697  /// \overload
698  /// This convenience overload invokes ExpandPopulationMask() with the
699  /// UsdPrimDefaultPredicate traversal predicate.
700  USD_API
702  std::function<bool (UsdRelationship const &)> const &relPred = nullptr,
703  std::function<bool (UsdAttribute const &)> const &attrPred = nullptr);
704 
705  /// @}
706 
707  // --------------------------------------------------------------------- //
708  /// \anchor Usd_primManagement
709  /// \name Prim Access, Creation and Mutation
710  /// All of the methods in this group that accept a prim path as argument
711  /// require paths in the namespace of the stage's root layer, \em regardless
712  /// of what the currently active UsdEditTarget is set to. In other words,
713  /// a UsdStage always presents a composed view of its scene, and all
714  /// prim operations are specified in the composed namespace.
715  /// @{
716  // --------------------------------------------------------------------- //
717 
718  /// Return the stage's "pseudo-root" prim, whose name is defined by Usd.
719  ///
720  /// The stage's named root prims are namespace children of this prim,
721  /// which exists to make the namespace hierarchy a tree instead of a
722  /// forest. This simplifies algorithms that want to traverse all prims.
723  ///
724  /// A UsdStage always has a pseudo-root prim, unless there was an error
725  /// opening or creating the stage, in which case this method returns
726  /// an invalid UsdPrim.
727  USD_API
728  UsdPrim GetPseudoRoot() const;
729 
730  /// Return the root UsdPrim on this stage whose name is the root layer's
731  /// defaultPrim metadata's value. Return an invalid prim if there is no
732  /// such prim or if the root layer's defaultPrim metadata is unset or is not
733  /// a valid prim name. Note that this function only examines this stage's
734  /// rootLayer. It does not consider sublayers of the rootLayer. See also
735  /// SdfLayer::GetDefaultPrim().
736  USD_API
737  UsdPrim GetDefaultPrim() const;
738 
739  /// Set the default prim layer metadata in this stage's root layer. This is
740  /// shorthand for:
741  /// \code
742  /// stage->GetRootLayer()->SetDefaultPrim(prim.GetName());
743  /// \endcode
744  /// Note that this function always authors to the stage's root layer. To
745  /// author to a different layer, use the SdfLayer::SetDefaultPrim() API.
746  USD_API
747  void SetDefaultPrim(const UsdPrim &prim);
748 
749  /// Clear the default prim layer metadata in this stage's root layer. This
750  /// is shorthand for:
751  /// \code
752  /// stage->GetRootLayer()->ClearDefaultPrim();
753  /// \endcode
754  /// Note that this function always authors to the stage's root layer. To
755  /// author to a different layer, use the SdfLayer::SetDefaultPrim() API.
756  USD_API
757  void ClearDefaultPrim();
758 
759  /// Return true if this stage's root layer has an authored opinion for the
760  /// default prim layer metadata. This is shorthand for:
761  /// \code
762  /// stage->GetRootLayer()->HasDefaultPrim();
763  /// \endcode
764  /// Note that this function only consults the stage's root layer. To
765  /// consult a different layer, use the SdfLayer::HasDefaultPrim() API.
766  USD_API
767  bool HasDefaultPrim() const;
768 
769  /// Return the UsdPrim at \p path, or an invalid UsdPrim if none exists.
770  ///
771  /// If \p path indicates a prim beneath an instance, returns an instance
772  /// proxy prim if a prim exists at the corresponding path in that instance's
773  /// prototype.
774  ///
775  /// Unlike OverridePrim() and DefinePrim(), this method will never author
776  /// scene description, and therefore is safe to use as a "reader" in the Usd
777  /// multi-threading model.
778  USD_API
779  UsdPrim GetPrimAtPath(const SdfPath &path) const;
780 
781  /// Return the UsdObject at \p path, or an invalid UsdObject if none exists.
782  ///
783  /// If \p path indicates a prim beneath an instance, returns an instance
784  /// proxy prim if a prim exists at the corresponding path in that instance's
785  /// prototype. If \p path indicates a property beneath a child of an
786  /// instance, returns a property whose parent prim is an instance proxy
787  /// prim.
788  ///
789  /// Example:
790  ///
791  /// \code
792  ///if (UsdObject obj = stage->GetObjectAtPath(path)) {
793  /// if (UsdPrim prim = obj.As<UsdPrim>()) {
794  /// // Do things with prim
795  /// }
796  /// else if (UsdProperty prop = obj.As<UsdProperty>()) {
797  /// // Do things with property. We can also cast to
798  /// // UsdRelationship or UsdAttribute using this same pattern.
799  /// }
800  ///}
801  ///else {
802  /// // No object at specified path
803  ///}
804  /// \endcode
805  USD_API
806  UsdObject GetObjectAtPath(const SdfPath &path) const;
807 
808  /// Return the UsdProperty at \p path, or an invalid UsdProperty
809  /// if none exists.
810  ///
811  /// This is equivalent to
812  /// \code{.cpp}
813  /// stage.GetObjectAtPath(path).As<UsdProperty>();
814  /// \endcode
815  /// \sa GetObjectAtPath(const SdfPath&) const
816  USD_API
818 
819  /// Return the UsdAttribute at \p path, or an invalid UsdAttribute
820  /// if none exists.
821  ///
822  /// This is equivalent to
823  /// \code{.cpp}
824  /// stage.GetObjectAtPath(path).As<UsdAttribute>();
825  /// \endcode
826  /// \sa GetObjectAtPath(const SdfPath&) const
827  USD_API
829 
830  /// Return the UsdAttribute at \p path, or an invalid UsdAttribute
831  /// if none exists.
832  ///
833  /// This is equivalent to
834  /// \code{.cpp}
835  /// stage.GetObjectAtPath(path).As<UsdRelationship>();
836  /// \endcode
837  /// \sa GetObjectAtPath(const SdfPath&) const
838  USD_API
840 private:
841  // Return the primData object at \p path.
842  Usd_PrimDataConstPtr _GetPrimDataAtPath(const SdfPath &path) const;
843  Usd_PrimDataPtr _GetPrimDataAtPath(const SdfPath &path);
844 
845  // Return the primData object at \p path. If \p path indicates a prim
846  // beneath an instance, return the primData object for the corresponding
847  // prim in the instance's prototype.
849  _GetPrimDataAtPathOrInPrototype(const SdfPath &path) const;
850 
851  /// See documentation on UsdPrim::GetInstances()
852  std::vector<UsdPrim>
853  _GetInstancesForPrototype(const UsdPrim& prototype) const;
854 
855 public:
856 
857  /// Traverse the active, loaded, defined, non-abstract prims on this stage
858  /// depth-first.
859  ///
860  /// Traverse() returns a UsdPrimRange , which allows low-latency
861  /// traversal, with the ability to prune subtrees from traversal. It
862  /// is python iterable, so in its simplest form, one can do:
863  ///
864  /// \code{.py}
865  /// for prim in stage.Traverse():
866  /// print prim.GetPath()
867  /// \endcode
868  ///
869  /// If either a pre-and-post-order traversal or a traversal rooted at a
870  /// particular prim is desired, construct a UsdPrimRange directly.
871  ///
872  /// You'll need to use the returned UsdPrimRange's iterator to perform
873  /// actions such as pruning subtrees. See the "Using Usd.PrimRange in
874  /// python" section in UsdPrimRange for more details and examples.
875  ///
876  /// This is equivalent to UsdPrimRange::Stage() .
877  USD_API
879 
880  /// \overload
881  /// Traverse the prims on this stage subject to \p predicate.
882  ///
883  /// This is equivalent to UsdPrimRange::Stage() .
884  USD_API
885  UsdPrimRange Traverse(const Usd_PrimFlagsPredicate &predicate);
886 
887  /// Traverse all the prims on this stage depth-first.
888  ///
889  /// \sa Traverse()
890  /// \sa UsdPrimRange::Stage()
891  USD_API
893 
894  /// Attempt to ensure a \a UsdPrim at \p path exists on this stage.
895  ///
896  /// If a prim already exists at \p path, return it. Otherwise author
897  /// \a SdfPrimSpecs with \a specifier == \a SdfSpecifierOver and empty
898  /// \a typeName at the current EditTarget to create this prim and any
899  /// nonexistent ancestors, then return it.
900  ///
901  /// The given \a path must be an absolute prim path that does not contain
902  /// any variant selections.
903  ///
904  /// If it is impossible to author any of the necessary PrimSpecs, (for
905  /// example, in case \a path cannot map to the current UsdEditTarget's
906  /// namespace) issue an error and return an invalid \a UsdPrim.
907  ///
908  /// If an ancestor of \p path identifies an \a inactive prim, author scene
909  /// description as described above but return an invalid prim, since the
910  /// resulting prim is descendant to an inactive prim.
911  ///
912  USD_API
914 
915  /// Attempt to ensure a \a UsdPrim at \p path is defined (according to
916  /// UsdPrim::IsDefined()) on this stage.
917  ///
918  /// If a prim at \p path is already defined on this stage and \p typeName is
919  /// empty or equal to the existing prim's typeName, return that prim.
920  /// Otherwise author an \a SdfPrimSpec with \a specifier ==
921  /// \a SdfSpecifierDef and \p typeName for the prim at \p path at the
922  /// current EditTarget. Author \a SdfPrimSpec s with \p specifier ==
923  /// \a SdfSpecifierDef and empty typeName at the current EditTarget for any
924  /// nonexistent, or existing but not \a Defined ancestors.
925  ///
926  /// The given \a path must be an absolute prim path that does not contain
927  /// any variant selections.
928  ///
929  /// If it is impossible to author any of the necessary PrimSpecs (for
930  /// example, in case \a path cannot map to the current UsdEditTarget's
931  /// namespace or one of the ancestors of \p path is inactive on the
932  /// UsdStage), issue an error and return an invalid \a UsdPrim.
933  ///
934  /// Note that this method may return a defined prim whose typeName does not
935  /// match the supplied \p typeName, in case a stronger typeName opinion
936  /// overrides the opinion at the current EditTarget.
937  ///
938  USD_API
940  const TfToken &typeName=TfToken());
941 
942  /// Author an \a SdfPrimSpec with \a specifier == \a SdfSpecifierClass for
943  /// the class at root prim path \p path at the current EditTarget. The
944  /// current EditTarget must have UsdEditTarget::IsLocalLayer() == true.
945  ///
946  /// The given \a path must be an absolute, root prim path that does not
947  /// contain any variant selections.
948  ///
949  /// If a defined (UsdPrim::IsDefined()) non-class prim already exists at
950  /// \p path, issue an error and return an invalid UsdPrim.
951  ///
952  /// If it is impossible to author the necessary PrimSpec, issue an error
953  /// and return an invalid \a UsdPrim.
954  USD_API
955  UsdPrim CreateClassPrim(const SdfPath &rootPrimPath);
956 
957  /// Remove all scene description for the given \p path and its subtree
958  /// <em>in the current UsdEditTarget</em>.
959  ///
960  /// This method does not do what you might initially think! Calling this
961  /// function will not necessarily cause the UsdPrim at \p path on this
962  /// stage to disappear. Completely eradicating a prim from a composition
963  /// can be an involved process, involving edits to many contributing layers,
964  /// some of which (in many circumstances) will not be editable by a client.
965  /// This method is a surgical instrument that \em can be used iteratively
966  /// to effect complete removal of a prim and its subtree from namespace,
967  /// assuming the proper permissions are acquired, but more commonly it
968  /// is used to perform layer-level operations; e.g.: ensuring that a given
969  /// layer (as expressed by a UsdEditTarget) provides no opinions for a
970  /// prim and its subtree.
971  ///
972  /// Generally, if your eye is attracted to this method, you probably want
973  /// to instead use UsdPrim::SetActive(false) , which will provide the
974  /// \ref Usd_ActiveInactive "composed effect" of removing the prim and
975  /// its subtree from the composition, without actually removing any
976  /// scene description, which as a bonus, means that the effect is
977  /// reversible at a later time!
978  USD_API
979  bool RemovePrim(const SdfPath& path);
980 
981  /// @}
982 
983  // --------------------------------------------------------------------- //
984  /// \anchor Usd_layerManagement
985  /// \name Layers and EditTargets
986  /// @{
987  // --------------------------------------------------------------------- //
988 
989  /// Return this stage's root session layer.
990  USD_API
991  SdfLayerHandle GetSessionLayer() const;
992 
993  /// Return this stage's root layer.
994  USD_API
995  SdfLayerHandle GetRootLayer() const;
996 
997  /// Return the path resolver context for all path resolution during
998  /// composition of this stage. Useful for external clients that want to
999  /// resolve paths with the same context as this stage, or create new
1000  /// stages with the same context.
1001  USD_API
1003 
1004  /// Resolve the given identifier using this stage's
1005  /// ArResolverContext and the layer of its GetEditTarget()
1006  /// as an anchor for relative references (e.g. \@./siblingFile.usd\@).
1007  ///
1008  /// \return a non-empty string containing either the same
1009  /// identifier that was passed in (if the identifier refers to an
1010  /// already-opened layer or an "anonymous", in-memory layer), or a resolved
1011  /// layer filepath. If the identifier was not resolvable, return the
1012  /// empty string.
1013  USD_API
1014  std::string
1015  ResolveIdentifierToEditTarget(std::string const &identifier) const;
1016 
1017  /// Return this stage's local layers in strong-to-weak order. If
1018  /// \a includeSessionLayers is true, return the linearized strong-to-weak
1019  /// sublayers rooted at the stage's session layer followed by the linearized
1020  /// strong-to-weak sublayers rooted at this stage's root layer. If
1021  /// \a includeSessionLayers is false, omit the sublayers rooted at this
1022  /// stage's session layer.
1023  USD_API
1024  SdfLayerHandleVector GetLayerStack(bool includeSessionLayers=true) const;
1025 
1026  /// Return a vector of all of the layers \em currently consumed by this
1027  /// stage, as determined by the composition arcs that were traversed to
1028  /// compose and populate the stage.
1029  ///
1030  /// The list of consumed layers will change with the stage's load-set and
1031  /// variant selections, so the return value should be considered only
1032  /// a snapshot. The return value will include the stage's session layer,
1033  /// if it has one. If \a includeClipLayers is true, we will also include
1034  /// all of the layers that this stage has had to open so far to perform
1035  /// value resolution of attributes affected by
1036  /// \ref Usd_Page_ValueClips "Value Clips"
1037  USD_API
1038  SdfLayerHandleVector GetUsedLayers(bool includeClipLayers=true) const;
1039 
1040  /// Return true if \a layer is one of the layers in this stage's local,
1041  /// root layerStack.
1042  USD_API
1043  bool HasLocalLayer(const SdfLayerHandle &layer) const;
1044 
1045  /// Return the stage's EditTarget.
1046  USD_API
1047  const UsdEditTarget &GetEditTarget() const;
1048 
1049  /// Return a UsdEditTarget for editing the layer at index \a i in the
1050  /// layer stack. This edit target will incorporate any layer time
1051  /// offset that applies to the sublayer.
1052  USD_API
1054 
1055  /// Return a UsdEditTarget for editing the given local \a layer.
1056  /// If the given layer appears more than once in the layer stack,
1057  /// the time offset to the first occurrence will be used.
1058  USD_API
1059  UsdEditTarget GetEditTargetForLocalLayer(const SdfLayerHandle &layer);
1060 
1061  /// Set the stage's EditTarget. If \a editTarget.IsLocalLayer(), check to
1062  /// see if it's a layer in this stage's local LayerStack. If not, issue an
1063  /// error and do nothing. If \a editTarget is invalid, issue an error
1064  /// and do nothing. If \a editTarget differs from the stage's current
1065  /// EditTarget, set the EditTarget and send
1066  /// UsdNotice::StageChangedEditTarget. Otherwise do nothing.
1067  USD_API
1068  void SetEditTarget(const UsdEditTarget &editTarget);
1069 
1070  /// Mute the layer identified by \p layerIdentifier. Muted layers are
1071  /// ignored by the stage; they do not participate in value resolution
1072  /// or composition and do not appear in any LayerStack. If the root
1073  /// layer of a reference or payload LayerStack is muted, the behavior
1074  /// is as if the muted layer did not exist, which means a composition
1075  /// error will be generated.
1076  ///
1077  /// A canonical identifier for each layer in \p layersToMute will be
1078  /// computed using ArResolver::CreateIdentifier using the stage's root
1079  /// layer as the anchoring asset. Any layer encountered during composition
1080  /// with the same identifier will be considered muted and ignored.
1081  ///
1082  /// Note that muting a layer will cause this stage to release all
1083  /// references to that layer. If no other client is holding on to
1084  /// references to that layer, it will be unloaded. In this case, if
1085  /// there are unsaved edits to the muted layer, those edits are lost.
1086  /// Since anonymous layers are not serialized, muting an anonymous
1087  /// layer will cause that layer and its contents to be lost in this
1088  /// case.
1089  ///
1090  /// Muting a layer that has not been used by this stage is not an error.
1091  /// If that layer is encountered later, muting will take effect and that
1092  /// layer will be ignored.
1093  ///
1094  /// The root layer of this stage may not be muted; attempting to do so
1095  /// will generate a coding error.
1096  USD_API
1097  void MuteLayer(const std::string &layerIdentifier);
1098 
1099  /// Unmute the layer identified by \p layerIdentifier if it had
1100  /// previously been muted.
1101  USD_API
1102  void UnmuteLayer(const std::string &layerIdentifier);
1103 
1104  /// Mute and unmute the layers identified in \p muteLayers and
1105  /// \p unmuteLayers.
1106  ///
1107  /// This is equivalent to calling UsdStage::UnmuteLayer for each layer
1108  /// in \p unmuteLayers followed by UsdStage::MuteLayer for each layer
1109  /// in \p muteLayers, however this method is more efficient as all
1110  /// operations are committed in a single batch.
1111  USD_API
1112  void MuteAndUnmuteLayers(const std::vector<std::string> &muteLayers,
1113  const std::vector<std::string> &unmuteLayers);
1114 
1115  /// Returns a vector of all layers that have been muted on this stage.
1116  USD_API
1117  const std::vector<std::string>& GetMutedLayers() const;
1118 
1119  /// Returns true if the layer specified by \p layerIdentifier is
1120  /// muted in this cache, false otherwise. See documentation on
1121  /// MuteLayer for details on how \p layerIdentifier is compared to the
1122  /// layers that have been muted.
1123  USD_API
1124  bool IsLayerMuted(const std::string& layerIdentifier) const;
1125 
1126  /// @}
1127 
1128  // --------------------------------------------------------------------- //
1129  /// \anchor Usd_stageSerialization
1130  /// \name Flatten & Export Utilities
1131  /// @{
1132  // --------------------------------------------------------------------- //
1133  // Future Work:
1134  // * Flatten sub-trees or individual prims
1135  // * Allow flattening of local LayerStack
1136  // * Move Flatten into a free-function to ensure it doesn't rely on
1137  // Stage internals.
1138 
1139  /// Writes out the composite scene as a single flattened layer into
1140  /// \a filename.
1141  ///
1142  /// If addSourceFileComment is true, a comment in the output layer
1143  /// will mention the input layer it was generated from.
1144  ///
1145  /// See UsdStage::Flatten for details of the flattening transformation.
1146  USD_API
1147  bool Export(const std::string &filename,
1148  bool addSourceFileComment=true,
1151 
1152  /// Writes the composite scene as a flattened Usd text
1153  /// representation into the given \a string.
1154  ///
1155  /// If addSourceFileComment is true, a comment in the output layer
1156  /// will mention the input layer it was generated from.
1157  ///
1158  /// See UsdStage::Flatten for details of the flattening transformation.
1159  USD_API
1161  bool addSourceFileComment=true) const;
1162 
1163  /// Returns a single, anonymous, merged layer for this composite
1164  /// scene.
1165  ///
1166  /// Specifically, this function removes **most** composition metadata and
1167  /// authors the resolved values for each object directly into the flattened
1168  /// layer.
1169  ///
1170  /// All VariantSets are removed and only the currently selected variants
1171  /// will be present in the resulting layer.
1172  ///
1173  /// Class prims will still exist, however all inherits arcs will have
1174  /// been removed and the inherited data will be copied onto each child
1175  /// object. Composition arcs authored on the class itself will be flattened
1176  /// into the class.
1177  ///
1178  /// Flatten preserves
1179  /// \ref Usd_Page_ScenegraphInstancing "scenegraph instancing" by creating
1180  /// independent roots for each prototype currently composed on this stage,
1181  /// and adding a single internal reference arc on each instance prim to its
1182  /// corresponding prototype.
1183  ///
1184  /// Time samples across sublayer offsets will will have the time offset and
1185  /// scale applied to each time index.
1186  ///
1187  /// Finally, any deactivated prims will be pruned from the result.
1188  ///
1189  USD_API
1190  SdfLayerRefPtr Flatten(bool addSourceFileComment=true) const;
1191  /// @}
1192 
1193 public:
1194  // --------------------------------------------------------------------- //
1195  /// \anchor Usd_stageMetadata
1196  /// \name Stage Metadata
1197  /// Stage metadata applies to the entire contents of the stage, and is
1198  /// recorded only in the stage's root or primary session-layer. Most of
1199  /// the other, specific metadata methods on UsdStage are defined in terms
1200  /// of these generic methods.
1201  /// @{
1202  // --------------------------------------------------------------------- //
1203 
1204  /// Return in \p value an authored or fallback value (if one was defined
1205  /// for the given metadatum) for Stage metadatum \p key. Order of
1206  /// resolution is session layer, followed by root layer, else fallback to
1207  /// the SdfSchema.
1208  ///
1209  /// \return true if we successfully retrieved a value of the requested type;
1210  /// false if \p key is not allowed as layer metadata or no value was found.
1211  /// Generates a coding error if we retrieved a stored value of a type other
1212  /// than the requested type
1213  ///
1214  /// \sa \ref Usd_OM_Metadata
1215  template <class T>
1216  bool GetMetadata(const TfToken &key, T *value) const;
1217  /// \overload
1218  USD_API
1219  bool GetMetadata(const TfToken &key, VtValue *value) const;
1220 
1221  /// Returns true if the \a key has a meaningful value, that is, if
1222  /// GetMetadata() will provide a value, either because it was authored
1223  /// or because the Stage metadata was defined with a meaningful fallback
1224  /// value.
1225  ///
1226  /// Returns false if \p key is not allowed as layer metadata.
1227  USD_API
1228  bool HasMetadata(const TfToken &key) const;
1229 
1230  /// Returns \c true if the \a key has an authored value, \c false if no
1231  /// value was authored or the only value available is the SdfSchema's
1232  /// metadata fallback.
1233  ///
1234  /// \note If a value for a metadatum \em not legal to author on layers
1235  /// is present in the root or session layer (which could happen through
1236  /// hand-editing or use of certain low-level API's), this method will
1237  /// still return \c false.
1238  USD_API
1239  bool HasAuthoredMetadata(const TfToken &key) const;
1240 
1241  /// Set the value of Stage metadatum \p key to \p value, if the stage's
1242  /// current UsdEditTarget is the root or session layer.
1243  ///
1244  /// If the current EditTarget is any other layer, raise a coding error.
1245  /// \return true if authoring was successful, false otherwise.
1246  /// Generates a coding error if \p key is not allowed as layer metadata.
1247  ///
1248  /// \sa \ref Usd_OM_Metadata
1249  template<typename T>
1250  bool SetMetadata(const TfToken &key, const T &value) const;
1251  /// \overload
1252  USD_API
1253  bool SetMetadata(const TfToken &key, const VtValue &value) const;
1254 
1255  /// Clear the value of stage metadatum \p key, if the stage's
1256  /// current UsdEditTarget is the root or session layer.
1257  ///
1258  /// If the current EditTarget is any other layer, raise a coding error.
1259  /// \return true if authoring was successful, false otherwise.
1260  /// Generates a coding error if \p key is not allowed as layer metadata.
1261  ///
1262  /// \sa \ref Usd_OM_Metadata
1263  USD_API
1264  bool ClearMetadata(const TfToken &key) const;
1265 
1266  /// Resolve the requested dictionary sub-element \p keyPath of
1267  /// dictionary-valued metadatum named \p key, returning the resolved
1268  /// value.
1269  ///
1270  /// If you know you need just a small number of elements from a dictionary,
1271  /// accessing them element-wise using this method can be much less
1272  /// expensive than fetching the entire dictionary with GetMetadata(key).
1273  ///
1274  /// \return true if we successfully retrieved a value of the requested type;
1275  /// false if \p key is not allowed as layer metadata or no value was found.
1276  /// Generates a coding error if we retrieved a stored value of a type other
1277  /// than the requested type
1278  ///
1279  /// The \p keyPath is a ':'-separated path addressing an element
1280  /// in subdictionaries. If \p keyPath is empty, returns an empty VtValue.
1281  template<typename T>
1282  bool GetMetadataByDictKey(const TfToken& key, const TfToken &keyPath,
1283  T* value) const;
1284  /// overload
1285  USD_API
1286  bool GetMetadataByDictKey(
1287  const TfToken& key, const TfToken &keyPath, VtValue *value) const;
1288 
1289  /// Return true if there exists any authored or fallback opinion for
1290  /// \p key and \p keyPath.
1291  ///
1292  /// The \p keyPath is a ':'-separated path identifying a value in
1293  /// subdictionaries stored in the metadata field at \p key. If
1294  /// \p keyPath is empty, returns \c false.
1295  ///
1296  /// Returns false if \p key is not allowed as layer metadata.
1297  ///
1298  /// \sa \ref Usd_Dictionary_Type
1299  USD_API
1300  bool HasMetadataDictKey(
1301  const TfToken& key, const TfToken &keyPath) const;
1302 
1303  /// Return true if there exists any authored opinion (excluding
1304  /// fallbacks) for \p key and \p keyPath.
1305  ///
1306  /// The \p keyPath is a ':'-separated path identifying a value in
1307  /// subdictionaries stored in the metadata field at \p key. If
1308  /// \p keyPath is empty, returns \c false.
1309  ///
1310  /// \sa \ref Usd_Dictionary_Type
1311  USD_API
1313  const TfToken& key, const TfToken &keyPath) const;
1314 
1315  /// Author \p value to the field identified by \p key and \p keyPath
1316  /// at the current EditTarget.
1317  ///
1318  /// The \p keyPath is a ':'-separated path identifying a value in
1319  /// subdictionaries stored in the metadata field at \p key. If
1320  /// \p keyPath is empty, no action is taken.
1321  ///
1322  /// \return true if the value is authored successfully, false otherwise.
1323  /// Generates a coding error if \p key is not allowed as layer metadata.
1324  ///
1325  /// \sa \ref Usd_Dictionary_Type
1326  template<typename T>
1327  bool SetMetadataByDictKey(const TfToken& key, const TfToken &keyPath,
1328  const T& value) const;
1329  /// \overload
1330  USD_API
1331  bool SetMetadataByDictKey(
1332  const TfToken& key, const TfToken &keyPath, const VtValue& value) const;
1333 
1334  /// Clear any authored value identified by \p key and \p keyPath
1335  /// at the current EditTarget.
1336  ///
1337  /// The \p keyPath is a ':'-separated path identifying a path in
1338  /// subdictionaries stored in the metadata field at \p key. If
1339  /// \p keyPath is empty, no action is taken.
1340  ///
1341  /// \return true if the value is cleared successfully, false otherwise.
1342  /// Generates a coding error if \p key is not allowed as layer metadata.
1343  ///
1344  /// \sa \ref Usd_Dictionary_Type
1345  USD_API
1347  const TfToken& key, const TfToken& keyPath) const;
1348 
1349  /// Writes the fallback prim types defined in the schema registry to the
1350  /// stage as dictionary valued fallback prim type metadata. If the stage
1351  /// already has fallback prim type metadata, the fallback types from the
1352  /// schema registry will be added to the existing metadata, only for types
1353  /// that are already present in the dictionary, i.e. this won't overwrite
1354  /// existing fallback entries.
1355  ///
1356  /// The current edit target determines whether the metadata is written to
1357  /// the root layer or the session layer. If the edit target specifies
1358  /// another layer besides these, this will produce an error.
1359  ///
1360  /// This function can be used at any point before calling Save or Export on
1361  /// a stage to record the fallback types for the current schemas. This
1362  /// allows another version of Usd to open this stage and treat prim types it
1363  /// doesn't recognize as a type it does recognize defined for it in this
1364  /// metadata.
1365  ///
1366  /// \sa \ref Usd_OM_FallbackPrimTypes UsdSchemaRegistry::GetFallbackPrimTypes
1367  USD_API
1368  void WriteFallbackPrimTypes();
1369 
1370  /// @}
1371 
1372  // --------------------------------------------------------------------- //
1373  /// \anchor Usd_timeCodeAPI
1374  /// \name TimeCode API
1375  /// Methods for managing the Stage's active timeSample range, time units,
1376  /// and intended rate of playback. See \ref Usd_OM_UsdTimeCode for more
1377  /// on time and TimeCodes in USD.
1378  /// @{
1379  // --------------------------------------------------------------------- //
1380  /// Returns the stage's start timeCode. If the stage has an associated
1381  /// session layer with a start timeCode opinion, this value is returned.
1382  /// Otherwise, the start timeCode opinion from the root layer is returned.
1383  USD_API
1384  double GetStartTimeCode() const;
1385 
1386  /// Sets the stage's start timeCode.
1387  ///
1388  /// The start timeCode is set in the current EditTarget, if it is the root
1389  /// layer of the stage or the session layer associated with the stage. If
1390  /// the current EditTarget is neither, a warning is issued and the start
1391  /// timeCode is not set.
1392  USD_API
1393  void SetStartTimeCode(double);
1394 
1395  /// Returns the stage's end timeCode. If the stage has an associated
1396  /// session layer with an end timeCode opinion, this value is returned.
1397  /// Otherwise, the end timeCode opinion from the root layer is returned.
1398  USD_API
1399  double GetEndTimeCode() const;
1400 
1401  /// Sets the stage's end timeCode.
1402  ///
1403  /// The end timeCode is set in the current EditTarget, if it is the root
1404  /// layer of the stage or the session layer associated with the stage. If
1405  /// the current EditTarget is neither, a warning is issued and the end
1406  /// timeCode is not set.
1407  USD_API
1408  void SetEndTimeCode(double);
1409 
1410  /// Returns true if the stage has both start and end timeCodes
1411  /// authored in the session layer or the root layer of the stage.
1412  USD_API
1413  bool HasAuthoredTimeCodeRange() const;
1414 
1415  /// Returns the stage's timeCodesPerSecond value.
1416  ///
1417  /// The timeCodesPerSecond value scales the time ordinate for the samples
1418  /// contained in the stage to seconds. If timeCodesPerSecond is 24, then a
1419  /// sample at time ordinate 24 should be viewed exactly one second after the
1420  /// sample at time ordinate 0.
1421  ///
1422  /// Like SdfLayer::GetTimeCodesPerSecond, this accessor uses a dynamic
1423  /// fallback to framesPerSecond. The order of precedence is:
1424  ///
1425  /// \li timeCodesPerSecond from session layer
1426  /// \li timeCodesPerSecond from root layer
1427  /// \li framesPerSecond from session layer
1428  /// \li framesPerSecond from root layer
1429  /// \li fallback value of 24
1430  USD_API
1431  double GetTimeCodesPerSecond() const;
1432 
1433  /// Sets the stage's timeCodesPerSecond value.
1434  ///
1435  /// The timeCodesPerSecond value is set in the current EditTarget, if it
1436  /// is the root layer of the stage or the session layer associated with the
1437  /// stage. If the current EditTarget is neither, a warning is issued and no
1438  /// value is set.
1439  ///
1440  /// \sa GetTimeCodesPerSecond()
1441  USD_API
1442  void SetTimeCodesPerSecond(double timeCodesPerSecond) const;
1443 
1444  /// Returns the stage's framesPerSecond value.
1445  ///
1446  /// This makes an advisory statement about how the contained data can be
1447  /// most usefully consumed and presented. It's primarily an indication of
1448  /// the expected playback rate for the data, but a timeline editing tool
1449  /// might also want to use this to decide how to scale and label its
1450  /// timeline.
1451  ///
1452  /// The default value of framesPerSecond is 24.
1453  USD_API
1454  double GetFramesPerSecond() const;
1455 
1456  /// Sets the stage's framesPerSecond value.
1457  ///
1458  /// The framesPerSecond value is set in the current EditTarget, if it
1459  /// is the root layer of the stage or the session layer associated with the
1460  /// stage. If the current EditTarget is neither, a warning is issued and no
1461  /// value is set.
1462  ///
1463  /// \sa GetFramesPerSecond()
1464  USD_API
1465  void SetFramesPerSecond(double framesPerSecond) const;
1466 
1467  /// @}
1468 
1469  // --------------------------------------------------------------------- //
1470  /// \anchor Usd_ColorConfigurationAPI
1471  /// \name Color Configuration API
1472  ///
1473  /// Methods for authoring and querying the color configuration to
1474  /// be used to interpret the per-attribute color-spaces. An external
1475  /// system (like OpenColorIO) is typically used for interpreting the
1476  /// configuration.
1477  ///
1478  /// Site-wide fallback values for the colorConfiguration and
1479  /// colorManagementSystem metadata can be set in the plugInfo.json file of
1480  /// a plugin using this structure:
1481  ///
1482  /// \code{.json}
1483  /// "UsdColorConfigFallbacks": {
1484  /// "colorConfiguration" = "https://github.com/imageworks/OpenColorIO-Configs/blob/master/aces_1.0.1/config.ocio",
1485  /// "colorManagementSystem" : "OpenColorIO"
1486  /// }
1487  /// \endcode
1488  ///
1489  /// The color space in which a given color or texture attribute is authored
1490  /// is set as token-valued metadata 'colorSpace' on the attribute. For
1491  /// color or texture attributes that don't have an authored 'colorSpace'
1492  /// value, the fallback color-space is gleaned from the color configuration
1493  /// oracle. This is usually the config's <b>scene_linear</b> role
1494  /// color-space.
1495  ///
1496  /// Here's the pseudo-code for determining an attribute's color-space.
1497  ///
1498  /// \code{.cpp}
1499  /// UsdStageRefPtr stage = UsdStage::Open(filePath);
1500  /// UsdPrim prim = stage->GetPrimAtPath("/path/to/prim")
1501  /// UsdAttribute attr = prim.GetAttribute("someColorAttr");
1502  /// TfToken colorSpace = attr.GetColorSpace();
1503  /// if (colorSpace.IsEmpty()) {
1504  /// // If colorSpace is empty, get the default from the stage's
1505  /// // colorConfiguration, using external API (not provided by USD).
1506  /// colorSpace = ExternalAPI::GetDefaultColorSpace(
1507  /// stage->GetColorConfiguration());
1508  /// }
1509  /// \endcode
1510  ///
1511  /// \sa \ref Usd_AttributeColorSpaceAPI "UsdAttribute ColorSpace API"
1512  ///
1513  ///
1514  /// @{
1515  // --------------------------------------------------------------------- //
1516 
1517  /// Sets the default color configuration to be used to interpret the
1518  /// per-attribute color-spaces in the composed USD stage. This is specified
1519  /// as asset path which can be resolved to the color spec file.
1520  ///
1521  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1522  USD_API
1523  void SetColorConfiguration(const SdfAssetPath &colorConfig) const;
1524 
1525  /// Returns the default color configuration used to interpret the per-
1526  /// attribute color-spaces in the composed USD stage.
1527  ///
1528  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1529  USD_API
1531 
1532  /// Sets the name of the color management system used to interpret the
1533  /// color configuration file pointed at by the colorConfiguration metadata.
1534  ///
1535  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1536  USD_API
1537  void SetColorManagementSystem(const TfToken &cms) const;
1538 
1539  /// Sets the name of the color management system to be used for loading
1540  /// and interpreting the color configuration file.
1541  ///
1542  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1543  USD_API
1545 
1546  /// Returns the global fallback values of 'colorConfiguration' and
1547  /// 'colorManagementSystem'. These are set in the plugInfo.json file
1548  /// of a plugin, but can be overridden by calling the static method
1549  /// SetColorConfigFallbacks().
1550  ///
1551  /// The python wrapping of this method returns a tuple containing
1552  /// (colorConfiguration, colorManagementSystem).
1553  ///
1554  ///
1555  /// \sa SetColorConfigFallbacks,
1556  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1557  USD_API
1558  static void GetColorConfigFallbacks(SdfAssetPath *colorConfiguration,
1559  TfToken *colorManagementSystem);
1560 
1561  /// Sets the global fallback values of color configuration metadata which
1562  /// includes the 'colorConfiguration' asset path and the name of the
1563  /// color management system. This overrides any fallback values authored
1564  /// in plugInfo files.
1565  ///
1566  /// If the specified value of \p colorConfiguration or
1567  /// \p colorManagementSystem is empty, then the corresponding fallback
1568  /// value isn't set. In other words, for this call to have an effect,
1569  /// at least one value must be non-empty. Additionally, these can't be
1570  /// reset to empty values.
1571  ///
1572  /// \sa GetColorConfigFallbacks()
1573  /// \ref Usd_ColorConfigurationAPI "Color Configuration API"
1574  USD_API
1575  static void
1576  SetColorConfigFallbacks(const SdfAssetPath &colorConfiguration,
1577  const TfToken &colorManagementSystem);
1578 
1579  /// @}
1580 
1581  // --------------------------------------------------------------------- //
1582  /// \anchor Usd_interpolation
1583  /// \name Attribute Value Interpolation
1584  /// Controls the interpolation behavior when retrieving attribute
1585  /// values. The default behavior is linear interpolation.
1586  /// See \ref Usd_AttributeInterpolation for more details.
1587  /// @{
1588  // --------------------------------------------------------------------- //
1589 
1590  /// Sets the interpolation type used during value resolution
1591  /// for all attributes on this stage. Changing this will cause a
1592  /// UsdNotice::StageContentsChanged notice to be sent, as values at
1593  /// times where no samples are authored may have changed.
1594  USD_API
1595  void SetInterpolationType(UsdInterpolationType interpolationType);
1596 
1597  /// Returns the interpolation type used during value resolution
1598  /// for all attributes on this stage.
1599  USD_API
1601 
1602  /// @}
1603 
1604  // --------------------------------------------------------------------- //
1605  /// \anchor Usd_instancing
1606  /// \name Instancing
1607  /// See \ref Usd_Page_ScenegraphInstancing for more details.
1608  /// @{
1609  // --------------------------------------------------------------------- //
1610 
1611  /// Returns all native instancing prototype prims.
1612  USD_API
1613  std::vector<UsdPrim> GetPrototypes() const;
1614 
1615  /// @}
1616 
1617 private:
1618  struct _IncludePayloadsPredicate;
1619 
1620  // --------------------------------------------------------------------- //
1621  // Stage Construction & Initialization
1622  // --------------------------------------------------------------------- //
1623 
1624  UsdStage(const SdfLayerRefPtr& rootLayer,
1625  const SdfLayerRefPtr& sessionLayer,
1626  const ArResolverContext& pathResolverContext,
1628  InitialLoadSet load);
1629 
1630  // Helper for Open() overloads -- searches and publishes to bound caches.
1631  template <class... Args>
1632  static UsdStageRefPtr _OpenImpl(InitialLoadSet load, Args const &... args);
1633 
1634  // Releases resources used by this stage.
1635  void _Close();
1636 
1637  // Common ref ptr initialization, called by public, static constructors.
1638  //
1639  // This method will either return a valid refptr (if the stage is correctly
1640  // initialized) or it will return a null ref pointer, deleting the
1641  // raw stage pointer in the process.
1642  static UsdStageRefPtr
1643  _InstantiateStage(const SdfLayerRefPtr &rootLayer,
1644  const SdfLayerRefPtr &sessionLayer,
1645  const ArResolverContext &pathResolverContext,
1647  InitialLoadSet load);
1648 
1649  // --------------------------------------------------------------------- //
1650  // Spec Existence & Definition Helpers
1651  // --------------------------------------------------------------------- //
1652 
1653  SdfPropertySpecHandleVector
1654  _GetPropertyStack(const UsdProperty &prop, UsdTimeCode time) const;
1655 
1656  std::vector<std::pair<SdfPropertySpecHandle, SdfLayerOffset>>
1657  _GetPropertyStackWithLayerOffsets(
1658  const UsdProperty &prop, UsdTimeCode time) const;
1659 
1660  static SdfPrimSpecHandleVector
1661  _GetPrimStack(const UsdPrim &prim);
1662 
1663  static std::vector<std::pair<SdfPrimSpecHandle, SdfLayerOffset>>
1664  _GetPrimStackWithLayerOffsets(const UsdPrim &prim);
1665 
1667  _GetSchemaProperty(const UsdProperty &prop) const;
1668 
1670  _GetSchemaAttribute(const UsdAttribute &attr) const;
1671 
1673  _GetSchemaRelationship(const UsdRelationship &rel) const;
1674 
1675  SdfAttributeSpecHandle
1676  _CreateNewSpecFromSchemaAttribute(
1677  const UsdPrim &prim,
1678  const UsdPrimDefinition::Attribute &attrDef);
1679 
1680  SdfRelationshipSpecHandle
1681  _CreateNewSpecFromSchemaRelationship(
1682  const UsdPrim &prim,
1683  const UsdPrimDefinition::Relationship &relDef);
1684 
1685  template <class PropType>
1687  _CreateNewPropertySpecFromSchema(const UsdProperty &prop);
1688 
1689  SdfPrimSpecHandle
1690  _CreatePrimSpecForEditing(const UsdPrim& prim);
1691 
1692  template <class PropType>
1694  _CreatePropertySpecForEditing(const UsdProperty &prop);
1695 
1696  SdfPropertySpecHandle
1697  _CreatePropertySpecForEditing(const UsdProperty &prop);
1698 
1699  SdfAttributeSpecHandle
1700  _CreateAttributeSpecForEditing(const UsdAttribute &attr);
1701 
1702  SdfRelationshipSpecHandle
1703  _CreateRelationshipSpecForEditing(const UsdRelationship &rel);
1704 
1705  // Check if the given path is valid to use with the prim creation API,
1706  // like DefinePrim. If it is valid, returns (true, GetPrimAtPath(path)).
1707  // Otherwise, returns (false, UsdPrim()).
1708  std::pair<bool, UsdPrim>
1709  _IsValidPathForCreatingPrim(const SdfPath &path) const;
1710 
1711  // Validates that editing a specified prim is allowed. If editing is not
1712  // allowed, issues a coding error like "Cannot <operation> ..." and
1713  // returns false. Otherwise, returns true.
1714  bool _ValidateEditPrim(const UsdPrim &prim, const char* operation) const;
1715  bool _ValidateEditPrimAtPath(const SdfPath &primPath,
1716  const char* operation) const;
1717 
1718  UsdPrim _DefinePrim(const SdfPath &path, const TfToken &typeName);
1719 
1720  bool _RemoveProperty(const SdfPath& path);
1721 
1722  UsdProperty _FlattenProperty(const UsdProperty &srcProp,
1723  const UsdPrim &dstParent,
1724  const TfToken &dstName);
1725 
1726  // --------------------------------------------------------------------- //
1727  // Value & Metadata Authoring
1728  // --------------------------------------------------------------------- //
1729 
1730  // Trait that allows us to call the correct versions of _SetValue and
1731  // _SetMetadata for types whose values need to be mapped when written to
1732  // different edit targets.
1733  template <class T>
1734  struct _IsEditTargetMappable {
1735  static const bool value =
1737  std::is_same<T, VtArray<SdfTimeCode>>::value ||
1739  std::is_same<T, VtArray<SdfPathExpression>>::value ||
1742  };
1743 
1744  // Set value for types that don't need to be mapped for edit targets.
1745  template <class T>
1747  _SetValue(
1748  UsdTimeCode time, const UsdAttribute &attr, const T &newValue);
1749 
1750  // Set value for types that do need to be mapped for edit targets.
1751  template <class T>
1753  _SetValue(
1754  UsdTimeCode time, const UsdAttribute &attr, const T &newValue);
1755 
1756  // Set value for dynamically typed VtValue. Will map the value across edit
1757  // targets if the held value type supports it.
1758  bool _SetValue(
1759  UsdTimeCode time, const UsdAttribute &attr, const VtValue &newValue);
1760 
1761  template <class T>
1762  bool _SetEditTargetMappedValue(
1763  UsdTimeCode time, const UsdAttribute &attr, const T &newValue);
1764 
1765  template <class T>
1766  bool _SetValueImpl(
1767  UsdTimeCode time, const UsdAttribute &attr, const T& value);
1768 
1769  bool _ClearValue(UsdTimeCode time, const UsdAttribute &attr);
1770 
1771  // Set metadata for types that don't need to be mapped across edit targets.
1772  template <class T>
1774  _SetMetadata(const UsdObject &object, const TfToken& key,
1775  const TfToken &keyPath, const T& value);
1776 
1777  // Set metadata for types that do need to be mapped for edit targets.
1778  template <class T>
1780  _SetMetadata(const UsdObject &object, const TfToken& key,
1781  const TfToken &keyPath, const T& value);
1782 
1783  // Set metadata for dynamically typed VtValue. Will map the value across
1784  // edit targets if the held value type supports it.
1785  USD_API
1786  bool _SetMetadata(const UsdObject &object,
1787  const TfToken& key,
1788  const TfToken &keyPath,
1789  const VtValue& value);
1790 
1791  template <class T>
1792  bool _SetEditTargetMappedMetadata(
1793  const UsdObject &obj, const TfToken& fieldName,
1794  const TfToken &keyPath, const T &newValue);
1795 
1796  template <class T>
1797  bool _SetMetadataImpl(
1798  const UsdObject &obj, const TfToken& fieldName,
1799  const TfToken &keyPath, const T &value);
1800 
1801  bool _ClearMetadata(const UsdObject &obj, const TfToken& fieldName,
1802  const TfToken &keyPath=TfToken());
1803 
1804  // --------------------------------------------------------------------- //
1805  // Misc Internal Helpers
1806  // --------------------------------------------------------------------- //
1807 
1808  // Pcp helpers.
1809  PcpCache const *_GetPcpCache() const { return _cache.get(); }
1810  PcpCache *_GetPcpCache() { return _cache.get(); }
1811 
1812  // Returns the PrimIndex, using the read-only PcpCache API. We expect prims
1813  // to be composed during initial stage composition, so this method should
1814  // not be used in that context.
1815  const PcpPrimIndex* _GetPcpPrimIndex(const SdfPath& primPath) const;
1816 
1817  // Helper to report pcp errors.
1818  void _ReportPcpErrors(const PcpErrorVector &errors,
1819  const std::string &context) const;
1820  void _ReportErrors(const PcpErrorVector &errors,
1821  const std::vector<std::string>& otherErrors,
1822  const std::string &context) const;
1823 
1824  // --------------------------------------------------------------------- //
1825  // Scenegraph Composition & Change Processing
1826  // --------------------------------------------------------------------- //
1827 
1828  // Compose the prim indexes in the subtrees rooted at the paths in
1829  // \p primIndexPaths. If \p instanceChanges is given, returns
1830  // changes to prototypes and instances due to the discovery of new instances
1831  // during composition.
1832  void _ComposePrimIndexesInParallel(
1833  const std::vector<SdfPath>& primIndexPaths,
1834  const std::string& context,
1835  Usd_InstanceChanges* instanceChanges = nullptr);
1836 
1837  // Recompose the subtree rooted at \p prim: compose its type, flags, and
1838  // list of children, then invoke _ComposeSubtree on all its children.
1839  void _ComposeSubtree(
1842  const SdfPath &primIndexPath = SdfPath());
1843  void _ComposeSubtreeImpl(
1845  UsdStagePopulationMask const *mask,
1846  const SdfPath &primIndexPath = SdfPath());
1847  void _ComposeSubtreesInParallel(
1848  const std::vector<Usd_PrimDataPtr> &prims,
1849  const std::vector<SdfPath> *primIndexPaths = nullptr);
1850 
1851  // Composes the full prim type info for the prim based on its type name
1852  // and applied API schemas.
1853  void _ComposePrimTypeInfoImpl(Usd_PrimDataPtr prim);
1854 
1855  // Compose subtree rooted at \p prim under \p parent. This function
1856  // ensures that the appropriate prim index is specified for \p prim if
1857  // \p parent is in a prototype.
1858  void _ComposeChildSubtree(Usd_PrimDataPtr prim,
1859  Usd_PrimDataConstPtr parent,
1860  UsdStagePopulationMask const *mask);
1861 
1862  // Compose \p prim's list of children and make any modifications necessary
1863  // to its _children member and the stage's _primMap, including possibly
1864  // instantiating new prims, or destroying existing subtrees of prims. The
1865  // any newly created prims *do not* have their prim index, type, flags, or
1866  // children composed.
1867  //
1868  // Compose only \p prim's direct children if recurse=false. Otherwise
1869  // recompose every descendent of \p prim. Callers that pass recurse=false
1870  // should invoke _ComposeSubtree on any newly created prims to ensure caches
1871  // are correctly populated.
1872  void _ComposeChildren(Usd_PrimDataPtr prim,
1873  UsdStagePopulationMask const *mask, bool recurse);
1874 
1875  // Instantiate a prim instance. There must not already be an instance
1876  // at \p primPath.
1877  Usd_PrimDataPtr _InstantiatePrim(const SdfPath &primPath);
1878 
1879  // Instantiate a prototype prim and sets its parent to pseudoroot.
1880  // There must not already be a prototype at \p primPath.
1881  Usd_PrimDataPtr _InstantiatePrototypePrim(const SdfPath &primPath);
1882 
1883  // For \p prim and all of its descendants, remove from _primMap and empty
1884  // their _children vectors.
1885  void _DestroyPrim(Usd_PrimDataPtr prim);
1886 
1887  // Destroy the prim subtrees rooted at each path in \p paths. \p paths may
1888  // not contain any path that is a descendent of another path in \p paths.
1889  void _DestroyPrimsInParallel(const std::vector<SdfPath>& paths);
1890 
1891  // Invoke _DestroyPrim() on all of \p prim's direct children.
1892  void _DestroyDescendents(Usd_PrimDataPtr prim);
1893 
1894  // Returns true if the object at the given path is a descendant of
1895  // an instance prim, i.e. a prim beneath an instance prim, or a property
1896  // of a prim beneath an instance prim.
1897  bool _IsObjectDescendantOfInstance(const SdfPath& path) const;
1898 
1899  // If the given prim is an instance, returns the corresponding
1900  // prototype prim. Otherwise, returns an invalid prim.
1901  Usd_PrimDataConstPtr _GetPrototypeForInstance(Usd_PrimDataConstPtr p) const;
1902 
1903  // Returns the path of the Usd prim using the prim index at the given path.
1904  SdfPath _GetPrimPathUsingPrimIndexAtPath(const SdfPath& primIndexPath) const;
1905 
1906  // Update stage contents in response to changes in scene description.
1907  void _HandleLayersDidChange(const SdfNotice::LayersDidChangeSentPerLayer &);
1908 
1909  // Update stage contents in response to changes to the asset resolver.
1910  void _HandleResolverDidChange(const ArNotice::ResolverChanged &);
1911 
1912  // Process stage change information stored in _pendingChanges.
1913  // _pendingChanges will be set to nullptr by the end of the function.
1914  void _ProcessPendingChanges();
1915 
1916  // Remove scene description for the prim at \p fullPath in the current edit
1917  // target.
1918  bool _RemovePrim(const SdfPath& fullPath);
1919 
1920  SdfPrimSpecHandle _GetPrimSpec(const SdfPath& fullPath);
1921 
1922  // Find and return the defining spec type for the property spec at the given
1923  // path, or SdfSpecTypeUnknown if none exists. The defining spec type is
1924  // either the builtin definition's spec type, if the indicated property is
1925  // builtin, otherwise it's the strongest authored spec's type if one exists,
1926  // otherwise it's SdfSpecTypeUnknown.
1927  SdfSpecType _GetDefiningSpecType(Usd_PrimDataConstPtr primData,
1928  const TfToken &propName) const;
1929 
1930  // Helper to apply Pcp changes and recompose the scenegraph accordingly,
1931  // given an optional initial set of paths to recompose.
1932  void _Recompose(const PcpChanges &changes);
1933  template <class T>
1934  void _Recompose(const PcpChanges &changes, T *pathsToRecompose);
1935  template <class T>
1936  void _RecomposePrims(T *pathsToRecompose);
1937 
1938  // Helper for _Recompose to find the subtrees that need to be
1939  // fully recomposed and to recompose the name children of the
1940  // parents of these subtrees. Note that [start, finish) must be a
1941  // sorted range of map iterators whose keys are paths with no descendent
1942  // paths. In C++20, consider using the ranges API to improve this.
1943  template <class Iter>
1944  void _ComputeSubtreesToRecompose(Iter start, Iter finish,
1945  std::vector<Usd_PrimDataPtr>* recompose);
1946 
1947  // return true if the path is valid for load/unload operations.
1948  // This method will emit errors when invalid paths are encountered.
1949  bool _IsValidForLoad(const SdfPath& path) const;
1950  bool _IsValidForUnload(const SdfPath& path) const;
1951 
1952  // Discover all payloads in a given subtree, adding the path of each
1953  // discovered prim index to the \p primIndexPaths set. If specified,
1954  // the corresponding UsdPrim path will be added to the \p usdPrimPaths
1955  // set. The root path will be considered for inclusion in the result set.
1956  //
1957  // Note that some payloads may not be discoverable in until an ancestral
1958  // payload has been included. UsdStage::LoadAndUnload takes this into
1959  // account.
1960  void _DiscoverPayloads(const SdfPath& rootPath,
1962  SdfPathSet* primIndexPaths,
1963  bool unloadedOnly = false,
1964  SdfPathSet* usdPrimPaths = nullptr) const;
1965 
1966  // ===================================================================== //
1967  // VALUE RESOLUTION //
1968  // ===================================================================== //
1969  // --------------------------------------------------------------------- //
1970  // Specialized Value Resolution
1971  // --------------------------------------------------------------------- //
1972 
1973  // Helpers for resolving values for metadata fields requiring
1974  // special behaviors.
1975  static SdfSpecifier _GetSpecifier(Usd_PrimDataConstPtr primData);
1976  static TfToken _GetKind(Usd_PrimDataConstPtr primData);
1977  static bool _IsActive(Usd_PrimDataConstPtr primData);
1978 
1979  // Custom is true if it is true anywhere in the stack.
1980  bool _IsCustom(const UsdProperty &prop) const;
1981 
1982  // Variability is determined by the weakest opinion in the stack.
1983  SdfVariability _GetVariability(const UsdProperty &prop) const;
1984 
1985  // Helper functions for resolving asset paths during value resolution.
1986  void _MakeResolvedAssetPaths(UsdTimeCode time, const UsdAttribute &attr,
1987  SdfAssetPath *assetPaths,
1988  size_t numAssetPaths,
1989  bool anchorAssetPathsOnly = false) const;
1990 
1991  void _MakeResolvedAssetPathsValue(UsdTimeCode time, const UsdAttribute &attr,
1992  VtValue *value,
1993  bool anchorAssetPathsOnly = false) const;
1994 
1995  void _MakeResolvedTimeCodes(UsdTimeCode time, const UsdAttribute &attr,
1996  SdfTimeCode *timeCodes,
1997  size_t numTimeCodes) const;
1998 
1999  void _MakeResolvedPathExpressions(
2000  UsdTimeCode time, const UsdAttribute &attr,
2001  SdfPathExpression *pathExprs,
2002  size_t numPathExprs) const;
2003 
2004  void _MakeResolvedAttributeValue(UsdTimeCode time, const UsdAttribute &attr,
2005  VtValue *value) const;
2006 
2007  // --------------------------------------------------------------------- //
2008  // Metadata Resolution
2009  // --------------------------------------------------------------------- //
2010 
2011 public:
2012  // Trait that allows us to call the correct version of _GetMetadata for
2013  // types that require type specific value resolution as opposed to just
2014  // strongest opinion. These types also use type specific resolution
2015  // in _GetValue.
2016  template <class T>
2018  static const bool value =
2020  std::is_same<T, VtArray<SdfAssetPath>>::value ||
2022  std::is_same<T, VtArray<SdfTimeCode>>::value ||
2024  std::is_same<T, VtArray<SdfPathExpression>>::value ||
2027  };
2028 
2029 private:
2030  // Get metadata for types that do not have type specific value resolution.
2031  template <class T>
2033  _GetMetadata(const UsdObject &obj,
2034  const TfToken& fieldName,
2035  const TfToken &keyPath,
2036  bool useFallbacks,
2037  T* result) const;
2038 
2039  // Get metadata for types that do have type specific value resolution.
2040  template <class T>
2042  _GetMetadata(const UsdObject &obj,
2043  const TfToken& fieldName,
2044  const TfToken &keyPath,
2045  bool useFallbacks,
2046  T* result) const;
2047 
2048  // Get metadata as a dynamically typed VtValue. Will perform type specific
2049  // value resolution if the returned held type requires it.
2050  bool _GetMetadata(const UsdObject &obj,
2051  const TfToken& fieldName,
2052  const TfToken &keyPath,
2053  bool useFallbacks,
2054  VtValue* result) const;
2055 
2056  // Gets a metadata value using only strongest value resolution. It is
2057  // assumed that result is holding a value that does not require type
2058  // specific value resolution.
2059  USD_API
2060  bool _GetStrongestResolvedMetadata(const UsdObject &obj,
2061  const TfToken& fieldName,
2062  const TfToken &keyPath,
2063  bool useFallbacks,
2064  SdfAbstractDataValue* result) const;
2065 
2066  // Gets a metadata value with the type specific value resolution for the
2067  // type applied. This is only implemented for types that
2068  // _HasTypeSpecificResolution.
2069  template <class T>
2070  USD_API
2071  bool _GetTypeSpecificResolvedMetadata(const UsdObject &obj,
2072  const TfToken& fieldName,
2073  const TfToken &keyPath,
2074  bool useFallbacks,
2075  T* result) const;
2076 
2077  template <class Composer>
2078  void _GetAttrTypeImpl(const UsdAttribute &attr,
2079  const TfToken &fieldName,
2080  bool useFallbacks,
2081  Composer *composer) const;
2082 
2083  template <class Composer>
2084  void _GetAttrVariabilityImpl(const UsdAttribute &attr,
2085  bool useFallbacks,
2086  Composer *composer) const;
2087 
2088  template <class Composer>
2089  void _GetPropCustomImpl(const UsdProperty &prop,
2090  bool useFallbacks,
2091  Composer *composer) const;
2092 
2093  template <class Composer>
2094  bool _GetSpecialPropMetadataImpl(const UsdObject &obj,
2095  const TfToken &fieldName,
2096  const TfToken &keyPath,
2097  bool useFallbacks,
2098  Composer *composer) const;
2099  template <class Composer>
2100  bool _GetMetadataImpl(const UsdObject &obj,
2101  const TfToken& fieldName,
2102  const TfToken& keyPath,
2103  bool includeFallbacks,
2104  Composer *composer) const;
2105 
2106  template <class Composer>
2107  bool _GetGeneralMetadataImpl(const UsdObject &obj,
2108  const TfToken& fieldName,
2109  const TfToken& keyPath,
2110  bool includeFallbacks,
2111  Composer *composer) const;
2112 
2113  // NOTE: The "authoredOnly" flag is not yet in use, but when we have
2114  // support for prim-based metadata fallbacks, they should be ignored when
2115  // this flag is set to true.
2116  bool _HasMetadata(const UsdObject &obj, const TfToken& fieldName,
2117  const TfToken &keyPath, bool useFallbacks) const;
2118 
2120  _ListMetadataFields(const UsdObject &obj, bool useFallbacks) const;
2121 
2122  void _GetAllMetadata(const UsdObject &obj,
2123  bool useFallbacks,
2125  bool anchorAssetPathsOnly = false) const;
2126 
2127  // --------------------------------------------------------------------- //
2128  // Default & TimeSample Resolution
2129  // --------------------------------------------------------------------- //
2130 
2131  void _GetResolveInfo(const UsdAttribute &attr,
2132  UsdResolveInfo *resolveInfo,
2133  const UsdTimeCode *time = nullptr) const;
2134 
2135  void _GetResolveInfoWithResolveTarget(
2136  const UsdAttribute &attr,
2137  const UsdResolveTarget &resolveTarget,
2138  UsdResolveInfo *resolveInfo,
2139  const UsdTimeCode *time = nullptr) const;
2140 
2141  template <class T> struct _ExtraResolveInfo;
2142 
2143  // Gets the value resolve info for the given attribute. If time is provided,
2144  // the resolve info is evaluated for that specific time (which may be
2145  // default). Otherwise, if time is null, the resolve info is evaluated for
2146  // "any numeric time" and will not populate values in extraInfo that
2147  // require a specific time to be evaluated.
2148  template <class T>
2149  void _GetResolveInfo(const UsdAttribute &attr,
2150  UsdResolveInfo *resolveInfo,
2151  const UsdTimeCode *time = nullptr,
2152  _ExtraResolveInfo<T> *extraInfo = nullptr) const;
2153 
2154  // Gets the value resolve info for the given attribute using the given
2155  // resolve target. If time is provided, the resolve info is evaluated for
2156  // that specific time (which may be default). Otherwise, if time is null,
2157  // the resolve info is evaluated for "any numeric time" and will not
2158  // populate values in extraInfo that require a specific time to be
2159  // evaluated.
2160  template <class T>
2161  void _GetResolveInfoWithResolveTarget(
2162  const UsdAttribute &attr,
2163  const UsdResolveTarget &resolveTarget,
2164  UsdResolveInfo *resolveInfo,
2165  const UsdTimeCode *time = nullptr,
2166  _ExtraResolveInfo<T> *extraInfo = nullptr) const;
2167 
2168  // Shared implementation function for _GetResolveInfo and
2169  // _GetResolveInfoWithResolveTarget. The only difference between how these
2170  // two functions behave is in how they create the Usd_Resolver used for
2171  // iterating over nodes and layers, thus they provide this implementation
2172  // with the needed MakeUsdResolverFn to create the Usd_Resolver.
2173  template <class T, class MakeUsdResolverFn>
2174  void _GetResolveInfoImpl(const UsdAttribute &attr,
2175  UsdResolveInfo *resolveInfo,
2176  const UsdTimeCode *time,
2177  _ExtraResolveInfo<T> *extraInfo,
2178  const MakeUsdResolverFn &makeUsdResolveFn) const;
2179 
2180  template <class T> struct _ResolveInfoResolver;
2181  struct _PropertyStackResolver;
2182 
2183  template <class Resolver, class MakeUsdResolverFn>
2184  void _GetResolvedValueAtDefaultImpl(
2185  const UsdProperty &prop,
2186  Resolver *resolver,
2187  const MakeUsdResolverFn &makeUsdResolverFn) const;
2188 
2189  template <class Resolver, class MakeUsdResolverFn>
2190  void _GetResolvedValueAtTimeImpl(
2191  const UsdProperty &prop,
2192  Resolver *resolver,
2193  const double *time,
2194  const MakeUsdResolverFn &makeUsdResolverFn) const;
2195 
2196  bool _GetValue(UsdTimeCode time, const UsdAttribute &attr,
2197  VtValue* result) const;
2198 
2199  template <class T>
2200  bool _GetValue(UsdTimeCode time, const UsdAttribute &attr,
2201  T* result) const;
2202 
2203  template <class T>
2204  bool _GetValueImpl(UsdTimeCode time, const UsdAttribute &attr,
2205  Usd_InterpolatorBase* interpolator,
2206  T* value) const;
2207 
2208  USD_API
2209  bool _GetValueFromResolveInfo(const UsdResolveInfo &info,
2210  UsdTimeCode time, const UsdAttribute &attr,
2211  VtValue* result) const;
2212 
2213  template <class T>
2214  USD_API
2215  bool _GetValueFromResolveInfo(const UsdResolveInfo &info,
2216  UsdTimeCode time, const UsdAttribute &attr,
2217  T* result) const;
2218 
2219  template <class T>
2220  bool _GetValueFromResolveInfoImpl(const UsdResolveInfo &info,
2221  UsdTimeCode time, const UsdAttribute &attr,
2222  Usd_InterpolatorBase* interpolator,
2223  T* value) const;
2224 
2225  template <class T>
2226  bool _GetDefaultValueFromResolveInfoImpl(const UsdResolveInfo &info,
2227  const UsdAttribute &attr,
2228  T* value) const;
2229 
2231  _GetAssetPathContext(UsdTimeCode time, const UsdAttribute &attr) const;
2232 
2233  // --------------------------------------------------------------------- //
2234  // Specialized Time Sample I/O
2235  // --------------------------------------------------------------------- //
2236 
2237  /// Gets the set of time samples authored for a given attribute
2238  /// within the \p interval. The interval may have any combination
2239  /// of open/infinite and closed/finite endpoints; it may not have
2240  /// open/finite endpoints, however, this restriction may be lifted
2241  /// in the future.
2242  /// Returns false on an error.
2243  bool _GetTimeSamplesInInterval(const UsdAttribute &attr,
2244  const GfInterval& interval,
2245  std::vector<double>* times) const;
2246 
2247  bool _GetTimeSamplesInIntervalFromResolveInfo(
2248  const UsdResolveInfo &info,
2249  const UsdAttribute &attr,
2250  const GfInterval& interval,
2251  std::vector<double>* times) const;
2252 
2253  size_t _GetNumTimeSamples(const UsdAttribute &attr) const;
2254 
2255  size_t _GetNumTimeSamplesFromResolveInfo(const UsdResolveInfo &info,
2256  const UsdAttribute &attr) const;
2257 
2258  /// Gets the bracketing times around a desiredTime. Only false on error
2259  /// or if no value exists (default or timeSamples). See
2260  /// UsdAttribute::GetBracketingTimeSamples for details.
2261  bool _GetBracketingTimeSamples(const UsdAttribute &attr,
2262  double desiredTime,
2263  bool authoredOnly,
2264  double* lower,
2265  double* upper,
2266  bool* hasSamples) const;
2267 
2268  bool _GetBracketingTimeSamplesFromResolveInfo(const UsdResolveInfo &info,
2269  const UsdAttribute &attr,
2270  double desiredTime,
2271  bool authoredOnly,
2272  double* lower,
2273  double* upper,
2274  bool* hasSamples) const;
2275 
2276  bool _ValueMightBeTimeVarying(const UsdAttribute &attr) const;
2277 
2278  bool _ValueMightBeTimeVaryingFromResolveInfo(const UsdResolveInfo &info,
2279  const UsdAttribute &attr) const;
2280 
2281  void _RegisterPerLayerNotices();
2282  void _RegisterResolverChangeNotice();
2283 
2284  // Helper to obtain a malloc tag string for this stage.
2285  inline char const *_GetMallocTagId() const;
2286 
2287 private:
2288 
2289  // The 'pseudo root' prim.
2290  Usd_PrimDataPtr _pseudoRoot;
2291 
2292  // The stage's root layer.
2293  SdfLayerRefPtr _rootLayer;
2294 
2295  // Every UsdStage has an implicit, in-memory session layer.
2296  // This is to allow for runtime overrides such as variant selections.
2297  SdfLayerRefPtr _sessionLayer;
2298 
2299  // The stage's EditTarget.
2300  UsdEditTarget _editTarget;
2301  bool _editTargetIsLocalLayer;
2302 
2303  std::unique_ptr<PcpCache> _cache;
2304  std::unique_ptr<Usd_ClipCache> _clipCache;
2305  std::unique_ptr<Usd_InstanceCache> _instanceCache;
2306 
2307  TfHashMap<TfToken, TfToken, TfHash> _invalidPrimTypeToFallbackMap;
2308 
2309  size_t _usedLayersRevision;
2310 
2311  // A concurrent map from Path to Prim, for fast random access.
2312  struct _TbbHashEq {
2313  inline bool equal(SdfPath const &l, SdfPath const &r) const {
2314  return l == r;
2315  }
2316  inline size_t hash(SdfPath const &path) const {
2317  return path.GetHash();
2318  }
2319  };
2320  using PathToNodeMap = tbb::concurrent_hash_map<
2321  SdfPath, Usd_PrimDataIPtr, _TbbHashEq>;
2322  PathToNodeMap _primMap;
2323 
2324  // The interpolation type used for all attributes on the stage.
2325  UsdInterpolationType _interpolationType;
2326 
2327  typedef std::vector<
2328  std::pair<SdfLayerHandle, TfNotice::Key> > _LayerAndNoticeKeyVec;
2329  _LayerAndNoticeKeyVec _layersAndNoticeKeys;
2330  size_t _lastChangeSerialNumber;
2331 
2332  TfNotice::Key _resolverChangeKey;
2333 
2334  // Data for pending change processing.
2335  class _PendingChanges;
2336  _PendingChanges* _pendingChanges;
2337 
2338  std::optional<WorkDispatcher> _dispatcher;
2339 
2340  // To provide useful aggregation of malloc stats, we bill everything
2341  // for this stage - from all access points - to this tag.
2342  std::unique_ptr<std::string> _mallocTagID;
2343 
2344  // The state used when instantiating the stage.
2345  const InitialLoadSet _initialLoadSet;
2346 
2347  // The population mask that applies to this stage.
2348  UsdStagePopulationMask _populationMask;
2349 
2350  // The load rules that apply to this stage.
2351  UsdStageLoadRules _loadRules;
2352 
2353  bool _isClosingStage;
2354  bool _isWritingFallbackPrimTypes;
2355 
2356  friend class UsdAPISchemaBase;
2357  friend class UsdAttribute;
2358  friend class UsdAttributeQuery;
2359  friend class UsdEditTarget;
2360  friend class UsdInherits;
2361  friend class UsdObject;
2362  friend class UsdPrim;
2363  friend class UsdProperty;
2364  friend class UsdRelationship;
2365  friend class UsdSpecializes;
2366  friend class UsdVariantSet;
2367  friend class UsdVariantSets;
2368  friend class Usd_AssetPathContext;
2369  friend class Usd_FlattenAccess;
2370  friend class Usd_PcpCacheAccess;
2371  friend class Usd_PrimData;
2372  friend class Usd_StageOpenRequest;
2373  template <class T> friend struct Usd_AttrGetValueHelper;
2375  template <class RefsOrPayloadsEditorType, class RefsOrPayloadsProxyType>
2376  friend struct Usd_ListEditImpl;
2377 };
2378 
2379 // UsdObject's typed metadata query relies on this specialization being
2380 // externally visible and exporting the primary template does not
2381 // automatically export this specialization.
2382 template <>
2383 USD_API
2384 bool
2385 UsdStage::_GetTypeSpecificResolvedMetadata(const UsdObject &obj,
2386  const TfToken& fieldName,
2387  const TfToken &keyPath,
2388  bool useFallbacks,
2389  SdfTimeSampleMap* result) const;
2390 
2391 template<typename T>
2392 bool
2394 {
2395  VtValue result;
2396  if (!GetMetadata(key, &result)){
2397  return false;
2398  }
2399 
2400  if (result.IsHolding<T>()){
2401  *value = result.UncheckedGet<T>();
2402  return true;
2403  } else {
2404  TF_CODING_ERROR("Requested type %s for stage metadatum %s does not"
2405  " match retrieved type %s",
2406  ArchGetDemangled<T>().c_str(),
2407  key.GetText(),
2408  result.GetTypeName().c_str());
2409  return false;
2410  }
2411 }
2412 
2413 template<typename T>
2414 bool
2415 UsdStage::SetMetadata(const TfToken& key, const T& value) const
2416 {
2417  VtValue in(value);
2418  return SetMetadata(key, in);
2419 }
2420 
2421 template<typename T>
2422 bool
2423 UsdStage::GetMetadataByDictKey(const TfToken& key, const TfToken &keyPath,
2424  T* value) const
2425 {
2426  VtValue result;
2427  if (!GetMetadataByDictKey(key, keyPath, &result)){
2428  return false;
2429  }
2430 
2431  if (result.IsHolding<T>()){
2432  *value = result.UncheckedGet<T>();
2433  return true;
2434  } else {
2435  TF_CODING_ERROR("Requested type %s for stage metadatum %s[%s] does not"
2436  " match retrieved type %s",
2437  ArchGetDemangled<T>().c_str(),
2438  key.GetText(),
2439  keyPath.GetText(),
2440  result.GetTypeName().c_str());
2441  return false;
2442  }
2443 }
2444 
2445 template<typename T>
2446 bool
2447 UsdStage::SetMetadataByDictKey(const TfToken& key, const TfToken &keyPath,
2448  const T& value) const
2449 {
2450  VtValue in(value);
2451  return SetMetadataByDictKey(key, keyPath, in);
2452 }
2453 
2454 // Get metadata for types that do not have type specific value resolution.
2455 template <class T>
2456 typename std::enable_if<
2458 UsdStage::_GetMetadata(const UsdObject &obj,
2459  const TfToken& fieldName,
2460  const TfToken &keyPath,
2461  bool useFallbacks,
2462  T* result) const
2463 {
2464  // Since these types don't have type specific value resolution, we can just
2465  // get the strongest metadata value and be done.
2466  SdfAbstractDataTypedValue<T> out(result);
2467  return _GetStrongestResolvedMetadata(
2468  obj, fieldName, keyPath, useFallbacks, &out);
2469 }
2470 
2471 // Get metadata for types that do have type specific value resolution.
2472 template <class T>
2473 typename std::enable_if<
2475 UsdStage::_GetMetadata(const UsdObject &obj,
2476  const TfToken& fieldName,
2477  const TfToken &keyPath,
2478  bool useFallbacks,
2479  T* result) const
2480 {
2481  // Call the templated type specifice resolved metadata implementation that
2482  // will only be implemented for types that support it.
2483  return _GetTypeSpecificResolvedMetadata(
2484  obj, fieldName, keyPath, useFallbacks, result);
2485 }
2486 
2487 
2488 // Set metadata for types that don't need to be mapped across edit targets.
2489 template <class T>
2491 UsdStage::_SetMetadata(const UsdObject &object, const TfToken& key,
2492  const TfToken &keyPath, const T& value)
2493 {
2494  // Since we know that we don't need to map the value for edit targets,
2495  // we can just type erase the value and set the metadata as is.
2497  return _SetMetadataImpl<SdfAbstractDataConstValue>(
2498  object, key, keyPath, in);
2499 }
2500 
2501 // Set metadata for types that do need to be mapped for edit targets.
2502 template <class T>
2504 UsdStage::_SetMetadata(const UsdObject &object, const TfToken& key,
2505  const TfToken &keyPath, const T& value)
2506 {
2507  return _SetEditTargetMappedMetadata(object, key, keyPath, value);
2508 }
2509 
2511 
2512 #endif //PXR_USD_USD_STAGE_H
2513 
UsdLoadPolicy
Definition: common.h:116
Definition: layer.h:97
std::string upper(string_view a)
Return an all-upper case version of a (locale-independent).
Definition: strutil.h:402
GT_API const UT_StringHolder filename
USD_API void MuteAndUnmuteLayers(const std::vector< std::string > &muteLayers, const std::vector< std::string > &unmuteLayers)
virtual USD_API ~UsdStage()
static SDF_API const SdfPath & AbsoluteRootPath()
USD_API double GetFramesPerSecond() const
#define USD_API
Definition: api.h:40
USD_API bool HasDefaultPrim() const
USD_API UsdPrim GetPrimAtPath(const SdfPath &path) const
T const & UncheckedGet() const &
Definition: value.h:1121
USD_API void SetInterpolationType(UsdInterpolationType interpolationType)
hboost::math::policies::policy< hboost::math::policies::domain_error< hboost::math::policies::ignore_error >, hboost::math::policies::pole_error< hboost::math::policies::ignore_error >, hboost::math::policies::overflow_error< hboost::math::policies::ignore_error >, hboost::math::policies::underflow_error< hboost::math::policies::ignore_error >, hboost::math::policies::denorm_error< hboost::math::policies::ignore_error >, hboost::math::policies::rounding_error< hboost::math::policies::ignore_error >, hboost::math::policies::evaluation_error< hboost::math::policies::ignore_error >, hboost::math::policies::indeterminate_result_error< hboost::math::policies::ignore_error > > policy
Definition: SYS_MathCbrt.h:35
USD_API std::vector< UsdPrim > GetPrototypes() const
Returns all native instancing prototype prims.
USD_API void Save()
USD_API ArResolverContext GetPathResolverContext() const
USD_API double GetStartTimeCode() const
static USD_API UsdStageRefPtr CreateInMemory(InitialLoadSet load=LoadAll)
USD_API bool HasMetadataDictKey(const TfToken &key, const TfToken &keyPath) const
GT_API const UT_StringHolder time
bool GetMetadata(const TfToken &key, T *value) const
Definition: stage.h:2393
USD_API UsdPrimRange Traverse()
USD_API bool Export(const std::string &filename, bool addSourceFileComment=true, const SdfLayer::FileFormatArguments &args=SdfLayer::FileFormatArguments()) const
GLuint start
Definition: glcorearb.h:475
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
GLsizei const GLfloat * value
Definition: glcorearb.h:824
SDF_DECLARE_HANDLES(SdfLayer)
GLsizei const GLchar *const * path
Definition: glcorearb.h:3341
std::map< std::string, std::string > FileFormatArguments
Definition: layer.h:123
USD_API UsdPrim CreateClassPrim(const SdfPath &rootPrimPath)
#define TF_CODING_ERROR
USD_API bool ClearMetadata(const TfToken &key) const
USD_API UsdRelationship GetRelationshipAtPath(const SdfPath &path) const
USD_API SdfPathSet GetLoadSet()
USD_API void Unload(const SdfPath &path=SdfPath::AbsoluteRootPath())
Definition: cache.h:93
IMATH_HOSTDEVICE constexpr bool equal(T1 a, T2 b, T3 t) IMATH_NOEXCEPT
Definition: ImathFun.h:105
USD_API bool IsLayerMuted(const std::string &layerIdentifier) const
USD_API void SetDefaultPrim(const UsdPrim &prim)
**But if you need a result
Definition: thread.h:613
USD_API void WriteFallbackPrimTypes()
InitialLoadSet
Definition: stage.h:164
USD_API void MuteLayer(const std::string &layerIdentifier)
friend struct Usd_ListEditImpl
Definition: stage.h:2376
USD_API SdfPathSet FindLoadable(const SdfPath &rootPath=SdfPath::AbsoluteRootPath())
static USD_API void SetGlobalVariantFallbacks(const PcpVariantFallbackMap &fallbacks)
size_t GetHash() const
Equality operator.
Definition: path.h:960
bool SetMetadataByDictKey(const TfToken &key, const TfToken &keyPath, const T &value) const
Definition: stage.h:2447
hboost::intrusive_ptr< Usd_PrimData > Usd_PrimDataIPtr
USD_API const UsdEditTarget & GetEditTarget() const
Return the stage's EditTarget.
GLenum GLuint GLint GLint layer
Definition: glcorearb.h:1299
GLenum GLint GLint GLint GLint GLuint dstName
Definition: glcorearb.h:2510
USD_API double GetEndTimeCode() const
USD_API SdfLayerRefPtr Flatten(bool addSourceFileComment=true) const
USD_API UsdPrim GetDefaultPrim() const
USD_API void SetColorConfiguration(const SdfAssetPath &colorConfig) const
USD_API TfToken GetColorManagementSystem() const
Definition: token.h:87
bool GetMetadataByDictKey(const TfToken &key, const TfToken &keyPath, T *value) const
Definition: stage.h:2423
USD_API UsdEditTarget GetEditTargetForLocalLayer(size_t i)
friend class Usd_AssetPathContext
Definition: stage.h:2368
USD_API SdfLayerHandleVector GetLayerStack(bool includeSessionLayers=true) const
USD_API void LoadAndUnload(const SdfPathSet &loadSet, const SdfPathSet &unloadSet, UsdLoadPolicy policy=UsdLoadWithDescendants)
USD_API SdfLayerHandle GetSessionLayer() const
Return this stage's root session layer.
GLint GLuint mask
Definition: glcorearb.h:124
Definition: prim.h:133
USD_API bool HasAuthoredMetadataDictKey(const TfToken &key, const TfToken &keyPath) const
SdfSpecifier
Definition: types.h:117
std::vector< TfToken > TfTokenVector
Convenience types.
Definition: token.h:457
USD_API bool HasAuthoredMetadata(const TfToken &key) const
Definition: path.h:290
static USD_API UsdStageRefPtr CreateNew(const std::string &identifier, InitialLoadSet load=LoadAll)
USD_API UsdProperty GetPropertyAtPath(const SdfPath &path) const
USD_API bool RemovePrim(const SdfPath &path)
USD_API void SetColorManagementSystem(const TfToken &cms) const
std::map< class TfToken, VtValue, TfDictionaryLessThan > UsdMetadataValueMap
Definition: common.h:81
char const * GetText() const
Definition: token.h:196
friend struct Usd_AttrGetValueHelper
Definition: stage.h:2373
static USD_API UsdStageRefPtr Open(const std::string &filePath, InitialLoadSet load=LoadAll)
bool SetMetadata(const TfToken &key, const T &value) const
Definition: stage.h:2415
USD_API bool HasAuthoredTimeCodeRange() const
USD_API void SetLoadRules(UsdStageLoadRules const &rules)
std::vector< PcpErrorBasePtr > PcpErrorVector
Definition: errors.h:78
USD_API void SetEditTarget(const UsdEditTarget &editTarget)
USD_API bool HasMetadata(const TfToken &key) const
USD_API void SetFramesPerSecond(double framesPerSecond) const
std::set< class SdfPath > SdfPathSet
A set of SdfPaths.
Definition: path.h:209
SdfVariability
Definition: types.h:173
USD_API bool HasLocalLayer(const SdfLayerHandle &layer) const
USD_API void UnmuteLayer(const std::string &layerIdentifier)
USD_API std::string ResolveIdentifierToEditTarget(std::string const &identifier) const
USD_API void SetEndTimeCode(double)
USD_API void Reload()
USD_API UsdPrimRange TraverseAll()
USD_API void SetTimeCodesPerSecond(double timeCodesPerSecond) const
PXR_NAMESPACE_CLOSE_SCOPE PXR_NAMESPACE_OPEN_SCOPE
Definition: path.h:1432
USD_API void ClearDefaultPrim()
USD_API SdfLayerHandle GetRootLayer() const
Return this stage's root layer.
SdfSpecType
Definition: types.h:85
std::string lower(string_view a)
Return an all-upper case version of a (locale-independent).
Definition: strutil.h:395
USD_API UsdInterpolationType GetInterpolationType() const
friend class Usd_FlattenAccess
Definition: stage.h:2369
static USD_API bool IsSupportedFile(const std::string &filePath)
friend class Usd_PcpCacheAccess
Definition: stage.h:2370
USD_API UsdObject GetObjectAtPath(const SdfPath &path) const
bool IsHolding() const
Definition: value.h:1081
UsdStageLoadRules const & GetLoadRules() const
Definition: stage.h:653
Load all loadable prims.
Definition: stage.h:166
friend struct Usd_AttrGetUntypedValueHelper
Definition: stage.h:2374
USD_API UsdPrim Load(const SdfPath &path=SdfPath::AbsoluteRootPath(), UsdLoadPolicy policy=UsdLoadWithDescendants)
static USD_API PcpVariantFallbackMap GetGlobalVariantFallbacks()
Get the global variant fallback preferences used in new UsdStages.
VT_API std::string GetTypeName() const
Return the type name of the held typeid.
#define PXR_NAMESPACE_CLOSE_SCOPE
Definition: pxr.h:91
USD_API SdfAssetPath GetColorConfiguration() const
USD_API const std::vector< std::string > & GetMutedLayers() const
Returns a vector of all layers that have been muted on this stage.
USD_API UsdPrim GetPseudoRoot() const
**If you just want to fire and args
Definition: thread.h:609
friend class Usd_StageOpenRequest
Definition: stage.h:2372
UsdInterpolationType
Definition: interpolation.h:44
USD_API UsdPrim DefinePrim(const SdfPath &path, const TfToken &typeName=TfToken())
Definition: core.h:1131
UsdStagePopulationMask GetPopulationMask() const
Return this stage's population mask.
Definition: stage.h:670
GLboolean r
Definition: glcorearb.h:1222
USD_API UsdPrim OverridePrim(const SdfPath &path)
static USD_API void GetColorConfigFallbacks(SdfAssetPath *colorConfiguration, TfToken *colorManagementSystem)
static USD_API UsdStageRefPtr OpenMasked(const std::string &filePath, UsdStagePopulationMask const &mask, InitialLoadSet load=LoadAll)
USD_API double GetTimeCodesPerSecond() const
std::map< double, VtValue > SdfTimeSampleMap
A map from sample times to sample values.
Definition: types.h:287
USD_API void SetPopulationMask(UsdStagePopulationMask const &mask)
Set this stage's population mask and recompose the stage.
USD_API void SetStartTimeCode(double)
USD_API bool ClearMetadataByDictKey(const TfToken &key, const TfToken &keyPath) const
type
Definition: core.h:1059
USD_API bool ExportToString(std::string *result, bool addSourceFileComment=true) const
USD_API void ExpandPopulationMask(Usd_PrimFlagsPredicate const &traversalPredicate, std::function< bool(UsdRelationship const &)> const &relPred=nullptr, std::function< bool(UsdAttribute const &)> const &attrPred=nullptr)
Definition: value.h:164
USD_API void SaveSessionLayers()
static USD_API void SetColorConfigFallbacks(const SdfAssetPath &colorConfiguration, const TfToken &colorManagementSystem)
std::map< std::string, std::vector< std::string > > PcpVariantFallbackMap
Definition: types.h:206
Load a prim plus all its descendants.
Definition: common.h:118
USD_API SdfLayerHandleVector GetUsedLayers(bool includeClipLayers=true) const
USD_API UsdAttribute GetAttributeAtPath(const SdfPath &path) const
Load no loadable prims.
Definition: stage.h:167