bboxCache.h
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_GEOM_BBOX_CACHE_H
25 #define PXR_USD_USD_GEOM_BBOX_CACHE_H
26 
27 #include "pxr/pxr.h"
28 #include "pxr/usd/usdGeom/api.h"
29 #include "pxr/usd/usdGeom/xformCache.h"
31 #include "pxr/usd/usd/attributeQuery.h"
32 #include "pxr/base/gf/bbox3d.h"
33 #include "pxr/base/tf/hash.h"
34 #include "pxr/base/tf/hashmap.h"
36 
37 #include <boost/optional.hpp>
38 #include <boost/shared_array.hpp>
39 
40 PXR_NAMESPACE_OPEN_SCOPE
41 
42 
43 class UsdGeomModelAPI;
44 
89 {
90 public:
108  USDGEOM_API
109  UsdGeomBBoxCache(UsdTimeCode time, TfTokenVector includedPurposes,
110  bool useExtentsHint=false, bool ignoreVisibility=false);
111 
113  USDGEOM_API
114  UsdGeomBBoxCache(UsdGeomBBoxCache const &other);
115 
117  USDGEOM_API
119 
129  USDGEOM_API
130  GfBBox3d ComputeWorldBound(const UsdPrim& prim);
131 
143  USDGEOM_API
145  const UsdPrim &prim,
146  const SdfPathSet &pathsToSkip,
147  const GfMatrix4d &primOverride,
148  const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides);
149 
150 
158  USDGEOM_API
160  const UsdPrim &relativeToAncestorPrim);
161 
170  USDGEOM_API
171  GfBBox3d ComputeLocalBound(const UsdPrim& prim);
172 
183  USDGEOM_API
185 
202  USDGEOM_API
204  const UsdPrim &prim,
205  const SdfPathSet &pathsToSkip,
206  const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides);
207 
213  USDGEOM_API
214  bool
216  const UsdGeomPointInstancer& instancer,
217  int64_t const *instanceIdBegin,
218  size_t numIds,
219  GfBBox3d *result);
220 
223  GfBBox3d
225  const UsdGeomPointInstancer& instancer, int64_t instanceId) {
226  GfBBox3d ret;
227  ComputePointInstanceWorldBounds(instancer, &instanceId, 1, &ret);
228  return ret;
229  }
230 
241  USDGEOM_API
242  bool
244  const UsdGeomPointInstancer &instancer,
245  int64_t const *instanceIdBegin,
246  size_t numIds,
247  const UsdPrim &relativeToAncestorPrim,
248  GfBBox3d *result);
249 
252  GfBBox3d
254  const UsdGeomPointInstancer &instancer,
255  int64_t instanceId,
256  const UsdPrim &relativeToAncestorPrim) {
257  GfBBox3d ret;
259  instancer, &instanceId, 1, relativeToAncestorPrim, &ret);
260  return ret;
261  }
262 
271  USDGEOM_API
272  bool
274  const UsdGeomPointInstancer& instancer,
275  int64_t const *instanceIdBegin,
276  size_t numIds,
277  GfBBox3d *result);
278 
280  GfBBox3d
282  const UsdGeomPointInstancer& instancer,
283  int64_t instanceId) {
284  GfBBox3d ret;
285  ComputePointInstanceLocalBounds(instancer, &instanceId, 1, &ret);
286  return ret;
287  }
288 
289 
300  USDGEOM_API
301  bool
303  const UsdGeomPointInstancer& instancer,
304  int64_t const *instanceIdBegin,
305  size_t numIds,
306  GfBBox3d *result);
307 
310  GfBBox3d
312  const UsdGeomPointInstancer& instancer,
313  int64_t instanceId) {
314  GfBBox3d ret;
316  instancer, &instanceId, 1, &ret);
317  return ret;
318  }
319 
321  USDGEOM_API
322  void Clear();
323 
332  USDGEOM_API
333  void SetIncludedPurposes(const TfTokenVector& includedPurposes);
334 
336  const TfTokenVector& GetIncludedPurposes() { return _includedPurposes; }
337 
340  bool GetUseExtentsHint() const {
341  return _useExtentsHint;
342  }
343 
346  bool GetIgnoreVisibility() const {
347  return _ignoreVisibility;
348  }
349 
353  USDGEOM_API
354  void SetTime(UsdTimeCode time);
355 
357  UsdTimeCode GetTime() const { return _time; }
358 
367  void SetBaseTime(UsdTimeCode baseTime) {
368  _baseTime = baseTime;
369  }
370 
374  return _baseTime.get_value_or(GetTime());
375  }
376 
379  void ClearBaseTime() {
380  _baseTime = boost::none;
381  }
382 
385  bool HasBaseTime() const {
386  return static_cast<bool>(_baseTime);
387  }
388 
389 private:
390  // Worker task.
391  class _BBoxTask;
392 
393  // Helper object for computing bounding boxes for instance prototypes.
394  class _PrototypeBBoxResolver;
395 
396  // Map of purpose tokens to associated bboxes.
397  typedef std::map<TfToken, GfBBox3d, TfTokenFastArbitraryLessThan>
398  _PurposeToBBoxMap;
399 
400  // Each individual prim will have it's own entry in the bbox cache. When
401  // instancing is involved we store the prototype prims and their children in
402  // the cache for use by each prim that instances each prototype. However,
403  // because of the way we compute and inherit purpose, we may end up needed
404  // to compute multitple different bboxes for prototypes and their children
405  // if the prims that instance them would cause these prototypes to inherit a
406  // different purpose value when the prims under the prototype don't have an
407  // authored purpose of their own.
408  //
409  // This struct is here to represent a prim and the purpose that it would
410  // inherit from the prim that instances it. It is used as the key for the
411  // map of prim's to the cached entries, allowing prims in prototypes to have
412  // more than one bbox cache entry for each distinct context needed to
413  // appropriately compute for all instances. instanceInheritablePurpose will
414  // always be empty for prims that aren't prototypes or children of
415  // prototypes, meaning that prims not in prototypes will only have one
416  // context each.
417  struct _PrimContext {
418  // The prim itself
419  UsdPrim prim;
420 
421  // The purpose that would be inherited from the instancing prim if this
422  // prim does not have an explicit purpose.
423  TfToken instanceInheritablePurpose;
424 
425  _PrimContext() = default;
426  explicit _PrimContext(const UsdPrim &prim_,
427  const TfToken &purpose = TfToken())
428  : prim(prim_), instanceInheritablePurpose(purpose) {};
429 
430  bool operator==(const _PrimContext &rhs) const {
431  return prim == rhs.prim &&
432  instanceInheritablePurpose == rhs.instanceInheritablePurpose;
433  }
434 
435  // Convenience stringify for debugging.
436  std::string ToString() const;
437  };
438 
439  template<typename TransformType>
440  GfBBox3d _ComputeBoundWithOverridesHelper(
441  const UsdPrim &prim,
442  const SdfPathSet &pathsToSkip,
443  const TransformType &primOverride,
444  const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides);
445 
446  bool
447  _ComputePointInstanceBoundsHelper(
448  const UsdGeomPointInstancer &instancer,
449  int64_t const *instanceIdBegin,
450  size_t numIds,
451  GfMatrix4d const &xform,
452  GfBBox3d *result);
453 
454  // Returns true if the \p prim should be included during child bounds
455  // accumulation.
456  bool _ShouldIncludePrim(const UsdPrim& prim);
457 
458  // True if \p attr or \p query may return different values given different
459  // time queries. Note that a true result implies the attribute may have no
460  // value, a default value or a single time sample value.
461  bool _IsVarying(const UsdAttribute& attr);
462  bool _IsVarying(const UsdAttributeQuery& query);
463 
464  // Populate the local bbox for the requested prim, without the
465  // local-to-world transform or local transform applied. Return true when
466  // bbox volume > 0.
467  bool _Resolve(const UsdPrim& prim, _PurposeToBBoxMap *bboxes);
468 
469  // Resolves a single prim. This method must be thread safe. Assumes the
470  // cache entry has been created for \p prim.
471  //
472  // \p inverseComponentCtm is used to combine all the child bboxes in
473  // component-relative space.
474  void _ResolvePrim(_BBoxTask* task,
475  const _PrimContext& prim,
476  const GfMatrix4d &inverseComponentCtm);
477 
478  struct _Entry {
479  _Entry()
480  : isComplete(false)
481  , isVarying(false)
482  , isIncluded(false)
483  { }
484 
485  // The cached bboxes for the various values of purpose token.
486  _PurposeToBBoxMap bboxes;
487 
488  // Queries for attributes that need to be re-computed at each
489  // time for this entry. This will be invalid for non-varying entries.
490  boost::shared_array<UsdAttributeQuery> queries;
491 
492  // Computed purpose info of the prim that's associated with the entry.
493  // This data includes the prim's actual computed purpose as well as
494  // whether this purpose is inheritable by child prims.
495  UsdGeomImageable::PurposeInfo purposeInfo;
496 
497  // True when data in the entry is valid.
498  bool isComplete;
499 
500  // True when the entry varies over time.
501  bool isVarying;
502 
503  // True when the entry is visible.
504  bool isIncluded;
505  };
506 
507  // Returns the cache entry for the given \p prim if one already exists.
508  // If no entry exists, creates (but does not resolve) entries for
509  // \p prim and all of its descendents. In this case, the prototype prims
510  // whose bounding boxes need to be resolved in order to resolve \p prim
511  // will be returned in \p prototypePrimContexts.
512  _Entry* _FindOrCreateEntriesForPrim(
513  const _PrimContext& prim,
514  std::vector<_PrimContext> *prototypePrimContexts);
515 
516  // Returns the combined bounding box for the currently included set of
517  // purposes given a _PurposeToBBoxMap.
518  GfBBox3d _GetCombinedBBoxForIncludedPurposes(
519  const _PurposeToBBoxMap &bboxes);
520 
521  // Populates \p bbox with the bounding box computed from the authored
522  // extents hint. Based on the included purposes, the extents in the
523  // extentsHint attribute are combined together to compute the bounding box.
524  bool _GetBBoxFromExtentsHint(
525  const UsdGeomModelAPI &geomModel,
526  const UsdAttributeQuery &extentsHintQuery,
527  _PurposeToBBoxMap *bboxes);
528 
529  // Returns whether the children of the given prim can be pruned
530  // from the traversal to pre-populate entries.
531  bool _ShouldPruneChildren(const UsdPrim &prim, _Entry *entry);
532 
533  // Helper function for computing a prim's purpose info efficiently by
534  // using the parent entry's cached computed purpose info and caching it
535  // its cache entry.
536  // Optionally this can recursively compute and cache the purposes for any
537  // existing parent entries in the cache that haven't had their purposes
538  // computed yet.
539  template <bool IsRecursive>
540  void _ComputePurposeInfo(_Entry *entry, const _PrimContext &prim);
541 
542  // Helper to determine if we should use extents hints for \p prim.
543  inline bool _UseExtentsHintForPrim(UsdPrim const &prim) const;
544 
545  // Specialize TfHashAppend for TfHash
546  template <typename HashState>
547  friend void TfHashAppend(HashState& h, const _PrimContext &key)
548  {
549  h.Append(key.prim);
550  h.Append(key.instanceInheritablePurpose);
551  }
552 
553  // Need hash_value for boost to key cache entries by prim context.
554  friend size_t hash_value(const _PrimContext &key) { return TfHash{}(key); }
555 
556  typedef TfHash _PrimContextHash;
557  typedef TfHashMap<_PrimContext, _Entry, _PrimContextHash> _PrimBBoxHashMap;
558 
559  // Finds the cache entry for the prim context if it exists.
560  _Entry *_FindEntry(const _PrimContext &primContext)
561  {
562  return TfMapLookupPtr(_bboxCache, primContext);
563  }
564 
565  // Returns the cache entry for the prim context, adding it if doesn't
566  // exist.
567  _Entry *_InsertEntry(const _PrimContext &primContext)
568  {
569  return &(_bboxCache[primContext]);
570  }
571 
572  WorkDispatcher _dispatcher;
573  UsdTimeCode _time;
574  boost::optional<UsdTimeCode> _baseTime;
575  TfTokenVector _includedPurposes;
576  UsdGeomXformCache _ctmCache;
577  _PrimBBoxHashMap _bboxCache;
578  bool _useExtentsHint;
579  bool _ignoreVisibility;
580 };
581 
582 
583 PXR_NAMESPACE_CLOSE_SCOPE
584 
585 #endif // PXR_USD_USD_GEOM_BBOX_CACHE_H
USDGEOM_API UsdGeomBBoxCache & operator=(UsdGeomBBoxCache const &other)
Copy assignment.
bool GetIgnoreVisibility() const
Returns whether prim visibility should be ignored when computing bounding boxes.
Definition: bboxCache.h:346
UsdGeomModelAPI extends the generic UsdModelAPI schema with geometry specific concepts such as cached...
Definition: modelAPI.h:148
A work dispatcher runs concurrent tasks.
Definition: dispatcher.h:75
USDGEOM_API bool ComputePointInstanceLocalBounds(const UsdGeomPointInstancer &instancer, int64_t const *instanceIdBegin, size_t numIds, GfBBox3d *result)
Compute the oriented bounding boxes of the given point instances.
Object for efficiently making repeated queries for attribute values.
const TfTokenVector & GetIncludedPurposes()
Get the current set of included purposes.
Definition: bboxCache.h:336
bool GetUseExtentsHint() const
Returns whether authored extent hints are used to compute bounding boxes.
Definition: bboxCache.h:340
void ClearBaseTime()
Clear this cache's baseTime if one has been set.
Definition: bboxCache.h:379
Caches bounds by recursively computing and aggregating bounds of children in world space and aggregat...
Definition: bboxCache.h:88
Scenegraph object for authoring and retrieving numeric, string, and array valued data,...
Definition: attribute.h:176
UsdTimeCode GetBaseTime() const
Return the base time if set, otherwise GetTime().
Definition: bboxCache.h:373
USDGEOM_API void Clear()
Clears all pre-cached values.
A user-extensible hashing mechanism for use with runtime hash tables.
Definition: hash.h:504
GfBBox3d ComputePointInstanceRelativeBound(const UsdGeomPointInstancer &instancer, int64_t instanceId, const UsdPrim &relativeToAncestorPrim)
Compute the bound of the given point instance in the space of an ancestor prim relativeToAncestorPrim...
Definition: bboxCache.h:253
USDGEOM_API GfBBox3d ComputeWorldBoundWithOverrides(const UsdPrim &prim, const SdfPathSet &pathsToSkip, const GfMatrix4d &primOverride, const TfHashMap< SdfPath, GfMatrix4d, SdfPath::Hash > &ctmOverrides)
Computes the bound of the prim's descendents in world space while excluding the subtrees rooted at th...
Token for efficient comparison, assignment, and hashing of known strings.
Definition: token.h:87
void SetBaseTime(UsdTimeCode baseTime)
Set the base time value for this bbox cache.
Definition: bboxCache.h:367
Stores a 4x4 matrix of double elements.
Definition: matrix4d.h:87
Represent a time value, which may be either numeric, holding a double value, or a sentinel value UsdT...
Definition: timeCode.h:84
USDGEOM_API bool ComputePointInstanceUntransformedBounds(const UsdGeomPointInstancer &instancer, int64_t const *instanceIdBegin, size_t numIds, GfBBox3d *result)
Computes the bound of the given point instances, but does not include the transform (if any) authored...
Value type containing information about a prim's computed effective purpose as well as storing whethe...
Definition: imageable.h:400
UsdPrim is the sole persistent scenegraph object on a UsdStage, and is the embodiment of a "Prim" as ...
Definition: prim.h:135
USDGEOM_API GfBBox3d ComputeWorldBound(const UsdPrim &prim)
Compute the bound of the given prim in world space, leveraging any pre-existing, cached bounds.
std::vector< TfToken > TfTokenVector
Convenience types.
Definition: token.h:442
USDGEOM_API bool ComputePointInstanceWorldBounds(const UsdGeomPointInstancer &instancer, int64_t const *instanceIdBegin, size_t numIds, GfBBox3d *result)
Compute the bound of the given point instances in world space.
GfBBox3d ComputePointInstanceUntransformedBound(const UsdGeomPointInstancer &instancer, int64_t instanceId)
Computes the bound of the given point instances, but does not include the instancer's transform.
Definition: bboxCache.h:311
UsdTimeCode GetTime() const
Get the current time from which this cache is reading values.
Definition: bboxCache.h:357
USDGEOM_API GfBBox3d ComputeRelativeBound(const UsdPrim &prim, const UsdPrim &relativeToAncestorPrim)
Compute the bound of the given prim in the space of an ancestor prim, relativeToAncestorPrim,...
Container::mapped_type * TfMapLookupPtr(Container &map, Key const &key)
Checks if an item exists in a map or TfHashMap, without copying it.
Definition: stl.h:141
USDGEOM_API bool ComputePointInstanceRelativeBounds(const UsdGeomPointInstancer &instancer, int64_t const *instanceIdBegin, size_t numIds, const UsdPrim &relativeToAncestorPrim, GfBBox3d *result)
Compute the bounds of the given point instances in the space of an ancestor prim relativeToAncestorPr...
USDGEOM_API GfBBox3d ComputeLocalBound(const UsdPrim &prim)
Computes the oriented bounding box of the given prim, leveraging any pre-existing,...
USDGEOM_API UsdGeomBBoxCache(UsdTimeCode time, TfTokenVector includedPurposes, bool useExtentsHint=false, bool ignoreVisibility=false)
Construct a new BBoxCache for a specific time and set of includedPurposes.
GfBBox3d ComputePointInstanceLocalBound(const UsdGeomPointInstancer &instancer, int64_t instanceId)
Compute the oriented bounding boxes of the given point instances.
Definition: bboxCache.h:281
GfBBox3d ComputePointInstanceWorldBound(const UsdGeomPointInstancer &instancer, int64_t instanceId)
Compute the bound of the given point instance in world space.
Definition: bboxCache.h:224
Encodes vectorized instancing of multiple, potentially animated, prototypes (object/instance masters)...
VT_API bool operator==(VtDictionary const &, VtDictionary const &)
Equality comparison.
USDGEOM_API void SetTime(UsdTimeCode time)
Use the new time when computing values and may clear any existing values cached for the previous time...
USDGEOM_API GfBBox3d ComputeUntransformedBound(const UsdPrim &prim)
Computes the bound of the prim's children leveraging any pre-existing, cached bounds,...
USDGEOM_API void SetIncludedPurposes(const TfTokenVector &includedPurposes)
Indicate the set of includedPurposes to use when resolving child bounds.
Basic type: arbitrarily oriented 3D bounding box.
Definition: bbox3d.h:84
A caching mechanism for transform matrices.
Definition: xformCache.h:57
bool HasBaseTime() const
Return true if this cache has a baseTime that's been explicitly set, false otherwise.
Definition: bboxCache.h:385