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