RavEngine
Loading...
Searching...
No Matches
GuAABBTreeQuery.h
1// Redistribution and use in source and binary forms, with or without
2// modification, are permitted provided that the following conditions
3// are met:
4// * Redistributions of source code must retain the above copyright
5// notice, this list of conditions and the following disclaimer.
6// * Redistributions in binary form must reproduce the above copyright
7// notice, this list of conditions and the following disclaimer in the
8// documentation and/or other materials provided with the distribution.
9// * Neither the name of NVIDIA CORPORATION nor the names of its
10// contributors may be used to endorse or promote products derived
11// from this software without specific prior written permission.
12//
13// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
14// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
17// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24//
25// Copyright (c) 2008-2022 NVIDIA Corporation. All rights reserved.
26// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
27// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
28
29#ifndef GU_AABBTREEQUERY_H
30#define GU_AABBTREEQUERY_H
31
32#include "GuBVHTestsSIMD.h"
33#include "GuAABBTreeBounds.h"
34#include "foundation/PxInlineArray.h"
35#include "GuAABBTreeNode.h"
36
37namespace physx
38{
39 namespace Gu
40 {
41#define RAW_TRAVERSAL_STACK_SIZE 256
42
44
45 static PX_FORCE_INLINE void getBoundsTimesTwo(Vec4V& center, Vec4V& extents, const PxBounds3* bounds, PxU32 poolIndex)
46 {
47 const PxBounds3* objectBounds = bounds + poolIndex;
48
49 // PT: it's safe to V4LoadU because the pointer comes from the AABBTreeBounds class
50 const Vec4V minV = V4LoadU(&objectBounds->minimum.x);
51 const Vec4V maxV = V4LoadU(&objectBounds->maximum.x);
52
53 center = V4Add(maxV, minV);
54 extents = V4Sub(maxV, minV);
55 }
56
58
59 template<const bool tHasIndices, typename Test, typename Node, typename QueryCallback>
60 static PX_FORCE_INLINE bool doOverlapLeafTest(const Test& test, const Node* node, const PxBounds3* bounds, const PxU32* indices, QueryCallback& visitor)
61 {
62 PxU32 nbPrims = node->getNbPrimitives();
63 const bool doBoxTest = nbPrims > 1;
64 const PxU32* prims = tHasIndices ? node->getPrimitives(indices) : NULL;
65 while(nbPrims--)
66 {
67 const PxU32 primIndex = tHasIndices ? *prims++ : node->getPrimitiveIndex();
68 if(doBoxTest)
69 {
70 Vec4V center2, extents2;
71 getBoundsTimesTwo(center2, extents2, bounds, primIndex);
72
73 const float half = 0.5f;
74 const FloatV halfV = FLoad(half);
75
76 const Vec4V extents_ = V4Scale(extents2, halfV);
77 const Vec4V center_ = V4Scale(center2, halfV);
78
79 if(!test(Vec3V_From_Vec4V(center_), Vec3V_From_Vec4V(extents_)))
80 continue;
81 }
82
83 if(!visitor.invoke(primIndex))
84 return false;
85 }
86 return true;
87 }
88
89 template<const bool tHasIndices, typename Test, typename Tree, typename Node, typename QueryCallback>
91 {
92 public:
93 bool operator()(const AABBTreeBounds& treeBounds, const Tree& tree, const Test& test, QueryCallback& visitor)
94 {
95 const PxBounds3* bounds = treeBounds.getBounds();
96
98 stack.forceSize_Unsafe(RAW_TRAVERSAL_STACK_SIZE);
99 const Node* const nodeBase = tree.getNodes();
100 stack[0] = nodeBase;
101 PxU32 stackIndex = 1;
102
103 while(stackIndex > 0)
104 {
105 const Node* node = stack[--stackIndex];
106 Vec3V center, extents;
107 node->getAABBCenterExtentsV(&center, &extents);
108 while(test(center, extents))
109 {
110 if(node->isLeaf())
111 {
112 if(!doOverlapLeafTest<tHasIndices, Test, Node>(test, node, bounds, tree.getIndices(), visitor))
113 return false;
114 break;
115 }
116
117 const Node* children = node->getPos(nodeBase);
118
119 node = children;
120 stack[stackIndex++] = children + 1;
121 if(stackIndex == stack.capacity())
122 stack.resizeUninitialized(stack.capacity() * 2);
123 node->getAABBCenterExtentsV(&center, &extents);
124 }
125 }
126 return true;
127 }
128 };
129
131
132 template <const bool tInflate, const bool tHasIndices, typename Node, typename QueryCallback> // use inflate=true for sweeps, inflate=false for raycasts
133 static PX_FORCE_INLINE bool doLeafTest( const Node* node, Gu::RayAABBTest& test, const PxBounds3* bounds, const PxU32* indices, PxReal& maxDist, QueryCallback& pcb)
134 {
135 PxU32 nbPrims = node->getNbPrimitives();
136 const bool doBoxTest = nbPrims > 1;
137 const PxU32* prims = tHasIndices ? node->getPrimitives(indices) : NULL;
138 while(nbPrims--)
139 {
140 const PxU32 primIndex = tHasIndices ? *prims++ : node->getPrimitiveIndex();
141 if(doBoxTest)
142 {
143 Vec4V center_, extents_;
144 getBoundsTimesTwo(center_, extents_, bounds, primIndex);
145
146 if(!test.check<tInflate>(Vec3V_From_Vec4V(center_), Vec3V_From_Vec4V(extents_)))
147 continue;
148 }
149
150 // PT:
151 // - 'maxDist' is the current best distance. It can be seen as a "maximum allowed distance" (as passed to the
152 // template by users initially) but also as the "current minimum impact distance", so the name is misleading.
153 // Either way this is where we write & communicate the final/best impact distance to users.
154 //
155 // - the invoke function also takes a distance parameter, and this one is in/out. In input we must pass the
156 // current best distance to the leaf node, so that subsequent leaf-level queries can cull things away as
157 // much as possible. In output users return a shrunk distance value if they found a hit. We need to pass a
158 // copy of 'maxDist' ('md') since it would be too dangerous to rely on the arbitrary user code to always do
159 // the right thing. In particular if we'd pass 'maxDist' to invoke directly, and the called code would NOT
160 // respect the passed max value, it could potentially return a hit further than the best 'maxDist'. At which
161 // point the '(md < oldMaxDist)' test would fail but the damage would have already been done ('maxDist' would
162 // have already been overwritten with a larger value than before). Hence, we need 'md'.
163 //
164 // - now 'oldMaxDist' however is more subtle. In theory we wouldn't need it and we could just use '(md < maxDist)'
165 // in the test below. But that opens the door to subtle bugs: 'maxDist' is a reference to some value somewhere
166 // in the user's code, and we call the same user in invoke. It turns out that the invoke code can access and
167 // modify 'maxDist' on their side, even if we do not pass it to invoke. It's basically the same problem as
168 // before, but much more difficult to see. It does happen with the current PhysX implementations of the invoke
169 // functions: they modify the 'md' that we send them, but *also* 'maxDist' without the code below knowing
170 // about it. So the subsequent test fails again because md == maxDist. A potential solution would have been to
171 // work on a local copy of 'maxDist' in operator(), only writing out the final distance when returning from the
172 // function. Another solution used below is to introduce that local copy just here in the leaf code: that's
173 // where 'oldMaxDist' comes from.
174
175 PxReal oldMaxDist = maxDist;
176 PxReal md = maxDist;
177 if(!pcb.invoke(md, primIndex))
178 return false;
179
180 if(md < oldMaxDist)
181 {
182 maxDist = md;
183 test.setDistance(md);
184 }
185 }
186 return true;
187 }
188
190
191 template <const bool tInflate, const bool tHasIndices, typename Tree, typename Node, typename QueryCallback> // use inflate=true for sweeps, inflate=false for raycasts
193 {
194 public:
195 bool operator()(
196 const AABBTreeBounds& treeBounds, const Tree& tree,
197 const PxVec3& origin, const PxVec3& unitDir, PxReal& maxDist, const PxVec3& inflation,
198 QueryCallback& pcb)
199 {
200 const PxBounds3* bounds = treeBounds.getBounds();
201
202 // PT: we will pass center*2 and extents*2 to the ray-box code, to save some work per-box
203 // So we initialize the test with values multiplied by 2 as well, to get correct results
204 Gu::RayAABBTest test(origin*2.0f, unitDir*2.0f, maxDist, inflation*2.0f);
205
207 stack.forceSize_Unsafe(RAW_TRAVERSAL_STACK_SIZE);
208 const Node* const nodeBase = tree.getNodes();
209 stack[0] = nodeBase;
210 PxU32 stackIndex = 1;
211
212 while(stackIndex--)
213 {
214 const Node* node = stack[stackIndex];
215 Vec3V center, extents;
216 node->getAABBCenterExtentsV2(&center, &extents);
217 if(test.check<tInflate>(center, extents)) // TODO: try timestamp ray shortening to skip this
218 {
219 while(!node->isLeaf())
220 {
221 const Node* children = node->getPos(nodeBase);
222
223 Vec3V c0, e0;
224 children[0].getAABBCenterExtentsV2(&c0, &e0);
225 const PxU32 b0 = test.check<tInflate>(c0, e0);
226
227 Vec3V c1, e1;
228 children[1].getAABBCenterExtentsV2(&c1, &e1);
229 const PxU32 b1 = test.check<tInflate>(c1, e1);
230
231 if(b0 && b1) // if both intersect, push the one with the further center on the stack for later
232 {
233 // & 1 because FAllGrtr behavior differs across platforms
234 const PxU32 bit = FAllGrtr(V3Dot(V3Sub(c1, c0), test.mDir), FZero()) & 1;
235 stack[stackIndex++] = children + bit;
236 node = children + (1 - bit);
237 if(stackIndex == stack.capacity())
238 stack.resizeUninitialized(stack.capacity() * 2);
239 }
240 else if(b0)
241 node = children;
242 else if(b1)
243 node = children + 1;
244 else
245 goto skip_leaf_code;
246 }
247
248 if(!doLeafTest<tInflate, tHasIndices, Node>(node, test, bounds, tree.getIndices(), maxDist, pcb))
249 return false;
250 skip_leaf_code:;
251 }
252 }
253 return true;
254 }
255 };
256
257
259 {
260 enum Enum {
261 eDontGoDeeper,
262 eGoDeeper,
263 eGoDeeperNegFirst,
264 eAbort
265 };
266 };
267
268 template<typename T>
269 void traverseBVH(const Gu::BVHNode* nodes, T& traversalController, PxI32 rootNodeIndex = 0)
270 {
271 PxI32 index = rootNodeIndex;
272
274
275 while (true)
276 {
277 const Gu::BVHNode& a = nodes[index];
278
279 TraversalControl::Enum control = traversalController.analyze(a, index);
280 if (control == TraversalControl::eAbort)
281 return;
282 if (!a.isLeaf() && (control == TraversalControl::eGoDeeper || control == TraversalControl::eGoDeeperNegFirst))
283 {
284 if (control == TraversalControl::eGoDeeperNegFirst)
285 {
286 todoStack.pushBack(a.getPosIndex());
287 index = a.getNegIndex(); //index gets processed next - assign negative index to it
288 }
289 else
290 {
291 todoStack.pushBack(a.getNegIndex());
292 index = a.getPosIndex(); //index gets processed next - assign positive index to it
293 }
294 continue;
295 }
296 if (todoStack.empty()) break;
297 index = todoStack.popBack();
298 }
299 }
300 }
301}
302
303#endif // SQ_AABBTREEQUERY_H
Definition GuAABBTreeBounds.h:39
Definition GuAABBTreeQuery.h:91
Definition GuAABBTreeQuery.h:193
PX_FORCE_INLINE bool empty() const
Definition PxArray.h:261
PX_FORCE_INLINE T & pushBack(const T &a)
Definition PxArray.h:296
PX_INLINE T popBack()
Definition PxArray.h:311
Class representing 3D range or axis aligned bounding box.
Definition PxBounds3.h:58
Definition PxInlineArray.h:43
3 Element vector class.
Definition PxVec3.h:50
#define PX_FORCE_INLINE
Definition PxPreprocessor.h:335
Sorts an array of objects in ascending order, assuming that the predicate implements the < operator:
Definition PxBoxController.h:39
Definition GuAABBTreeNode.h:44
Definition GuBVHTestsSIMD.h:46
Definition GuAABBTreeQuery.h:259
Definition PxVecMathAoSScalar.h:77
Definition PxVecMathAoSScalar.h:65