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