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_IMAGING_USD_IMAGING_DELEGATE_H
25 #define PXR_USD_IMAGING_USD_IMAGING_DELEGATE_H
26 
27 /// \file usdImaging/delegate.h
28 
29 #include "pxr/pxr.h"
30 #include "pxr/usdImaging/usdImaging/api.h"
31 #include "pxr/usdImaging/usdImaging/version.h"
32 #include "pxr/usdImaging/usdImaging/collectionCache.h"
33 #include "pxr/usdImaging/usdImaging/primvarDescCache.h"
34 #include "pxr/usdImaging/usdImaging/resolvedAttributeCache.h"
35 #include "pxr/usdImaging/usdImaging/instancerContext.h"
36 
37 #include "pxr/imaging/cameraUtil/conformWindow.h"
38 
39 #include "pxr/imaging/hd/coordSys.h"
40 #include "pxr/imaging/hd/sceneDelegate.h"
41 #include "pxr/imaging/hd/selection.h"
42 #include "pxr/imaging/hd/version.h"
43 
44 #include "pxr/imaging/pxOsd/subdivTags.h"
45 #include "pxr/usd/sdf/path.h"
46 #include "pxr/usd/sdf/pathTable.h"
47 #include "pxr/usd/usd/attribute.h"
48 #include "pxr/usd/usd/notice.h"
49 #include "pxr/usd/usd/prim.h"
50 #include "pxr/usd/usd/stage.h"
51 #include "pxr/usd/usdGeom/cube.h"
52 #include "pxr/usd/usdGeom/sphere.h"
53 #include "pxr/usd/usdGeom/xformCache.h"
54 #include "pxr/base/vt/value.h"
55 
56 #include "pxr/base/gf/range3d.h"
57 #include "pxr/base/gf/interval.h"
58 #include "pxr/base/tf/declarePtrs.h"
59 #include "pxr/base/tf/hashmap.h"
60 #include "pxr/base/tf/hashset.h"
61 #include "pxr/base/tf/denseHashSet.h"
62 
63 #include <boost/container/flat_map.hpp>
64 #include <tbb/spin_rw_mutex.h>
65 #include <map>
66 #include <string>
67 
68 PXR_NAMESPACE_OPEN_SCOPE
69 
70 
71 TF_DECLARE_WEAK_PTRS(UsdImagingDelegate);
72 typedef std::vector<UsdPrim> UsdPrimVector;
73 
74 class UsdImagingPrimAdapter;
75 class UsdImagingIndexProxy;
76 class UsdImagingInstancerContext;
77 
78 typedef boost::container::flat_map<SdfPath, bool> PickabilityMap;
79 
80 using UsdImagingPrimAdapterSharedPtr = std::shared_ptr<UsdImagingPrimAdapter>;
81 
82 /// \class UsdImagingDelegate
83 ///
84 /// The primary translation layer between the Hydra (Hd) core and the Usd
85 /// scene graph.
86 ///
87 class UsdImagingDelegate : public HdSceneDelegate, public TfWeakBase {
88     typedef UsdImagingDelegate This;
89 public:
90 
91     typedef TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> RigidXformOverridesMap;
92 
93     USDIMAGING_API
94     UsdImagingDelegate(HdRenderIndex *parentIndex,
95                        SdfPath const& delegateID);
96 
97     USDIMAGING_API
98     virtual ~UsdImagingDelegate();
99 
100     USDIMAGING_API
101     virtual void Sync(HdSyncRequestVector* request) override;
102 
103     // Helper for clients who don't want to drive the sync behavior (unit
104     // tests). Note this method is not virtual.
105     USDIMAGING_API
106     void SyncAll(bool includeUnvarying);
107 
108     /// Populates the rootPrim in the HdRenderIndex.
109     USDIMAGING_API
110     void Populate(UsdPrim const& rootPrim);
111 
112     /// Populates the rootPrim in the HdRenderIndex, excluding all paths in the
113     /// \p excludedPrimPaths, as well as their prim children.
114     USDIMAGING_API
115     void Populate(UsdPrim const& rootPrim,
116                   SdfPathVector const& excludedPrimPaths,
117                   SdfPathVector const &invisedPrimPaths=SdfPathVector());
118 
119     /// For each delegate in \p delegates, sets the current time from
120     /// which data wil be read to the corresponding time in \p times.
121     ///
122     /// This is equivalent to calling SetTime on each delegate individually.
123     /// However, this method will try to parallelize certain operations,
124     /// making it potentially more efficient.
125     USDIMAGING_API
126     static void SetTimes(const std::vector<UsdImagingDelegate*>& delegates,
127                          const std::vector<UsdTimeCode>& times);
128 
129     /// Sets the current time from which data will be read by the delegate.
130     ///
131     /// Changing the current time immediately triggers invalidation in the
132     /// HdChangeTracker. Redundantly setting the time to its existing value is a
133     /// no-op and will not trigger invalidation.
134     USDIMAGING_API
135     void SetTime(UsdTimeCode time);
136 
137     /// Returns the current time.
GetTime()138     UsdTimeCode GetTime() const { return _time; }
139 
140     /// Apply a relative offset to the current time.
141     /// This has no effect in the case of the default USD timecode.
142     UsdTimeCode GetTimeWithOffset(float offset) const;
143 
144     /// Applies any scene edits which have been queued up by notices from USD.
145     USDIMAGING_API
146     void ApplyPendingUpdates();
147 
148     /// Returns the refinement level that is used when prims have no explicit
149     /// level set.
150     ///
151     /// The refinement level indicates how many iterations to apply when
152     /// subdividing subdivision surfaces or other refinable primitives.
153     ///
154     /// Refinement level is always in the range [0,8].
GetRefineLevelFallback()155     int GetRefineLevelFallback() const { return _refineLevelFallback; }
156 
157     /// Sets the fallback refinement level to \p level, triggers dirty
158     /// refine level bit to be set on all Rprims that don't have explicit refine
159     /// levels set.
160     ///
161     /// Level is expected to be in the range [0,8], where 0 indicates no
162     /// refinement.
163     USDIMAGING_API
164     void SetRefineLevelFallback(int level);
165 
166     /// Removes any explicit refine level set for the given USD prim.
167     /// Marks dirty if a change in level occurs.
168     USDIMAGING_API
169     void ClearRefineLevel(SdfPath const& usdPath);
170 
171     /// Sets an explicit refinement level for the given USD prim.
172     /// If no level is explicitly set, the fallback is used;
173     /// see GetRefineLevelFallback().
174     /// If setting an explicit level does not change the effective level, no
175     /// dirty bit is set.
176     USDIMAGING_API
177     void SetRefineLevel(SdfPath const& usdPath, int level);
178 
179     /// Returns the fallback repr name.
GetReprFallback()180     HdReprSelector GetReprFallback() const { return _reprFallback; }
181 
182     /// Sets the fallback repr name. Note that currently UsdImagingDelegate
183     /// doesn't support per-prim repr.
184     USDIMAGING_API
185     void SetReprFallback(HdReprSelector const &repr);
186 
187     /// Returns the fallback cull style.
GetCullStyleFallback()188     HdCullStyle GetCullStyleFallback() const { return _cullStyleFallback; }
189 
190     /// Sets the fallback cull style.
191     USDIMAGING_API
192     void SetCullStyleFallback(HdCullStyle cullStyle);
193 
194     /// Sets the root transform for the entire delegate, which is applied to all
195     /// render prims generated. Setting this value will immediately invalidate
196     /// existing rprim transforms.
197     USDIMAGING_API
198     void SetRootTransform(GfMatrix4d const& xf);
199 
200     /// Returns the root transform for the entire delegate.
GetRootTransform()201     const GfMatrix4d &GetRootTransform() const { return _rootXf; }
202 
203     /// Sets the root visibility for the entire delegate, which is applied to
204     /// all render prims generated. Setting this value will immediately
205     /// invalidate existing rprim visibility.
206     USDIMAGING_API
207     void SetRootVisibility(bool isVisible);
208 
209     /// Returns the root visibility for the entire delegate.
GetRootVisibility()210     bool GetRootVisibility() const { return _rootIsVisible; }
211 
212     /// Set the list of paths that must be invised.
213     USDIMAGING_API
214     void SetInvisedPrimPaths(SdfPathVector const &invisedPaths);
215 
216     /// Set transform value overrides on a set of paths.
217     USDIMAGING_API
218     void SetRigidXformOverrides(RigidXformOverridesMap const &overrides);
219 
220     /// Returns the root paths of pickable objects.
221     USDIMAGING_API
222     PickabilityMap GetPickabilityMap() const;
223 
224     /// Sets pickability for a specific path.
225     USDIMAGING_API
226     void SetPickability(SdfPath const& path, bool pickable);
227 
228     /// Clears any pickability opinions that this delegates might have.
229     USDIMAGING_API
230     void ClearPickabilityMap();
231 
232     /// Sets display of prims with purpose "render"
233     USDIMAGING_API
234     void SetDisplayRender(const bool displayRender);
GetDisplayRender()235     bool GetDisplayRender() const { return _displayRender; }
236 
237     /// Sets display of prims with purpose "proxy"
238     USDIMAGING_API
239     void SetDisplayProxy(const bool displayProxy);
GetDisplayProxy()240     bool GetDisplayProxy() const { return _displayProxy; }
241 
242     /// Sets display of prims with purpose "guide"
243     USDIMAGING_API
244     void SetDisplayGuides(const bool displayGuides);
GetDisplayGuides()245     bool GetDisplayGuides() const { return _displayGuides; }
246 
247     /// Returns whether draw modes are enabled.
248     USDIMAGING_API
249     void SetUsdDrawModesEnabled(bool enableUsdDrawModes);
GetUsdDrawModesEnabled()250     bool GetUsdDrawModesEnabled() const { return _enableUsdDrawModes; }
251 
252     /// Enables custom shading on prims.
253     USDIMAGING_API
254     void SetSceneMaterialsEnabled(bool enable);
255 
256     /// Enables lights found in the usdscene.
257     USDIMAGING_API
258     void SetSceneLightsEnabled(bool enable);
259 
260     /// Set the window policy on all scene cameras. This comes from
261     /// the application.
262     USDIMAGING_API
263     void SetWindowPolicy(CameraUtilConformWindowPolicy policy);
264 
265     /// Sets display of unloaded prims as bounding boxes.
266     /// Unloaded prims will need to satisfy one of the following set of
267     /// conditions in order to see them:
268     ///   1. The prim is a UsdGeomBoundable with an authored 'extent' attribute.
269     ///   2. The prim is a UsdPrim.IsModel() and has an authored 'extentsHint'
270     ///      attribute (see UsdGeomModelAPI::GetExtentsHint).
271     /// Effective only for delegates that support draw modes (see
272     /// GetUsdDrawModesEnabled()).
273     USDIMAGING_API
274     void SetDisplayUnloadedPrimsWithBounds(bool displayUnloaded);
GetDisplayUnloadedPrimsWithBounds()275     bool GetDisplayUnloadedPrimsWithBounds() const {
276         return _displayUnloadedPrimsWithBounds;
277     }
278 
279     /// Setup for the shutter open and close to be used for motion sampling.
280     USDIMAGING_API
281     void SetCameraForSampling(SdfPath const& id);
282 
283     /// Returns the current interval that will be used when using the
284     /// sample* API in the scene delegate.
285     USDIMAGING_API
286     GfInterval GetCurrentTimeSamplingInterval();
287 
288     // ---------------------------------------------------------------------- //
289     // See HdSceneDelegate for documentation of the following virtual methods.
290     // ---------------------------------------------------------------------- //
291     USDIMAGING_API
292     virtual TfToken GetRenderTag(SdfPath const& id) override;
293     USDIMAGING_API
294     virtual HdMeshTopology GetMeshTopology(SdfPath const& id) override;
295     USDIMAGING_API
296     virtual HdBasisCurvesTopology GetBasisCurvesTopology(SdfPath const& id)
297         override;
298     typedef PxOsdSubdivTags SubdivTags;
299 
300     // XXX: animated subdiv tags are not currently supported
301     // XXX: subdiv tags currently fetched on-demand
302     USDIMAGING_API
303     virtual SubdivTags GetSubdivTags(SdfPath const& id) override;
304 
305     USDIMAGING_API
306     virtual GfRange3d GetExtent(SdfPath const & id) override;
307     USDIMAGING_API
308     virtual GfMatrix4d GetTransform(SdfPath const & id) override;
309     USDIMAGING_API
310     virtual bool GetVisible(SdfPath const & id) override;
311     USDIMAGING_API
312     virtual bool GetDoubleSided(SdfPath const & id) override;
313     USDIMAGING_API
314     virtual HdCullStyle GetCullStyle(SdfPath const &id) override;
315 
316     /// Gets the explicit display style for the given prim, if no refine level
317     /// is explicitly set, the fallback is returned; also see
318     /// GetRefineLevelFallback().
319     USDIMAGING_API
320     virtual HdDisplayStyle GetDisplayStyle(SdfPath const& id) override;
321 
322     USDIMAGING_API
323     virtual VtValue Get(SdfPath const& id, TfToken const& key) override;
324     USDIMAGING_API
325     virtual VtValue GetIndexedPrimvar(SdfPath const& id,
326                                       TfToken const& key,
327                                       VtIntArray *outIndices) override;
328     USDIMAGING_API
329     HdIdVectorSharedPtr
330     virtual GetCoordSysBindings(SdfPath const& id) override;
331     USDIMAGING_API
332     virtual HdReprSelector GetReprSelector(SdfPath const &id) override;
333     USDIMAGING_API
334     virtual VtArray<TfToken> GetCategories(SdfPath const &id) override;
335     USDIMAGING_API
336     virtual std::vector<VtArray<TfToken>>
337     GetInstanceCategories(SdfPath const &instancerId) override;
338     USDIMAGING_API
339     virtual HdPrimvarDescriptorVector
340     GetPrimvarDescriptors(SdfPath const& id,
341                           HdInterpolation interpolation) override;
342     USDIMAGING_API
343     virtual VtIntArray GetInstanceIndices(SdfPath const &instancerId,
344                                           SdfPath const &prototypeId) override;
345     USDIMAGING_API
346     virtual GfMatrix4d GetInstancerTransform(SdfPath const &instancerId)
347         override;
348 
349     USDIMAGING_API
350     virtual SdfPath GetInstancerId(SdfPath const &primId) override;
351 
352     USDIMAGING_API
353     virtual SdfPathVector GetInstancerPrototypes(SdfPath const &instancerId) override;
354 
355     // Motion samples
356     USDIMAGING_API
357     virtual size_t
358     SampleTransform(SdfPath const & id, size_t maxNumSamples,
359                     float *times, GfMatrix4d *samples) override;
360     USDIMAGING_API
361     virtual size_t
362     SampleInstancerTransform(SdfPath const &instancerId,
363                              size_t maxSampleCount, float *times,
364                              GfMatrix4d *samples) override;
365     USDIMAGING_API
366     virtual size_t
367     SamplePrimvar(SdfPath const& id, TfToken const& key,
368                   size_t maxNumSamples, float *times,
369                   VtValue *samples) override;
370 
371     USDIMAGING_API
372     virtual size_t
373     SampleIndexedPrimvar(SdfPath const& id, TfToken const& key,
374                          size_t maxNumSamples, float *times,
375                          VtValue *samples, VtIntArray *indices) override;
376 
377     // Material Support
378     USDIMAGING_API
379     virtual SdfPath GetMaterialId(SdfPath const &rprimId) override;
380 
381     USDIMAGING_API
382     virtual VtValue GetMaterialResource(SdfPath const &materialId) override;
383 
384     // Light Support
385     USDIMAGING_API
386     virtual VtValue GetLightParamValue(SdfPath const &id,
387                                        TfToken const &paramName) override;
388     // Camera Support
389     USDIMAGING_API
390     virtual VtValue GetCameraParamValue(SdfPath const &id,
391                                         TfToken const &paramName) override;
392 
393     // Volume Support
394     USDIMAGING_API
395     virtual HdVolumeFieldDescriptorVector
396     GetVolumeFieldDescriptors(SdfPath const &volumeId) override;
397 
398     // Picking path resolution
399     // Resolves a \p rprimId and \p instanceIndex back to the original USD
400     // gprim and instance index.  For point-instanced prims, \p instanceContext
401     // returns extra information about which instance this is of which level of
402     // point-instancer.  For example:
403     //   /World/PI instances /World/PI/proto/PI
404     //   /World/PI/proto/PI instances /World/PI/proto/PI/proto/Gprim
405     //   instancerContext = [/World/PI, 0], [/World/PI/proto/PI, 1] means that
406     //   this instance represents "protoIndex = 0" of /World/PI, etc.
407 
408     USDIMAGING_API
409     virtual SdfPath
410     GetScenePrimPath(SdfPath const& rprimId,
411                      int instanceIndex,
412                      HdInstancerContext *instancerContext = nullptr) override;
413 
414     // ExtComputation support
415     USDIMAGING_API
416     TfTokenVector
417     GetExtComputationSceneInputNames(SdfPath const& computationId) override;
418 
419     USDIMAGING_API
420     HdExtComputationInputDescriptorVector
421     GetExtComputationInputDescriptors(SdfPath const& computationId) override;
422 
423     USDIMAGING_API
424     HdExtComputationOutputDescriptorVector
425     GetExtComputationOutputDescriptors(SdfPath const& computationId) override;
426 
427     USDIMAGING_API
428     HdExtComputationPrimvarDescriptorVector
429     GetExtComputationPrimvarDescriptors(SdfPath const& computationId,
430                                         HdInterpolation interpolation) override;
431 
432     USDIMAGING_API
433     VtValue GetExtComputationInput(SdfPath const& computationId,
434                                    TfToken const& input) override;
435 
436     USDIMAGING_API
437     size_t SampleExtComputationInput(SdfPath const& computationId,
438                                      TfToken const& input,
439                                      size_t maxSampleCount,
440                                      float *sampleTimes,
441                                      VtValue *sampleValues) override;
442 
443     USDIMAGING_API
444     std::string GetExtComputationKernel(SdfPath const& computationId) override;
445 
446     USDIMAGING_API
447     void InvokeExtComputation(SdfPath const& computationId,
448                               HdExtComputationContext *context) override;
449 
450 public:
451     // Converts a cache path to a path in the render index.
452     USDIMAGING_API
ConvertCachePathToIndexPath(SdfPath const & cachePath)453     SdfPath ConvertCachePathToIndexPath(SdfPath const& cachePath) {
454         SdfPathMap::const_iterator it = _cache2indexPath.find(cachePath);
455         if (it != _cache2indexPath.end()) {
456             return it->second;
457         }
458 
459         // For pure/plain usdImaging, there is no prefix to replace
460         SdfPath const &delegateID = GetDelegateID();
461         if (delegateID == SdfPath::AbsoluteRootPath()) {
462             return cachePath;
463         }
464         if (cachePath.IsEmpty()) {
465             return cachePath;
466         }
467 
468         return cachePath.ReplacePrefix(SdfPath::AbsoluteRootPath(), delegateID);
469     }
470 
471     /// Convert the given Hydra ID to a UsdImaging cache path,
472     /// by stripping the scene delegate prefix.
473     ///
474     /// The UsdImaging cache path is the same as a USD prim path,
475     /// except for instanced prims, which get a name-mangled encoding.
476     USDIMAGING_API
ConvertIndexPathToCachePath(SdfPath const & indexPath)477     SdfPath ConvertIndexPathToCachePath(SdfPath const& indexPath) {
478         SdfPathMap::const_iterator it = _index2cachePath.find(indexPath);
479         if (it != _index2cachePath.end()) {
480             return it->second;
481         }
482 
483         // For pure/plain usdImaging, there is no prefix to replace
484         SdfPath const &delegateID = GetDelegateID();
485         if (delegateID == SdfPath::AbsoluteRootPath()) {
486             return indexPath;
487         }
488 
489         return indexPath.ReplacePrefix(delegateID, SdfPath::AbsoluteRootPath());
490     }
491 
492     /// Populate HdxSelection for given \p path (root) and \p instanceIndex.
493     /// If indexPath is an instancer and instanceIndex is ALL_INSTANCES (-1),
494     /// all instances will be selected.
495     ///
496     /// Note: if usdPath points to a gprim, "instanceIndex" (if provided)
497     /// is assumed to be the hydra-computed instance index returned from
498     /// picking code.
499     ///
500     /// If usdPath points to a point instancer, "instanceIndex" is assumed to
501     /// be the instance of the point instancer to selection highlight (e.g.
502     /// instance N of the protoIndices array).  This would correspond to
503     /// returning one of the tuples from GetScenePrimPath's "instancerContext".
504     ///
505     /// In any other case, the interpretation of instanceIndex is undefined.
506     static constexpr int ALL_INSTANCES = -1;
507     USDIMAGING_API
508     bool PopulateSelection(HdSelection::HighlightMode const& highlightMode,
509                            const SdfPath &usdPath,
510                            int instanceIndex,
511                            HdSelectionSharedPtr const &result);
512 
513     /// Returns true if \p usdPath is included in invised path list.
514     USDIMAGING_API
515     bool IsInInvisedPaths(const SdfPath &usdPath) const;
516 
517 private:
518     // Internal Get and SamplePrimvar
519     VtValue _Get(SdfPath const& id, TfToken const& key, VtIntArray *outIndices);
520 
521     size_t _SamplePrimvar(SdfPath const& id, TfToken const& key,
522                           size_t maxNumSamples, float *times, VtValue *samples,
523                           VtIntArray *indices);
524 
525     // Internal friend class.
526     class _Worker;
527     friend class UsdImagingIndexProxy;
528     friend class UsdImagingPrimAdapter;
529 
_ValidateRefineLevel(int level)530     bool _ValidateRefineLevel(int level) {
531         if (!(0 <= level && level <= 8)) {
532             TF_CODING_ERROR("Invalid refinement level(%d), "
533                             "expected range is [0,8]",
534                             level);
535             return false;
536         }
537         return true;
538     }
539 
540     void _AddTask(UsdImagingDelegate::_Worker *worker, SdfPath const& usdPath);
541 
542     // ---------------------------------------------------------------------- //
543     // Draw mode support
544     // ---------------------------------------------------------------------- //
545     // Determine whether to assign a draw mode adapter to the given prim.
546     bool _IsDrawModeApplied(UsdPrim const& prim);
547     // Get the inherited model:drawMode attribute of the given prim.
548     TfToken _GetModelDrawMode(UsdPrim const& prim);
549 
550     // ---------------------------------------------------------------------- //
551     // Usd Change Processing / Notice Handlers
552     // ---------------------------------------------------------------------- //
553     void _OnUsdObjectsChanged(UsdNotice::ObjectsChanged const&,
554                               UsdStageWeakPtr const& sender);
555 
556     // The lightest-weight update, it does fine-grained invalidation of
557     // individual properties at the given path (prim or property).
558     //
559     // If \p path is a prim path, changedPrimInfoFields will be populated
560     // with the list of scene description fields that caused this prim to
561     // be refreshed.
562     void _RefreshUsdObject(SdfPath const& usdPath,
563                            TfTokenVector const& changedPrimInfoFields,
564                            UsdImagingIndexProxy* proxy,
565                            SdfPathSet* allTrackedVariabilityPaths);
566 
567     // Heavy-weight invalidation of an entire prim subtree. All cached data is
568     // reconstructed for all prims below \p rootPath.
569     //
570     // By default, _ResyncPrim will remove each affected prim and call
571     // Repopulate() on those prims individually. If repopulateFromRoot is
572     // true, Repopulate() will be called on \p rootPath instead. This is slower,
573     // but handles changes in tree topology.
574     void _ResyncUsdPrim(SdfPath const& usdRootPath, UsdImagingIndexProxy* proxy,
575                         bool repopulateFromRoot = false);
576 
577     // ---------------------------------------------------------------------- //
578     // Usd Data-Access Helper Methods
579     // ---------------------------------------------------------------------- //
_GetUsdPrim(SdfPath const & usdPath)580     UsdPrim _GetUsdPrim(SdfPath const& usdPath) {
581         UsdPrim const& p =
582                     _stage->GetPrimAtPath(usdPath.GetAbsoluteRootOrPrimPath());
583         TF_VERIFY(p, "No prim found for id: %s",
584                   usdPath.GetAbsoluteRootOrPrimPath().GetText());
585         return p;
586     }
587 
588     VtValue _GetUsdPrimAttribute(SdfPath const& cachePath,
589                                  TfToken const &attrName);
590 
591     void _UpdateSingleValue(SdfPath const& cachePath, int dirtyFlags);
592 
593     // ---------------------------------------------------------------------- //
594     // Cache structures and related methods for population.
595     // ---------------------------------------------------------------------- //
596 
597     // Returns true if this delegate can be populated, false otherwise.
598     bool _CanPopulate(UsdPrim const& rootPrim) const;
599 
600     // Set the delegate's state to reflect that it will be populated from
601     // the given root prim with the given excluded paths.
602     void _SetStateForPopulation(UsdPrim const& rootPrim,
603                                 SdfPathVector const& excludedPaths,
604                                 SdfPathVector const& invisedPaths);
605 
606     // Populates this delegate's render index from the paths specified
607     // in the given index proxy.
608     void _Populate(class UsdImagingIndexProxy* proxy);
609 
610     // Execute all variability update tasks that have been added to the given
611     // worker.
612     static void _ExecuteWorkForVariabilityUpdate(_Worker* worker);
613 
614     /// Returns true if the given prim is visible, taking into account inherited
615     /// visibility values. Inherited values are strongest, Usd has no notion of
616     /// "super vis/invis".
617     bool _GetVisible(UsdPrim const& prim);
618 
619     /// Helper method for filtering discovered primvar names.
620     TfTokenVector _GetPrimvarNames(SdfPath const& usdPath,
621                                    TfToken const& interpolation);
622 
623     // ---------------------------------------------------------------------- //
624     // Helper methods for updating the delegate on time changes
625     // ---------------------------------------------------------------------- //
626 
627     // Execute all time update tasks that have been added to the given worker.
628     static void _ExecuteWorkForTimeUpdate(_Worker* worker);
629 
630     // ---------------------------------------------------------------------- //
631     // Core Delegate state
632     // ---------------------------------------------------------------------- //
633 
634     // Usd Prim Type to Adapter lookup table.
635     typedef TfHashMap<TfToken, UsdImagingPrimAdapterSharedPtr,
636                 TfToken::HashFunctor> _AdapterMap;
637     _AdapterMap _adapterMap;
638 
639     // Per-Hydra-Primitive tracking data
640     struct _HdPrimInfo {
641         UsdImagingPrimAdapterSharedPtr adapter; // The adapter to use for the
642                                                 // prim
643         UsdPrim           usdPrim;          // Reference to the Usd prim
644         HdDirtyBits       timeVaryingBits;  // Dirty Bits to set when
645                                             // time changes
646         HdDirtyBits       dirtyBits;        // Current dirty state of the prim.
647         TfDenseHashSet<SdfPath, SdfPath::Hash>
648                           extraDependencies;// Dependencies that aren't usdPrim.
649     };
650 
651     typedef TfHashMap<SdfPath, _HdPrimInfo, SdfPath::Hash> _HdPrimInfoMap;
652 
653     // Map from cache path to Hydra prim info
654     _HdPrimInfoMap _hdPrimInfoMap;
655 
656     typedef std::multimap<SdfPath, SdfPath> _DependencyMap;
657 
658     // Map from USD path to Hydra path, for tracking USD->hydra dependencies.
659     _DependencyMap _dependencyInfo;
660 
661     void _GatherDependencies(SdfPath const& subtree,
662                              SdfPathVector *affectedCachePaths);
663 
664     // SdfPath::ReplacePrefix() is used frequently to convert between
665     // cache path and Hydra render index path and is a performance bottleneck.
666     // These maps pre-computes these conversion.
667     typedef TfHashMap<SdfPath, SdfPath, SdfPath::Hash> SdfPathMap;
668     SdfPathMap _cache2indexPath;
669     SdfPathMap _index2cachePath;
670 
671     // Only use this method when we think no existing adapter has been
672     // established. For example, during initial Population.
673     UsdImagingPrimAdapterSharedPtr const& _AdapterLookup(
674                                                 UsdPrim const& prim,
675                                                 bool ignoreInstancing = false);
676     UsdImagingPrimAdapterSharedPtr const& _AdapterLookup(
677                                                 TfToken const& adapterKey);
678 
679     // Obtain the prim tracking data for the given cache path.
680     _HdPrimInfo *_GetHdPrimInfo(const SdfPath &cachePath);
681 
682     Usd_PrimFlagsConjunction _GetDisplayPredicate() const;
683     Usd_PrimFlagsConjunction _GetDisplayPredicateForPrototypes() const;
684 
685     // Mark render tags dirty for all prims.
686     // This is done in response to toggling the purpose-based display settings.
687     void _MarkRenderTagsDirty();
688 
689     typedef TfHashSet<SdfPath, SdfPath::Hash> _DirtySet;
690 
691     // Set of cache paths that are due a Sync()
692     _DirtySet _dirtyCachePaths;
693 
694     /// Refinement level per-USD-prim and fallback.
695     typedef TfHashMap<SdfPath, int, SdfPath::Hash> _RefineLevelMap;
696     /// Map from USD prim path to refine level.
697     _RefineLevelMap _refineLevelMap;
698 
699     /// Cached/pre-fetched primvar descriptors.
700     UsdImagingPrimvarDescCache _primvarDescCache;
701 
702     /// Usd binding.
703     UsdStageRefPtr _stage;
704     SdfPath _rootPrimPath;
705     SdfPathVector _excludedPrimPaths;
706     SdfPathVector _invisedPrimPaths;
707 
708     RigidXformOverridesMap _rigidXformOverrides;
709 
710     // Aspects of the delegate root that apply to all items in the index.
711     SdfPath _compensationPath;
712 
713     GfMatrix4d _rootXf;
714     bool _rootIsVisible;
715 
716     /// The current time from which the delegate will read data.
717     UsdTimeCode _time;
718 
719     /// Path to the camera that its shutter will be used for time samples.
720     SdfPath _cameraPathForSampling;
721 
722     int _refineLevelFallback;
723     HdReprSelector _reprFallback;
724     HdCullStyle _cullStyleFallback;
725 
726     // Cache of which prims are time-varying.
727     SdfPathVector _timeVaryingPrimCache;
728     bool _timeVaryingPrimCacheValid;
729 
730     // Change processing
731     TfNotice::Key _objectsChangedNoticeKey;
732     SdfPathVector _usdPathsToResync;
733 
734     // Map from path of Usd object to update to list of changed scene
735     // description fields for that object. This list of fields is only
736     // populated for prim paths.
737     typedef std::unordered_map<SdfPath, TfTokenVector, SdfPath::Hash>
738         _PathsToUpdateMap;
739     _PathsToUpdateMap _usdPathsToUpdate;
740 
741     UsdImaging_XformCache _xformCache;
742     UsdImaging_MaterialBindingImplData _materialBindingImplData;
743     UsdImaging_MaterialBindingCache _materialBindingCache;
744     UsdImaging_CoordSysBindingImplData _coordSysBindingImplData;
745     UsdImaging_CoordSysBindingCache _coordSysBindingCache;
746     UsdImaging_VisCache _visCache;
747     UsdImaging_PurposeCache _purposeCache;
748     UsdImaging_DrawModeCache _drawModeCache;
749     UsdImaging_CollectionCache _collectionCache;
750     UsdImaging_InheritedPrimvarCache _inheritedPrimvarCache;
751     UsdImaging_PointInstancerIndicesCache _pointInstancerIndicesCache;
752 
753     // Pickability
754     PickabilityMap _pickablesMap;
755 
756     // Purpose-based rendering toggles
757     bool _displayRender;
758     bool _displayProxy;
759     bool _displayGuides;
760     bool _enableUsdDrawModes;
761 
762     const bool _hasDrawModeAdapter;
763 
764     /// Enable custom shading of prims
765     bool _sceneMaterialsEnabled;
766 
767     /// Enable lights found in the usdscene
768     bool _sceneLightsEnabled;
769 
770     CameraUtilConformWindowPolicy _appWindowPolicy;
771 
772     // Enable HdCoordSys tracking
773     const bool _coordSysEnabled;
774 
775     // Display unloaded prims with Bounds adapter
776     bool _displayUnloadedPrimsWithBounds;
777 
778     UsdImagingDelegate() = delete;
779     UsdImagingDelegate(UsdImagingDelegate const &) = delete;
780     UsdImagingDelegate &operator =(UsdImagingDelegate const &) = delete;
781 };
782 
783 PXR_NAMESPACE_CLOSE_SCOPE
784 
785 #endif //PXR_USD_IMAGING_USD_IMAGING_DELEGATE_H
786