forked from dreamworksanimation/USD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbboxCache.cpp
1412 lines (1208 loc) · 49.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 Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache 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/tf/pyLock.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/token.h"
#include <tbb/enumerable_thread_specific.h>
#include <algorithm>
PXR_NAMESPACE_OPEN_SCOPE
// 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 {
UsdPrim _prim;
GfMatrix4d _inverseComponentCtm;
UsdGeomBBoxCache* _owner;
_ThreadXformCache* _xfCaches;
public:
_BBoxTask() : _owner(nullptr), _xfCaches(nullptr) {}
_BBoxTask(const UsdPrim& prim, const GfMatrix4d &inverseComponentCtm,
UsdGeomBBoxCache* owner, _ThreadXformCache* xfCaches)
: _prim(prim)
, _inverseComponentCtm(inverseComponentCtm)
, _owner(owner)
, _xfCaches(xfCaches)
{
}
explicit operator bool() const {
return _owner;
}
void operator()() {
// Do not save state here; all state should be accumulated externally.
_owner->_ResolvePrim(this, _prim, _inverseComponentCtm);
}
_ThreadXformCache* GetXformCaches() { return _xfCaches; }
};
// -------------------------------------------------------------------------- //
// _MasterBBoxResolver
//
// If a master prim has instances nested within it, resolving its bbox
// will depend on the masters for those instances being resolved first.
// These dependencies form an acyclic graph where a given master may depend
// on and be a dependency for one or more masters.
//
// This helper object tracks those dependencies as tasks are dispatched
// and completed.
// -------------------------------------------------------------------------- //
class UsdGeomBBoxCache::_MasterBBoxResolver
{
private:
UsdGeomBBoxCache* _owner;
struct _MasterTask
{
_MasterTask() : numDependencies(0) { }
// Number of dependencies -- master prims that must be resolved
// before this master can be resolved.
tbb::atomic<size_t> numDependencies;
// List of master prims that depend on this master.
std::vector<UsdPrim> dependentMasters;
};
typedef TfHashMap<UsdPrim, _MasterTask, boost::hash<UsdPrim> >
_MasterTaskMap;
public:
_MasterBBoxResolver(UsdGeomBBoxCache* bboxCache)
: _owner(bboxCache)
{
}
void Resolve(const std::vector<UsdPrim>& masterPrims)
{
TRACE_FUNCTION();
_MasterTaskMap masterTasks;
for (const auto& masterPrim : masterPrims) {
_PopulateTasksForMaster(masterPrim, &masterTasks);
}
// Using the owner's xform cache won't provide a benefit
// because the masters are separate parts of the scenegraph
// that won't be traversed when resolving other bounding boxes.
_ThreadXformCache xfCache;
for (const auto& t : masterTasks) {
if (t.second.numDependencies == 0) {
_owner->_dispatcher.Run(
&_MasterBBoxResolver::_ExecuteTaskForMaster,
this, t.first, &masterTasks, &xfCache, &_owner->_dispatcher);
}
}
_owner->_dispatcher.Wait();
}
private:
void _PopulateTasksForMaster(const UsdPrim& masterPrim,
_MasterTaskMap* masterTasks)
{
std::pair<_MasterTaskMap::iterator, bool> masterTaskStatus =
masterTasks->insert(std::make_pair(masterPrim, _MasterTask()));
if (!masterTaskStatus.second) {
return;
}
std::vector<UsdPrim> requiredMasters;
_owner->_FindOrCreateEntriesForPrim(masterPrim, &requiredMasters);
{
// In order to resolve the bounding box for masterPrim, we need to
// compute the bounding boxes for all masters for nested instances.
_MasterTask& masterTaskData = masterTaskStatus.first->second;
masterTaskData.numDependencies = requiredMasters.size();
}
// Recursively populate the task map for the masters needed for
// nested instances.
for (const auto& reqMaster : requiredMasters) {
_PopulateTasksForMaster(reqMaster, masterTasks);
(*masterTasks)[reqMaster].dependentMasters.push_back(masterPrim);
}
}
void _ExecuteTaskForMaster(const UsdPrim& master,
_MasterTaskMap* masterTasks,
_ThreadXformCache* xfCaches,
WorkArenaDispatcher* dispatcher)
{
UsdGeomBBoxCache::_BBoxTask(
master, GfMatrix4d(1.0), _owner, xfCaches)();
// Update all of the master prims that depended on the completed master
// and dispatch new tasks for those whose dependencies have been
// resolved. We're guaranteed that all the entries were populated by
// _PopulateTasksForMaster, so we don't check the result of 'find()'.
const _MasterTask& masterData = masterTasks->find(master)->second;
for (const auto& dependentMaster : masterData.dependentMasters) {
_MasterTask& dependentMasterData =
masterTasks->find(dependentMaster)->second;
if (dependentMasterData.numDependencies.fetch_and_decrement() == 1){
dispatcher->Run(
&_MasterBBoxResolver::_ExecuteTaskForMaster,
this, dependentMaster, masterTasks, 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)
: _time(time)
, _includedPurposes(includedPurposes)
, _ctmCache(time)
, _useExtentsHint(useExtentsHint)
{
}
UsdGeomBBoxCache::UsdGeomBBoxCache(UsdGeomBBoxCache const &other)
: _time(other._time)
, _baseTime(other._baseTime)
, _includedPurposes(other._includedPurposes)
, _ctmCache(other._ctmCache)
, _bboxCache(other._bboxCache)
, _useExtentsHint(other._useExtentsHint)
{
}
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;
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 = ancestorCtm.GetInverse() * primCtm;
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);
}
GfBBox3d
UsdGeomBBoxCache::ComputeUntransformedBound(
const UsdPrim &prim,
const SdfPathSet &pathsToSkip,
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 travesal 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 travesal 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);
} else {
// Compute bound relative to the path for which we know the
// corrected prim-relative CTM.
bbox = ComputeRelativeBound(p,
prim.GetStage()->GetPrimAtPath(overrideIter->first));
// The override CTM is already relative to the given prim.
const GfMatrix4d &overrideXform = overrideIter->second;
bbox.Transform(overrideXform);
}
result = GfBBox3d::Combine(result, bbox);
it.PruneChildren();
}
return result;
}
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;
TF_FOR_ALL(purposeIt, _includedPurposes) {
_PurposeToBBoxMap::const_iterator it = bboxes.find(*purposeIt);
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");
TF_FOR_ALL(it, _bboxCache) {
if (clearUnvarying || it->second.isVarying) {
it->second.isComplete = false;
// Clear cached bboxes.
it->second.bboxes.clear();
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] invalidating %s "
"for time change\n",
it->first.GetPath().GetText());
}
}
_time = time;
_ctmCache.SetTime(_time);
}
// -------------------------------------------------------------------------- //
// UsdGeomBBoxCache Private API
// -------------------------------------------------------------------------- //
bool
UsdGeomBBoxCache::_ShouldIncludePrim(const UsdPrim& prim)
{
TRACE_FUNCTION();
// Only imageable prims participate in child bounds accumulation.
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;
}
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();
}
TfToken
UsdGeomBBoxCache::_ComputePurpose(const UsdPrim &prim)
{
TfToken purpose;
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.
//
_PrimBBoxHashMap::iterator parentEntryIter =
_bboxCache.find(parentPrim);
if (parentEntryIter != _bboxCache.end()) {
const TfToken &parentPurpose = parentEntryIter->second.purpose;
// parentPurpose could be empty when "prim" is the root prim of the
// subgraph for which bounds are being computed. In this case, we
// fallback to using UsdGeomImageable::ComputePurpose().
if (!parentPurpose.IsEmpty()) {
if (parentPurpose == UsdGeomTokens->default_) {
if (img) {
img.GetPurposeAttr().Get(&purpose);
} else {
purpose = UsdGeomTokens->default_;
}
} else {
purpose = parentPurpose;
}
}
}
}
if (purpose.IsEmpty()) {
purpose = img ? img.ComputePurpose()
: UsdGeomTokens->default_;
}
return purpose;
}
// 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;
}
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 UsdPrim& prim,
std::vector<UsdPrim>* masterPrims)
{
// If the bound is in the cache, return it.
_Entry* entry = TfMapLookupPtr(_bboxCache, prim);
if (entry && entry->isComplete) {
const _PurposeToBBoxMap& bboxes = entry->bboxes;
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] hit: %s %s\n",
prim.GetPath().GetText(),
TfStringify(_GetCombinedBBoxForIncludedPurposes(bboxes)).c_str());
return entry;
}
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] miss: %s\n",
prim.GetPath().GetText());
// Pre-populate all cache entries, note that some entries may already exist.
// Note also we do not exclude unloaded prims - we want them because they
// may have authored extentsHints we can use; thus we can have bboxes in
// model-hierarchy-only.
TfHashSet<UsdPrim, _UsdPrimHash> seenMasterPrims;
UsdPrimRange range(
prim, (UsdPrimIsActive && UsdPrimIsDefined && !UsdPrimIsAbstract));
for (auto it = range.begin(); it != range.end(); ++it) {
_PrimBBoxHashMap::iterator cacheIt = _bboxCache.insert(
std::make_pair(*it, _Entry())).first;
if (_ShouldPruneChildren(*it, &cacheIt->second)) {
// The entry already exists and is complete, we don't need
// the child entries for this query.
it.PruneChildren();
}
if (it->IsInstance()) {
// This prim is an instance, so we need to compute
// bounding boxes for the master prims.
const UsdPrim master = it->GetMaster();
if (seenMasterPrims.insert(master).second) {
masterPrims->push_back(master);
}
it.PruneChildren();
}
}
// isIncluded only gets cached in the multi-threaded path for child prims,
// make sure the prim we're querying has the correct flag cached also. We
// can't do this in _ResolvePrim because we need to the flag for children
// before recursing upon them.
//
// 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 above (e.g., the prim is a class).
entry = &(_bboxCache[prim]);
entry->isIncluded = _ShouldIncludePrim(prim);
return entry;
}
bool
UsdGeomBBoxCache::_Resolve(
const UsdPrim& prim,
UsdGeomBBoxCache::_PurposeToBBoxMap *bboxes)
{
TRACE_FUNCTION();
// NOTE: Bounds are cached in local space, but computed in world space.
// Drop the GIL here if we have it before we spawn parallel tasks, since
// resolving properties on prims in worker threads may invoke plugin code
// that needs the GIL.
TF_PY_ALLOW_THREADS_IN_SCOPE();
// If the bound is in the cache, return it.
std::vector<UsdPrim> masterPrims;
_Entry* entry = _FindOrCreateEntriesForPrim(prim, &masterPrims);
if (entry && entry->isComplete) {
*bboxes = entry->bboxes;
return (!bboxes->empty());
}
// Resolve all master prims first to avoid having to synchronize
// tasks that depend on the same master.
if (!masterPrims.empty()) {
_MasterBBoxResolver bboxesForMasters(this);
bboxesForMasters.Resolve(masterPrims);
}
// XXX: This swapping out is dubious... see XXX below.
_ThreadXformCache xfCaches;
xfCaches.local().Swap(_ctmCache);
// Find the nearest ancestor prim that's a model or a subcomponent.
UsdPrim modelPrim = _GetNearestComponent(prim);
GfMatrix4d inverseComponentCtm = _ctmCache.GetLocalToWorldTransform(
modelPrim).GetInverse();
_dispatcher.Run(_BBoxTask(prim, inverseComponentCtm, this, &xfCaches));
_dispatcher.Wait();
// We save the result of one of the caches, but it might be interesting to
// merge them all here at some point.
// XXX: Is this valid? This only makes sense if we're *100% certain* that
// rootTask above runs in this thread. If it's picked up by another worker
// it won't populate the local xfCaches we're swapping with.
xfCaches.local().Swap(_ctmCache);
// Note: the map may contain unresolved entries, but future queries will
// populate them.
// If the bound is in the cache, return it.
entry = TfMapLookupPtr(_bboxCache, prim);
*bboxes = entry->bboxes;
return (!bboxes->empty());
}
bool
UsdGeomBBoxCache::_GetBBoxFromExtentsHint(
const UsdGeomModelAPI &geomModel,
const UsdAttributeQuery &extentsHintQuery,
_PurposeToBBoxMap *bboxes)
{
VtVec3fArray extents;
if (!extentsHintQuery || !extentsHintQuery.Get(&extents, _time)){
if (TfDebug::IsEnabled(USDGEOM_BBOX) &&
!geomModel.GetPrim().IsLoaded()){
TF_DEBUG(USDGEOM_BBOX).Msg("[BBox Cache] MISSING extentsHint for "
"UNLOADED model %s.\n",
geomModel.GetPrim().GetPath()