-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
bboxCache.cpp
1526 lines (1322 loc) · 55.5 KB
/
bboxCache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2016 Pixar
//
// Licensed under the terms set forth in the LICENSE.txt file available at
// https://openusd.org/license.
//
#include "pxr/pxr.h"
#include "pxr/usd/usdGeom/bboxCache.h"
#include "pxr/usd/kind/registry.h"
#include "pxr/usd/usdGeom/boundable.h"
#include "pxr/usd/usdGeom/debugCodes.h"
#include "pxr/usd/usdGeom/modelAPI.h"
#include "pxr/usd/usdGeom/pointBased.h"
#include "pxr/usd/usdGeom/xform.h"
#include "pxr/usd/usd/modelAPI.h"
#include "pxr/usd/usd/primRange.h"
#include "pxr/base/trace/trace.h"
#include "pxr/base/work/withScopedParallelism.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/token.h"
#include <tbb/enumerable_thread_specific.h>
#include <algorithm>
#include <atomic>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
// For code that knows at compile time whether we need to apply a transform.
// Such code is told through a template parameter TransformType whether to
// apply a transform (TransformType = GfMatrix4d) or not (TransformType =
// _IdentityTransform).
class _IdentityTransform
{
};
// Overloads to transform GfBBox3d.
inline void
_Transform(GfBBox3d * const bbox, const _IdentityTransform &m)
{
}
inline void
_Transform(GfBBox3d * const bbox, const GfMatrix4d &m)
{
bbox->Transform(m);
}
}
// Thread-local Xform cache.
// This should be replaced with (TBD) multi-threaded XformCache::Prepopulate
typedef tbb::enumerable_thread_specific<UsdGeomXformCache> _ThreadXformCache;
// -------------------------------------------------------------------------- //
// _BBoxTask
// -------------------------------------------------------------------------- //
class UsdGeomBBoxCache::_BBoxTask {
UsdGeomBBoxCache::_PrimContext _primContext;
GfMatrix4d _inverseComponentCtm;
UsdGeomBBoxCache* _owner;
_ThreadXformCache* _xfCaches;
public:
_BBoxTask() : _owner(nullptr), _xfCaches(nullptr) {}
_BBoxTask(const _PrimContext& primContext,
const GfMatrix4d &inverseComponentCtm,
UsdGeomBBoxCache* owner, _ThreadXformCache* xfCaches)
: _primContext(primContext)
, _inverseComponentCtm(inverseComponentCtm)
, _owner(owner)
, _xfCaches(xfCaches)
{
}
explicit operator bool() const {
return _owner;
}
void operator()() const {
// Do not save state here; all state should be accumulated externally.
_owner->_ResolvePrim(const_cast<_BBoxTask const *>(this), _primContext, _inverseComponentCtm);
}
_ThreadXformCache* GetXformCaches() const { return _xfCaches; }
};
// -------------------------------------------------------------------------- //
// _PrototypeBBoxResolver
//
// If a prototype prim has instances nested within it, resolving its bbox
// will depend on the prototypes for those instances being resolved first.
// These dependencies form an acyclic graph where a given prototype may depend
// on and be a dependency for one or more prototypes.
//
// This helper object tracks those dependencies as tasks are dispatched
// and completed.
// -------------------------------------------------------------------------- //
class UsdGeomBBoxCache::_PrototypeBBoxResolver
{
private:
UsdGeomBBoxCache* _owner;
struct _PrototypeTask
{
_PrototypeTask()
: numDependencies(0) { }
_PrototypeTask(const _PrototypeTask &other)
: dependentPrototypes(other.dependentPrototypes)
{
numDependencies.store(other.numDependencies.load());
}
_PrototypeTask(_PrototypeTask &&other)
: dependentPrototypes(std::move(other.dependentPrototypes))
{
numDependencies.store(other.numDependencies.load());
}
// Number of dependencies -- prototype prims that must be resolved
// before this prototype can be resolved.
std::atomic<size_t> numDependencies;
// List of prototype prims that depend on this prototype.
std::vector<_PrimContext> dependentPrototypes;
};
typedef TfHashMap<_PrimContext, _PrototypeTask, _PrimContextHash>
_PrototypeTaskMap;
public:
_PrototypeBBoxResolver(UsdGeomBBoxCache* bboxCache)
: _owner(bboxCache)
{
}
void Resolve(const std::vector<_PrimContext> &prototypePrimContexts)
{
TRACE_FUNCTION();
_PrototypeTaskMap prototypeTasks;
for (const auto& prototypePrim : prototypePrimContexts) {
_PopulateTasksForPrototype(prototypePrim, &prototypeTasks);
}
// Using the owner's xform cache won't provide a benefit
// because the prototypes are separate parts of the scenegraph
// that won't be traversed when resolving other bounding boxes.
_ThreadXformCache xfCache;
for (const auto& t : prototypeTasks) {
if (t.second.numDependencies == 0) {
_owner->_dispatcher.Run(
&_PrototypeBBoxResolver::_ExecuteTaskForPrototype,
this, t.first, &prototypeTasks, &xfCache,
&_owner->_dispatcher);
}
}
_owner->_dispatcher.Wait();
}
private:
void _PopulateTasksForPrototype(const _PrimContext& prototypePrim,
_PrototypeTaskMap* prototypeTasks)
{
std::pair<_PrototypeTaskMap::iterator, bool> prototypeTaskStatus =
prototypeTasks->insert(std::make_pair(
prototypePrim, _PrototypeTask()));
if (!prototypeTaskStatus.second) {
return;
}
std::vector<_PrimContext> requiredPrototypes;
_owner->_FindOrCreateEntriesForPrim(prototypePrim, &requiredPrototypes);
{
// In order to resolve the bounding box for prototypePrim, we need
// to compute the bounding boxes for all prototypes for nested
// instances.
_PrototypeTask& prototypeTaskData =
prototypeTaskStatus.first->second;
prototypeTaskData.numDependencies = requiredPrototypes.size();
}
// Recursively populate the task map for the prototypes needed for
// nested instances.
for (const auto& reqPrototype : requiredPrototypes) {
_PopulateTasksForPrototype(reqPrototype, prototypeTasks);
(*prototypeTasks)[reqPrototype].dependentPrototypes.push_back(
prototypePrim);
}
}
void _ExecuteTaskForPrototype(const _PrimContext& prototype,
_PrototypeTaskMap* prototypeTasks,
_ThreadXformCache* xfCaches,
WorkDispatcher* dispatcher)
{
UsdGeomBBoxCache::_BBoxTask(
prototype, GfMatrix4d(1.0), _owner, xfCaches)();
// Update all of the prototype prims that depended on the completed
// prototype and dispatch new tasks for those whose dependencies have
// been resolved. We're guaranteed that all the entries were populated
// by _PopulateTasksForPrototype, so we don't check the result of
// 'find()'.
const _PrototypeTask& prototypeData =
prototypeTasks->find(prototype)->second;
for (const auto& dependentPrototype :
prototypeData.dependentPrototypes) {
_PrototypeTask& dependentPrototypeData =
prototypeTasks->find(dependentPrototype)->second;
if (dependentPrototypeData.numDependencies
.fetch_sub(1) == 1){
dispatcher->Run(
&_PrototypeBBoxResolver::_ExecuteTaskForPrototype,
this, dependentPrototype, prototypeTasks, xfCaches,
dispatcher);
}
}
}
};
// -------------------------------------------------------------------------- //
// Helper functions for managing query objects
// -------------------------------------------------------------------------- //
namespace
{
// Enumeration of queries stored for each cached entry that varies
// over time.
enum _Queries {
Extent = 0,
// Note: code in _ResolvePrim relies on ExtentsHint being last.
ExtentsHint,
NumQueries
};
}
#define DEFINE_QUERY_ACCESSOR(Name, Schema) \
static const UsdAttributeQuery& \
_GetOrCreate##Name##Query(const UsdPrim& prim, UsdAttributeQuery* q) \
{ \
if (!*q) { \
if (Schema s = Schema(prim)) { \
UsdAttribute attr = s.Get##Name##Attr(); \
if (TF_VERIFY(attr, "Unable to get attribute '%s' on prim " \
"at path <%s>", #Name, \
prim.GetPath().GetText())) { \
*q = UsdAttributeQuery(attr); \
} \
} \
} \
return *q; \
}
DEFINE_QUERY_ACCESSOR(Extent, UsdGeomBoundable);
DEFINE_QUERY_ACCESSOR(Visibility, UsdGeomImageable);
// ExtentsHint is a custom attribute so we need an additional check
// to see if the attribute exists.
static const UsdAttributeQuery&
_GetOrCreateExtentsHintQuery(UsdGeomModelAPI& geomModel, UsdAttributeQuery* q)
{
if (!*q) {
UsdAttribute extentsHintAttr = geomModel.GetExtentsHintAttr();
if (extentsHintAttr) {
*q = UsdAttributeQuery(extentsHintAttr);
}
}
return *q;
}
// -------------------------------------------------------------------------- //
// UsdGeomBBoxCache Public API
// -------------------------------------------------------------------------- //
UsdGeomBBoxCache::UsdGeomBBoxCache(
UsdTimeCode time, TfTokenVector includedPurposes,
bool useExtentsHint, bool ignoreVisibility)
: _time(time)
, _includedPurposes(includedPurposes)
, _ctmCache(time)
, _useExtentsHint(useExtentsHint)
, _ignoreVisibility(ignoreVisibility)
{
}
UsdGeomBBoxCache::UsdGeomBBoxCache(UsdGeomBBoxCache const &other)
: _time(other._time)
, _baseTime(other._baseTime)
, _includedPurposes(other._includedPurposes)
, _ctmCache(other._ctmCache)
, _bboxCache(other._bboxCache)
, _useExtentsHint(other._useExtentsHint)
, _ignoreVisibility(other._ignoreVisibility)
{
}
UsdGeomBBoxCache &
UsdGeomBBoxCache::operator=(UsdGeomBBoxCache const &other)
{
if (this == &other)
return *this;
_time = other._time;
_baseTime = other._baseTime;
_includedPurposes = other._includedPurposes;
_ctmCache = other._ctmCache;
_bboxCache = other._bboxCache;
_useExtentsHint = other._useExtentsHint;
_ignoreVisibility = other._ignoreVisibility;
return *this;
}
GfBBox3d
UsdGeomBBoxCache::ComputeWorldBound(const UsdPrim& prim)
{
GfBBox3d bbox;
if (!prim) {
TF_CODING_ERROR("Invalid prim: %s", UsdDescribe(prim).c_str());
return bbox;
}
_PurposeToBBoxMap bboxes;
if (!_Resolve(prim, &bboxes))
return bbox;
bbox = _GetCombinedBBoxForIncludedPurposes(bboxes);
GfMatrix4d ctm = _ctmCache.GetLocalToWorldTransform(prim);
bbox.Transform(ctm);
return bbox;
}
GfBBox3d
UsdGeomBBoxCache::ComputeRelativeBound(const UsdPrim& prim,
const UsdPrim &relativeToAncestorPrim)
{
GfBBox3d bbox;
if (!prim) {
TF_CODING_ERROR("Invalid prim: %s", UsdDescribe(prim).c_str());
return bbox;
}
_PurposeToBBoxMap bboxes;
if (!_Resolve(prim, &bboxes))
return bbox;
bbox = _GetCombinedBBoxForIncludedPurposes(bboxes);
GfMatrix4d primCtm = _ctmCache.GetLocalToWorldTransform(prim);
GfMatrix4d ancestorCtm =
_ctmCache.GetLocalToWorldTransform(relativeToAncestorPrim);
GfMatrix4d relativeCtm = primCtm * ancestorCtm.GetInverse();
bbox.Transform(relativeCtm);
return bbox;
}
GfBBox3d
UsdGeomBBoxCache::ComputeLocalBound(const UsdPrim& prim)
{
GfBBox3d bbox;
if (!prim) {
TF_CODING_ERROR("Invalid prim: %s", UsdDescribe(prim).c_str());
return bbox;
}
_PurposeToBBoxMap bboxes;
if (!_Resolve(prim, &bboxes))
return bbox;
bbox = _GetCombinedBBoxForIncludedPurposes(bboxes);
// The value of resetsXformStack does not affect the local bound.
bool resetsXformStack = false;
bbox.Transform(_ctmCache.GetLocalTransformation(prim, &resetsXformStack));
return bbox;
}
GfBBox3d
UsdGeomBBoxCache::ComputeUntransformedBound(const UsdPrim& prim)
{
GfBBox3d empty;
if (!prim) {
TF_CODING_ERROR("Invalid prim: %s", UsdDescribe(prim).c_str());
return empty;
}
_PurposeToBBoxMap bboxes;
if (!_Resolve(prim, &bboxes))
return empty;
return _GetCombinedBBoxForIncludedPurposes(bboxes);
}
template<typename TransformType>
GfBBox3d
UsdGeomBBoxCache::_ComputeBoundWithOverridesHelper(
const UsdPrim &prim,
const SdfPathSet &pathsToSkip,
const TransformType &primOverride,
const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides)
{
GfBBox3d empty;
if (!prim) {
TF_CODING_ERROR("Invalid prim: %s", UsdDescribe(prim).c_str());
return empty;
}
// Use a path table to populate a hash map containing all ancestors of the
// paths in pathsToSkip.
SdfPathTable<bool> ancestorsOfPathsToSkip;
for (const SdfPath &p : pathsToSkip) {
ancestorsOfPathsToSkip[p.GetParentPath()] = true;
}
// Use a path table to populate a hash map containing all ancestors of the
// paths in ctmOverrides.
SdfPathTable<bool> ancestorsOfOverrides;
for (const auto &override : ctmOverrides) {
ancestorsOfOverrides[override.first.GetParentPath()] = true;
}
GfBBox3d result;
UsdPrimRange range(prim);
for (auto it = range.begin(); it != range.end(); ++it) {
const UsdPrim &p = *it;
const SdfPath &primPath = p.GetPath();
// If this is one of the paths to be skipped, then prune subtree and
// continue traversal.
if (pathsToSkip.count(primPath)) {
it.PruneChildren();
continue;
}
// If this is an ancestor of a path that's skipped, then we must
// continue the traversal down to find prims whose bounds can be
// included.
if (ancestorsOfPathsToSkip.find(primPath) !=
ancestorsOfPathsToSkip.end()) {
continue;
}
// Check if any of the descendants of the prim have transform overrides.
// If yes, we need to continue the traversal down to find prims whose
// bounds can be included.
if (ancestorsOfOverrides.find(primPath) != ancestorsOfOverrides.end()) {
continue;
}
// Check to see if any of the ancestors of the prim or the prim itself
// has an xform override.
SdfPath pathWithOverride = primPath;
bool foundAncestorWithOverride = false;
TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash>::const_iterator
overrideIter;
while (pathWithOverride != prim.GetPath()) {
overrideIter = ctmOverrides.find(pathWithOverride);
if (overrideIter != ctmOverrides.end()) {
// We're only interested in the nearest override since we
// have the override CTMs in the given prim's space.
foundAncestorWithOverride = true;
break;
}
pathWithOverride = pathWithOverride.GetParentPath();
}
GfBBox3d bbox;
if (!foundAncestorWithOverride) {
bbox = ComputeRelativeBound(p, prim);
_Transform(&bbox, primOverride);
} else {
// Compute bound relative to the path for which we know the
// corrected prim-relative CTM.
bbox = ComputeRelativeBound(p,
prim.GetStage()->GetPrimAtPath(overrideIter->first));
// Apply the override CTM.
const GfMatrix4d &overrideXform = overrideIter->second;
bbox.Transform(overrideXform);
}
result = GfBBox3d::Combine(result, bbox);
it.PruneChildren();
}
return result;
}
GfBBox3d
UsdGeomBBoxCache::ComputeUntransformedBound(
const UsdPrim &prim,
const SdfPathSet &pathsToSkip,
const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides)
{
return _ComputeBoundWithOverridesHelper(
prim,
pathsToSkip,
_IdentityTransform(),
ctmOverrides);
}
GfBBox3d
UsdGeomBBoxCache::ComputeWorldBoundWithOverrides(
const UsdPrim &prim,
const SdfPathSet &pathsToSkip,
const GfMatrix4d &primOverride,
const TfHashMap<SdfPath, GfMatrix4d, SdfPath::Hash> &ctmOverrides)
{
return _ComputeBoundWithOverridesHelper(
prim,
pathsToSkip,
primOverride,
ctmOverrides);
}
bool
UsdGeomBBoxCache::_ComputePointInstanceBoundsHelper(
const UsdGeomPointInstancer &instancer,
int64_t const *instanceIdBegin,
size_t numIds,
GfMatrix4d const &xform,
GfBBox3d *result)
{
UsdTimeCode time = GetTime(), baseTime = GetBaseTime();
VtIntArray protoIndices;
if (!instancer.GetProtoIndicesAttr().Get(&protoIndices, time)) {
TF_WARN("%s -- no prototype indices",
instancer.GetPrim().GetPath().GetText());
return false;
}
VtIntArray const &cprotoIndices = protoIndices;
const UsdRelationship prototypes = instancer.GetPrototypesRel();
SdfPathVector protoPaths;
if (!prototypes.GetTargets(&protoPaths) || protoPaths.empty()) {
TF_WARN("%s -- no prototypes", instancer.GetPrim().GetPath().GetText());
return false;
}
// verify that all the protoIndices are in bounds.
for (auto protoIndex: cprotoIndices) {
if (protoIndex < 0 ||
static_cast<size_t>(protoIndex) >= protoPaths.size()) {
TF_WARN("%s -- invalid prototype index: %d. Should be in [0, %zu)",
instancer.GetPrim().GetPath().GetText(),
protoIndex,
protoPaths.size());
return false;
}
}
// Note that we do NOT apply any masking when computing the instance
// transforms. This is so that for a particular instance we can determine
// both its transform and its prototype. Otherwise, the instanceTransforms
// array would have masked instances culled out and we would lose the
// mapping to the prototypes.
// Masked instances will be culled before being applied to the extent below.
VtMatrix4dArray instanceTransforms;
if (!instancer.ComputeInstanceTransformsAtTime(
&instanceTransforms,
time,
baseTime,
UsdGeomPointInstancer::IncludeProtoXform,
UsdGeomPointInstancer::IgnoreMask)) {
TF_WARN("%s -- could not compute instance transforms",
instancer.GetPrim().GetPath().GetText());
return false;
}
VtMatrix4dArray const &cinstanceTransforms = instanceTransforms;
const UsdStagePtr stage = instancer.GetPrim().GetStage();
for (int64_t const *iid = instanceIdBegin, * const iend = iid + numIds;
iid != iend; ++iid) {
const int protoIndex = cprotoIndices[*iid];
const SdfPath& protoPath = protoPaths[protoIndex];
const UsdPrim& protoPrim = stage->GetPrimAtPath(protoPath);
// Get the prototype bounding box and apply the instance transform and
// the caller's transform.
GfBBox3d &thisBounds = *result++;
thisBounds = ComputeUntransformedBound(protoPrim);
thisBounds.Transform(cinstanceTransforms[*iid] * xform);
}
return true;
}
bool
UsdGeomBBoxCache::ComputePointInstanceWorldBounds(
UsdGeomPointInstancer const &instancer,
int64_t const *instanceIdBegin,
size_t numIds,
GfBBox3d *result)
{
return _ComputePointInstanceBoundsHelper(
instancer, instanceIdBegin, numIds,
_ctmCache.GetLocalToWorldTransform(instancer.GetPrim()), result);
}
bool
UsdGeomBBoxCache::ComputePointInstanceRelativeBounds(
const UsdGeomPointInstancer &instancer,
int64_t const *instanceIdBegin,
size_t numIds,
const UsdPrim &relativeToAncestorPrim,
GfBBox3d *result)
{
GfMatrix4d primCtm =
_ctmCache.GetLocalToWorldTransform(instancer.GetPrim());
GfMatrix4d ancestorCtm =
_ctmCache.GetLocalToWorldTransform(relativeToAncestorPrim);
GfMatrix4d relativeCtm = ancestorCtm.GetInverse() * primCtm;
return _ComputePointInstanceBoundsHelper(
instancer, instanceIdBegin, numIds, relativeCtm, result);
}
bool
UsdGeomBBoxCache::ComputePointInstanceLocalBounds(
const UsdGeomPointInstancer& instancer,
int64_t const *instanceIdBegin,
size_t numIds,
GfBBox3d *result)
{
// The value of resetsXformStack does not affect the local bound.
bool resetsXformStack = false;
return _ComputePointInstanceBoundsHelper(
instancer, instanceIdBegin, numIds,
_ctmCache.GetLocalTransformation(
instancer.GetPrim(), &resetsXformStack), result);
}
bool
UsdGeomBBoxCache::ComputePointInstanceUntransformedBounds(
const UsdGeomPointInstancer& instancer,
int64_t const *instanceIdBegin,
size_t numIds,
GfBBox3d *result)
{
return _ComputePointInstanceBoundsHelper(
instancer, instanceIdBegin, numIds, GfMatrix4d(1), result);
}
void
UsdGeomBBoxCache::Clear()
{
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] CLEARED\n");
_ctmCache.Clear();
_bboxCache.clear();
}
void
UsdGeomBBoxCache::SetIncludedPurposes(const TfTokenVector& includedPurposes)
{
_includedPurposes = includedPurposes;
}
GfBBox3d
UsdGeomBBoxCache::_GetCombinedBBoxForIncludedPurposes(
const _PurposeToBBoxMap &bboxes)
{
GfBBox3d combinedBound;
for (const TfToken &purpose : _includedPurposes) {
_PurposeToBBoxMap::const_iterator it = bboxes.find(purpose);
if (it != bboxes.end()) {
const GfBBox3d &bboxForPurpose = it->second;
if (!bboxForPurpose.GetRange().IsEmpty())
combinedBound = GfBBox3d::Combine(combinedBound,
bboxForPurpose);
}
}
return combinedBound;
}
void
UsdGeomBBoxCache::SetTime(UsdTimeCode time)
{
if (time == _time)
return;
// If we're switching time into or out of default, then clear all the
// entries in the cache.
//
// This is done because the _IsVarying() check (below) returns false for an
// attribute when
// * it has a default value,
// * it has a single time sample and
// * its default value is different from the varying time sample.
//
// This is an optimization that works well when playing through a shot and
// computing bboxes sequentially.
//
// It should not common to compute bboxes at the default frame. Hence,
// clearing all values here should not cause any performance issues.
//
bool clearUnvarying = false;
if (_time == UsdTimeCode::Default() || time == UsdTimeCode::Default())
clearUnvarying = true;
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] Setting time: %f "
" clearUnvarying: %s\n",
time.GetValue(),
clearUnvarying ? "true": "false");
for (auto &primAndEntry : _bboxCache) {
if (clearUnvarying || primAndEntry.second.isVarying) {
primAndEntry.second.isComplete = false;
// Clear cached bboxes.
primAndEntry.second.bboxes.clear();
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] invalidating %s "
"for time change\n",
primAndEntry.first.ToString().c_str());
}
}
_time = time;
_ctmCache.SetTime(_time);
}
// -------------------------------------------------------------------------- //
// UsdGeomBBoxCache Private API
// -------------------------------------------------------------------------- //
bool
UsdGeomBBoxCache::_ShouldIncludePrim(const UsdPrim& prim)
{
TRACE_FUNCTION();
// If the prim is typeless or has an unknown type, it may have descendants
// that are imageable. Hence, we include it in bbox computations.
if (!prim.IsA<UsdTyped>()) {
return true;
}
// If the prim is typed it can participate in child bound accumulation only
// if it is imageable.
if (!prim.IsA<UsdGeomImageable>()) {
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] excluded, not IMAGEABLE type. "
"prim: %s, primType: %s\n",
prim.GetPath().GetText(),
prim.GetTypeName().GetText());
return false;
}
if (!_ignoreVisibility) {
UsdGeomImageable img(prim);
TfToken vis;
if (img.GetVisibilityAttr().Get(&vis, _time)
&& vis == UsdGeomTokens->invisible) {
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] excluded for VISIBILITY. "
"prim: %s visibility at time %s: %s\n",
prim.GetPath().GetText(),
TfStringify(_time).c_str(),
vis.GetText());
return false;
}
}
return true;
}
template <class AttributeOrQuery>
static bool
_IsVaryingImpl(const UsdTimeCode time, const AttributeOrQuery& attr)
{
// XXX: Copied from UsdImagingDelegate::_TrackVariability.
// XXX: This logic is highly sensitive to the underlying quantization of
// time. Also, the epsilon value (.000001) may become zero for large
// time values.
double lower, upper, queryTime;
bool hasSamples;
queryTime = time.IsDefault() ? 1.000001 : time.GetValue() + 0.000001;
// TODO: migrate this logic into UsdAttribute.
if (attr.GetBracketingTimeSamples(queryTime, &lower, &upper, &hasSamples)
&& hasSamples)
{
// The potential results are:
// * Requested time was between two time samples
// * Requested time was out of the range of time samples (lesser)
// * Requested time was out of the range of time samples (greater)
// * There was a time sample exactly at the requested time or
// there was exactly one time sample.
// The following logic determines which of these states we are in.
// Between samples?
if (lower != upper) {
return true;
}
// Out of range (lower) or exactly on a time sample?
attr.GetBracketingTimeSamples(lower+.000001,
&lower, &upper, &hasSamples);
if (lower != upper) {
return true;
}
// Out of range (greater)?
attr.GetBracketingTimeSamples(lower-.000001,
&lower, &upper, &hasSamples);
if (lower != upper) {
return true;
}
// Really only one time sample --> not varying for our purposes
}
return false;
}
bool
UsdGeomBBoxCache::_IsVarying(const UsdAttribute& attr)
{
return _IsVaryingImpl(_time, attr);
}
bool
UsdGeomBBoxCache::_IsVarying(const UsdAttributeQuery& query)
{
return _IsVaryingImpl(_time, query);
}
// Returns true if the given prim is a component or a subcomponent.
static
bool
_IsComponentOrSubComponent(const UsdPrim &prim)
{
UsdModelAPI model(prim);
TfToken kind;
if (!model.GetKind(&kind))
return false;
return KindRegistry::IsA(kind, KindTokens->component) ||
KindRegistry::IsA(kind, KindTokens->subcomponent);
}
// Returns the nearest ancestor prim that's a component or a subcomponent, or
// the stage's pseudoRoot if none are found. For the purpose of computing
// bounding boxes, subcomponents as treated similar to components, i.e. child
// bounds are accumulated in subcomponent-space for prims that are underneath
// a subcomponent.
//
static
UsdPrim
_GetNearestComponent(const UsdPrim &prim)
{
UsdPrim modelPrim = prim;
while (modelPrim) {
if (_IsComponentOrSubComponent(modelPrim))
return modelPrim;
modelPrim = modelPrim.GetParent();
}
// If we get here, it means we did not find a model or a subcomponent at or
// above the given prim. Hence, return the stage's pseudoRoot.
return prim.GetStage()->GetPseudoRoot();
}
template <bool IsRecursive>
void
UsdGeomBBoxCache::_ComputePurposeInfo(
_Entry *entry, const _PrimContext &primContext)
{
if (entry->purposeInfo) {
return;
}
const UsdPrim &prim = primContext.prim;
// Special case for prototype prims. Prototypes don't actually have their
// own purpose attribute. The prims that instance the prototype will provide
// its purpose. It's important that we apply the instancing prim's purpose
// to this prototype prim context so that the prototype's children can
// properly inherit the instancing prim's purpose if needed. Note that this
// only applies if the instancing prim provides a purpose that is
// inheritable.
if (prim.IsPrototype()) {
if (primContext.instanceInheritablePurpose.IsEmpty()) {
// If the instancing prim's purpose is not inheritable, this
// prototype prim context won't provide an inheritable purpose to
// its children either.
entry->purposeInfo = UsdGeomImageable::PurposeInfo(
UsdGeomTokens->default_, false);
} else {
// Otherwise this prototype can provide the instancing prim's
// inheritable pupose to its children.
entry->purposeInfo = UsdGeomImageable::PurposeInfo(
primContext.instanceInheritablePurpose, true);
}
} else {
UsdGeomImageable img(prim);
UsdPrim parentPrim = prim.GetParent();
if (parentPrim && parentPrim.GetPath() != SdfPath::AbsoluteRootPath()) {
// Try and get the parent prim's purpose first. If we find it in the
// cache, we can compute this prim's purpose efficiently by avoiding
// the n^2 recursion which results from using the
// UsdGeomImageable::ComputePurpose() API directly.
// If this prim is in a prototype then its parent prim will be too.
// The parent prim's context will have the same inheritable purpose
// from the instance as this prim context does.
_PrimContext parentPrimContext(
parentPrim, primContext.instanceInheritablePurpose);
_Entry *parentEntry = _FindEntry(parentPrimContext);
if (parentEntry) {
if (IsRecursive) {
// If this is recursive make sure the parent's purpose is
// computed and cached first.
_ComputePurposeInfo<IsRecursive>(
parentEntry, parentPrimContext);
entry->purposeInfo = img.ComputePurposeInfo(
parentEntry->purposeInfo);
return;
} else {
// Not recursive. just check that the parent purpose has
// been computed.
if (parentEntry->purposeInfo) {
entry->purposeInfo = img.ComputePurposeInfo(
parentEntry->purposeInfo);
return;
}
TF_DEBUG(USDGEOM_BBOX).Msg(
"[BBox Cache] Computing purpose for <%s> before purpose"
"of parent <%s> is cached\n",
primContext.ToString().c_str(),
parentPrimContext.ToString().c_str());
}
}
}
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] Computing purpose without "
"cached parent for <%s>\n",
primContext.ToString().c_str());
entry->purposeInfo = img.ComputePurposeInfo();
}
}
// Helper to determine if we should use extents hints for \p prim.
bool UsdGeomBBoxCache::
_UseExtentsHintForPrim(UsdPrim const &prim) const
{
return _useExtentsHint && prim.IsModel() &&
prim.GetPath() != SdfPath::AbsoluteRootPath();
}
bool
UsdGeomBBoxCache::_ShouldPruneChildren(const UsdPrim &prim,
UsdGeomBBoxCache::_Entry *entry)
{
// If the entry is already complete, we don't need to try to initialize it.
if (entry->isComplete) {
return true;
}
// Check if prim is a UsdGeomBoundable. Boundables should always provide
// their own extent and do not require participation from descendants.
if (prim.IsA<UsdGeomBoundable>()) {
return true;
}
if (!_UseExtentsHintForPrim(prim)) {
return false;
}
UsdAttribute extentsHintAttr = UsdGeomModelAPI(prim).GetExtentsHintAttr();
VtVec3fArray extentsHint;
return (extentsHintAttr
&& extentsHintAttr.Get(&extentsHint, _time)
&& extentsHint.size() >= 2);
}
UsdGeomBBoxCache::_Entry*
UsdGeomBBoxCache::_FindOrCreateEntriesForPrim(
const _PrimContext& primContext,
std::vector<_PrimContext> *prototypePrimContexts)
{
// Add an entry for the prim to the cache and if the bound is already in
// the cache, return it.
//
// Note that this means we always have an entry for the given prim,
// even if that prim does not pass the predicate given to the tree
// iterator below (e.g., the prim is a class).