file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecPlane.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_PLANE_H #define GU_VEC_PLANE_H /** \addtogroup geomutils @{ */ #include "foundation/PxVec3.h" #include "foundation/PxPlane.h" #include "foundation/PxVecMath.h" /** \brief Representation of a plane. Plane equation used: a*x + b*y + c*z + d = 0 */ namespace physx { namespace Gu { class PlaneV { public: /** \brief Constructor */ PX_FORCE_INLINE PlaneV() { } /** \brief Constructor from a normal and a distance */ PX_FORCE_INLINE PlaneV(const aos::FloatVArg nx, const aos::FloatVArg ny, const aos::FloatVArg nz, const aos::FloatVArg _d) { set(nx, ny, nz, _d); } PX_FORCE_INLINE PlaneV(const PxPlane& plane) { using namespace aos; const Vec3V _n = V3LoadU(plane.n); const FloatV _d = FLoad(plane.d); nd = V4SetW(Vec4V_From_Vec3V(_n), _d); } /** \brief Constructor from three points */ PX_FORCE_INLINE PlaneV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2) { set(p0, p1, p2); } /** \brief Constructor from a normal and a distance */ PX_FORCE_INLINE PlaneV(const aos::Vec3VArg _n, const aos::FloatVArg _d) { nd = aos::V4SetW(aos::Vec4V_From_Vec3V(_n), _d); } /** \brief Copy constructor */ PX_FORCE_INLINE PlaneV(const PlaneV& plane) : nd(plane.nd) { } /** \brief Destructor */ PX_FORCE_INLINE ~PlaneV() { } /** \brief Sets plane to zero. */ PX_FORCE_INLINE PlaneV& setZero() { nd = aos::V4Zero(); return *this; } PX_FORCE_INLINE PlaneV& set(const aos::FloatVArg nx, const aos::FloatVArg ny, const aos::FloatVArg nz, const aos::FloatVArg _d) { using namespace aos; const Vec3V n= V3Merge(nx, ny, nz); nd = V4SetW(Vec4V_From_Vec3V(n), _d); return *this; } PX_FORCE_INLINE PlaneV& set(const aos::Vec3VArg _normal, aos::FloatVArg _d) { nd = aos::V4SetW(aos::Vec4V_From_Vec3V(_normal), _d); return *this; } /** \brief Computes the plane equation from 3 points. */ PlaneV& set(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2) { using namespace aos; const Vec3V edge0 = V3Sub(p1, p0); const Vec3V edge1 = V3Sub(p2, p0); const Vec3V n = V3Normalize(V3Cross(edge0, edge1)); // See comments in set() for computation of d const FloatV d = FNeg(V3Dot(p0, n)); nd = V4SetW(Vec4V_From_Vec3V(n), d); return *this; } /*** \brief Computes distance, assuming plane is normalized \sa normalize */ PX_FORCE_INLINE aos::FloatV distance(const aos::Vec3VArg p) const { // Valid for plane equation a*x + b*y + c*z + d = 0 using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return FAdd(V3Dot(p, n), V4GetW(nd)); } PX_FORCE_INLINE aos::BoolV belongs(const aos::Vec3VArg p) const { using namespace aos; const FloatV eps = FLoad(1.0e-7f); return FIsGrtr(eps, FAbs(distance(p))); } /** \brief projects p into the plane */ PX_FORCE_INLINE aos::Vec3V project(const aos::Vec3VArg p) const { // Pretend p is on positive side of plane, i.e. plane.distance(p)>0. // To project the point we have to go in a direction opposed to plane's normal, i.e.: using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return V3Sub(p, V3Scale(n, V4GetW(nd))); } PX_FORCE_INLINE aos::FloatV signedDistanceHessianNormalForm(const aos::Vec3VArg point) const { using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return FAdd(V3Dot(n, point), V4GetW(nd)); } PX_FORCE_INLINE aos::Vec3V getNormal() const { return aos::Vec3V_From_Vec4V(nd); } PX_FORCE_INLINE aos::FloatV getSignDist() const { return aos::V4GetW(nd); } /** \brief find an arbitrary point in the plane */ PX_FORCE_INLINE aos::Vec3V pointInPlane() const { // Project origin (0,0,0) to plane: // (0) - normal * distance(0) = - normal * ((p|(0)) + d) = -normal*d using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return V3Neg(V3Scale(n, V4GetW(nd))); } PX_FORCE_INLINE void normalize() { using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); const FloatV denom = FRecip(V3Length(n)); V4Scale(nd, denom); } aos::Vec4V nd; //!< The normal to the plan , w store the distance from the origin }; } } /** @} */ #endif
5,975
C
25.798206
129
0.674142
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPA.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuEPA.h" #include "GuEPAFacet.h" #include "GuGJKSimplex.h" #include "CmPriorityQueue.h" #include "foundation/PxAllocator.h" namespace physx { namespace Gu { using namespace aos; class ConvexV; struct FacetDistanceComparator { bool operator()(const Facet* left, const Facet* right) const { return *left < *right; } }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class EPA { public: EPA(){} GjkStatus PenetrationDepth(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output); bool expandPoint(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound); bool expandSegment(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound); bool expandTriangle(PxI32& numVerts, const FloatVArg upperBound); Facet* addFacet(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::FloatVArg upper); bool originInTetrahedron(const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, const aos::Vec3VArg p4); Cm::InlinePriorityQueue<Facet*, MaxFacets, FacetDistanceComparator> heap; aos::Vec3V aBuf[MaxSupportPoints]; aos::Vec3V bBuf[MaxSupportPoints]; Facet facetBuf[MaxFacets]; EdgeBuffer edgeBuffer; EPAFacetManager facetManager; private: PX_NOCOPY(EPA) }; #if PX_VC #pragma warning(pop) #endif PX_FORCE_INLINE bool EPA::originInTetrahedron(const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, const aos::Vec3VArg p4) { using namespace aos; return BAllEqFFFF(PointOutsideOfPlane4(p1, p2, p3, p4)) == 1; } static PX_FORCE_INLINE void doSupport(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg dir, aos::Vec3V& supportA, aos::Vec3V& supportB, aos::Vec3V& support) { const Vec3V tSupportA = a.support(V3Neg(dir)); const Vec3V tSupportB = b.support(dir); //avoid LHS supportA = tSupportA; supportB = tSupportB; support = V3Sub(tSupportA, tSupportB); } GjkStatus epaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* PX_RESTRICT aInd, const PxU8* PX_RESTRICT bInd, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { PX_ASSERT(size > 0 && size <=4); Vec3V A[4]; Vec3V B[4]; //ML: we construct a simplex based on the gjk simplex indices for(PxU32 i=0; i<size; ++i) { A[i] = a.supportPoint(aInd[i]); B[i] = b.supportPoint(bInd[i]); } EPA epa; return epa.PenetrationDepth(a, b, A, B, size, takeCoreShape, tolerenceLength, output); } GjkStatus epaPenetration(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT aPnt, const aos::Vec3V* PX_RESTRICT bPnt, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { PX_ASSERT(size > 0 && size <=4); const Vec3V* A = aPnt; const Vec3V* B = bPnt; EPA epa; return epa.PenetrationDepth(a, b, A, B, size, takeCoreShape, tolerenceLength, output); } //ML: this function returns the signed distance of a point to a plane PX_FORCE_INLINE aos::FloatV Facet::getPlaneDist(const aos::Vec3VArg p, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf) const { const Vec3V pa0(aBuf[m_indices[0]]); const Vec3V pb0(bBuf[m_indices[0]]); const Vec3V p0 = V3Sub(pa0, pb0); return V3Dot(m_planeNormal, V3Sub(p, p0)); } //ML: This function: // (1)calculates the distance from orign((0, 0, 0)) to a triangle plane // (2) rejects triangle if the triangle is degenerate (two points are identical) // (3) rejects triangle to be added into the heap if the plane distance is large than upper aos::BoolV Facet::isValid2(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, const aos::FloatVArg upper) { using namespace aos; const FloatV eps = FEps(); const Vec3V pa0(aBuf[i0]); const Vec3V pa1(aBuf[i1]); const Vec3V pa2(aBuf[i2]); const Vec3V pb0(bBuf[i0]); const Vec3V pb1(bBuf[i1]); const Vec3V pb2(bBuf[i2]); const Vec3V p0 = V3Sub(pa0, pb0); const Vec3V p1 = V3Sub(pa1, pb1); const Vec3V p2 = V3Sub(pa2, pb2); const Vec3V v0 = V3Sub(p1, p0); const Vec3V v1 = V3Sub(p2, p0); const Vec3V denormalizedNormal = V3Cross(v0, v1); FloatV norValue = V3Dot(denormalizedNormal, denormalizedNormal); //if norValue < eps, this triangle is degenerate const BoolV con = FIsGrtr(norValue, eps); norValue = FSel(con, norValue, FOne()); const Vec3V planeNormal = V3Scale(denormalizedNormal, FRsqrt(norValue)); const FloatV planeDist = V3Dot(planeNormal, p0); m_planeNormal = planeNormal; FStore(planeDist, &m_planeDist); return BAnd(con, FIsGrtrOrEq(upper, planeDist)); } //ML: if the triangle is valid(not degenerate and within lower and upper bound), we need to add it into the heap. Otherwise, we just return //the triangle so that the facet can be linked to other facets in the expanded polytope. Facet* EPA::addFacet(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::FloatVArg upper) { using namespace aos; PX_ASSERT(i0 != i1 && i0 != i2 && i1 != i2); //ML: we move the control in the calling code so we don't need to check weather we will run out of facets or not PX_ASSERT(facetManager.getNumUsedID() < MaxFacets); const PxU32 facetId = facetManager.getNewID(); PxPrefetchLine(&facetBuf[facetId], 128); Facet * facet = PX_PLACEMENT_NEW(&facetBuf[facetId],Facet(i0, i1, i2)); facet->m_FacetId = PxU8(facetId); const BoolV validTriangle = facet->isValid2(i0, i1, i2, aBuf, bBuf, upper); if(BAllEqTTTT(validTriangle)) { heap.push(facet); facet->m_inHeap = true; } else { facet->m_inHeap = false; } return facet; } //ML: this function performs a flood fill over the boundary of the current polytope. void Facet::silhouette(const PxU32 _index, const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager) { using namespace aos; const FloatV zero = FZero(); Edge stack[MaxFacets]; stack[0] = Edge(this, _index); PxI32 size = 1; while(size--) { Facet* const PX_RESTRICT f = stack[size].m_facet; const PxU32 index = stack[size].m_index; PX_ASSERT(f->Valid()); if(!f->m_obsolete) { //ML: if the point is above the facet, the facet has an reflex edge, which will make the polytope concave. Therefore, we need to //remove this facet and make sure the expanded polytope is convex. const FloatV pointPlaneDist = f->getPlaneDist(w, aBuf, bBuf); if(FAllGrtr(zero, pointPlaneDist)) { //ML: facet isn't visible from w (we don't have a reflex edge), this facet will be on the boundary and part of the new polytope so that //we will push it into our edgeBuffer if(!edgeBuffer.Insert(f, index)) return; } else { //ML:facet is visible from w, therefore, we need to remove this facet from the heap and push its adjacent facets onto the stack f->m_obsolete = true; // Facet is visible from w const PxU32 next(incMod3(index)); const PxU32 next2(incMod3(next)); stack[size++] = Edge(f->m_adjFacets[next2],PxU32(f->m_adjEdges[next2])); stack[size++] = Edge(f->m_adjFacets[next], PxU32(f->m_adjEdges[next])); PX_ASSERT(size <= MaxFacets); if(!f->m_inHeap) { //if the facet isn't in the heap, we can release that memory manager.deferredFreeID(f->m_FacetId); } } } } } //ML: this function perform flood fill for the adjancent facet and store the boundary facet into the edgeBuffer void Facet::silhouette(const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager) { m_obsolete = true; for(PxU32 a = 0; a < 3; ++a) { m_adjFacets[a]->silhouette(PxU32(m_adjEdges[a]), w, aBuf, bBuf, edgeBuffer, manager); } } bool EPA::expandPoint(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound) { const Vec3V x = V3UnitX(); Vec3V q0 = V3Sub(aBuf[0], bBuf[0]); Vec3V q1; doSupport(a, b, x, aBuf[1], bBuf[1], q1); if (V3AllEq(q0, q1)) return false; return expandSegment(a, b, numVerts, upperBound); } //ML: this function use the segement to create a triangle bool EPA::expandSegment(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound) { const Vec3V q0 = V3Sub(aBuf[0], bBuf[0]); const Vec3V q1 = V3Sub(aBuf[1], bBuf[1]); const Vec3V v = V3Sub(q1, q0); const Vec3V absV = V3Abs(v); const FloatV x = V3GetX(absV); const FloatV y = V3GetY(absV); const FloatV z = V3GetZ(absV); Vec3V axis = V3UnitX(); const BoolV con0 = BAnd(FIsGrtr(x, y), FIsGrtr(z, y)); if (BAllEqTTTT(con0)) { axis = V3UnitY(); } else if(FAllGrtr(x, z)) { axis = V3UnitZ(); } const Vec3V n = V3Normalize(V3Cross(axis, v)); Vec3V q2; doSupport(a, b, n, aBuf[2], bBuf[2], q2); return expandTriangle(numVerts, upperBound); } bool EPA::expandTriangle(PxI32& numVerts, const FloatVArg upperBound) { numVerts = 3; Facet * PX_RESTRICT f0 = addFacet(0, 1, 2, upperBound); Facet * PX_RESTRICT f1 = addFacet(1, 0, 2, upperBound); if(heap.empty()) return false; f0->link(0, f1, 0); f0->link(1, f1, 2); f0->link(2, f1, 1); return true; } //ML: this function calculates contact information. If takeCoreShape flag is true, this means the two closest points will be on the core shape used in the support functions. //For example, we treat sphere/capsule as a point/segment in the support function for GJK/EPA, so that the core shape for sphere/capsule is a point/segment. For PCM, we need //to take the point from the core shape because this will allows us recycle the contacts more stably. For SQ sweeps, we need to take the point on the surface of the sphere/capsule //when we calculate MTD because this is what will be reported to the user. Therefore, the takeCoreShape flag will be set to be false in SQ. static void calculateContactInformation(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, Facet* facet, const GjkConvex& a, const GjkConvex& b, const bool takeCoreShape, GjkOutput& output) { const FloatV zero = FZero(); Vec3V _pa, _pb; facet->getClosestPoint(aBuf, bBuf, _pa, _pb); //dist > 0 means two shapes are penetrated. If dist < 0(when origin isn't inside the polytope), two shapes status are unknown const FloatV dist = FAbs(facet->getPlaneDist()); const Vec3V planeNormal = V3Neg(facet->getPlaneNormal()); if(takeCoreShape) { output.closestA = _pa; output.closestB = _pb; output.normal = planeNormal; output.penDep = FNeg(dist); } else { //for sphere/capusule to take the surface point const BoolV aQuadratic = a.isMarginEqRadius(); const BoolV bQuadratic = b.isMarginEqRadius(); const FloatV marginA = FSel(aQuadratic, a.getMargin(), zero); const FloatV marginB = FSel(bQuadratic, b.getMargin(), zero); const FloatV sumMargin = FAdd(marginA, marginB); output.closestA = V3NegScaleSub(planeNormal, marginA, _pa); output.closestB = V3ScaleAdd(planeNormal, marginB, _pb); output.normal = planeNormal; output.penDep = FNeg(FAdd(dist, sumMargin)); } } //ML: This function returns one of three status codes: //(1)EPA_FAIL: the algorithm failed to create a valid polytope(the origin wasn't inside the polytope) from the input simplex //(2)EPA_CONTACT : the algorithm found the MTD and converged successfully. //(3)EPA_DEGENERATE: the algorithm cannot make further progress and the result is unknown. GjkStatus EPA::PenetrationDepth(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { using namespace aos; PX_UNUSED(tolerenceLength); PxPrefetchLine(&facetBuf[0]); PxPrefetchLine(&facetBuf[0], 128); const FloatV zero = FZero(); const FloatV _max = FMax(); FloatV upper_bound(_max); aBuf[0]=A[0]; aBuf[1]=A[1]; aBuf[2]=A[2]; aBuf[3]=A[3]; bBuf[0]=B[0]; bBuf[1]=B[1]; bBuf[2]=B[2]; bBuf[3]=B[3]; PxI32 numVertsLocal = 0; heap.clear(); //if the simplex isn't a tetrahedron, we need to construct one before we can expand it switch (size) { case 1: { // Touching contact. Yes, we have a collision and the penetration will be zero if(!expandPoint(a, b, numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 2: { // We have a line segment inside the Minkowski sum containing the // origin. we need to construct two back to back triangles which link to each other if(!expandSegment(a, b, numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 3: { // We have a triangle inside the Minkowski sum containing // the origin. We need to construct two back to back triangles which link to each other if(!expandTriangle(numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 4: { //check for input face normal. All face normals in this tetrahedron should be all pointing either inwards or outwards. If all face normals are pointing outward, we are good to go. Otherwise, we need to //shuffle the input vertexes and make sure all face normals are pointing outward const Vec3V pa0(aBuf[0]); const Vec3V pa1(aBuf[1]); const Vec3V pa2(aBuf[2]); const Vec3V pa3(aBuf[3]); const Vec3V pb0(bBuf[0]); const Vec3V pb1(bBuf[1]); const Vec3V pb2(bBuf[2]); const Vec3V pb3(bBuf[3]); const Vec3V p0 = V3Sub(pa0, pb0); const Vec3V p1 = V3Sub(pa1, pb1); const Vec3V p2 = V3Sub(pa2, pb2); const Vec3V p3 = V3Sub(pa3, pb3); const Vec3V v1 = V3Sub(p1, p0); const Vec3V v2 = V3Sub(p2, p0); const Vec3V planeNormal = V3Normalize(V3Cross(v1, v2)); const FloatV signDist = V3Dot(planeNormal, V3Sub(p3, p0)); if (FAllGrtr(signDist, zero)) { //shuffle the input vertexes const Vec3V tempA0 = aBuf[2]; const Vec3V tempB0 = bBuf[2]; aBuf[2] = aBuf[1]; bBuf[2] = bBuf[1]; aBuf[1] = tempA0; bBuf[1] = tempB0; } Facet * PX_RESTRICT f0 = addFacet(0, 1, 2, upper_bound); Facet * PX_RESTRICT f1 = addFacet(0, 3, 1, upper_bound); Facet * PX_RESTRICT f2 = addFacet(0, 2, 3, upper_bound); Facet * PX_RESTRICT f3 = addFacet(1, 3, 2, upper_bound); if (heap.empty()) return EPA_FAIL; #if EPA_DEBUG PX_ASSERT(f0->m_planeDist >= -1e-2f); PX_ASSERT(f1->m_planeDist >= -1e-2f); PX_ASSERT(f2->m_planeDist >= -1e-2f); PX_ASSERT(f3->m_planeDist >= -1e-2f); #endif f0->link(0, f1, 2); f0->link(1, f3, 2); f0->link(2, f2, 0); f1->link(0, f2, 2); f1->link(1, f3, 0); f2->link(1, f3, 1); numVertsLocal = 4; break; } } const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin()); const FloatV eps = FMul(minMargin, FLoad(0.1f)); Facet* PX_RESTRICT facet = NULL; Vec3V tempa, tempb, q; do { facetManager.processDeferredIds(); facet = heap.pop(); //get the shortest distance triangle of origin from the list facet->m_inHeap = false; if (!facet->isObsolete()) { PxPrefetchLine(edgeBuffer.m_pEdges); PxPrefetchLine(edgeBuffer.m_pEdges,128); PxPrefetchLine(edgeBuffer.m_pEdges,256); const Vec3V planeNormal = facet->getPlaneNormal(); const FloatV planeDist = facet->getPlaneDist(); tempa = a.support(planeNormal); tempb = b.support(V3Neg(planeNormal)); q = V3Sub(tempa, tempb); PxPrefetchLine(&aBuf[numVertsLocal],128); PxPrefetchLine(&bBuf[numVertsLocal],128); //calculate the distance from support point to the origin along the plane normal. Because the support point is search along //the plane normal, which means the distance should be positive. However, if the origin isn't contained in the polytope, dist //might be negative const FloatV dist = V3Dot(q, planeNormal); const BoolV con0 = FIsGrtrOrEq(eps, FAbs(FSub(dist, planeDist))); if (BAllEqTTTT(con0)) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); if (takeCoreShape) { const FloatV toleranceEps = FMul(FLoad(1e-3f), tolerenceLength); const Vec3V dif = V3Sub(output.closestA, output.closestB); const FloatV pen = FAdd(FAbs(output.penDep), toleranceEps); const FloatV sqDif = V3Dot(dif, dif); const FloatV length = FSel(FIsGrtr(sqDif, zero), FSqrt(sqDif), zero); if (FAllGrtr(length, pen)) return EPA_DEGENERATE; } return EPA_CONTACT; } //update the upper bound to the minimum between existing upper bound and the distance upper_bound = FMin(upper_bound, dist); aBuf[numVertsLocal]=tempa; bBuf[numVertsLocal]=tempb; const PxU32 index =PxU32(numVertsLocal++); // Compute the silhouette cast by the new vertex // Note that the new vertex is on the positive side // of the current facet, so the current facet will // not be in the polytope. Start local search // from this facet. edgeBuffer.MakeEmpty(); facet->silhouette(q, aBuf, bBuf, edgeBuffer, facetManager); if (!edgeBuffer.IsValid()) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } Edge* PX_RESTRICT edge=edgeBuffer.Get(0); PxU32 bufferSize=edgeBuffer.Size(); //check to see whether we have enough space in the facet manager to create new facets if(bufferSize > facetManager.getNumRemainingIDs()) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } Facet *firstFacet = addFacet(edge->getTarget(), edge->getSource(),index, upper_bound); PX_ASSERT(firstFacet); firstFacet->link(0, edge->getFacet(), edge->getIndex()); Facet * PX_RESTRICT lastFacet = firstFacet; #if EPA_DEBUG bool degenerate = false; for(PxU32 i=1; (i<bufferSize) && (!degenerate); ++i) { edge=edgeBuffer.Get(i); Facet* PX_RESTRICT newFacet = addFacet(edge->getTarget(), edge->getSource(),index, upper_bound); PX_ASSERT(newFacet); const bool b0 = newFacet->link(0, edge->getFacet(), edge->getIndex()); const bool b1 = newFacet->link(2, lastFacet, 1); degenerate = degenerate || !b0 || !b1; lastFacet = newFacet; } if (degenerate) PxDebugBreak(); #else for (PxU32 i = 1; i<bufferSize; ++i) { edge = edgeBuffer.Get(i); Facet* PX_RESTRICT newFacet = addFacet(edge->getTarget(), edge->getSource(), index, upper_bound); newFacet->link(0, edge->getFacet(), edge->getIndex()); newFacet->link(2, lastFacet, 1); lastFacet = newFacet; } #endif firstFacet->link(2, lastFacet, 1); } facetManager.freeID(facet->m_FacetId); } while((heap.size() > 0) && FAllGrtr(upper_bound, heap.top()->getPlaneDist()) && numVertsLocal != MaxSupportPoints); calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } } }
21,172
C++
32.93109
211
0.687512
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecTetrahedron.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_TETRAHEDRON_H #define GU_VEC_TETRAHEDRON_H /** \addtogroup geomutils @{ */ #include "GuVecConvex.h" #include "GuConvexSupportTable.h" #include "GuDistancePointTriangle.h" namespace physx { namespace Gu { class TetrahedronV : public ConvexV { public: /** \brief Constructor */ PX_FORCE_INLINE TetrahedronV() : ConvexV(ConvexType::eTETRAHEDRON) { margin = 0.02f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Constructor \param[in] p0 Point 0 \param[in] p1 Point 1 \param[in] p2 Point 2 \param[in] p3 Point 3 */ PX_FORCE_INLINE TetrahedronV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; //const FloatV zero = FZero(); const FloatV num = FLoad(0.25f); center = V3Scale(V3Add(V3Add(p0, p1), V3Add(p2, p3)), num); //vertsX store all the x elements form those four point vertsX = V4SetW(V4SetZ(V4SetY(Vec4V_From_Vec3V(p0), V3GetX(p1)), V3GetX(p2)), V3GetX(p3)); //vertsY store all the y elements from those four point vertsY = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetY(p0)), V3GetY(p1)), V3GetY(p2)), V3GetY(p3)); //vertsZ store all the z elements from those four point vertsZ = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetZ(p0)), V3GetZ(p1)), V3GetZ(p2)), V3GetZ(p3)); verts[0] = p0; verts[1] = p1; verts[2] = p2; verts[3] = p3; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } PX_FORCE_INLINE TetrahedronV(const PxVec3* pts) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; const Vec3V p0 = V3LoadU(pts[0]); const Vec3V p1 = V3LoadU(pts[1]); const Vec3V p2 = V3LoadU(pts[2]); const Vec3V p3 = V3LoadU(pts[3]); const FloatV num = FLoad(0.25f); center = V3Scale(V3Add(V3Add(p0, p1), V3Add(p2, p3)), num); vertsX = V4SetW(V4SetZ(V4SetY(Vec4V_From_Vec3V(p0), V3GetX(p1)), V3GetX(p2)), V3GetX(p3)); vertsY = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetY(p0)), V3GetY(p1)), V3GetY(p2)), V3GetY(p3)); vertsZ = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetZ(p0)), V3GetZ(p1)), V3GetZ(p2)), V3GetZ(p3)); verts[0] = p0; verts[1] = p1; verts[2] = p2; verts[3] = p3; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Copy constructor \param[in] tetrahedron Tetrahedron to copy */ PX_FORCE_INLINE TetrahedronV(const Gu::TetrahedronV& tetrahedron) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; vertsX = tetrahedron.vertsX; vertsY = tetrahedron.vertsY; vertsZ = tetrahedron.vertsZ; verts[0] = tetrahedron.verts[0]; verts[1] = tetrahedron.verts[1]; verts[2] = tetrahedron.verts[2]; verts[3] = tetrahedron.verts[3]; center = tetrahedron.center; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Destructor */ PX_FORCE_INLINE ~TetrahedronV() { } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FMax(); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; vertsX = V4Add(vertsX, V4Splat(V3GetX(offset))); vertsY = V4Add(vertsY, V4Splat(V3GetY(offset))); vertsZ = V4Add(vertsZ, V4Splat(V3GetZ(offset))); verts[0] = V3Add(verts[0], offset); verts[1] = V3Add(verts[1], offset); verts[2] = V3Add(verts[2], offset); verts[3] = V3Add(verts[3], offset); } PX_FORCE_INLINE aos::Vec4V getProjection(const aos::Vec3VArg dir) const { using namespace aos; const Vec4V dx = V4Scale(vertsX, V3GetX(dir)); const Vec4V dy = V4Scale(vertsY, V3GetY(dir)); const Vec4V dz = V4Scale(vertsZ, V3GetZ(dir)); return V4Add(dx, V4Add(dy, dz)); } //dir is in local space, verts in the local space PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir) const { using namespace aos; const Vec4V d = getProjection(dir); const FloatV d0 = V4GetX(d); const FloatV d1 = V4GetY(d); const FloatV d2 = V4GetZ(d); const FloatV d3 = V4GetW(d); const BoolV con0 = BAnd(BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)), FIsGrtr(d0, d3)); const BoolV con1 = BAnd(FIsGrtr(d1, d2), FIsGrtr(d1, d3)); const BoolV con2 = FIsGrtr(d2, d3); return V3Sel(con0, verts[0], V3Sel(con1, verts[1], V3Sel(con2, verts[2], verts[3]))); } //dir is in b space PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //verts are in local space // const Vec3V _dir = aToB.rotateInv(dir); //transform dir back to a space const Vec3V _dir = aTobT.rotate(dir); //transform dir back to a space const Vec3V maxPoint = supportLocal(_dir); return aToB.transform(maxPoint);//transform maxPoint to the b space } PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index) const { using namespace aos; const Vec4V d = getProjection(dir); const FloatV d0 = V4GetX(d); const FloatV d1 = V4GetY(d); const FloatV d2 = V4GetZ(d); const FloatV d3 = V4GetW(d); const BoolV con0 = BAnd(BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)), FIsGrtr(d0, d3)); const BoolV con1 = BAnd(FIsGrtr(d1, d2), FIsGrtr(d1, d3)); const BoolV con2 = FIsGrtr(d2, d3); const VecI32V vIndex = VecI32V_Sel(con0, I4Load(0), VecI32V_Sel(con1, I4Load(1), VecI32V_Sel(con2, I4Load(2), I4Load(3)))); PxI32_From_VecI32V(vIndex, &index); //return V3Sel(con0, v0, V3Sel(con1, v1, v2)); return verts[index]; } PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { //don't put margin in the triangle using namespace aos; //transfer dir into the local space of triangle // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); return aToB.transform(supportLocal(_dir, index));//transform the support poin to b space } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return verts[index]; } /** \brief Array of Vertices. */ aos::Vec3V verts[4]; aos::Vec4V vertsX; aos::Vec4V vertsY; aos::Vec4V vertsZ; }; } } #endif
8,210
C
31.975903
145
0.672473
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvexHull.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEXHULL_H #define GU_VEC_CONVEXHULL_H #include "common/PxPhysXCommonConfig.h" #include "geometry/PxMeshScale.h" #include "GuConvexMesh.h" #include "GuVecConvex.h" #include "GuConvexMeshData.h" #include "GuBigConvexData.h" #include "GuConvexSupportTable.h" #include "GuCubeIndex.h" #include "foundation/PxFPU.h" #include "foundation/PxVecQuat.h" #include "GuShapeConvex.h" namespace physx { namespace Gu { #define CONVEX_MARGIN_RATIO 0.1f #define CONVEX_MIN_MARGIN_RATIO 0.05f #define CONVEX_SWEEP_MARGIN_RATIO 0.025f #define TOLERANCE_MARGIN_RATIO 0.08f #define TOLERANCE_MIN_MARGIN_RATIO 0.05f //This margin is used in Persistent contact manifold PX_SUPPORT_FORCE_INLINE aos::FloatV CalculatePCMConvexMargin(const Gu::ConvexHullData* hullData, const aos::Vec3VArg scale, const PxReal toleranceLength, const PxReal toleranceRatio = TOLERANCE_MIN_MARGIN_RATIO) { using namespace aos; const Vec3V extents= V3Mul(V3LoadU(hullData->mInternal.mExtents), scale); const FloatV min = V3ExtractMin(extents); const FloatV toleranceMargin = FLoad(toleranceLength * toleranceRatio); //ML: 25% of the minimum extents of the internal AABB as this convex hull's margin return FMin(FMul(min, FLoad(0.25f)), toleranceMargin); } PX_SUPPORT_FORCE_INLINE aos::FloatV CalculateMTDConvexMargin(const Gu::ConvexHullData* hullData, const aos::Vec3VArg scale) { using namespace aos; const Vec3V extents = V3Mul(V3LoadU(hullData->mInternal.mExtents), scale); const FloatV min = V3ExtractMin(extents); //ML: 25% of the minimum extents of the internal AABB as this convex hull's margin return FMul(min, FLoad(0.25f)); } //This minMargin is used in PCM contact gen PX_SUPPORT_FORCE_INLINE void CalculateConvexMargin(const InternalObjectsData& internalObject, PxReal& margin, PxReal& minMargin, PxReal& sweepMargin, const aos::Vec3VArg scale) { using namespace aos; const Vec3V extents = V3Mul(V3LoadU(internalObject.mExtents), scale); const FloatV min_ = V3ExtractMin(extents); PxReal minExtent; FStore(min_, &minExtent); //margin is used as acceptanceTolerance for overlap. margin = minExtent * CONVEX_MARGIN_RATIO; //minMargin is used in the GJK termination condition minMargin = minExtent * CONVEX_MIN_MARGIN_RATIO; //this is used for sweep(gjkRaycast) sweepMargin = minExtent * CONVEX_SWEEP_MARGIN_RATIO; } PX_SUPPORT_FORCE_INLINE aos::Mat33V ConstructSkewMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation) { using namespace aos; Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); Mat33V trans = M33Trnsps(rot); trans.col0 = V3Scale(trans.col0, V3GetX(scale)); trans.col1 = V3Scale(trans.col1, V3GetY(scale)); trans.col2 = V3Scale(trans.col2, V3GetZ(scale)); return M33MulM33(trans, rot); } PX_SUPPORT_FORCE_INLINE void ConstructSkewMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation, aos::Mat33V& vertex2Shape, aos::Mat33V& shape2Vertex, aos::Vec3V& center, const bool idtScale) { using namespace aos; PX_ASSERT(!V3AllEq(scale, V3Zero())); if(idtScale) { //create identity buffer const Mat33V identity = M33Identity(); vertex2Shape = identity; shape2Vertex = identity; } else { const FloatV scaleX = V3GetX(scale); const Vec3V invScale = V3Recip(scale); //this is uniform scale if(V3AllEq(V3Splat(scaleX), scale)) { vertex2Shape = M33Diagonal(scale); shape2Vertex = M33Diagonal(invScale); } else { Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); const Mat33V trans = M33Trnsps(rot); /* vertex2shape skewMat = Inv(R)*Diagonal(scale)*R; */ const Mat33V temp(V3Scale(trans.col0, scaleX), V3Scale(trans.col1, V3GetY(scale)), V3Scale(trans.col2, V3GetZ(scale))); vertex2Shape = M33MulM33(temp, rot); //don't need it in the support function /* shape2Vertex invSkewMat =(invSkewMat)= Inv(R)*Diagonal(1/scale)*R; */ shape2Vertex.col0 = V3Scale(trans.col0, V3GetX(invScale)); shape2Vertex.col1 = V3Scale(trans.col1, V3GetY(invScale)); shape2Vertex.col2 = V3Scale(trans.col2, V3GetZ(invScale)); shape2Vertex = M33MulM33(shape2Vertex, rot); //shape2Vertex = M33Inverse(vertex2Shape); } //transform center to shape space center = M33MulV3(vertex2Shape, center); } } PX_SUPPORT_FORCE_INLINE aos::Mat33V ConstructVertex2ShapeMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation) { using namespace aos; Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); const Mat33V trans = M33Trnsps(rot); /* vertex2shape skewMat = Inv(R)*Diagonal(scale)*R; */ const Mat33V temp(V3Scale(trans.col0, V3GetX(scale)), V3Scale(trans.col1, V3GetY(scale)), V3Scale(trans.col2, V3GetZ(scale))); return M33MulM33(temp, rot); } class ConvexHullV : public ConvexV { class TinyBitMap { public: PxU32 m[8]; PX_FORCE_INLINE TinyBitMap() { m[0] = m[1] = m[2] = m[3] = m[4] = m[5] = m[6] = m[7] = 0; } PX_FORCE_INLINE void set(PxU8 v) { m[v >> 5] |= 1 << (v & 31); } PX_FORCE_INLINE bool get(PxU8 v) const { return (m[v >> 5] & 1 << (v & 31)) != 0; } }; public: /** \brief Constructor */ PX_SUPPORT_INLINE ConvexHullV() : ConvexV(ConvexType::eCONVEXHULL) { } PX_SUPPORT_INLINE ConvexHullV(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center, const aos::Vec3VArg scale, const aos::QuatVArg scaleRot, const bool idtScale) : ConvexV(ConvexType::eCONVEXHULL, _center) { using namespace aos; hullData = _hullData; const PxVec3* PX_RESTRICT tempVerts = _hullData->getHullVertices(); verts = tempVerts; numVerts = _hullData->mNbHullVertices; CalculateConvexMargin(_hullData->mInternal, margin, minMargin, sweepMargin, scale); ConstructSkewMatrix(scale, scaleRot, vertex2Shape, shape2Vertex, center, idtScale); data = _hullData->mBigConvexRawData; } PX_SUPPORT_INLINE ConvexHullV(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center) : ConvexV(ConvexType::eCONVEXHULL, _center) { using namespace aos; hullData = _hullData; verts = _hullData->getHullVertices(); numVerts = _hullData->mNbHullVertices; data = _hullData->mBigConvexRawData; } //this is used by CCD system PX_SUPPORT_INLINE ConvexHullV(const PxGeometry& geom) : ConvexV(ConvexType::eCONVEXHULL, aos::V3Zero()) { using namespace aos; const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom); const Gu::ConvexHullData* hData = _getHullData(convexGeom); const Vec3V vScale = V3LoadU_SafeReadW(convexGeom.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vRot = QuatVLoadU(&convexGeom.scale.rotation.x); const bool idtScale = convexGeom.scale.isIdentity(); hullData = hData; const PxVec3* PX_RESTRICT tempVerts = hData->getHullVertices(); verts = tempVerts; numVerts = hData->mNbHullVertices; CalculateConvexMargin(hData->mInternal, margin, minMargin, sweepMargin, vScale); ConstructSkewMatrix(vScale, vRot, vertex2Shape, shape2Vertex, center, idtScale); data = hData->mBigConvexRawData; } //this is used by convex vs tetrahedron collision PX_SUPPORT_INLINE ConvexHullV(const Gu::PolygonalData& polyData, const Cm::FastVertex2ShapeScaling& convexScale) : ConvexV(ConvexType::eCONVEXHULL, aos::V3LoadU(polyData.mCenter)) { using namespace aos; const Vec3V vScale = V3LoadU(polyData.mScale.scale); verts = polyData.mVerts; numVerts = PxU8(polyData.mNbVerts); CalculateConvexMargin(polyData.mInternal, margin, minMargin, sweepMargin, vScale); const PxMat33& v2s = convexScale.getVertex2ShapeSkew(); const PxMat33& s2v = convexScale.getShape2VertexSkew(); vertex2Shape.col0 = V3LoadU(v2s.column0); vertex2Shape.col1 = V3LoadU(v2s.column1); vertex2Shape.col2 = V3LoadU(v2s.column2); shape2Vertex.col0 = V3LoadU(s2v.column0); shape2Vertex.col1 = V3LoadU(s2v.column1); shape2Vertex.col2 = V3LoadU(s2v.column2); data = polyData.mBigData; } PX_SUPPORT_INLINE void initialize(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center, const aos::Vec3VArg scale, const aos::QuatVArg scaleRot, const bool idtScale) { using namespace aos; const PxVec3* tempVerts = _hullData->getHullVertices(); CalculateConvexMargin(_hullData->mInternal, margin, minMargin, sweepMargin, scale); ConstructSkewMatrix(scale, scaleRot, vertex2Shape, shape2Vertex, center, idtScale); verts = tempVerts; numVerts = _hullData->mNbHullVertices; //rot = _rot; center = _center; // searchIndex = 0; data = _hullData->mBigConvexRawData; hullData = _hullData; if (_hullData->mBigConvexRawData) { PxPrefetchLine(hullData->mBigConvexRawData->mValencies); PxPrefetchLine(hullData->mBigConvexRawData->mValencies, 128); PxPrefetchLine(hullData->mBigConvexRawData->mAdjacentVerts); } } PX_FORCE_INLINE void resetMargin(const PxReal toleranceLength) { const PxReal toleranceMinMargin = toleranceLength * TOLERANCE_MIN_MARGIN_RATIO; const PxReal toleranceMargin = toleranceLength * TOLERANCE_MARGIN_RATIO; margin = PxMin(margin, toleranceMargin); minMargin = PxMin(minMargin, toleranceMinMargin); } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { using namespace aos; return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[index])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } PX_NOINLINE PxU32 hillClimbing(const aos::Vec3VArg _dir)const { using namespace aos; const Gu::Valency* valency = data->mValencies; const PxU8* adjacentVerts = data->mAdjacentVerts; //NotSoTinyBitMap visited; PxU32 smallBitMap[8] = {0,0,0,0,0,0,0,0}; // PxU32 index = searchIndex; PxU32 index = 0; { PxVec3 vertexSpaceDirection; V3StoreU(_dir, vertexSpaceDirection); const PxU32 offset = ComputeCubemapNearestOffset(vertexSpaceDirection, data->mSubdiv); //const PxU32 offset = ComputeCubemapOffset(vertexSpaceDirection, data->mSubdiv); index = data->mSamples[offset]; } Vec3V maxPoint = V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) FloatV max = V3Dot(maxPoint, _dir); PxU32 initialIndex = index; do { initialIndex = index; const PxU32 numNeighbours = valency[index].mCount; const PxU32 offset = valency[index].mOffset; for(PxU32 a = 0; a < numNeighbours; ++a) { const PxU32 neighbourIndex = adjacentVerts[offset + a]; const Vec3V vertex = V3LoadU_SafeReadW(verts[neighbourIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const FloatV dist = V3Dot(vertex, _dir); if(FAllGrtr(dist, max)) { const PxU32 ind = neighbourIndex>>5; const PxU32 mask = PxU32(1 << (neighbourIndex & 31)); if((smallBitMap[ind] & mask) == 0) { smallBitMap[ind] |= mask; max = dist; index = neighbourIndex; } } } }while(index != initialIndex); return index; } PX_SUPPORT_INLINE PxU32 bruteForceSearch(const aos::Vec3VArg _dir)const { using namespace aos; //brute force PxVec3 dir; V3StoreU(_dir, dir); PxReal max = verts[0].dot(dir); PxU32 maxIndex = 0; for (PxU32 i = 1; i < numVerts; ++i) { const PxReal dist = verts[i].dot(dir); if (dist > max) { max = dist; maxIndex = i; } } return maxIndex; } //points are in vertex space, _dir in vertex space PX_NOINLINE PxU32 supportVertexIndex(const aos::Vec3VArg _dir)const { using namespace aos; if(data) return hillClimbing(_dir); else return bruteForceSearch(_dir); } //dir is in the vertex space PX_SUPPORT_INLINE void bruteForceSearchMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //brute force PxVec3 dir; V3StoreU(_dir, dir); //get the support point from the orignal margin PxReal _max = verts[0].dot(dir); PxReal _min = _max; for(PxU32 i = 1; i < numVerts; ++i) { const PxReal dist = verts[i].dot(dir); _max = PxMax(dist, _max); _min = PxMin(dist, _min); } min = FLoad(_min); max = FLoad(_max); } //This function is used in the full contact manifold generation code, points are in vertex space. //This function support scaling, _dir is in the shape space PX_SUPPORT_INLINE void supportVertexMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //dir is in the vertex space const Vec3V dir = M33TrnspsMulV3(vertex2Shape, _dir); if(data) { const PxU32 maxIndex= hillClimbing(dir); const PxU32 minIndex= hillClimbing(V3Neg(dir)); const Vec3V maxPoint= M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[maxIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const Vec3V minPoint= M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[minIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) min = V3Dot(_dir, minPoint); max = V3Dot(_dir, maxPoint); } else { //dir is in the vertex space bruteForceSearchMinMax(dir, min, max); } } //This function is used in the full contact manifold generation code PX_SUPPORT_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* _verts)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) _verts[i] = M33MulV3(vertex2Shape, V3LoadU_SafeReadW(originalVerts[inds[i]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'populateVerts' is always called with polyData.mVerts) } //This function is used in epa //dir is in the shape space PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; //scale dir and put it in the vertex space const Vec3V _dir = M33TrnspsMulV3(vertex2Shape, dir); const PxU32 maxIndex = supportVertexIndex(_dir); return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[maxIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this is used in the sat test for the full contact gen PX_SUPPORT_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //dir is in the shape space supportVertexMinMax(dir, min, max); } //This function is used in epa PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the shape space // const Vec3V dir_ = aTob.rotateInv(dir);//relTra.rotateInv(dir); const Vec3V dir_ = aTobT.rotate(dir);//relTra.rotateInv(dir); const Vec3V maxPoint =supportLocal(dir_); //translate maxPoint from shape space of a back to the b space return aTob.transform(maxPoint);//relTra.transform(maxPoint); } //dir in the shape space, this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; //scale dir and put it in the vertex space, for non-uniform scale, we don't want the scale in the dir, therefore, we are using //the transpose of the inverse of shape2Vertex(which is vertex2shape). This will allow us igore the scale and keep the rotation const Vec3V dir_ = M33TrnspsMulV3(vertex2Shape, dir); //get the extreme point index const PxU32 maxIndex = supportVertexIndex(dir_); index = PxI32(maxIndex); //p is in the shape space return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[index])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir from b space to the shape space of a space // const Vec3V dir_ = aTob.rotateInv(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V dir_ = aTobT.rotate(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V p = supportLocal(dir_, index); //transfrom from a to b space return aTob.transform(p); } aos::Mat33V vertex2Shape;//inv(R)*S*R aos::Mat33V shape2Vertex;//inv(vertex2Shape) const Gu::ConvexHullData* hullData; const BigConvexRawData* data; const PxVec3* verts; PxU8 numVerts; }; } } #endif //
18,982
C
34.088725
229
0.715783
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecCapsule.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CAPSULE_H #define GU_VEC_CAPSULE_H /** \addtogroup geomutils @{ */ #include "geometry/PxCapsuleGeometry.h" #include "GuVecConvex.h" #include "GuConvexSupportTable.h" namespace physx { namespace Gu { PX_FORCE_INLINE aos::FloatV CalculateCapsuleMinMargin(const aos::FloatVArg radius) { using namespace aos; const FloatV ratio = aos::FLoad(0.05f); return FMul(radius, ratio); } class CapsuleV : public ConvexV { public: /** \brief Constructor */ PX_INLINE CapsuleV():ConvexV(ConvexType::eCAPSULE) { bMarginIsRadius = true; } //constructor for sphere PX_INLINE CapsuleV(const aos::Vec3VArg p, const aos::FloatVArg radius_) : ConvexV(ConvexType::eCAPSULE) { using namespace aos; center = p; radius = radius_; p0 = p; p1 = p; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } PX_INLINE CapsuleV(const aos::Vec3VArg center_, const aos::Vec3VArg v_, const aos::FloatVArg radius_) : ConvexV(ConvexType::eCAPSULE, center_) { using namespace aos; radius = radius_; p0 = V3Add(center_, v_); p1 = V3Sub(center_, v_); FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } PX_INLINE CapsuleV(const PxGeometry& geom) : ConvexV(ConvexType::eCAPSULE, aos::V3Zero()) { using namespace aos; const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); const Vec3V axis = V3Scale(V3UnitX(), FLoad(capsuleGeom.halfHeight)); const FloatV r = FLoad(capsuleGeom.radius); p0 = axis; p1 = V3Neg(axis); radius = r; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } /** \brief Constructor \param _radius Radius of the capsule. */ /** \brief Destructor */ PX_INLINE ~CapsuleV() { } PX_FORCE_INLINE void initialize(const aos::Vec3VArg _p0, const aos::Vec3VArg _p1, const aos::FloatVArg _radius) { using namespace aos; radius = _radius; p0 = _p0; p1 = _p1; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); center = V3Scale(V3Add(_p0, _p1), FHalf()); } PX_INLINE aos::Vec3V computeDirection() const { return aos::V3Sub(p1, p0); } PX_FORCE_INLINE aos::FloatV getRadius() const { return radius; } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return (&p0)[1-index]; } PX_FORCE_INLINE void getIndex(const aos::BoolV con, PxI32& index)const { using namespace aos; const VecI32V v = VecI32V_From_BoolV(con); const VecI32V t = VecI32V_And(v, VecI32V_One()); PxI32_From_VecI32V(t, &index); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; p0 = V3Add(p0, offset); p1 = V3Add(p1, offset); } //dir, p0 and p1 are in the local space of dir PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; //const Vec3V _dir = V3Normalize(dir); const FloatV dist0 = V3Dot(p0, dir); const FloatV dist1 = V3Dot(p1, dir); return V3Sel(FIsGrtr(dist0, dist1), p0, p1); } PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the local space of a // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); const Vec3V p = supportLocal(_dir); //transform p back to the local space of b return aToB.transform(p); } //dir, p0 and p1 are in the local space of dir PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; const FloatV dist0 = V3Dot(p0, dir); const FloatV dist1 = V3Dot(p1, dir); const BoolV comp = FIsGrtr(dist0, dist1); getIndex(comp, index); return V3Sel(comp, p0, p1); } PX_FORCE_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir into the local space of a // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); const Vec3V p = supportLocal(_dir, index); //transform p back to the local space of b return aToB.transform(p); } PX_FORCE_INLINE aos::Vec3V supportLocal(aos::Vec3V& support, const PxI32& index, const aos::BoolV comp)const { PX_UNUSED(index); using namespace aos; const Vec3V p = V3Sel(comp, p0, p1); support = p; return p; } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FZero(); } //don't change the order of p0 and p1, the getPoint function depend on the order aos::Vec3V p0; //!< Start of segment aos::Vec3V p1; //!< End of segment aos::FloatV radius; }; } } #endif
6,770
C
27.56962
144
0.691581
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKType.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKTYPE_H #define GU_GJKTYPE_H #include "GuVecConvex.h" #include "foundation/PxVecTransform.h" namespace physx { namespace Gu { class ConvexHullV; class ConvexHullNoScaleV; class BoxV; template <typename Convex> struct ConvexGeom { typedef Convex Type; }; template <> struct ConvexGeom<ConvexHullV> { typedef ConvexHullV Type; }; template <> struct ConvexGeom<ConvexHullNoScaleV> { typedef ConvexHullNoScaleV Type; }; template <> struct ConvexGeom<BoxV> { typedef BoxV Type; }; struct GjkConvex { GjkConvex(const ConvexV& convex) : mConvex(convex) {} virtual ~GjkConvex() {} PX_FORCE_INLINE aos::FloatV getMinMargin() const { return mConvex.getMinMargin(); } PX_FORCE_INLINE aos::BoolV isMarginEqRadius() const { return mConvex.isMarginEqRadius(); } PX_FORCE_INLINE bool getMarginIsRadius() const { return mConvex.getMarginIsRadius(); } PX_FORCE_INLINE aos::FloatV getMargin() const { return mConvex.getMargin(); } template <typename Convex> PX_FORCE_INLINE const Convex& getConvex() const { return static_cast<const Convex&>(mConvex); } virtual aos::Vec3V supportPoint(const PxI32 index) const { return doVirtualSupportPoint(index); } virtual aos::Vec3V support(const aos::Vec3VArg v) const { return doVirtualSupport(v); } virtual aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return doVirtualSupport(dir, index); } virtual aos::FloatV getSweepMargin() const { return doVirtualGetSweepMargin(); } virtual aos::Vec3V getCenter() const = 0; protected: const ConvexV& mConvex; private: // PT: following functions call the v-table. I think this curious pattern is needed for the de-virtualization // approach used in the GJK code, combined with the GuGJKTest file that is only used externally. aos::Vec3V doVirtualSupportPoint(const PxI32 index) const { return supportPoint(index); } aos::Vec3V doVirtualSupport(const aos::Vec3VArg v) const { return support(v); } aos::Vec3V doVirtualSupport(const aos::Vec3VArg dir, PxI32& index) const { return support(dir, index); } aos::FloatV doVirtualGetSweepMargin() const { return getSweepMargin(); } //PX_NOCOPY(GjkConvex) GjkConvex& operator = (const GjkConvex&); }; template <typename Convex> struct LocalConvex : public GjkConvex { LocalConvex(const Convex& convex) : GjkConvex(convex){} // PT: I think we omit the virtual on purpose here, for the de-virtualization approach, i.e. the code calls these // functions directly (bypassing the v-table). In fact I think we don't need virtuals at all here, it's probably // only for external cases and/or cases where we want to reduce code size. // The mix of virtual/force-inline/inline below is confusing/unclear. // GjkConvex PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index) const { return getConvex<Convex>().supportPoint(index); } aos::Vec3V support(const aos::Vec3VArg v) const { return getConvex<Convex>().supportLocal(v); } aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return getConvex<Convex>().supportLocal(dir, index); } PX_INLINE aos::FloatV getSweepMargin() const { return getConvex<Convex>().getSweepMargin(); } virtual aos::Vec3V getCenter() const { return getConvex<Convex>().getCenter(); } //~GjkConvex //ML: we can't force inline function, otherwise win modern will throw compiler error PX_INLINE LocalConvex<typename ConvexGeom<Convex>::Type > getGjkConvex() const { return LocalConvex<typename ConvexGeom<Convex>::Type >(static_cast<const typename ConvexGeom<Convex>::Type&>(GjkConvex::mConvex)); } typedef LocalConvex<typename ConvexGeom<Convex>::Type > ConvexGeomType; typedef Convex Type; private: //PX_NOCOPY(LocalConvex<Convex>) LocalConvex<Convex>& operator = (const LocalConvex<Convex>&); }; template <typename Convex> struct RelativeConvex : public GjkConvex { RelativeConvex(const Convex& convex, const aos::PxMatTransformV& aToB) : GjkConvex(convex), mAToB(aToB), mAToBTransposed(aToB) { aos::V3Transpose(mAToBTransposed.rot.col0, mAToBTransposed.rot.col1, mAToBTransposed.rot.col2); } // GjkConvex PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index) const { return mAToB.transform(getConvex<Convex>().supportPoint(index)); } aos::Vec3V support(const aos::Vec3VArg v) const { return getConvex<Convex>().supportRelative(v, mAToB, mAToBTransposed); } aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return getConvex<Convex>().supportRelative(dir, mAToB, mAToBTransposed, index); } PX_INLINE aos::FloatV getSweepMargin() const { return getConvex<Convex>().getSweepMargin(); } virtual aos::Vec3V getCenter() const { return mAToB.transform(getConvex<Convex>().getCenter()); } //~GjkConvex PX_FORCE_INLINE const aos::PxMatTransformV& getRelativeTransform() const { return mAToB; } //ML: we can't force inline function, otherwise win modern will throw compiler error PX_INLINE RelativeConvex<typename ConvexGeom<Convex>::Type > getGjkConvex() const { return RelativeConvex<typename ConvexGeom<Convex>::Type >(static_cast<const typename ConvexGeom<Convex>::Type&>(GjkConvex::mConvex), mAToB); } typedef RelativeConvex<typename ConvexGeom<Convex>::Type > ConvexGeomType; typedef Convex Type; private: //PX_NOCOPY(RelativeConvex<Convex>) RelativeConvex<Convex>& operator = (const RelativeConvex<Convex>&); const aos::PxMatTransformV& mAToB; aos::PxMatTransformV mAToBTransposed; // PT: precomputed mAToB transpose (because 'rotate' is faster than 'rotateInv') }; } } #endif
7,447
C
47.051613
153
0.731301
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvexHullNoScale.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEXHULL_NOSCALE_H #define GU_VEC_CONVEXHULL_NOSCALE_H #include "foundation/PxUnionCast.h" #include "common/PxPhysXCommonConfig.h" #include "GuVecConvexHull.h" namespace physx { namespace Gu { class ConvexHullNoScaleV : public ConvexHullV { public: /** \brief Constructor */ PX_SUPPORT_INLINE ConvexHullNoScaleV(): ConvexHullV() { } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { using namespace aos; return V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //This funcation is just to load the PxVec3 to Vec3V. However, for GuVecConvexHul.h, this is used to transform all the verts from vertex space to shape space PX_SUPPORT_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts_)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) verts_[i] = V3LoadU_SafeReadW(originalVerts[inds[i]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'populateVerts' is always called with polyData.mVerts) } //This function is used in epa //dir is in the shape space PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; const PxU32 maxIndex = supportVertexIndex(dir); return V3LoadU_SafeReadW(verts[maxIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this is used in the sat test for the full contact gen PX_SUPPORT_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { supportVertexMinMax(dir, min, max); } //This function is used in epa PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the shape space const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir); const Vec3V maxPoint = supportLocal(_dir); //translate maxPoint from shape space of a back to the b space return aTob.transform(maxPoint);//relTra.transform(maxPoint); } //dir in the shape space, this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; //scale dir and put it in the vertex space, for non-uniform scale, we don't want the scale in the dir, therefore, we are using //the transpose of the inverse of shape2Vertex(which is vertex2shape). This will allow us igore the scale and keep the rotation //get the extreme point index const PxU32 maxIndex = supportVertexIndex(dir); index = PxI32(maxIndex); return V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir from b space to the shape space of a space const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V p = supportLocal(_dir, index); //transfrom from a to b space return aTob.transform(p); } PX_SUPPORT_INLINE void bruteForceSearchMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //brute force //get the support point from the orignal margin FloatV _max = V3Dot(V3LoadU_SafeReadW(verts[0]), _dir); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) FloatV _min = _max; for(PxU32 i = 1; i < numVerts; ++i) { PxPrefetchLine(&verts[i], 128); const Vec3V vertex = V3LoadU_SafeReadW(verts[i]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const FloatV dist = V3Dot(vertex, _dir); _max = FMax(dist, _max); _min = FMin(dist, _min); } min = _min; max = _max; } //This function support no scaling, dir is in the shape space(the same as vertex space) PX_SUPPORT_INLINE void supportVertexMinMax(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; if(data) { const PxU32 maxIndex= hillClimbing(dir); const PxU32 minIndex= hillClimbing(V3Neg(dir)); const Vec3V maxPoint= V3LoadU_SafeReadW(verts[maxIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const Vec3V minPoint= V3LoadU_SafeReadW(verts[minIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) min = V3Dot(dir, minPoint); max = V3Dot(dir, maxPoint); } else { bruteForceSearchMinMax(dir, min, max); } } }; #define PX_CONVEX_TO_NOSCALECONVEX(x) (static_cast<const ConvexHullNoScaleV*>(x)) } } #endif //
7,126
C
41.933735
205
0.731827
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEX_H #define GU_VEC_CONVEX_H #include "foundation/PxVecMath.h" #define PX_SUPPORT_INLINE PX_FORCE_INLINE #define PX_SUPPORT_FORCE_INLINE PX_FORCE_INLINE namespace physx { namespace Gu { struct ConvexType { enum Type { eCONVEXHULL, eCONVEXHULLNOSCALE, eSPHERE, eBOX, eCAPSULE, eTRIANGLE, eTETRAHEDRON, eCUSTOM }; }; class ConvexV { public: PX_FORCE_INLINE ConvexV(const ConvexType::Type type_) : type(type_), bMarginIsRadius(false) { margin = 0.f; minMargin = 0.f; sweepMargin = 0.f; center = aos::V3Zero(); } PX_FORCE_INLINE ConvexV(const ConvexType::Type type_, const aos::Vec3VArg center_) : type(type_), bMarginIsRadius(false) { using namespace aos; center = center_; margin = 0.f; minMargin = 0.f; sweepMargin = 0.f; } //everytime when someone transform the object, they need to up PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { center = _center; } PX_FORCE_INLINE void setMargin(const aos::FloatVArg margin_) { aos::FStore(margin_, &margin); } PX_FORCE_INLINE void setMargin(const PxReal margin_) { margin = margin_; } PX_FORCE_INLINE void setMinMargin(const aos::FloatVArg minMargin_) { aos::FStore(minMargin_, & minMargin); } PX_FORCE_INLINE void setSweepMargin(const aos::FloatVArg sweepMargin_) { aos::FStore(sweepMargin_, &sweepMargin); } PX_FORCE_INLINE aos::Vec3V getCenter()const { return center; } PX_FORCE_INLINE aos::FloatV getMargin() const { return aos::FLoad(margin); } PX_FORCE_INLINE aos::FloatV getMinMargin() const { return aos::FLoad(minMargin); } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FLoad(sweepMargin); } PX_FORCE_INLINE ConvexType::Type getType() const { return type; } PX_FORCE_INLINE aos::BoolV isMarginEqRadius()const { return aos::BLoad(bMarginIsRadius); } PX_FORCE_INLINE bool getMarginIsRadius() const { return bMarginIsRadius; } PX_FORCE_INLINE PxReal getMarginF() const { return margin; } protected: ~ConvexV(){} aos::Vec3V center; PxReal margin; //margin is the amount by which we shrunk the shape for a convex or box. If the shape are sphere/capsule, margin is the radius PxReal minMargin; //minMargin is some percentage of marginBase, which is used to determine the termination condition for gjk PxReal sweepMargin; //sweepMargin minMargin is some percentage of marginBase, which is used to determine the termination condition for gjkRaycast ConvexType::Type type; bool bMarginIsRadius; }; PX_FORCE_INLINE aos::FloatV getContactEps(const aos::FloatV& _marginA, const aos::FloatV& _marginB) { using namespace aos; const FloatV ratio = FLoad(0.25f); const FloatV minMargin = FMin(_marginA, _marginB); return FMul(minMargin, ratio); } PX_FORCE_INLINE aos::FloatV getSweepContactEps(const aos::FloatV& _marginA, const aos::FloatV& _marginB) { using namespace aos; const FloatV ratio = FLoad(100.f); const FloatV minMargin = FAdd(_marginA, _marginB); return FMul(minMargin, ratio); } } } #endif
4,864
C
26.027778
149
0.717722
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPA.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_EPA_H #define GU_EPA_H #include "GuGJKUtil.h" #include "GuGJKType.h" namespace physx { namespace Gu { //ML: The main entry point for EPA. // //This function returns one of three status codes: //(1)EPA_FAIL: the algorithm failed to create a valid polytope(the origin wasn't inside the polytope) from the input simplex. //(2)EPA_CONTACT : the algorithm found the MTD and converged successfully. //(3)EPA_DEGENERATE: the algorithm cannot make further progress and the result is unknown. GjkStatus epaPenetration( const GjkConvex& a, //convex a in the space of convex b const GjkConvex& b, //convex b const PxU8* PX_RESTRICT aInd, //warm start index for convex a to create an initial simplex const PxU8* PX_RESTRICT bInd, //warm start index for convex b to create an initial simplex const PxU8 size, //number of warm-start indices const bool takeCoreShape, //indicates whether we take support point from the core shape or surface of capsule/sphere const aos::FloatV tolerenceLength, //the length of meter GjkOutput& output); //result GjkStatus epaPenetration( const GjkConvex& a, //convex a in the space of convex b const GjkConvex& b, //convex b const aos::Vec3V* PX_RESTRICT aPnt, //warm start point for convex a to create an initial simplex const aos::Vec3V* PX_RESTRICT bPnt, //warm start point for convex b to create an initial simplex const PxU8 size, //number of warm-start indices const bool takeCoreShape, //indicates whether we take support point from the core shape or surface of capsule/sphere const aos::FloatV tolerenceLength, //the length of meter GjkOutput& output); //result } } #endif
3,542
C
50.347825
127
0.718238
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecSphere.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_SPHERE_H #define GU_VEC_SPHERE_H /** \addtogroup geomutils @{ */ #include "geometry/PxSphereGeometry.h" #include "GuVecConvex.h" #include "GuConvexSupportTable.h" /** \brief Represents a sphere defined by its center point and radius. */ namespace physx { namespace Gu { class SphereV : public ConvexV { public: /** \brief Constructor */ PX_INLINE SphereV(): ConvexV(ConvexType::eSPHERE) { radius = aos::FZero(); bMarginIsRadius = true; } PX_INLINE SphereV(const aos::Vec3VArg _center, const aos::FloatV _radius) : ConvexV(ConvexType::eSPHERE, _center) { using namespace aos; radius = _radius; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } /** \brief Copy constructor */ PX_INLINE SphereV(const SphereV& sphere) : ConvexV(ConvexType::eSPHERE), radius(sphere.radius) { margin = sphere.margin; minMargin = sphere.minMargin; sweepMargin = sphere.sweepMargin; bMarginIsRadius = true; } PX_INLINE SphereV(const PxGeometry& geom) : ConvexV(ConvexType::eSPHERE, aos::V3Zero()) { using namespace aos; const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); const FloatV r = FLoad(sphereGeom.radius); radius = r; margin = sphereGeom.radius; minMargin = sphereGeom.radius; sweepMargin = sphereGeom.radius; bMarginIsRadius = true; } /** \brief Destructor */ PX_INLINE ~SphereV() { } PX_INLINE void setV(const aos::Vec3VArg _center, const aos::FloatVArg _radius) { center = _center; radius = _radius; } /** \brief Checks the sphere is valid. \return true if the sphere is valid */ PX_INLINE bool isValid() const { // Consistency condition for spheres: Radius >= 0.0f using namespace aos; return BAllEqTTTT(FIsGrtrOrEq(radius, FZero())) != 0; } /** \brief Tests if a point is contained within the sphere. \param[in] p the point to test \return true if inside the sphere */ PX_INLINE bool contains(const aos::Vec3VArg p) const { using namespace aos; const FloatV rr = FMul(radius, radius); const FloatV cc = V3LengthSq(V3Sub(center, p)); return FAllGrtrOrEq(rr, cc) != 0; } /** \brief Tests if a sphere is contained within the sphere. \param sphere [in] the sphere to test \return true if inside the sphere */ PX_INLINE bool contains(const SphereV& sphere) const { using namespace aos; const Vec3V centerDif= V3Sub(center, sphere.center); const FloatV radiusDif = FSub(radius, sphere.radius); const FloatV cc = V3Dot(centerDif, centerDif); const FloatV rr = FMul(radiusDif, radiusDif); const BoolV con0 = FIsGrtrOrEq(radiusDif, FZero());//might contain const BoolV con1 = FIsGrtr(rr, cc);//return true return BAllEqTTTT(BAnd(con0, con1))==1; } /** \brief Tests if a box is contained within the sphere. \param minimum [in] minimum value of the box \param maximum [in] maximum value of the box \return true if inside the sphere */ PX_INLINE bool contains(const aos::Vec3VArg minimum, const aos::Vec3VArg maximum) const { //compute the sphere which wrap around the box using namespace aos; const FloatV zero = FZero(); const FloatV half = FHalf(); const Vec3V boxSphereCenter = V3Scale(V3Add(maximum, minimum), half); const Vec3V v = V3Scale(V3Sub(maximum, minimum), half); const FloatV boxSphereR = V3Length(v); const Vec3V w = V3Sub(center, boxSphereCenter); const FloatV wLength = V3Length(w); const FloatV dif = FSub(FSub(radius, wLength), boxSphereR); return FAllGrtrOrEq(dif, zero) != 0; } /** \brief Tests if the sphere intersects another sphere \param sphere [in] the other sphere \return true if spheres overlap */ PX_INLINE bool intersect(const SphereV& sphere) const { using namespace aos; const Vec3V centerDif = V3Sub(center, sphere.center); const FloatV cc = V3Dot(centerDif, centerDif); const FloatV r = FAdd(radius, sphere.radius); const FloatV rr = FMul(r, r); return FAllGrtrOrEq(rr, cc) != 0; } //return point in local space PX_FORCE_INLINE aos::Vec3V getPoint(const PxU8) { return aos::V3Zero(); } // //sweep code need to have full version PX_FORCE_INLINE aos::Vec3V supportSweep(const aos::Vec3VArg dir)const { using namespace aos; const Vec3V _dir = V3Normalize(dir); return V3ScaleAdd(_dir, radius, center); } //make the support function the same as support margin PX_FORCE_INLINE aos::Vec3V support(const aos::Vec3VArg)const { return center;//_margin is the same as radius } PX_FORCE_INLINE aos::Vec3V supportMargin(const aos::Vec3VArg dir, const aos::FloatVArg _margin, aos::Vec3V& support)const { PX_UNUSED(_margin); PX_UNUSED(dir); support = center; return center;//_margin is the same as radius } PX_FORCE_INLINE aos::BoolV isMarginEqRadius()const { return aos::BTTTT(); } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FZero(); } aos::FloatV radius; //!< Sphere's center, w component is radius }; } } #endif
6,911
C
27.444444
123
0.698452
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecTriangle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_TRIANGLE_H #define GU_VEC_TRIANGLE_H /** \addtogroup geomutils @{ */ #include "GuVecConvex.h" #include "GuConvexSupportTable.h" #include "GuDistancePointTriangle.h" namespace physx { namespace Gu { class TriangleV : public ConvexV { public: /** \brief Constructor */ PX_FORCE_INLINE TriangleV() : ConvexV(ConvexType::eTRIANGLE) { margin = 0.02f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Constructor \param[in] p0 Point 0 \param[in] p1 Point 1 \param[in] p2 Point 2 */ PX_FORCE_INLINE TriangleV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2): ConvexV(ConvexType::eTRIANGLE) { using namespace aos; //const FloatV zero = FZero(); const FloatV num = FLoad(0.333333f); center = V3Scale(V3Add(V3Add(p0, p1), p2), num); verts[0] = p0; verts[1] = p1; verts[2] = p2; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } PX_FORCE_INLINE TriangleV(const PxVec3* pts) : ConvexV(ConvexType::eTRIANGLE) { using namespace aos; const Vec3V p0 = V3LoadU(pts[0]); const Vec3V p1 = V3LoadU(pts[1]); const Vec3V p2 = V3LoadU(pts[2]); const FloatV num = FLoad(0.333333f); center = V3Scale(V3Add(V3Add(p0, p1), p2), num); verts[0] = p0; verts[1] = p1; verts[2] = p2; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Copy constructor \param[in] triangle Tri to copy */ PX_FORCE_INLINE TriangleV(const Gu::TriangleV& triangle) : ConvexV(ConvexType::eTRIANGLE) { using namespace aos; verts[0] = triangle.verts[0]; verts[1] = triangle.verts[1]; verts[2] = triangle.verts[2]; center = triangle.center; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Destructor */ PX_FORCE_INLINE ~TriangleV() { } PX_FORCE_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* vertexs)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) { vertexs[i] = V3LoadU(originalVerts[inds[i]]); } } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FMax(); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; verts[0] = V3Add(verts[0], offset); verts[1] = V3Add(verts[1], offset); verts[2] = V3Add(verts[2], offset); } /** \brief Compute the normal of the Triangle. \return Triangle normal. */ PX_FORCE_INLINE aos::Vec3V normal() const { using namespace aos; const Vec3V ab = V3Sub(verts[1], verts[0]); const Vec3V ac = V3Sub(verts[2], verts[0]); const Vec3V n = V3Cross(ab, ac); return V3Normalize(n); } /** \brief Compute the unnormalized normal of the Triangle. \param[out] _normal Triangle normal (not normalized). */ PX_FORCE_INLINE void denormalizedNormal(aos::Vec3V& _normal) const { using namespace aos; const Vec3V ab = V3Sub(verts[1], verts[0]); const Vec3V ac = V3Sub(verts[2], verts[0]); _normal = V3Cross(ab, ac); } PX_FORCE_INLINE aos::FloatV area() const { using namespace aos; const FloatV half = FLoad(0.5f); const Vec3V ba = V3Sub(verts[0], verts[1]); const Vec3V ca = V3Sub(verts[0], verts[2]); const Vec3V v = V3Cross(ba, ca); return FMul(V3Length(v), half); } //dir is in local space, verts in the local space PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir) const { using namespace aos; const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; const FloatV d0 = V3Dot(v0, dir); const FloatV d1 = V3Dot(v1, dir); const FloatV d2 = V3Dot(v2, dir); const BoolV con0 = BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)); const BoolV con1 = FIsGrtr(d1, d2); return V3Sel(con0, v0, V3Sel(con1, v1, v2)); } PX_FORCE_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const { using namespace aos; const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; FloatV d0 = V3Dot(v0, dir); FloatV d1 = V3Dot(v1, dir); FloatV d2 = V3Dot(v2, dir); max = FMax(d0, FMax(d1, d2)); min = FMin(d0, FMin(d1, d2)); } //dir is in b space PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //verts are in local space // const Vec3V _dir = aToB.rotateInv(dir); //transform dir back to a space const Vec3V _dir = aTobT.rotate(dir); //transform dir back to a space const Vec3V maxPoint = supportLocal(_dir); return aToB.transform(maxPoint);//transform maxPoint to the b space } PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index) const { using namespace aos; const VecI32V vZero = VecI32V_Zero(); const VecI32V vOne = VecI32V_One(); const VecI32V vTwo = VecI32V_Two(); const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; const FloatV d0 = V3Dot(v0, dir); const FloatV d1 = V3Dot(v1, dir); const FloatV d2 = V3Dot(v2, dir); const BoolV con0 = BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)); const BoolV con1 = FIsGrtr(d1, d2); const VecI32V vIndex = VecI32V_Sel(con0, vZero, VecI32V_Sel(con1, vOne, vTwo)); PxI32_From_VecI32V(vIndex, &index); return V3Sel(con0, v0, V3Sel(con1, v1, v2)); } PX_FORCE_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { //don't put margin in the triangle using namespace aos; //transfer dir into the local space of triangle // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); return aToB.transform(supportLocal(_dir, index));//transform the support poin to b space } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return verts[index]; } /** \brief Array of Vertices. */ aos::Vec3V verts[3]; }; } } #endif
7,925
C
28.574627
144
0.674322
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJK.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJK_H #define GU_GJK_H #include "GuGJKType.h" #include "GuGJKUtil.h" #include "GuConvexSupportTable.h" #include "GuGJKSimplex.h" #include "foundation/PxFPU.h" #define GJK_SEPERATING_AXIS_VALIDATE 0 namespace physx { namespace Gu { class ConvexV; #if GJK_SEPERATING_AXIS_VALIDATE template<typename ConvexA, typename ConvexB> static void validateSeparatingAxis(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg separatingAxis) { using namespace aos; const Vec3V minV0 = a.ConvexA::support(V3Neg(separatingAxis)); const Vec3V maxV0 = a.ConvexA::support(separatingAxis); const Vec3V minV1 = b.ConvexB::support(V3Neg(separatingAxis)); const Vec3V maxV1 = b.ConvexB::support(separatingAxis); const FloatV min0 = V3Dot(minV0, separatingAxis); const FloatV max0 = V3Dot(maxV0, separatingAxis); const FloatV min1 = V3Dot(minV1, separatingAxis); const FloatV max1 = V3Dot(maxV1, separatingAxis); PX_ASSERT(FAllGrtr(min1, max0) || FAllGrtr(min0, max1)); } #endif /* initialSearchDir :initial search direction in the mincowsky sum, it should be in the local space of ConvexB closestA :it is the closest point in ConvexA in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage closestB :it is the closest point in ConvexB in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage normal :normal pointing from ConvexA to ConvexB in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage distance :the distance of the closest points between ConvexA and ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage contactDist :the distance which we will generate contact information if ConvexA and ConvexB are both separated within contactDist */ //*Each convex has //* a support function //* a margin - the amount by which we shrunk the shape for a convex or box. If the shape are sphere/capsule, margin is the radius //* a minMargin - some percentage of margin, which is used to determine the termination condition for gjk //*We'll report: //* GJK_NON_INTERSECT if the sign distance between the shapes is greater than the sum of the margins and the the contactDistance //* GJK_CLOSE if the minimum distance between the shapes is less than the sum of the margins and the the contactDistance //* GJK_CONTACT if the two shapes are overlapped with each other template<typename ConvexA, typename ConvexB> GjkStatus gjk(const ConvexA& a, const ConvexB& b, const aos::Vec3V& initialSearchDir, const aos::FloatV& contactDist, aos::Vec3V& closestA, aos::Vec3V& closestB, aos::Vec3V& normal, aos::FloatV& distance) { using namespace aos; Vec3V Q[4]; Vec3V A[4]; Vec3V B[4]; const FloatV zero = FZero(); PxU32 size=0; //const Vec3V _initialSearchDir = aToB.p; Vec3V closest = V3Sel(FIsGrtr(V3Dot(initialSearchDir, initialSearchDir), zero), initialSearchDir, V3UnitX()); Vec3V v = V3Normalize(closest); // ML: eps2 is the square value of an epsilon value which applied in the termination condition for two shapes overlap. // GJK will terminate based on sq(v) < eps and indicate that two shapes are overlapping. // we calculate the eps based on 10% of the minimum margin of two shapes const FloatV tenPerc = FLoad(0.1f); const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin()); const FloatV eps = FMax(FLoad(1e-6f), FMul(minMargin, tenPerc)); // ML:epsRel is square value of 1.5% which applied to the distance of a closest point(v) to the origin. // If |v|- v/|v|.dot(w) < epsRel*|v|, // two shapes are clearly separated, GJK terminate and return non intersect. // This adjusts the termination condition based on the length of v // which avoids ill-conditioned terminations. const FloatV epsRel = FLoad(0.000225f);//1.5%. FloatV dist = FMax(); FloatV prevDist; Vec3V prevClos, prevDir; const BoolV bTrue = BTTTT(); BoolV bNotTerminated = bTrue; BoolV bNotDegenerated = bTrue; //ML: we treate sphere as a point and capsule as segment in the support function, so that we need to add on radius const BoolV aQuadratic = a.isMarginEqRadius(); const BoolV bQuadratic = b.isMarginEqRadius(); const FloatV sumMargin = FAdd(FSel(aQuadratic, a.getMargin(), zero), FSel(bQuadratic, b.getMargin(), zero)); const FloatV separatingDist = FAdd(sumMargin, contactDist); const FloatV relDif = FSub(FOne(), epsRel); do { prevDist = dist; prevClos = closest; prevDir = v; //de-virtualize, we don't need to use a normalize direction to get the support point //this will allow the cpu better pipeline the normalize calculation while it does the //support map const Vec3V supportA=a.ConvexA::support(V3Neg(closest)); const Vec3V supportB=b.ConvexB::support(closest); //calculate the support point const Vec3V support = V3Sub(supportA, supportB); const FloatV signDist = V3Dot(v, support); if(FAllGrtr(signDist, separatingDist)) { //ML:gjk found a separating axis for these two objects and the distance is large than the seperating distance, gjk might not converage so that //we won't generate contact information #if GJK_SEPERATING_AXIS_VALIDATE validateSeparatingAxis(a, b, v); #endif return GJK_NON_INTERSECT; } const BoolV con = BAnd(FIsGrtr(signDist, sumMargin), FIsGrtr(signDist, FMul(relDif, dist))); if(BAllEqTTTT(con)) { //ML:: gjk converage and we get the closest point information Vec3V closA, closB; //normal point from A to B const Vec3V n = V3Neg(v); getClosestPoint(Q, A, B, closest, closA, closB, size); closestA = V3Sel(aQuadratic, V3ScaleAdd(n, a.getMargin(), closA), closA); closestB = V3Sel(bQuadratic, V3NegScaleSub(n, b.getMargin(), closB), closB); distance = FMax(zero, FSub(dist, sumMargin)); normal = n;//V3Normalize(V3Neg(closest)); return GJK_CLOSE; } PX_ASSERT(size < 4); A[size]=supportA; B[size]=supportB; Q[size++]=support; //calculate the closest point between two convex hull closest = GJKCPairDoSimplex(Q, A, B, support, size); dist = V3Length(closest); v = V3ScaleInv(closest, dist); bNotDegenerated = FIsGrtr(prevDist, dist); bNotTerminated = BAnd(FIsGrtr(dist, eps), bNotDegenerated); }while(BAllEqTTTT(bNotTerminated)); if(BAllEqTTTT(bNotDegenerated)) { //GJK_CONTACT distance = zero; return GJK_CONTACT; } //GJK degenerated, use the previous closest point const FloatV acceptancePerc = FLoad(0.2f); const FloatV acceptanceMargin = FMul(acceptancePerc, FMin(a.getMargin(), b.getMargin())); const FloatV acceptanceDist = FSel(FIsGrtr(sumMargin, zero), sumMargin, acceptanceMargin); Vec3V closA, closB; const Vec3V n = V3Neg(prevDir);//V3Normalize(V3Neg(prevClos)); getClosestPoint(Q, A, B, prevClos, closA, closB, size); closestA = V3Sel(aQuadratic, V3ScaleAdd(n, a.getMargin(), closA), closA); closestB = V3Sel(bQuadratic, V3NegScaleSub(n, b.getMargin(), closB), closB); normal = n; dist = FMax(zero, FSub(prevDist, sumMargin)); distance = dist; return FAllGrtr(dist, acceptanceDist) ? GJK_CLOSE: GJK_CONTACT; } } } #endif
9,035
C
40.260274
183
0.728943
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKRaycast.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKRAYCAST_H #define GU_GJKRAYCAST_H #include "GuGJKType.h" #include "GuGJKSimplex.h" #include "GuConvexSupportTable.h" #include "GuGJKPenetration.h" #include "GuEPA.h" namespace physx { namespace Gu { /* ConvexA is in the local space of ConvexB lambda : the time of impact(TOI) initialLambda : the start time of impact value (disable) s : the sweep ray origin r : the normalized sweep ray direction scaled by the sweep distance. r should be in ConvexB's space normal : the contact normal inflation : the amount by which we inflate the swept shape. If the inflated shapes aren't initially-touching, the TOI will return the time at which both shapes are at a distance equal to inflation separated. If inflation is 0 the TOI will return the time at which both shapes are touching. */ template<class ConvexA, class ConvexB> bool gjkRaycast(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation) { PX_UNUSED(initialLambda); using namespace aos; const FloatV inflation = FLoad(_inflation); const Vec3V zeroV = V3Zero(); const FloatV zero = FZero(); const FloatV one = FOne(); const BoolV bTrue = BTTTT(); const FloatV maxDist = FLoad(PX_MAX_REAL); FloatV _lambda = zero;//initialLambda; Vec3V x = V3ScaleAdd(r, _lambda, s); PxU32 size=1; //const Vec3V dir = V3Sub(a.getCenter(), b.getCenter()); const Vec3V _initialSearchDir = V3Sel(FIsGrtr(V3Dot(initialDir, initialDir), FEps()), initialDir, V3UnitX()); const Vec3V initialSearchDir = V3Normalize(_initialSearchDir); const Vec3V initialSupportA(a.ConvexA::support(V3Neg(initialSearchDir))); const Vec3V initialSupportB( b.ConvexB::support(initialSearchDir)); Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set Vec3V v = V3Neg(Q[0]); Vec3V supportA = initialSupportA; Vec3V supportB = initialSupportB; Vec3V support = Q[0]; const FloatV minMargin = FMin(a.ConvexA::getSweepMargin(), b.ConvexB::getSweepMargin()); const FloatV eps1 = FMul(minMargin, FLoad(0.1f)); const FloatV inflationPlusEps(FAdd(eps1, inflation)); const FloatV eps2 = FMul(eps1, eps1); const FloatV inflation2 = FMul(inflationPlusEps, inflationPlusEps); Vec3V clos(Q[0]); Vec3V preClos = clos; //Vec3V closA(initialSupportA); FloatV sDist = V3Dot(v, v); FloatV minDist = sDist; //Vec3V closAA = initialSupportA; //Vec3V closBB = initialSupportB; BoolV bNotTerminated = FIsGrtr(sDist, eps2); BoolV bNotDegenerated = bTrue; Vec3V nor = v; while(BAllEqTTTT(bNotTerminated)) { minDist = sDist; preClos = clos; const Vec3V vNorm = V3Normalize(v); const Vec3V nvNorm = V3Neg(vNorm); supportA=a.ConvexA::support(vNorm); supportB=V3Add(x, b.ConvexB::support(nvNorm)); //calculate the support point support = V3Sub(supportA, supportB); const Vec3V w = V3Neg(support); const FloatV vw = FSub(V3Dot(vNorm, w), inflationPlusEps); if(FAllGrtr(vw, zero)) { const FloatV vr = V3Dot(vNorm, r); if(FAllGrtrOrEq(vr, zero)) { return false; } else { const FloatV _oldLambda = _lambda; _lambda = FSub(_lambda, FDiv(vw, vr)); if(FAllGrtr(_lambda, _oldLambda)) { if(FAllGrtr(_lambda, one)) { return false; } const Vec3V bPreCenter = x; x = V3ScaleAdd(r, _lambda, s); const Vec3V offSet =V3Sub(x, bPreCenter); const Vec3V b0 = V3Add(B[0], offSet); const Vec3V b1 = V3Add(B[1], offSet); const Vec3V b2 = V3Add(B[2], offSet); B[0] = b0; B[1] = b1; B[2] = b2; Q[0]=V3Sub(A[0], b0); Q[1]=V3Sub(A[1], b1); Q[2]=V3Sub(A[2], b2); supportB = V3Add(x, b.ConvexB::support(nvNorm)); support = V3Sub(supportA, supportB); minDist = maxDist; nor = v; //size=0; } } } PX_ASSERT(size < 4); A[size]=supportA; B[size]=supportB; Q[size++]=support; //calculate the closest point between two convex hull clos = GJKCPairDoSimplex(Q, A, B, support, size); v = V3Neg(clos); sDist = V3Dot(clos, clos); bNotDegenerated = FIsGrtr(minDist, sDist); bNotTerminated = BAnd(FIsGrtr(sDist, inflation2), bNotDegenerated); } const BoolV aQuadratic = a.isMarginEqRadius(); //ML:if the Minkowski sum of two objects are too close to the original(eps2 > sDist), we can't take v because we will lose lots of precision. Therefore, we will take //previous configuration's normal which should give us a reasonable approximation. This effectively means that, when we do a sweep with inflation, we always keep v because //the shapes converge separated. If we do a sweep without inflation, we will usually use the previous configuration's normal. nor = V3Sel(BAnd(FIsGrtr(sDist, eps2), bNotDegenerated), v, nor); nor = V3Neg(V3NormalizeSafe(nor, V3Zero())); normal = nor; lambda = _lambda; const Vec3V closestP = V3Sel(bNotDegenerated, clos, preClos); Vec3V closA = zeroV, closB = zeroV; getClosestPoint(Q, A, B, closestP, closA, closB, size); closestA = V3Sel(aQuadratic, V3NegScaleSub(nor, a.getMargin(), closA), closA); return true; } /* ConvexA is in the local space of ConvexB lambda : the time of impact(TOI) initialLambda : the start time of impact value (disable) s : the sweep ray origin in ConvexB's space r : the normalized sweep ray direction scaled by the sweep distance. r should be in ConvexB's space normal : the contact normal in ConvexB's space closestA : the tounching contact in ConvexB's space inflation : the amount by which we inflate the swept shape. If the inflated shapes aren't initially-touching, the TOI will return the time at which both shapes are at a distance equal to inflation separated. If inflation is 0 the TOI will return the time at which both shapes are touching. */ template<class ConvexA, class ConvexB> bool gjkRaycastPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap) { using namespace aos; Vec3V closA; Vec3V norm; FloatV _lambda; if(gjkRaycast(a, b, initialDir, initialLambda, s, r, _lambda, norm, closA, _inflation)) { const FloatV zero = FZero(); lambda = _lambda; if(FAllEq(_lambda, zero) && initialOverlap) { //time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point const FloatV contactDist = getSweepContactEps(a.getMargin(), b.getMargin()); FloatV sDist(zero); PxU8 aIndices[4]; PxU8 bIndices[4]; PxU8 size=0; GjkOutput output; //PX_COMPILE_TIME_ASSERT(typename Shrink<ConvexB>::Type != Gu::BoxV); #ifdef USE_VIRTUAL_GJK GjkStatus status = gjkPenetration<ConvexA, ConvexB>(a, b, #else typename ConvexA::ConvexGeomType convexA = a.getGjkConvex(); typename ConvexB::ConvexGeomType convexB = b.getGjkConvex(); GjkStatus status = gjkPenetration<typename ConvexA::ConvexGeomType, typename ConvexB::ConvexGeomType>(convexA, convexB, #endif initialDir, contactDist, false, aIndices, bIndices, size, output); //norm = V3Neg(norm); if(status == GJK_CONTACT) { closA = output.closestA; sDist = output.penDep; norm = output.normal; } else if(status == EPA_CONTACT) { status = epaPenetration(a, b, aIndices, bIndices, size, false, FLoad(1.f), output); if (status == EPA_CONTACT || status == EPA_DEGENERATE) { closA = output.closestA; sDist = output.penDep; norm = output.normal; } else { //ML: if EPA fail, we will use the ray direction as the normal and set pentration to be zero closA = V3Zero(); sDist = zero; norm = V3Normalize(V3Neg(r)); } } else { //ML:: this will be gjk degenerate case. However, we can still //reply on the previous iteration's closest feature information closA = output.closestA; sDist = output.penDep; norm = output.normal; } lambda = FMin(zero, sDist); } closestA = closA; normal = norm; return true; } return false; } } } #endif
10,397
C
34.979239
254
0.692219
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKUtil.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKUTIL_H #define GU_GJKUTIL_H #include "foundation/PxVecMath.h" /* This file is used to avoid the inner loop cross DLL calls */ namespace physx { namespace Gu { enum GjkStatus { GJK_NON_INTERSECT, // two shapes doesn't intersect GJK_CLOSE, // two shapes doesn't intersect and gjk algorithm will return closest point information GJK_CONTACT, // two shapes overlap within margin GJK_UNDEFINED, // undefined status GJK_DEGENERATE, // gjk can't converage EPA_CONTACT, // two shapes intersect EPA_DEGENERATE, // epa can't converage EPA_FAIL // epa fail to construct an initial polygon to work with }; struct GjkOutput { public: GjkOutput() { using namespace aos; closestA = closestB = normal = V3Zero(); penDep = FZero(); } aos::Vec3V closestA; aos::Vec3V closestB; aos::Vec3V normal; aos::Vec3V searchDir; aos::FloatV penDep; }; }//Gu }//physx #endif
2,598
C
33.653333
101
0.747113
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKTest.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuGJK.h" #include "GuGJKRaycast.h" #include "GuGJKPenetration.h" #include "GuGJKTest.h" namespace physx { namespace Gu { using namespace aos; GjkStatus testGjk(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const FloatVArg contactDist, Vec3V& closestA, Vec3V& closestB, Vec3V& normal, FloatV& dist) { return gjk<GjkConvex, GjkConvex>(a, b, initialSearchDir, contactDist, closestA, closestB, normal, dist); } bool testGjkRaycast(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal inflation) { return gjkRaycast(a, b, initialSearchDir, initialLambda, s, r, lambda, normal, closestA, inflation); } GjkStatus testGjkPenetration(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const FloatVArg contactDist, PxU8* aIndices, PxU8* bIndices, PxU8& size, GjkOutput& output) { return gjkPenetration<GjkConvex, GjkConvex>(a, b, initialSearchDir, contactDist, true, aIndices, bIndices, size, output); } GjkStatus testEpaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* aIndices, const PxU8* bIndices, const PxU8 size, GjkOutput& output) { return epaPenetration(a, b, aIndices, bIndices, size, true, aos::FLoad(1.f), output); } } }
3,091
C++
45.149253
196
0.765448
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuFeatureCode.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuConvexEdgeFlags.h" #include "GuFeatureCode.h" using namespace physx; using namespace Gu; static FeatureCode computeFeatureCode(PxReal u, PxReal v) { // Analysis if(u==0.0f) { if(v==0.0f) { // Vertex 0 return FC_VERTEX0; } else if(v==1.0f) { // Vertex 2 return FC_VERTEX2; } else { // Edge 0-2 return FC_EDGE20; } } else if(u==1.0f) { if(v==0.0f) { // Vertex 1 return FC_VERTEX1; } } else { if(v==0.0f) { // Edge 0-1 return FC_EDGE01; } else { if((u+v)>=0.9999f) { // Edge 1-2 return FC_EDGE12; } else { // Face return FC_FACE; } } } return FC_UNDEFINED; } bool Gu::selectNormal(PxU8 data, PxReal u, PxReal v) { bool useFaceNormal = false; const FeatureCode FC = computeFeatureCode(u, v); switch(FC) { case FC_VERTEX0: if(!(data & (Gu::ETD_CONVEX_EDGE_01|Gu::ETD_CONVEX_EDGE_20))) useFaceNormal = true; break; case FC_VERTEX1: if(!(data & (Gu::ETD_CONVEX_EDGE_01|Gu::ETD_CONVEX_EDGE_12))) useFaceNormal = true; break; case FC_VERTEX2: if(!(data & (Gu::ETD_CONVEX_EDGE_12|Gu::ETD_CONVEX_EDGE_20))) useFaceNormal = true; break; case FC_EDGE01: if(!(data & Gu::ETD_CONVEX_EDGE_01)) useFaceNormal = true; break; case FC_EDGE12: if(!(data & Gu::ETD_CONVEX_EDGE_12)) useFaceNormal = true; break; case FC_EDGE20: if(!(data & Gu::ETD_CONVEX_EDGE_20)) useFaceNormal = true; break; case FC_FACE: useFaceNormal = true; break; case FC_UNDEFINED: break; }; return useFaceNormal; }
3,284
C++
24.664062
74
0.683009
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleCapsule.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuDistanceSegmentSegment.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" using namespace physx; bool Gu::contactCapsuleCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxCapsuleGeometry& capsuleGeom0 = checkedCast<PxCapsuleGeometry>(shape0); const PxCapsuleGeometry& capsuleGeom1 = checkedCast<PxCapsuleGeometry>(shape1); // PT: get capsules in local space PxVec3 dir[2]; Segment segment[2]; { const PxVec3 capsuleLocalSegment0 = getCapsuleHalfHeightVector(transform0, capsuleGeom0); const PxVec3 capsuleLocalSegment1 = getCapsuleHalfHeightVector(transform1, capsuleGeom1); const PxVec3 delta = transform1.p - transform0.p; segment[0].p0 = capsuleLocalSegment0; segment[0].p1 = -capsuleLocalSegment0; dir[0] = -capsuleLocalSegment0*2.0f; segment[1].p0 = capsuleLocalSegment1 + delta; segment[1].p1 = -capsuleLocalSegment1 + delta; dir[1] = -capsuleLocalSegment1*2.0f; } // PT: compute distance between capsules' segments PxReal s,t; const PxReal squareDist = distanceSegmentSegmentSquared(segment[0], segment[1], &s, &t); const PxReal radiusSum = capsuleGeom0.radius + capsuleGeom1.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; const PxReal inflatedSumSquared = inflatedSum*inflatedSum; if(squareDist >= inflatedSumSquared) return false; // PT: TODO: optimize this away PxReal segLen[2]; segLen[0] = dir[0].magnitude(); segLen[1] = dir[1].magnitude(); if (segLen[0]) dir[0] *= 1.0f / segLen[0]; if (segLen[1]) dir[1] *= 1.0f / segLen[1]; if (PxAbs(dir[0].dot(dir[1])) > 0.9998f) //almost parallel, ca. 1 degree difference --> generate two contact points at ends { PxU32 numCons = 0; PxReal segLenEps[2]; segLenEps[0] = segLen[0] * 0.001f;//0.1% error is ok. segLenEps[1] = segLen[1] * 0.001f; //project the two end points of each onto the axis of the other and take those 4 points. //we could also generate a single normal at the single closest point, but this would be 'unstable'. for (PxU32 destShapeIndex = 0; destShapeIndex < 2; destShapeIndex ++) { for (PxU32 startEnd = 0; startEnd < 2; startEnd ++) { const PxU32 srcShapeIndex = 1-destShapeIndex; //project start/end of srcShapeIndex onto destShapeIndex. PxVec3 pos[2]; pos[destShapeIndex] = startEnd ? segment[srcShapeIndex].p1 : segment[srcShapeIndex].p0; const PxReal p = dir[destShapeIndex].dot(pos[destShapeIndex] - segment[destShapeIndex].p0); if (p >= -segLenEps[destShapeIndex] && p <= (segLen[destShapeIndex] + segLenEps[destShapeIndex])) { pos[srcShapeIndex] = p * dir[destShapeIndex] + segment[destShapeIndex].p0; PxVec3 normal = pos[1] - pos[0]; const PxReal normalLenSq = normal.magnitudeSquared(); if (normalLenSq > 1e-6f && normalLenSq < inflatedSumSquared) { const PxReal distance = PxSqrt(normalLenSq); normal *= 1.0f/distance; PxVec3 point = pos[1] - normal * (srcShapeIndex ? capsuleGeom1 : capsuleGeom0).radius; point += transform0.p; contactBuffer.contact(point, normal, distance - radiusSum); numCons++; } } } } if (numCons) //if we did not have contacts, then we may have the case where they are parallel, but are stacked end to end, in which case the old code will generate good contacts. return true; } // Collision response PxVec3 pos1 = segment[0].getPointAt(s); PxVec3 pos2 = segment[1].getPointAt(t); PxVec3 normal = pos1 - pos2; const PxReal normalLenSq = normal.magnitudeSquared(); if (normalLenSq < 1e-6f) { // PT: TODO: revisit this. "FW" sounds old. // Zero normal -> pick the direction of segment 0. // Not always accurate but consistent with FW. if (segLen[0] > 1e-6f) normal = dir[0]; else normal = PxVec3(1.0f, 0.0f, 0.0f); } else { normal *= PxRecipSqrt(normalLenSq); } pos1 += transform0.p; contactBuffer.contact(pos1 - normal * capsuleGeom0.radius, normal, PxSqrt(squareDist) - radiusSum); return true; }
5,760
C++
37.664429
180
0.722743
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneConvex.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuConvexMeshData.h" #include "GuContactMethodImpl.h" #include "GuConvexMesh.h" #include "CmScaling.h" #include "CmMatrix34.h" using namespace physx; using namespace Cm; bool Gu::contactPlaneConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const ConvexHullData* hullData = _getHullData(shapeConvex); const PxVec3* PX_RESTRICT hullVertices = hullData->getHullVertices(); PxU32 numHullVertices = hullData->mNbHullVertices; // PxPrefetch128(hullVertices); // Plane is implicitly <1,0,0> 0 in localspace const Matrix34FromTransform convexToPlane0 (transform0.transformInv(transform1)); const PxMat33 convexToPlane_rot(convexToPlane0[0], convexToPlane0[1], convexToPlane0[2] ); bool idtScale = shapeConvex.scale.isIdentity(); FastVertex2ShapeScaling convexScaling; // PT: TODO: remove default ctor if(!idtScale) convexScaling.init(shapeConvex.scale); const PxMat34 convexToPlane(convexToPlane_rot * convexScaling.getVertex2ShapeSkew(), convexToPlane0[3]); //convexToPlane = context.mVertex2ShapeSkew[1].getVertex2WorldSkew(convexToPlane); const Matrix34FromTransform planeToW(transform0); // This is rather brute-force bool status = false; const PxVec3 contactNormal = -planeToW.m.column0; while(numHullVertices--) { const PxVec3& vertex = *hullVertices++; // if(numHullVertices) // PxPrefetch128(hullVertices); const PxVec3 pointInPlane = convexToPlane.transform(vertex); //TODO: this multiply could be factored out! if(pointInPlane.x <= params.mContactDistance) { // const PxVec3 pointInW = planeToW.transform(pointInPlane); // contactBuffer.contact(pointInW, -planeToW.m.column0, pointInPlane.x); status = true; PxContactPoint* PX_RESTRICT pt = contactBuffer.contact(); if(pt) { pt->normal = contactNormal; pt->point = planeToW.transform(pointInPlane); pt->separation = pointInPlane.x; pt->internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX; } } } return status; }
3,936
C++
38.767676
108
0.762195
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneCapsule.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" #include "GuSegment.h" using namespace physx; bool Gu::contactPlaneCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1); const PxTransform capsuleToPlane = transform0.transformInv(transform1); //Capsule in plane space Segment segment; getCapsuleSegment(capsuleToPlane, shapeCapsule, segment); const PxVec3 negPlaneNormal = transform0.q.getBasisVector0(); bool contact = false; const PxReal separation0 = segment.p0.x - shapeCapsule.radius; const PxReal separation1 = segment.p1.x - shapeCapsule.radius; if(separation0 <= params.mContactDistance) { const PxVec3 temp(segment.p0.x - shapeCapsule.radius, segment.p0.y, segment.p0.z); const PxVec3 point = transform0.transform(temp); contactBuffer.contact(point, -negPlaneNormal, separation0); contact = true; } if(separation1 <= params.mContactDistance) { const PxVec3 temp(segment.p1.x - shapeCapsule.radius, segment.p1.y, segment.p1.z); const PxVec3 point = transform0.transform(temp); contactBuffer.contact(point, -negPlaneNormal, separation1); contact = true; } return contact; }
3,096
C++
40.293333
84
0.766796
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereSphere.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; bool Gu::contactSphereSphere(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom0 = checkedCast<PxSphereGeometry>(shape0); const PxSphereGeometry& sphereGeom1 = checkedCast<PxSphereGeometry>(shape1); PxVec3 delta = transform0.p - transform1.p; const PxReal distanceSq = delta.magnitudeSquared(); const PxReal radiusSum = sphereGeom0.radius + sphereGeom1.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; if(distanceSq >= inflatedSum*inflatedSum) return false; // We do a *manual* normalization to check for singularity condition const PxReal magn = PxSqrt(distanceSq); if(magn<=0.00001f) delta = PxVec3(1.0f, 0.0f, 0.0f); // PT: spheres are exactly overlapping => can't create normal => pick up random one else delta *= 1.0f/magn; // PT: TODO: why is this formula different from the original code? const PxVec3 contact = delta * ((sphereGeom0.radius + magn - sphereGeom1.radius)*-0.5f) + transform0.p; contactBuffer.contact(contact, delta, magn - radiusSum); return true; }
2,874
C++
44.63492
119
0.761308
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneBox.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxUnionCast.h" #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "CmMatrix34.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Cm; bool Gu::contactPlaneBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); const PxVec3 negPlaneNormal = -transform0.q.getBasisVector0(); //Make sure we have a normalized plane //PX_ASSERT(PxAbs(shape0.mNormal.magnitudeSquared() - 1.0f) < 0.000001f); const Matrix34FromTransform boxMatrix(transform1); const Matrix34FromTransform boxToPlane(transform0.transformInv(transform1)); PxVec3 point; PX_ASSERT(contactBuffer.count==0); /* for(int vx=-1; vx<=1; vx+=2) for(int vy=-1; vy<=1; vy+=2) for(int vz=-1; vz<=1; vz+=2) { //point = boxToPlane.transform(PxVec3(shapeBox.halfExtents.x*vx, shapeBox.halfExtents.y*vy, shapeBox.halfExtents.z*vz)); //PxReal planeEq = point.x; //Optimized a bit point.set(shapeBox.halfExtents.x*vx, shapeBox.halfExtents.y*vy, shapeBox.halfExtents.z*vz); const PxReal planeEq = boxToPlane.m.column0.x*point.x + boxToPlane.m.column1.x*point.y + boxToPlane.m.column2.x*point.z + boxToPlane.p.x; if(planeEq <= contactDistance) { contactBuffer.contact(boxMatrix.transform(point), negPlaneNormal, planeEq); //no point in making more than 4 contacts. if (contactBuffer.count >= 6) //was: 4) actually, with strong interpenetration more than just the bottom surface goes through, //and we want to find the *deepest* 4 vertices, really. return true; } }*/ // PT: the above code is shock full of LHS/FCMPs. And there's no point in limiting the number of contacts to 6 when the max possible is 8. const PxReal limit = params.mContactDistance - boxToPlane.p.x; const PxReal dx = shapeBox.halfExtents.x; const PxReal dy = shapeBox.halfExtents.y; const PxReal dz = shapeBox.halfExtents.z; const PxReal bxdx = boxToPlane.m.column0.x * dx; const PxReal bxdy = boxToPlane.m.column1.x * dy; const PxReal bxdz = boxToPlane.m.column2.x * dz; PxReal depths[8]; depths[0] = bxdx + bxdy + bxdz - limit; depths[1] = bxdx + bxdy - bxdz - limit; depths[2] = bxdx - bxdy + bxdz - limit; depths[3] = bxdx - bxdy - bxdz - limit; depths[4] = - bxdx + bxdy + bxdz - limit; depths[5] = - bxdx + bxdy - bxdz - limit; depths[6] = - bxdx - bxdy + bxdz - limit; depths[7] = - bxdx - bxdy - bxdz - limit; //const PxU32* binary = reinterpret_cast<const PxU32*>(depths); const PxU32* binary = PxUnionCast<PxU32*, PxF32*>(depths); if(binary[0] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, dy, dz)), negPlaneNormal, depths[0] + params.mContactDistance); if(binary[1] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, dy, -dz)), negPlaneNormal, depths[1] + params.mContactDistance); if(binary[2] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, -dy, dz)), negPlaneNormal, depths[2] + params.mContactDistance); if(binary[3] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, -dy, -dz)), negPlaneNormal, depths[3] + params.mContactDistance); if(binary[4] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, dy, dz)), negPlaneNormal, depths[4] + params.mContactDistance); if(binary[5] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, dy, -dz)), negPlaneNormal, depths[5] + params.mContactDistance); if(binary[6] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, -dy, dz)), negPlaneNormal, depths[6] + params.mContactDistance); if(binary[7] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, -dy, -dz)), negPlaneNormal, depths[7] + params.mContactDistance); return contactBuffer.count > 0; }
5,739
C++
45.666666
141
0.731835
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereBox.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; //This version is ported 1:1 from novodex static PX_FORCE_INLINE bool ContactSphereBox(const PxVec3& sphereOrigin, PxReal sphereRadius, const PxVec3& boxExtents, // const PxcCachedTransforms& boxCacheTransform, const PxTransform32& boxTransform, PxVec3& point, PxVec3& normal, PxReal& separation, PxReal contactDistance) { // const PxTransform& boxTransform = boxCacheTransform.getShapeToWorld(); //returns true on contact const PxVec3 delta = sphereOrigin - boxTransform.p; // s1.center - s2.center; PxVec3 dRot = boxTransform.rotateInv(delta); //transform delta into OBB body coords. //check if delta is outside ABB - and clip the vector to the ABB. bool outside = false; if (dRot.x < -boxExtents.x) { outside = true; dRot.x = -boxExtents.x; } else if (dRot.x > boxExtents.x) { outside = true; dRot.x = boxExtents.x; } if (dRot.y < -boxExtents.y) { outside = true; dRot.y = -boxExtents.y; } else if (dRot.y > boxExtents.y) { outside = true; dRot.y = boxExtents.y; } if (dRot.z < -boxExtents.z) { outside = true; dRot.z =-boxExtents.z; } else if (dRot.z > boxExtents.z) { outside = true; dRot.z = boxExtents.z; } if (outside) //if clipping was done, sphere center is outside of box. { point = boxTransform.rotate(dRot); //get clipped delta back in world coords. normal = delta - point; //what we clipped away. const PxReal lenSquared = normal.magnitudeSquared(); const PxReal inflatedDist = sphereRadius + contactDistance; if (lenSquared > inflatedDist * inflatedDist) return false; //disjoint //normalize to make it into the normal: separation = PxRecipSqrt(lenSquared); normal *= separation; separation *= lenSquared; //any plane that touches the sphere is tangential, so a vector from contact point to sphere center defines normal. //we could also use point here, which has same direction. //this is either a faceFace or a vertexFace contact depending on whether the box's face or vertex collides, but we did not distinguish. //We'll just use vertex face for now, this info isn't really being used anyway. //contact point is point on surface of cube closest to sphere center. point += boxTransform.p; separation -= sphereRadius; return true; } else { //center is in box, we definitely have a contact. PxVec3 locNorm; //local coords contact normal /*const*/ PxVec3 absdRot; absdRot = PxVec3(PxAbs(dRot.x), PxAbs(dRot.y), PxAbs(dRot.z)); /*const*/ PxVec3 distToSurface = boxExtents - absdRot; //dist from embedded center to box surface along 3 dimensions. //find smallest element of distToSurface if (distToSurface.y < distToSurface.x) { if (distToSurface.y < distToSurface.z) { //y locNorm = PxVec3(0.0f, dRot.y > 0.0f ? 1.0f : -1.0f, 0.0f); separation = -distToSurface.y; } else { //z locNorm = PxVec3(0.0f,0.0f, dRot.z > 0.0f ? 1.0f : -1.0f); separation = -distToSurface.z; } } else { if (distToSurface.x < distToSurface.z) { //x locNorm = PxVec3(dRot.x > 0.0f ? 1.0f : -1.0f, 0.0f, 0.0f); separation = -distToSurface.x; } else { //z locNorm = PxVec3(0.0f,0.0f, dRot.z > 0.0f ? 1.0f : -1.0f); separation = -distToSurface.z; } } //separation so far is just the embedding of the center point; we still have to push out all of the radius. point = sphereOrigin; normal = boxTransform.rotate(locNorm); separation -= sphereRadius; return true; } } bool Gu::contactSphereBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom = checkedCast<PxSphereGeometry>(shape0); const PxBoxGeometry& boxGeom = checkedCast<PxBoxGeometry>(shape1); PxVec3 normal; PxVec3 point; PxReal separation; if(!ContactSphereBox(transform0.p, sphereGeom.radius, boxGeom.halfExtents, transform1, point, normal, separation, params.mContactDistance)) return false; contactBuffer.contact(point, normal, separation); return true; }
5,868
C++
32.729885
140
0.709271
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuIntersectionEdgeEdge.h" #include "GuDistanceSegmentTriangle.h" #include "GuIntersectionRayTriangle.h" #include "GuIntersectionTriangleBox.h" #include "GuInternal.h" #include "GuContactMethodImpl.h" #include "GuFeatureCode.h" #include "GuMidphaseInterface.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuConvexEdgeFlags.h" #include "GuBox.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; #define DEBUG_RENDER_MESHCONTACTS 0 #if DEBUG_RENDER_MESHCONTACTS #include "PxPhysics.h" #include "PxScene.h" #endif #define USE_AABB_TRI_CULLING //#define USE_CAPSULE_TRI_PROJ_CULLING //#define USE_CAPSULE_TRI_SAT_CULLING #define VISUALIZE_TOUCHED_TRIS 0 #define VISUALIZE_CULLING_BOX 0 #if VISUALIZE_TOUCHED_TRIS #include "PxRenderOutput.h" #include "PxsContactManager.h" #include "PxsContext.h" static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); PxRenderOutput& out = context.mRenderOutput; out << color << m << PxRenderOutput::LINES << a << b; } static void gVisualizeTri(const PxVec3& a, const PxVec3& b, const PxVec3& c, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); PxRenderOutput& out = context.mRenderOutput; out << color << m << PxRenderOutput::TRIANGLES << a << b << c; } static PxU32 gColors[8] = { 0xff0000ff, 0xff00ff00, 0xffff0000, 0xff00ffff, 0xffff00ff, 0xffffff00, 0xff000080, 0xff008000}; #endif static const float fatBoxEdgeCoeff = 0.01f; static bool PxcTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const PxVec3* PX_RESTRICT triVerts, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project triangle float Min1, Max1; { Min1 = Max1 = triVerts[0].dot(axis); const PxReal dp1 = triVerts[1].dot(axis); Min1 = physx::intrinsics::selectMin(Min1, dp1); Max1 = physx::intrinsics::selectMax(Max1, dp1); const PxReal dp2 = triVerts[2].dot(axis); Min1 = physx::intrinsics::selectMin(Min1, dp2); Max1 = physx::intrinsics::selectMax(Max1, dp2); } // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } PX_FORCE_INLINE static PxVec3 PxcComputeTriangleNormal(const PxVec3* PX_RESTRICT triVerts) { return ((triVerts[0]-triVerts[1]).cross(triVerts[0]-triVerts[2])).getNormalized(); } PX_FORCE_INLINE static PxVec3 PxcComputeTriangleCenter(const PxVec3* PX_RESTRICT triVerts) { static const PxReal inv3 = 1.0f / 3.0f; return (triVerts[0] + triVerts[1] + triVerts[2]) * inv3; } static bool PxcCapsuleTriOverlap3(PxU8 edgeFlags, const Segment& segment, PxReal radius, const PxVec3* PX_RESTRICT triVerts, PxReal* PX_RESTRICT t=NULL, PxVec3* PX_RESTRICT pp=NULL) { PxReal penDepth = PX_MAX_REAL; // Test normal PxVec3 sep = PxcComputeTriangleNormal(triVerts); if(!PxcTestAxis(sep, segment, radius, triVerts, penDepth)) return false; // Test edges // ML:: use the active edge flag instead of the concave flag const PxU32 activeEdgeFlag[] = {ETD_CONVEX_EDGE_01, ETD_CONVEX_EDGE_12, ETD_CONVEX_EDGE_20}; const PxVec3 capsuleAxis = (segment.p1 - segment.p0).getNormalized(); for(PxU32 i=0;i<3;i++) { //bool active =((edgeFlags & ignoreEdgeFlag[i]) == 0); if(edgeFlags & activeEdgeFlag[i]) { const PxVec3 e0 = triVerts[i]; // const PxVec3 e1 = triVerts[(i+1)%3]; const PxVec3 e1 = triVerts[PxGetNextIndex3(i)]; const PxVec3 edge = e0 - e1; PxVec3 cross = capsuleAxis.cross(edge); if(!isAlmostZero(cross)) { cross = cross.getNormalized(); PxReal d; if(!PxcTestAxis(cross, segment, radius, triVerts, d)) return false; if(d<penDepth) { penDepth = d; sep = cross; } } } } const PxVec3 capsuleCenter = segment.computeCenter(); const PxVec3 triCenter = PxcComputeTriangleCenter(triVerts); const PxVec3 witness = capsuleCenter - triCenter; if(sep.dot(witness) < 0.0f) sep = -sep; if(t) *t = penDepth; if(pp) *pp = sep; return true; } static void PxcGenerateVFContacts( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex, PxReal contactDistance) { const PxVec3* PX_RESTRICT Ptr = &segment.p0; for(PxU32 i=0;i<2;i++) { const PxVec3& Pos = Ptr[i]; PxReal t,u,v; if(intersectRayTriangleCulling(Pos, -normal, triVerts[0], triVerts[1], triVerts[2], t, u, v, 1e-3f) && t < radius + contactDistance) { const PxVec3 Hit = meshAbsPose.transform(Pos - t * normal); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(Hit, wn, t-radius, triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << Hit << (Hit + wn * 10.0f); #endif } } } // PT: PxcGenerateEEContacts2 uses a segment-triangle distance function, which breaks when the segment // intersects the triangle, in which case you need to switch to a penetration-depth computation. // If you don't do this thin capsules don't work. static void PxcGenerateEEContacts( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex) { PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); for(PxU32 i=0;i<3;i++) { PxReal dist; PxVec3 ip; if(intersectEdgeEdge(triVerts[i], triVerts[PxGetNextIndex3(i)], -normal, s0, s1, dist, ip)) { ip = meshAbsPose.transform(ip); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(ip, wn, - (radius + dist), triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << ip << (ip + wn * 10.0f); #endif } } } static void PxcGenerateEEContacts2( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex, PxReal contactDistance) { PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); for(PxU32 i=0;i<3;i++) { PxReal dist; PxVec3 ip; if(intersectEdgeEdge(triVerts[i], triVerts[PxGetNextIndex3(i)], normal, s0, s1, dist, ip) && dist < radius+contactDistance) { ip = meshAbsPose.transform(ip); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(ip, wn, dist - radius, triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << ip << (ip + wn * 10.0f); #endif } } } namespace { struct CapsuleMeshContactGeneration { PxContactBuffer& mContactBuffer; const PxMat34 mMeshAbsPose; const Segment& mMeshCapsule; #ifdef USE_AABB_TRI_CULLING PxVec3p mBC; PxVec3p mBE; #endif PxReal mInflatedRadius; PxReal mContactDistance; PxReal mShapeCapsuleRadius; CapsuleMeshContactGeneration(PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius) : mContactBuffer (contactBuffer), mMeshAbsPose (Matrix34FromTransform(transform1)), mMeshCapsule (meshCapsule), mInflatedRadius (inflatedRadius), mContactDistance (contactDistance), mShapeCapsuleRadius (shapeCapsuleRadius) { PX_ASSERT(contactBuffer.count==0); #ifdef USE_AABB_TRI_CULLING mBC = (meshCapsule.p0 + meshCapsule.p1)*0.5f; const PxVec3p be = (meshCapsule.p0 - meshCapsule.p1)*0.5f; mBE.x = fabsf(be.x) + inflatedRadius; mBE.y = fabsf(be.y) + inflatedRadius; mBE.z = fabsf(be.z) + inflatedRadius; #endif } void processTriangle(PxU32 triangleIndex, const PxTrianglePadded& tri, PxU8 extraData/*, const PxU32* vertInds*/) { #ifdef USE_AABB_TRI_CULLING #if VISUALIZE_CULLING_BOX { PxRenderOutput& out = context.mRenderOutput; PxTransform idt = PxTransform(PxIdentity); out << idt; out << 0xffffffff; out << PxDebugBox(mBC, mBE, true); } #endif #endif const PxVec3& p0 = tri.verts[0]; const PxVec3& p1 = tri.verts[1]; const PxVec3& p2 = tri.verts[2]; #ifdef USE_AABB_TRI_CULLING // PT: this one is safe because triangle class is padded // PT: TODO: is this test really needed? Not done in midphase already? if(!intersectTriangleBox_Unsafe(mBC, mBE, p0, p1, p2)) return; #endif #ifdef USE_CAPSULE_TRI_PROJ_CULLING PxVec3 triCenter = (p0 + p1 + p2)*0.33333333f; PxVec3 delta = mBC - triCenter; PxReal depth; if(!PxcTestAxis(delta, mMeshCapsule, mInflatedRadius, tri.verts, depth)) return; #endif #if VISUALIZE_TOUCHED_TRIS gVisualizeTri(p0, p1, p2, context, PxDebugColor::eARGB_RED); #endif #ifdef USE_CAPSULE_TRI_SAT_CULLING PxVec3 SepAxis; if(!PxcCapsuleTriOverlap3(extraData, mMeshCapsule, mInflatedRadius, tri.verts, NULL, &SepAxis)) return; #endif PxReal t,u,v; const PxVec3 p1_p0 = p1 - p0; const PxVec3 p2_p0 = p2 - p0; const PxReal squareDist = distanceSegmentTriangleSquared(mMeshCapsule, p0, p1_p0, p2_p0, &t, &u, &v); // PT: do cheaper test first! if(squareDist >= mInflatedRadius*mInflatedRadius) return; // PT: backface culling without the normalize // PT: TODO: consider doing before the segment-triangle distance test if it's cheaper const PxVec3 planeNormal = p1_p0.cross(p2_p0); const PxF32 planeD = planeNormal.dot(p0); // PT: actually -d compared to PxcPlane if(planeNormal.dot(mBC) < planeD) return; if(squareDist > 0.001f*0.001f) { // Contact information PxVec3 normal; if(selectNormal(extraData, u, v)) { normal = planeNormal.getNormalized(); } else { const PxVec3 pointOnTriangle = computeBarycentricPoint(p0, p1, p2, u, v); const PxVec3 pointOnSegment = mMeshCapsule.getPointAt(t); normal = pointOnSegment - pointOnTriangle; const PxReal l = normal.magnitude(); if(l == 0.0f) return; normal = normal / l; } PxcGenerateEEContacts2(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, normal, triangleIndex, mContactDistance); PxcGenerateVFContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, normal, triangleIndex, mContactDistance); } else { PxVec3 SepAxis; if(!PxcCapsuleTriOverlap3(extraData, mMeshCapsule, mInflatedRadius, tri.verts, NULL, &SepAxis)) return; PxcGenerateEEContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, SepAxis, triangleIndex); PxcGenerateVFContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, SepAxis, triangleIndex, mContactDistance); } } private: CapsuleMeshContactGeneration& operator=(const CapsuleMeshContactGeneration&); }; struct CapsuleMeshContactGenerationCallback_NoScale : MeshHitCallback<PxGeomRaycastHit> { CapsuleMeshContactGeneration mGeneration; const TriangleMesh* mMeshData; CapsuleMeshContactGenerationCallback_NoScale( PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius, const TriangleMesh* meshData ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius), mMeshData (meshData) { PX_ASSERT(contactBuffer.count==0); } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* /*vInds*/) { PxTrianglePadded tri; // PT: TODO: revisit this, avoid the copy tri.verts[0] = v0; tri.verts[1] = v1; tri.verts[2] = v2; const PxU32 triangleIndex = hit.faceIndex; //ML::set all the edges to be active, if the mExtraTrigData exist, we overwrite this flag const PxU8 extraData = getConvexEdgeFlags(mMeshData->getExtraTrigData(), triangleIndex); mGeneration.processTriangle(triangleIndex, tri, extraData); return true; } private: CapsuleMeshContactGenerationCallback_NoScale& operator=(const CapsuleMeshContactGenerationCallback_NoScale&); }; struct CapsuleMeshContactGenerationCallback_Scale : CapsuleMeshContactGenerationCallback_NoScale { const FastVertex2ShapeScaling& mScaling; CapsuleMeshContactGenerationCallback_Scale( PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, const FastVertex2ShapeScaling& scaling, PxReal contactDistance, PxReal shapeCapsuleRadius, const TriangleMesh* meshData ) : CapsuleMeshContactGenerationCallback_NoScale(contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius, meshData), mScaling (scaling) { } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* /*vInds*/) { PxTrianglePadded tri; getScaledVertices(tri.verts, v0, v1, v2, false, mScaling); const PxU32 triangleIndex = hit.faceIndex; //ML::set all the edges to be active, if the mExtraTrigData exist, we overwrite this flag PxU8 extraData = getConvexEdgeFlags(mMeshData->getExtraTrigData(), triangleIndex); if(mScaling.flipsNormal()) flipConvexEdgeFlags(extraData); mGeneration.processTriangle(triangleIndex, tri, extraData); return true; } private: CapsuleMeshContactGenerationCallback_Scale& operator=(const CapsuleMeshContactGenerationCallback_Scale&); }; } // PT: computes local capsule without going to world-space static PX_FORCE_INLINE Segment computeLocalCapsule(const PxTransform& transform0, const PxTransform& transform1, const PxCapsuleGeometry& shapeCapsule) { const PxVec3 halfHeight = getCapsuleHalfHeightVector(transform0, shapeCapsule); const PxVec3 delta = transform1.p - transform0.p; return Segment( transform1.rotateInv(halfHeight - delta), transform1.rotateInv(-halfHeight - delta)); } bool Gu::contactCapsuleMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; //AM: inflate! const Segment meshCapsule = computeLocalCapsule(transform0, transform1, shapeCapsule); const TriangleMesh* meshData = _getMeshData(shapeMesh); //bound the capsule in shape space by an OBB: Box queryBox; { const Capsule queryCapsule(meshCapsule, inflatedRadius); queryBox.create(queryCapsule); } if(shapeMesh.scale.isIdentity()) { CapsuleMeshContactGenerationCallback_NoScale callback(contactBuffer, transform1, meshCapsule, inflatedRadius, params.mContactDistance, shapeCapsule.radius, meshData); // PT: TODO: switch to capsule query here Midphase::intersectOBB(meshData, queryBox, callback, true); } else { const FastVertex2ShapeScaling meshScaling(shapeMesh.scale); CapsuleMeshContactGenerationCallback_Scale callback(contactBuffer, transform1, meshCapsule, inflatedRadius, meshScaling, params.mContactDistance, shapeCapsule.radius, meshData); //switched from capsuleCollider to boxCollider so we can support nonuniformly scaled meshes by scaling the query region: //apply the skew transform to the box: meshScaling.transformQueryBounds(queryBox.center, queryBox.extents, queryBox.rot); Midphase::intersectOBB(meshData, queryBox, callback, true); } return contactBuffer.count > 0; } namespace { struct CapsuleHeightfieldContactGenerationCallback : OverlapReport { CapsuleMeshContactGeneration mGeneration; const HeightFieldUtil& mHfUtil; const PxTransform& mTransform1; CapsuleHeightfieldContactGenerationCallback( PxContactBuffer& contactBuffer, const PxTransform& transform1, const HeightFieldUtil& hfUtil, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius ) : mGeneration (contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius), mHfUtil (hfUtil), mTransform1 (transform1) { PX_ASSERT(contactBuffer.count==0); } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { const PxU8 nextInd[] = {2,0,1}; while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTrianglePadded currentTriangle; // in world space PxU32 adjInds[3]; mHfUtil.getTriangle(mTransform1, currentTriangle, vertIndices, adjInds, triangleIndex, false, false); PxVec3 normal; currentTriangle.normal(normal); PxU8 triFlags = 0; //KS - temporary until we can calculate triFlags for HF for(PxU32 a = 0; a < 3; ++a) { if(adjInds[a] != 0xFFFFFFFF) { PxTriangle adjTri; mHfUtil.getTriangle(mTransform1, adjTri, NULL, NULL, adjInds[a], false, false); //We now compare the triangles to see if this edge is active PxVec3 adjNormal; adjTri.denormalizedNormal(adjNormal); PxU32 otherIndex = nextInd[a]; PxF32 projD = adjNormal.dot(currentTriangle.verts[otherIndex] - adjTri.verts[0]); if(projD < 0.f) { adjNormal.normalize(); PxF32 proj = adjNormal.dot(normal); if(proj < 0.999f) { triFlags |= 1 << (a+3); } } } else { triFlags |= 1 << (a+3); } } mGeneration.processTriangle(triangleIndex, currentTriangle, triFlags); } return true; } private: CapsuleHeightfieldContactGenerationCallback& operator=(const CapsuleHeightfieldContactGenerationCallback&); }; } bool Gu::contactCapsuleHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; //AM: inflate! const Segment meshCapsule = computeLocalCapsule(transform0, transform1, shapeCapsule); // We must be in local space to use the cache const HeightFieldUtil hfUtil(shapeMesh); CapsuleHeightfieldContactGenerationCallback callback( contactBuffer, transform1, hfUtil, meshCapsule, inflatedRadius, params.mContactDistance, shapeCapsule.radius); //switched from capsuleCollider to boxCollider so we can support nonuniformly scaled meshes by scaling the query region: //bound the capsule in shape space by an AABB: // PT: TODO: improve these bounds (see computeCapsuleBounds) hfUtil.overlapAABBTriangles(transform0, transform1, getLocalCapsuleBounds(inflatedRadius, shapeCapsule.halfHeight), callback); return contactBuffer.count > 0; }
21,271
C++
32.341693
196
0.74162
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactConvexMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuConvexUtilsInternal.h" #include "GuInternal.h" #include "GuContactPolygonPolygon.h" #include "GuConvexEdgeFlags.h" #include "GuSeparatingAxes.h" #include "GuContactMethodImpl.h" #include "GuMidphaseInterface.h" #include "GuConvexHelper.h" #include "GuTriangleCache.h" #include "GuHeightFieldUtil.h" #include "GuEntityReport.h" #include "GuIntersectionTriangleBox.h" #include "GuBox.h" #include "CmUtils.h" #include "foundation/PxAlloca.h" #include "foundation/PxFPU.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace aos; using namespace intrinsics; //sizeof(SavedContactData)/sizeof(PxU32) = 17, 1088/17 = 64 triangles in the local array #define LOCAL_CONTACTS_SIZE 1088 #define LOCAL_TOUCHED_TRIG_SIZE 192 //#define USE_TRIANGLE_NORMAL #define TEST_INTERNAL_OBJECTS static PX_FORCE_INLINE void projectTriangle(const PxVec3& localSpaceDirection, const PxVec3* PX_RESTRICT triangle, PxReal& min1, PxReal& max1) { const PxReal dp0 = triangle[0].dot(localSpaceDirection); const PxReal dp1 = triangle[1].dot(localSpaceDirection); min1 = selectMin(dp0, dp1); max1 = selectMax(dp0, dp1); const PxReal dp2 = triangle[2].dot(localSpaceDirection); min1 = selectMin(min1, dp2); max1 = selectMax(max1, dp2); } #ifdef TEST_INTERNAL_OBJECTS static PX_FORCE_INLINE void boxSupport(const float extents[3], const PxVec3& sv, float p[3]) { const PxU32* iextents = reinterpret_cast<const PxU32*>(extents); const PxU32* isv = reinterpret_cast<const PxU32*>(&sv); PxU32* ip = reinterpret_cast<PxU32*>(p); ip[0] = iextents[0]|(isv[0]&PX_SIGN_BITMASK); ip[1] = iextents[1]|(isv[1]&PX_SIGN_BITMASK); ip[2] = iextents[2]|(isv[2]&PX_SIGN_BITMASK); } #if PX_DEBUG static const PxReal testInternalObjectsEpsilon = 1.0e-3f; #endif static PX_FORCE_INLINE bool testInternalObjects(const PxVec3& localAxis0, const PolygonalData& polyData0, const PxVec3* PX_RESTRICT triangleInHullSpace, float dmin) { PxReal min1, max1; projectTriangle(localAxis0, triangleInHullSpace, min1, max1); const float dp = polyData0.mCenter.dot(localAxis0); float p0[3]; boxSupport(polyData0.mInternal.mExtents, localAxis0, p0); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float bestRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const PxReal min0 = dp - bestRadius; const PxReal max0 = dp + bestRadius; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; const float depth = selectMin(d0, d1); if(depth>dmin) return false; return true; } #endif static PX_FORCE_INLINE bool testNormal( const PxVec3& sepAxis, PxReal min0, PxReal max0, const PxVec3* PX_RESTRICT triangle, PxReal& depth, PxReal contactDistance) { PxReal min1, max1; projectTriangle(sepAxis, triangle, min1, max1); if(max0+contactDistance<min1 || max1+contactDistance<min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static PX_FORCE_INLINE bool testSepAxis(const PxVec3& sepAxis, const PolygonalData& polyData0, const PxVec3* PX_RESTRICT triangle, const PxMat34& m0to1, const FastVertex2ShapeScaling& convexScaling, PxReal& depth, PxReal contactDistance) { PxReal min0, max0; (polyData0.mProjectHull)(polyData0, sepAxis, m0to1, convexScaling, min0, max0); PxReal min1, max1; projectTriangle(sepAxis, triangle, min1, max1); if(max0+contactDistance < min1 || max1+contactDistance < min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static bool testFacesSepAxesBackface( const PolygonalData& polyData0, const PxMat34& /*world0*/, const PxMat34& /*world1*/, const PxMat34& m0to1, const PxVec3& witness, const PxVec3* PX_RESTRICT triangle, const FastVertex2ShapeScaling& convexScaling, PxU32& numHullIndices, PxU32* hullIndices_, PxReal& dmin, PxVec3& sep, PxU32& id, PxReal contactDistance, bool idtConvexScale ) { id = PX_INVALID_U32; const PxU32 numHullPolys = polyData0.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; const PxVec3& trans = m0to1.p; { PxU32* hullIndices = hullIndices_; // PT: when the center of one object is inside the other object (deep penetrations) this discards everything! // PT: when this happens, the backup procedure is used to come up with good results anyway. // PT: it's worth having a special codepath here for identity scales, to skip all the normalizes/division. Lot faster without. if(idtConvexScale) { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; #ifdef USE_TRIANGLE_NORMAL if(PL.normal.dot(witness) > 0.0f) #else // ### this is dubious since the triangle center is likely to be very close to the hull, if not inside. Why not use the triangle normal? if(PL.distance(witness) < 0.0f) #endif continue; //backface culled *hullIndices++ = i; const PxVec3 sepAxis = m0to1.rotate(PL.n); const PxReal dp = sepAxis.dot(trans); PxReal d; if(!testNormal(sepAxis, P.getMin(vertices) + dp, P.getMax() + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } } } else { #ifndef USE_TRIANGLE_NORMAL //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceWitness = convexScaling % witness; #endif for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; #ifdef USE_TRIANGLE_NORMAL if(PL.normal.dot(witness) > 0.0f) #else // ### this is dubious since the triangle center is likely to be very close to the hull, if not inside. Why not use the triangle normal? if(PL.distance(vertSpaceWitness) < 0.0f) #endif continue; //backface culled //normals transform by inverse transpose: (and transpose(skew) == skew as its symmetric) PxVec3 shapeSpaceNormal = convexScaling % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); *hullIndices++ = i; const PxVec3 sepAxis = m0to1.rotate(shapeSpaceNormal); PxReal d; const PxReal dp = sepAxis.dot(trans); const float oneOverM = 1.0f / magnitude; if(!testNormal(sepAxis, P.getMin(vertices) * oneOverM + dp, P.getMax() * oneOverM + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } } } numHullIndices = PxU32(hullIndices - hullIndices_); } // Backup if(id == PX_INVALID_U32) { if(idtConvexScale) { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; const PxVec3 sepAxis = m0to1.rotate(PL.n); const PxReal dp = sepAxis.dot(trans); PxReal d; if(!testNormal(sepAxis, P.getMin(vertices) + dp, P.getMax() + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } hullIndices_[i] = i; } } else { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; PxVec3 shapeSpaceNormal = convexScaling % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); const PxVec3 sepAxis = m0to1.rotate(shapeSpaceNormal); PxReal d; const PxReal dp = sepAxis.dot(trans); const float oneOverM = 1.0f / magnitude; if(!testNormal(sepAxis, P.getMin(vertices) * oneOverM + dp, P.getMax() * oneOverM + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } hullIndices_[i] = i; } } numHullIndices = numHullPolys; } return true; } static PX_FORCE_INLINE bool edgeCulling(const PxPlane& plane, const PxVec3& p0, const PxVec3& p1, PxReal contactDistance) { return plane.distance(p0)<=contactDistance || plane.distance(p1)<=contactDistance; } static bool performEETests( const PolygonalData& polyData0, const PxU8 triFlags, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3* PX_RESTRICT triangle, PxU32 numHullIndices, const PxU32* PX_RESTRICT hullIndices, const PxPlane& localTriPlane, const FastVertex2ShapeScaling& convexScaling, PxVec3& vec, PxReal& dmin, PxReal contactDistance, PxReal toleranceLength, PxU32 id0, PxU32 /*triangleIndex*/) { PX_UNUSED(toleranceLength); // Only used in Debug // Cull candidate triangle edges vs to hull plane PxU32 nbTriangleAxes = 0; PxVec3 triangleAxes[3]; { const HullPolygonData& P = polyData0.mPolygons[id0]; const PxPlane& vertSpacePlane = P.mPlane; const PxVec3 newN = m1to0.rotate(vertSpacePlane.n); PxPlane hullWitness(convexScaling * newN, vertSpacePlane.d - m1to0.p.dot(newN)); //technically not a fully xformed plane, just use property of x|My == Mx|y for symmetric M. if((triFlags & ETD_CONVEX_EDGE_01) && edgeCulling(hullWitness, triangle[0], triangle[1], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[0] - triangle[1]); if((triFlags & ETD_CONVEX_EDGE_12) && edgeCulling(hullWitness, triangle[1], triangle[2], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[1] - triangle[2]); if((triFlags & ETD_CONVEX_EDGE_20) && edgeCulling(hullWitness, triangle[2], triangle[0], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[2] - triangle[0]); } //PxcPlane vertexSpacePlane = localTriPlane.getTransformed(m1to0); //vertexSpacePlane.normal = convexScaling * vertexSpacePlane.normal; //technically not a fully xformed plane, just use property of x|My == Mx|y for symmetric M. const PxVec3 newN = m1to0.rotate(localTriPlane.n); PxPlane vertexSpacePlane(convexScaling * newN, localTriPlane.d - m1to0.p.dot(newN)); const PxVec3* PX_RESTRICT hullVerts = polyData0.mVerts; SeparatingAxes SA; SA.reset(); const PxU8* PX_RESTRICT vrefBase0 = polyData0.mPolygonVertexRefs; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; while(numHullIndices--) { const HullPolygonData& P = polygons[*hullIndices++]; const PxU8* PX_RESTRICT data = vrefBase0 + P.mVRef8; PxU32 numEdges = nbTriangleAxes; const PxVec3* edges = triangleAxes; // TODO: cheap edge culling as in convex/convex! while(numEdges--) { const PxVec3& currentPolyEdge = *edges++; // Loop through polygon vertices == polygon edges; PxU32 numVerts = P.mNbVerts; for(PxU32 j = 0; j < numVerts; j++) { PxU32 j1 = j+1; if(j1>=numVerts) j1 = 0; const PxU32 VRef0 = data[j]; const PxU32 VRef1 = data[j1]; if(edgeCulling(vertexSpacePlane, hullVerts[VRef0], hullVerts[VRef1], contactDistance)) { const PxVec3 currentHullEdge = m0to1.rotate(convexScaling * (hullVerts[VRef0] - hullVerts[VRef1])); //matrix mult is distributive! PxVec3 sepAxis = currentHullEdge.cross(currentPolyEdge); if(!isAlmostZero(sepAxis)) SA.addAxis(sepAxis.getNormalized()); } } } } dmin = PX_MAX_REAL; PxU32 numAxes = SA.getNumAxes(); const PxVec3* PX_RESTRICT axes = SA.getAxes(); #ifdef TEST_INTERNAL_OBJECTS PxVec3 triangleInHullSpace[3]; if(numAxes) { triangleInHullSpace[0] = m1to0.transform(triangle[0]); triangleInHullSpace[1] = m1to0.transform(triangle[1]); triangleInHullSpace[2] = m1to0.transform(triangle[2]); } #endif while(numAxes--) { const PxVec3& currentAxis = *axes++; #ifdef TEST_INTERNAL_OBJECTS const PxVec3 localAxis0 = m1to0.rotate(currentAxis); if(!testInternalObjects(localAxis0, polyData0, triangleInHullSpace, dmin)) { #if PX_DEBUG PxReal dtest; if(testSepAxis(currentAxis, polyData0, triangle, m0to1, convexScaling, dtest, contactDistance)) { PX_ASSERT(dtest + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; if(!testSepAxis(currentAxis, polyData0, triangle, m0to1, convexScaling, d, contactDistance)) { return false; } if(d < dmin) { dmin = d; vec = currentAxis; } } return true; } static bool triangleConvexTest( const PolygonalData& polyData0, const PxU8 triFlags, PxU32 index, const PxVec3* PX_RESTRICT localPoints, const PxPlane& localPlane, const PxVec3& groupCenterHull, const PxMat34& world0, const PxMat34& world1, const PxMat34& m0to1, const PxMat34& m1to0, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, PxVec3& groupAxis, PxReal& groupMinDepth, bool& faceContact, bool idtConvexScale ) { PxU32 id0 = PX_INVALID_U32; PxReal dmin0 = PX_MAX_REAL; PxVec3 vec0; PxU32 numHullIndices = 0; PxU32* PX_RESTRICT const hullIndices = reinterpret_cast<PxU32*>(PxAlloca(polyData0.mNbPolygons*sizeof(PxU32))); // PT: we test the hull normals first because they don't need any hull projection. If we can early exit thanks // to those, we completely avoid all hull projections. bool status = testFacesSepAxesBackface(polyData0, world0, world1, m0to1, groupCenterHull, localPoints, convexScaling, numHullIndices, hullIndices, dmin0, vec0, id0, contactDistance, idtConvexScale); if(!status) return false; groupAxis = PxVec3(0); groupMinDepth = PX_MAX_REAL; const PxReal eps = 0.0001f; // DE7748 //Test in mesh-space PxVec3 sepAxis; PxReal depth; { // Test triangle normal PxReal d; if(!testSepAxis(localPlane.n, polyData0, localPoints, m0to1, convexScaling, d, contactDistance)) return false; if(d<dmin0+eps) // if(d<dmin0) { depth = d; sepAxis = localPlane.n; faceContact = true; } else { depth = dmin0; sepAxis = vec0; faceContact = false; } } if(depth < groupMinDepth) { groupMinDepth = depth; groupAxis = world1.rotate(sepAxis); } if(!performEETests(polyData0, triFlags, m0to1, m1to0, localPoints, numHullIndices, hullIndices, localPlane, convexScaling, sepAxis, depth, contactDistance, toleranceLength, id0, index)) return false; if(depth < groupMinDepth) { groupMinDepth = depth; groupAxis = world1.rotate(sepAxis); faceContact = false; } return true; } namespace { struct ConvexMeshContactGeneration { PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& mDelayedContacts; CacheMap<CachedEdge, 128> mEdgeCache; CacheMap<CachedVertex, 128> mVertCache; const Matrix34FromTransform m0to1; const Matrix34FromTransform m1to0; PxVec3 mHullCenterMesh; PxVec3 mHullCenterWorld; const PolygonalData& mPolyData0; const PxMat34& mWorld0; const PxMat34& mWorld1; const FastVertex2ShapeScaling& mConvexScaling; PxReal mContactDistance; PxReal mToleranceLength; bool mIdtMeshScale, mIdtConvexScale; PxReal mCCDEpsilon; const PxTransform& mTransform0; const PxTransform& mTransform1; PxContactBuffer& mContactBuffer; bool mAnyHits; ConvexMeshContactGeneration( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ); void processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds); void generateLastContacts(); bool generateContacts( const PxPlane& localPlane, const PxVec3* PX_RESTRICT localPoints, const PxVec3& triCenter, PxVec3& groupAxis, PxReal groupMinDepth, PxU32 index) const; private: ConvexMeshContactGeneration& operator=(const ConvexMeshContactGeneration&); }; // 17 entries. 1088/17 = 64 triangles in the local array struct SavedContactData { PxU32 mTriangleIndex; // 1 PxVec3 mVerts[3]; // 10 PxU32 mInds[3]; // 13 PxVec3 mGroupAxis; // 16 PxReal mGroupMinDepth; // 17 }; } ConvexMeshContactGeneration::ConvexMeshContactGeneration( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ) : mDelayedContacts(delayedContacts), m0to1 (t0to1), m1to0 (t1to0), mPolyData0 (polyData0), mWorld0 (world0), mWorld1 (world1), mConvexScaling (convexScaling), mContactDistance(contactDistance), mToleranceLength(toleranceLength), mIdtConvexScale (idtConvexScale), mCCDEpsilon (cCCDEpsilon), mTransform0 (transform0), mTransform1 (transform1), mContactBuffer (contactBuffer) { delayedContacts.forceSize_Unsafe(0); mAnyHits = false; // Hull center in local space const PxVec3& hullCenterLocal = mPolyData0.mCenter; // Hull center in mesh space mHullCenterMesh = m0to1.transform(hullCenterLocal); // Hull center in world space mHullCenterWorld = mWorld0.transform(hullCenterLocal); } struct ConvexMeshContactGenerationCallback : MeshHitCallback<PxGeomRaycastHit> { ConvexMeshContactGeneration mGeneration; const FastVertex2ShapeScaling& mMeshScaling; const PxU8* PX_RESTRICT mExtraTrigData; bool mIdtMeshScale; const TriangleMesh* mMeshData; const BoxPadded& mBox; ConvexMeshContactGenerationCallback( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const TriangleMesh* meshData, const PxU8* PX_RESTRICT extraTrigData, const FastVertex2ShapeScaling& meshScaling, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtMeshScale, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const BoxPadded& box ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, contactDistance, toleranceLength, idtConvexScale, cCCDEpsilon, transform0, transform1, contactBuffer), mMeshScaling (meshScaling), mExtraTrigData (extraTrigData), mIdtMeshScale (idtMeshScale), mMeshData (meshData), mBox (box) { } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { // PT: this one is safe because incoming vertices from midphase are always safe to V4Load (by design) // PT: TODO: is this test really needed? Not done in midphase already? if(!intersectTriangleBox(mBox, v0, v1, v2)) return true; PxVec3 verts[3]; getScaledVertices(verts, v0, v1, v2, mIdtMeshScale, mMeshScaling); const PxU32 triangleIndex = hit.faceIndex; PxU8 extraData = getConvexEdgeFlags(mExtraTrigData, triangleIndex); const PxU32* vertexIndices = vinds; PxU32 localStorage[3]; if(mMeshScaling.flipsNormal()) { flipConvexEdgeFlags(extraData); localStorage[0] = vinds[0]; localStorage[1] = vinds[2]; localStorage[2] = vinds[1]; vertexIndices = localStorage; } mGeneration.processTriangle(verts, triangleIndex, extraData, vertexIndices); return true; } protected: ConvexMeshContactGenerationCallback &operator=(const ConvexMeshContactGenerationCallback &); }; bool ConvexMeshContactGeneration::generateContacts( const PxPlane& localPlane, const PxVec3* PX_RESTRICT localPoints, const PxVec3& triCenter, PxVec3& groupAxis, PxReal groupMinDepth, PxU32 index) const { const PxVec3 worldGroupCenter = mWorld1.transform(triCenter); const PxVec3 deltaC = mHullCenterWorld - worldGroupCenter; if(deltaC.dot(groupAxis) < 0.0f) groupAxis = -groupAxis; const PxU32 id = (mPolyData0.mSelectClosestEdgeCB)(mPolyData0, mConvexScaling, mWorld0.rotateTranspose(-groupAxis)); const HullPolygonData& HP = mPolyData0.mPolygons[id]; PX_ALIGN(16, PxPlane) shapeSpacePlane0; if(mIdtConvexScale) V4StoreA(V4LoadU(&HP.mPlane.n.x), &shapeSpacePlane0.n.x); else mConvexScaling.transformPlaneToShapeSpace(HP.mPlane.n, HP.mPlane.d, shapeSpacePlane0.n, shapeSpacePlane0.d); const PxVec3 hullNormalWorld = mWorld0.rotate(shapeSpacePlane0.n); const PxReal d0 = PxAbs(hullNormalWorld.dot(groupAxis)); const PxVec3 triNormalWorld = mWorld1.rotate(localPlane.n); const PxReal d1 = PxAbs(triNormalWorld.dot(groupAxis)); const bool d0biggerd1 = d0 > d1; ////////////////////NEW DIST HANDLING////////////////////// //TODO: skip this if there is no dist involved! PxReal separation = - groupMinDepth; //convert to real distance. separation = fsel(separation, separation, 0.0f); //don't do anything when penetrating! //printf("\nseparation = %f", separation); PxReal contactGenPositionShift = separation + mCCDEpsilon; //if we're at a distance, shift so we're within penetration. PxVec3 contactGenPositionShiftVec = groupAxis * contactGenPositionShift; //shift one of the bodies this distance toward the other just for Pierre's contact generation. Then the bodies should be penetrating exactly by MIN_SEPARATION_FOR_PENALTY - ideal conditions for this contact generator. //note: for some reason this has to change sign! //this will make contact gen always generate contacts at about MSP. Shift them back to the true real distance, and then to a solver compliant distance given that //the solver converges to MSP penetration, while we want it to converge to 0 penetration. //to real distance: // PxReal polyPolySeparationShift = separation; //(+ or - depending on which way normal goes) //The system: We always shift convex 0 (arbitrary). If the contact is attached to convex 0 then we will need to shift the contact point, otherwise not. //TODO: make these overwrite orig location if its safe to do so. PxMat34 world0_(mWorld0); PxTransform transform0_(mTransform0); world0_.p -= contactGenPositionShiftVec; transform0_.p = world0_.p; //reset this too. const PxTransform t0to1_ = mTransform1.transformInv(transform0_); const PxTransform t1to0_ = transform0_.transformInv(mTransform1); const Matrix34FromTransform m0to1_(t0to1_); const Matrix34FromTransform m1to0_(t1to0_); PxVec3* scaledVertices0; PxU8* stackIndices0; GET_SCALEX_CONVEX(scaledVertices0, stackIndices0, mIdtConvexScale, HP.mNbVerts, mConvexScaling, mPolyData0.mVerts, mPolyData0.getPolygonVertexRefs(HP)) const PxU8 indices[3] = {0, 1, 2}; const PxMat33 RotT0 = findRotationMatrixFromZ(shapeSpacePlane0.n); const PxMat33 RotT1 = findRotationMatrixFromZ(localPlane.n); if(d0biggerd1) { if(contactPolygonPolygonExt( HP.mNbVerts, scaledVertices0, stackIndices0, world0_, shapeSpacePlane0, RotT0, 3, localPoints, indices, mWorld1, localPlane, RotT1, hullNormalWorld, m0to1_, m1to0_, PXC_CONTACT_NO_FACE_INDEX, index, mContactBuffer, true, contactGenPositionShiftVec, contactGenPositionShift)) { return true; } } else { if(contactPolygonPolygonExt( 3, localPoints, indices, mWorld1, localPlane, RotT1, HP.mNbVerts, scaledVertices0, stackIndices0, world0_, shapeSpacePlane0, RotT0, triNormalWorld, m1to0_, m0to1_, PXC_CONTACT_NO_FACE_INDEX, index, mContactBuffer, false, contactGenPositionShiftVec, contactGenPositionShift)) { return true; } } return false; } enum FeatureCode { FC_VERTEX0, FC_VERTEX1, FC_VERTEX2, FC_EDGE01, FC_EDGE12, FC_EDGE20, FC_FACE, FC_UNDEFINED }; static FeatureCode computeFeatureCode(const PxVec3& point, const PxVec3* verts) { const PxVec3& triangleOrigin = verts[0]; const PxVec3 triangleEdge0 = verts[1] - verts[0]; const PxVec3 triangleEdge1 = verts[2] - verts[0]; const PxVec3 kDiff = triangleOrigin - point; const PxReal fA00 = triangleEdge0.magnitudeSquared(); const PxReal fA01 = triangleEdge0.dot(triangleEdge1); const PxReal fA11 = triangleEdge1.magnitudeSquared(); const PxReal fB0 = kDiff.dot(triangleEdge0); const PxReal fB1 = kDiff.dot(triangleEdge1); const PxReal fDet = PxAbs(fA00*fA11 - fA01*fA01); const PxReal u = fA01*fB1-fA11*fB0; const PxReal v = fA01*fB0-fA00*fB1; FeatureCode fc = FC_UNDEFINED; if(u + v <= fDet) { if(u < 0.0f) { if(v < 0.0f) // region 4 { if(fB0 < 0.0f) { if(-fB0 >= fA00) fc = FC_VERTEX1; else fc = FC_EDGE01; } else { if(fB1 >= 0.0f) fc = FC_VERTEX0; else if(-fB1 >= fA11) fc = FC_VERTEX2; else fc = FC_EDGE20; } } else // region 3 { if(fB1 >= 0.0f) fc = FC_VERTEX0; else if(-fB1 >= fA11) fc = FC_VERTEX2; else fc = FC_EDGE20; } } else if(v < 0.0f) // region 5 { if(fB0 >= 0.0f) fc = FC_VERTEX0; else if(-fB0 >= fA00) fc = FC_VERTEX1; else fc = FC_EDGE01; } else // region 0 { // minimum at interior PxVec3 if(fDet==0.0f) fc = FC_VERTEX0; else fc = FC_FACE; } } else { PxReal fTmp0, fTmp1, fNumer, fDenom; if(u < 0.0f) // region 2 { fTmp0 = fA01 + fB0; fTmp1 = fA11 + fB1; if(fTmp1 > fTmp0) { fNumer = fTmp1 - fTmp0; fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX1; else fc = FC_EDGE12; } else { if(fTmp1 <= 0.0f) fc = FC_VERTEX2; else if(fB1 >= 0.0f) fc = FC_VERTEX0; else fc = FC_EDGE20; } } else if(v < 0.0f) // region 6 { fTmp0 = fA01 + fB1; fTmp1 = fA00 + fB0; if(fTmp1 > fTmp0) { fNumer = fTmp1 - fTmp0; fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX2; else fc = FC_EDGE12; } else { if(fTmp1 <= 0.0f) fc = FC_VERTEX1; else if(fB0 >= 0.0f) fc = FC_VERTEX0; else fc = FC_EDGE01; } } else // region 1 { fNumer = fA11 + fB1 - fA01 - fB0; if(fNumer <= 0.0f) { fc = FC_VERTEX2; } else { fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX1; else fc = FC_EDGE12; } } } return fc; } //static bool validateVertex(PxU32 vref, const PxU32 count, const ContactPoint* PX_RESTRICT contacts, const TriangleMesh& meshData) //{ // PxU32 previous = 0xffffffff; // for(PxU32 i=0;i<count;i++) // { // if(contacts[i].internalFaceIndex1==previous) // continue; // previous = contacts[i].internalFaceIndex1; // // const TriangleIndices T(meshData, contacts[i].internalFaceIndex1); // if( T.mVRefs[0]==vref // || T.mVRefs[1]==vref // || T.mVRefs[2]==vref) // return false; // } // return true; //} //static PX_FORCE_INLINE bool testEdge(PxU32 vref0, PxU32 vref1, PxU32 tvref0, PxU32 tvref1) //{ // if(tvref0>tvref1) // PxSwap(tvref0, tvref1); // // if(tvref0==vref0 && tvref1==vref1) // return false; // return true; //} //static bool validateEdge(PxU32 vref0, PxU32 vref1, const PxU32 count, const ContactPoint* PX_RESTRICT contacts, const TriangleMesh& meshData) //{ // if(vref0>vref1) // PxSwap(vref0, vref1); // // PxU32 previous = 0xffffffff; // for(PxU32 i=0;i<count;i++) // { // if(contacts[i].internalFaceIndex1==previous) // continue; // previous = contacts[i].internalFaceIndex1; // // const TriangleIndices T(meshData, contacts[i].internalFaceIndex1); // ///* if(T.mVRefs[0]==vref0 || T.mVRefs[0]==vref1) // return false; // if(T.mVRefs[1]==vref0 || T.mVRefs[1]==vref1) // return false; // if(T.mVRefs[2]==vref0 || T.mVRefs[2]==vref1) // return false;*/ // // PT: wow, this was wrong??? ###FIX // if(!testEdge(vref0, vref1, T.mVRefs[0], T.mVRefs[1])) // return false; // if(!testEdge(vref0, vref1, T.mVRefs[1], T.mVRefs[2])) // return false; // if(!testEdge(vref0, vref1, T.mVRefs[2], T.mVRefs[0])) // return false; // } // return true; //} //static bool validateEdge(PxU32 vref0, PxU32 vref1, const PxU32* vertIndices, const PxU32 nbIndices) //{ // if(vref0>vref1) // PxSwap(vref0, vref1); // // for(PxU32 i=0;i<nbIndices;i+=3) // { // if(!testEdge(vref0, vref1, vertIndices[i+0], vertIndices[i+1])) // return false; // if(!testEdge(vref0, vref1, vertIndices[i+1], vertIndices[i+2])) // return false; // if(!testEdge(vref0, vref1, vertIndices[i+2], vertIndices[i+0])) // return false; // } // return true; //} //#endif void ConvexMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds) { const PxPlane localPlane(verts[0], verts[1], verts[2]); // Backface culling if(localPlane.distance(mHullCenterMesh)<0.0f) // if(localPlane.normal.dot(mHullCenterMesh - T.mVerts[0]) <= 0.0f) return; ////////////////////////////////////////////////////////////////////////// const PxVec3 triCenter = (verts[0] + verts[1] + verts[2])*(1.0f/3.0f); // Group center in hull space #ifdef USE_TRIANGLE_NORMAL const PxVec3 groupCenterHull = m1to0.rotate(localPlane.normal); #else const PxVec3 groupCenterHull = m1to0.transform(triCenter); #endif ////////////////////////////////////////////////////////////////////////// PxVec3 groupAxis; PxReal groupMinDepth; bool faceContact; if(!triangleConvexTest( mPolyData0, triFlags, triangleIndex, verts, localPlane, groupCenterHull, mWorld0, mWorld1, m0to1, m1to0, mConvexScaling, mContactDistance, mToleranceLength, groupAxis, groupMinDepth, faceContact, mIdtConvexScale )) return; if(faceContact) { // PT: generate face contacts immediately to save memory & avoid recomputing triangle data later if(generateContacts( localPlane, verts, triCenter, groupAxis, groupMinDepth, triangleIndex)) { mAnyHits = true; mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1])); mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[2])); mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2])); mVertCache.addData(CachedVertex(vertInds[0])); mVertCache.addData(CachedVertex(vertInds[1])); mVertCache.addData(CachedVertex(vertInds[2])); } else { int stop=1; (void)stop; } } else { const PxU32 nb = sizeof(SavedContactData)/sizeof(PxU32); // PT: no "pushBack" please (useless data copy + LHS) PxU32 newSize = nb + mDelayedContacts.size(); mDelayedContacts.reserve(newSize); SavedContactData* PX_RESTRICT cd = reinterpret_cast<SavedContactData*>(mDelayedContacts.end()); mDelayedContacts.forceSize_Unsafe(newSize); cd->mTriangleIndex = triangleIndex; cd->mVerts[0] = verts[0]; cd->mVerts[1] = verts[1]; cd->mVerts[2] = verts[2]; cd->mInds[0] = vertInds[0]; cd->mInds[1] = vertInds[1]; cd->mInds[2] = vertInds[2]; cd->mGroupAxis = groupAxis; cd->mGroupMinDepth = groupMinDepth; } } void ConvexMeshContactGeneration::generateLastContacts() { // Process delayed contacts PxU32 nbEntries = mDelayedContacts.size(); if(nbEntries) { nbEntries /= sizeof(SavedContactData)/sizeof(PxU32); // PT: TODO: replicate this fix in sphere-vs-mesh ###FIX //const PxU32 count = mContactBuffer.count; //const ContactPoint* PX_RESTRICT contacts = mContactBuffer.contacts; const SavedContactData* PX_RESTRICT cd = reinterpret_cast<const SavedContactData*>(mDelayedContacts.begin()); for(PxU32 i=0;i<nbEntries;i++) { const SavedContactData& currentContact = cd[i]; const PxU32 triangleIndex = currentContact.mTriangleIndex; // PT: unfortunately we must recompute this triangle-data here. // PT: TODO: find a way not to // const TriangleVertices T(*mMeshData, mMeshScaling, triangleIndex); // const TriangleIndices T(*mMeshData, triangleIndex); const PxU32 ref0 = currentContact.mInds[0]; const PxU32 ref1 = currentContact.mInds[1]; const PxU32 ref2 = currentContact.mInds[2]; // PT: TODO: why bother with the feature code at all? Use edge cache directly? // const FeatureCode FC = computeFeatureCode(mHullCenterMesh, T.mVerts); const FeatureCode FC = computeFeatureCode(mHullCenterMesh, currentContact.mVerts); bool generateContact = false; switch(FC) { // PT: trying the same as in sphere-mesh here case FC_VERTEX0: generateContact = !mVertCache.contains(CachedVertex(ref0)); break; case FC_VERTEX1: generateContact =!mVertCache.contains(CachedVertex(ref1)); break; case FC_VERTEX2: generateContact = !mVertCache.contains(CachedVertex(ref2)); break; case FC_EDGE01: generateContact = !mEdgeCache.contains(CachedEdge(ref0, ref1)); break; case FC_EDGE12: generateContact = !mEdgeCache.contains(CachedEdge(ref1, ref2)); break; case FC_EDGE20: generateContact = !mEdgeCache.contains(CachedEdge(ref0, ref2)); break; case FC_FACE: generateContact = true; break; case FC_UNDEFINED: break; }; if(!generateContact) continue; // const PxcPlane localPlane(T.mVerts[0], T.mVerts[1], T.mVerts[2]); const PxPlane localPlane(currentContact.mVerts[0], currentContact.mVerts[1], currentContact.mVerts[2]); // const PxVec3 triCenter = (T.mVerts[0] + T.mVerts[1] + T.mVerts[2])*(1.0f/3.0f); const PxVec3 triCenter = (currentContact.mVerts[0] + currentContact.mVerts[1] + currentContact.mVerts[2])*(1.0f/3.0f); PxVec3 groupAxis = currentContact.mGroupAxis; if(generateContacts( localPlane, // T.mVerts, currentContact.mVerts, triCenter, groupAxis, currentContact.mGroupMinDepth, triangleIndex)) { mAnyHits = true; //We don't add the edges to the data - this is important because we don't want to reject triangles //because we generated an edge contact with an adjacent triangle /*mEdgeCache.addData(CachedEdge(ref0, ref1)); mEdgeCache.addData(CachedEdge(ref0, ref2)); mEdgeCache.addData(CachedEdge(ref1, ref2)); mVertCache.addData(CachedVertex(ref0)); mVertCache.addData(CachedVertex(ref1)); mVertCache.addData(CachedVertex(ref2));*/ } } } } ///////////// static bool contactHullMesh2(const PolygonalData& polyData0, const PxBounds3& hullAABB, const PxTriangleMeshGeometry& shape1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& convexScaling, const FastVertex2ShapeScaling& meshScaling, bool idtConvexScale, bool idtMeshScale) { //Just a sanity-check in debug-mode PX_ASSERT(shape1.getType() == PxGeometryType::eTRIANGLEMESH); //////////////////// // Compute matrices const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); // Compute relative transforms const PxTransform t0to1 = transform1.transformInv(transform0); const PxTransform t1to0 = transform0.transformInv(transform1); BoxPadded hullOBB; computeHullOBB(hullOBB, hullAABB, params.mContactDistance, world0, world1, meshScaling, idtMeshScale); // Setup the collider const TriangleMesh* PX_RESTRICT meshData = _getMeshData(shape1); PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE> delayedContacts; ConvexMeshContactGenerationCallback blockCallback( delayedContacts, t0to1, t1to0, polyData0, world0, world1, meshData, meshData->getExtraTrigData(), meshScaling, convexScaling, params.mContactDistance, params.mToleranceLength, idtMeshScale, idtConvexScale, params.mMeshContactMargin, transform0, transform1, contactBuffer, hullOBB ); Midphase::intersectOBB(meshData, hullOBB, blockCallback, false); blockCallback.mGeneration.generateLastContacts(); return blockCallback.mGeneration.mAnyHits; } ///////////// bool Gu::contactConvexMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const bool idtScaleMesh = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData0; const bool idtScaleConvex = getConvexData(shapeConvex, convexScaling, hullAABB, polyData0); return contactHullMesh2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, convexScaling, meshScaling, idtScaleConvex, idtScaleMesh); } bool Gu::contactBoxMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); const PxBounds3 hullAABB(-shapeBox.halfExtents, shapeBox.halfExtents); const bool idtScaleMesh = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling idtScaling; return contactHullMesh2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, idtScaling, meshScaling, true, idtScaleMesh); } ///////////// namespace { struct ConvexVsHeightfieldContactGenerationCallback : OverlapReport { ConvexMeshContactGeneration mGeneration; HeightFieldUtil& mHfUtil; ConvexVsHeightfieldContactGenerationCallback( HeightFieldUtil& hfUtil, PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ) : mGeneration(delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, contactDistance, toleranceLength, idtConvexScale, cCCDEpsilon, transform0, transform1, contactBuffer), mHfUtil(hfUtil) { } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { const PxU8 nextInd[] = {2,0,1}; while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTriangle currentTriangle; // in world space PxU32 adjInds[3]; mHfUtil.getTriangle(mGeneration.mTransform1, currentTriangle, vertIndices, adjInds, triangleIndex, false, false); PxVec3 normal; currentTriangle.normal(normal); PxU8 triFlags = 0; //KS - temporary until we can calculate triFlags for HF for(PxU32 a = 0; a < 3; ++a) { if(adjInds[a] != 0xFFFFFFFF) { PxTriangle adjTri; mHfUtil.getTriangle(mGeneration.mTransform1, adjTri, NULL, NULL, adjInds[a], false, false); //We now compare the triangles to see if this edge is active PxVec3 adjNormal; adjTri.denormalizedNormal(adjNormal); PxU32 otherIndex = nextInd[a]; PxF32 projD = adjNormal.dot(currentTriangle.verts[otherIndex] - adjTri.verts[0]); if(projD < 0.f) { adjNormal.normalize(); PxF32 proj = adjNormal.dot(normal); if(proj < 0.999f) { triFlags |= 1 << (a+3); } } } else triFlags |= (1 << (a+3)); } mGeneration.processTriangle(currentTriangle.verts, triangleIndex, triFlags, vertIndices); } return true; } protected: ConvexVsHeightfieldContactGenerationCallback &operator=(const ConvexVsHeightfieldContactGenerationCallback &); }; } static bool contactHullHeightfield2(const PolygonalData& polyData0, const PxBounds3& hullAABB, const PxHeightFieldGeometry& shape1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& convexScaling, bool idtConvexScale) { //We need to create a callback that fills triangles from the HF HeightFieldUtil hfUtil(shape1); const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); //////////////////// // Compute relative transforms const PxTransform t0to1 = transform1.transformInv(transform0); const PxTransform t1to0 = transform0.transformInv(transform1); PxInlineArray<PxU32, LOCAL_CONTACTS_SIZE> delayedContacts; ConvexVsHeightfieldContactGenerationCallback blockCallback(hfUtil, delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, params.mContactDistance, params.mToleranceLength, idtConvexScale, params.mMeshContactMargin, transform0, transform1, contactBuffer); hfUtil.overlapAABBTriangles0to1(t0to1, hullAABB, blockCallback); blockCallback.mGeneration.generateLastContacts(); return blockCallback.mGeneration.mAnyHits; } bool Gu::contactConvexHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); //Create a triangle cache from the HF triangles and then feed triangles to NP mesh methods const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData0; const bool idtScaleConvex = getConvexData(shapeConvex, convexScaling, hullAABB, polyData0); const PxVec3 inflation(params.mContactDistance); hullAABB.minimum -= inflation; hullAABB.maximum += inflation; return contactHullHeightfield2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, convexScaling, idtScaleConvex); } bool Gu::contactBoxHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); //Create a triangle cache from the HF triangles and then feed triangles to NP mesh methods const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); const PxVec3 inflatedExtents = shapeBox.halfExtents + PxVec3(params.mContactDistance); const PxBounds3 hullAABB = PxBounds3(-inflatedExtents, inflatedExtents); const FastVertex2ShapeScaling idtScaling; return contactHullHeightfield2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, idtScaling, true); }
44,847
C++
29.592087
291
0.715722
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPolygonPolygon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONTACTPOLYGONPOLYGON_H #define GU_CONTACTPOLYGONPOLYGON_H #include "foundation/Px.h" #include "common/PxPhysXCommonConfig.h" namespace physx { class PxContactBuffer; namespace Cm { class FastVertex2ShapeScaling; } namespace Gu { PX_PHYSX_COMMON_API PxMat33 findRotationMatrixFromZ(const PxVec3& to); PX_PHYSX_COMMON_API bool contactPolygonPolygonExt( PxU32 numVerts0, const PxVec3* vertices0, const PxU8* indices0,//polygon 0 const PxMat34& world0, const PxPlane& localPlane0, //xform of polygon 0, plane of polygon const PxMat33& RotT0, PxU32 numVerts1, const PxVec3* vertices1, const PxU8* indices1,//polygon 1 const PxMat34& world1, const PxPlane& localPlane1, //xform of polygon 1, plane of polygon const PxMat33& RotT1, const PxVec3& worldSepAxis, //world normal of separating plane - this is the world space normal of polygon0!! const PxMat34& transform0to1, const PxMat34& transform1to0,//transforms between polygons PxU32 polyIndex0, PxU32 polyIndex1, //face indices for contact callback, PxContactBuffer& contactBuffer, bool flipNormal, const PxVec3& posShift, float sepShift ); // shape order, post gen shift. } } #endif
3,006
C
43.880596
130
0.736527
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleConvex.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuConvexMesh.h" #include "GuConvexHelper.h" #include "GuContactMethodImpl.h" #include "GuVecConvexHull.h" #include "GuVecCapsule.h" #include "GuInternal.h" #include "GuGJK.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; /////////// // #include "PxRenderOutput.h" // #include "PxsContext.h" // static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) // { // PxMat44 m = PxMat44::identity(); // // PxRenderOutput& out = context.mRenderOutput; // out << color << m << RenderOutput::LINES << a << b; // } /////////// static const PxReal fatConvexEdgeCoeff = 0.01f; static bool intersectEdgeEdgePreca(const PxVec3& p1, const PxVec3& p2, const PxVec3& v1, const PxPlane& plane, PxU32 i, PxU32 j, float coeff, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip, float limit) { // if colliding edge (p3,p4) does not cross plane return no collision // same as if p3 and p4 on same side of plane return 0 // // Derivation: // d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // if d3 and d4 have the same sign, they're on the same side of the plane => no collision // We test both sides at the same time by only testing Sign(d3 * d4). // ### put that in the Plane class // ### also check that code in the triangle class that might be similar const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp>0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision PxVec3 v2 = p4 - p3; temp = plane.n.dot(v2); if(temp==0.0f) return false; // ### epsilon would be better // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))*coeff; if(dist<limit) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; // no collision } static bool GuTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, const PxMat34& worldTM, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project convex PxReal Min1, Max1; (polyData.mProjectHull)(polyData, axis, worldTM, scaling, Min1, Max1); // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } static bool GuCapsuleConvexOverlap(const Segment& segment, PxReal radius, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, const PxTransform& transform, PxReal* t, PxVec3* pp, bool isSphere) { // TODO: // - test normal & edge in same loop // - local space // - use precomputed face value // - optimize projection PxVec3 Sep(0,0,0); PxReal PenDepth = PX_MAX_REAL; PxU32 nbPolys = polyData.mNbPolygons; const HullPolygonData* polys = polyData.mPolygons; const Matrix34FromTransform worldTM(transform); // Test normals for(PxU32 i=0;i<nbPolys;i++) { const HullPolygonData& poly = polys[i]; const PxPlane& vertSpacePlane = poly.mPlane; const PxVec3 worldNormal = worldTM.rotate(vertSpacePlane.n); PxReal d; if(!GuTestAxis(worldNormal, segment, radius, polyData, scaling, worldTM, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = worldNormal; } } // Test edges if(!isSphere) { PxVec3 CapsuleAxis(segment.p1 - segment.p0); CapsuleAxis = CapsuleAxis.getNormalized(); for(PxU32 i=0;i<nbPolys;i++) { const HullPolygonData& poly = polys[i]; const PxPlane& vertSpacePlane = poly.mPlane; const PxVec3 worldNormal = worldTM.rotate(vertSpacePlane.n); PxVec3 Cross = CapsuleAxis.cross(worldNormal); if(!isAlmostZero(Cross)) { Cross = Cross.getNormalized(); PxReal d; if(!GuTestAxis(Cross, segment, radius, polyData, scaling, worldTM, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = Cross; } } } } const PxVec3 Witness = segment.computeCenter() - transform.transform(polyData.mCenter); if(Sep.dot(Witness) < 0.0f) Sep = -Sep; if(t) *t = PenDepth; if(pp) *pp = Sep; return true; } static bool raycast_convexMesh2( const PolygonalData& polyData, const PxVec3& vrayOrig, const PxVec3& vrayDir, PxReal maxDist, PxF32& t) { PxU32 nPolys = polyData.mNbPolygons; const HullPolygonData* PX_RESTRICT polys = polyData.mPolygons; /* Purely convex planes based algorithm Iterate all planes of convex, with following rules: * determine of ray origin is inside them all or not. * planes parallel to ray direction are immediate early out if we're on the outside side (plane normal is sep axis) * else - for all planes the ray direction "enters" from the front side, track the one furthest along the ray direction (A) - for all planes the ray direction "exits" from the back side, track the one furthest along the negative ray direction (B) if the ray origin is outside the convex and if along the ray, A comes before B, the directed line stabs the convex at A */ PxReal latestEntry = -FLT_MAX; PxReal earliestExit = FLT_MAX; while(nPolys--) { const HullPolygonData& poly = *polys++; const PxPlane& vertSpacePlane = poly.mPlane; const PxReal distToPlane = vertSpacePlane.distance(vrayOrig); const PxReal dn = vertSpacePlane.n.dot(vrayDir); const PxReal distAlongRay = -distToPlane/dn; if (dn > 1E-7f) //the ray direction "exits" from the back side { earliestExit = physx::intrinsics::selectMin(earliestExit, distAlongRay); } else if (dn < -1E-7f) //the ray direction "enters" from the front side { /* if (distAlongRay > latestEntry) { latestEntry = distAlongRay; }*/ latestEntry = physx::intrinsics::selectMax(latestEntry, distAlongRay); } else { //plane normal and ray dir are orthogonal if(distToPlane > 0.0f) return false; //a plane is parallel with ray -- and we're outside the ray -- we definitely miss the entire convex! } } if(latestEntry < earliestExit && latestEntry != -FLT_MAX && latestEntry < maxDist-1e-5f) { t = latestEntry; return true; } return false; } // PT: version based on Gu::raycast_convexMesh to handle scaling, but modified to make sure it works when ray starts inside the convex static void GuGenerateVFContacts2(PxContactBuffer& contactBuffer, // const PxTransform& convexPose, const PolygonalData& polyData, // Convex data const PxMeshScale& scale, // PxU32 nbPts, const PxVec3* PX_RESTRICT points, const PxReal radius, // Capsule's radius // const PxVec3& normal, const PxReal contactDistance) { PX_ASSERT(PxAbs(normal.magnitudeSquared()-1)<1e-4f); //scaling: transform the ray to vertex space const PxMat34 world2vertexSkew = scale.getInverse() * convexPose.getInverse(); const PxVec3 vrayDir = world2vertexSkew.rotate( -normal ); const PxReal maxDist = contactDistance + radius; for(PxU32 i=0;i<nbPts;i++) { const PxVec3& rayOrigin = points[i]; const PxVec3 vrayOrig = world2vertexSkew.transform(rayOrigin); PxF32 t; if(raycast_convexMesh2(polyData, vrayOrig, vrayDir, maxDist, t)) { contactBuffer.contact(rayOrigin - t * normal, normal, t - radius); } } } static void GuGenerateEEContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, const PxReal contactDistance, // const PolygonalData& polyData, const PxTransform& transform, const FastVertex2ShapeScaling& scaling, // const PxVec3& normal) { PxU32 numPolygons = polyData.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData.mPolygons; const PxU8* PX_RESTRICT vertexData = polyData.mPolygonVertexRefs; ConvexEdge edges[512]; PxU32 nbEdges = findUniqueConvexEdges(512, edges, numPolygons, polygons, vertexData); // PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatConvexEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = v1.cross(normal); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[ii]*normal[jj]-v1[jj]*normal[ii]); // const PxVec3* PX_RESTRICT verts = polyData.mVerts; for(PxU32 i=0;i<nbEdges;i++) { const PxU8 vi0 = edges[i].vref0; const PxU8 vi1 = edges[i].vref1; // PxVec3 p1 = transform.transform(verts[vi0]); // PxVec3 p2 = transform.transform(verts[vi1]); // makeFatEdge(p1, p2, fatConvexEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3 p1 = transform.transform(scaling * verts[vi0]); const PxVec3 p2 = transform.transform(scaling * verts[vi1]); PxReal dist; PxVec3 ip; // if(intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) // if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, -FLT_MAX)) if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, -radius-contactDistance)) // if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, 0)) { contactBuffer.contact(ip-normal*dist, normal, - (radius + dist)); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } static void GuGenerateEEContacts2b(PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const PxMat34& transform, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, // const PxVec3& normal, const PxReal contactDistance) { // TODO: // - local space const PxVec3 localDir = transform.rotateTranspose(normal); PxU32 polyIndex = (polyData.mSelectClosestEdgeCB)(polyData, scaling, localDir); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatConvexEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = -(v1.cross(normal)); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[jj]*normal[ii]-v1[ii]*normal[jj]); // const PxVec3* PX_RESTRICT verts = polyData.mVerts; const HullPolygonData& polygon = polyData.mPolygons[polyIndex]; const PxU8* PX_RESTRICT vRefBase = polyData.mPolygonVertexRefs + polygon.mVRef8; PxU32 numEdges = polygon.mNbVerts; PxU32 a = numEdges - 1; PxU32 b = 0; while(numEdges--) { // const PxVec3 p1 = transform.transform(verts[vRefBase[a]]); // const PxVec3 p2 = transform.transform(verts[vRefBase[b]]); const PxVec3 p1 = transform.transform(scaling * verts[vRefBase[a]]); const PxVec3 p2 = transform.transform(scaling * verts[vRefBase[b]]); PxReal dist; PxVec3 ip; // bool contact = intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); bool contact = intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip, 0.0f); if(contact && dist < radius + contactDistance) { contactBuffer.contact(ip-normal*dist, normal, dist - radius); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } a = b; b++; } } bool Gu::contactCapsuleConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); // Get actual shape data // PT: the capsule can be a sphere in this case so we do this special piece of code: PxCapsuleGeometry shapeCapsule = static_cast<const PxCapsuleGeometry&>(shape0); if(shape0.getType()==PxGeometryType::eSPHERE) shapeCapsule.halfHeight = 0.0f; const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); PxVec3 onSegment, onConvex; PxReal distance; PxVec3 normal_; { const ConvexMesh* cm = static_cast<const ConvexMesh*>(shapeConvex.convexMesh); using namespace aos; Vec3V closA, closB, normalV; GjkStatus status; FloatV dist; { const Vec3V zeroV = V3Zero(); const ConvexHullData* hullData = &cm->getHull(); const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const PxMatTransformV aToB(transform1.transformInv(transform0)); const ConvexHullV convexHull(hullData, zeroV, vScale, vQuat, shapeConvex.scale.isIdentity()); //transform capsule(a) into the local space of convexHull(b), treat capsule as segment const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), FZero()); const LocalConvex<CapsuleV> convexA(capsule); const LocalConvex<ConvexHullV> convexB(convexHull); const Vec3V initialSearchDir = V3Sub(convexA.getCenter(), convexB.getCenter()); status = gjk<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, FMax(),closA, closB, normalV, dist); } if(status == GJK_CONTACT) distance = 0.f; else { //const FloatV sqDist = FMul(dist, dist); V3StoreU(closB, onConvex); FStore(dist, &distance); V3StoreU(normalV, normal_); onConvex = transform1.transform(onConvex); normal_ = transform1.rotate(normal_); } } const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; if(distance >= inflatedRadius) return false; Segment worldSegment; getCapsuleSegment(transform0, shapeCapsule, worldSegment); const bool isSphere = worldSegment.p0 == worldSegment.p1; const PxU32 nbPts = PxU32(isSphere ? 1 : 2); PX_ASSERT(contactBuffer.count==0); FastVertex2ShapeScaling convexScaling; const bool idtConvexScale = shapeConvex.scale.isIdentity(); if(!idtConvexScale) convexScaling.init(shapeConvex.scale); PolygonalData polyData; getPolygonalData_Convex(&polyData, _getHullData(shapeConvex), convexScaling); // if(0) if(distance > 0.f) { // PT: the capsule segment doesn't intersect the convex => distance-based version PxVec3 normal = -normal_; // PT: generate VF contacts for segment's vertices vs convex GuGenerateVFContacts2( contactBuffer, transform1, polyData, shapeConvex.scale, nbPts, &worldSegment.p0, shapeCapsule.radius, normal, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts if(!isSphere) { const Matrix34FromTransform worldTM(transform1); GuGenerateEEContacts2b(contactBuffer, worldSegment, shapeCapsule.radius, worldTM, polyData, convexScaling, normal, params.mContactDistance); } // PT: run VF case for convex-vertex-vs-capsule only if we don't have any contact yet if(!contactBuffer.count) { // gVisualizeLine(onConvex, onConvex + normal, context, PxDebugColor::eARGB_RED); //PxReal distance = PxSqrt(sqDistance); contactBuffer.contact(onConvex, normal, distance - shapeCapsule.radius); } } else { // PT: the capsule segment intersects the convex => penetration-based version //printf("Penetration-based:\n"); // PT: compute penetration vector (MTD) PxVec3 SepAxis; if(!GuCapsuleConvexOverlap(worldSegment, shapeCapsule.radius, polyData, convexScaling, transform1, NULL, &SepAxis, isSphere)) { //printf("- no overlap\n"); return false; } // PT: generate VF contacts for segment's vertices vs convex GuGenerateVFContacts2( contactBuffer, transform1, polyData, shapeConvex.scale, nbPts, &worldSegment.p0, shapeCapsule.radius, SepAxis, params.mContactDistance); // PT: early exit if we already have 2 stable contacts //printf("- %d VF contacts\n", contactBuffer.count); if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts if(!isSphere) { GuGenerateEEContacts(contactBuffer, worldSegment, shapeCapsule.radius, params.mContactDistance, polyData, transform1, convexScaling, SepAxis); //printf("- %d total contacts\n", contactBuffer.count); } } return true; }
18,893
C++
31.688581
235
0.703806
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "common/PxRenderOutput.h" #include "GuDistancePointTriangle.h" #include "GuContactMethodImpl.h" #include "GuFeatureCode.h" #include "GuMidphaseInterface.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuBox.h" #include "foundation/PxSort.h" #define DEBUG_RENDER_MESHCONTACTS 0 using namespace physx; using namespace Gu; static const bool gDrawTouchedTriangles = false; static void outputErrorMessage() { #if PX_CHECKED PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Dropping contacts in sphere vs mesh: exceeded limit of 64 "); #endif } /////////////////////////////////////////////////////////////////////////////// // PT: a customized version that also returns the feature code static PxVec3 closestPtPointTriangle(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& s, float& t, FeatureCode& fc) { // Check if P in vertex region outside A const PxVec3 ab = b - a; const PxVec3 ac = c - a; const PxVec3 ap = p - a; const float d1 = ab.dot(ap); const float d2 = ac.dot(ap); if(d1<=0.0f && d2<=0.0f) { s = 0.0f; t = 0.0f; fc = FC_VERTEX0; return a; // Barycentric coords 1,0,0 } // Check if P in vertex region outside B const PxVec3 bp = p - b; const float d3 = ab.dot(bp); const float d4 = ac.dot(bp); if(d3>=0.0f && d4<=d3) { s = 1.0f; t = 0.0f; fc = FC_VERTEX1; return b; // Barycentric coords 0,1,0 } // Check if P in edge region of AB, if so return projection of P onto AB const float vc = d1*d4 - d3*d2; if(vc<=0.0f && d1>=0.0f && d3<=0.0f) { const float v = d1 / (d1 - d3); s = v; t = 0.0f; fc = FC_EDGE01; return a + v * ab; // barycentric coords (1-v, v, 0) } // Check if P in vertex region outside C const PxVec3 cp = p - c; const float d5 = ab.dot(cp); const float d6 = ac.dot(cp); if(d6>=0.0f && d5<=d6) { s = 0.0f; t = 1.0f; fc = FC_VERTEX2; return c; // Barycentric coords 0,0,1 } // Check if P in edge region of AC, if so return projection of P onto AC const float vb = d5*d2 - d1*d6; if(vb<=0.0f && d2>=0.0f && d6<=0.0f) { const float w = d2 / (d2 - d6); s = 0.0f; t = w; fc = FC_EDGE20; return a + w * ac; // barycentric coords (1-w, 0, w) } // Check if P in edge region of BC, if so return projection of P onto BC const float va = d3*d6 - d5*d4; if(va<=0.0f && (d4-d3)>=0.0f && (d5-d6)>=0.0f) { const float w = (d4-d3) / ((d4 - d3) + (d5-d6)); s = 1.0f-w; t = w; fc = FC_EDGE12; return b + w * (c-b); // barycentric coords (0, 1-w, w) } // P inside face region. Compute Q through its barycentric coords (u,v,w) const float denom = 1.0f / (va + vb + vc); const float v = vb * denom; const float w = vc * denom; s = v; t = w; fc = FC_FACE; return a + ab*v + ac*w; } /////////////////////////////////////////////////////////////////////////////// // PT: we use a separate structure to make sorting faster struct SortKey { float mSquareDist; PxU32 mIndex; PX_FORCE_INLINE bool operator < (const SortKey& data) const { return mSquareDist < data.mSquareDist; } }; struct TriangleData { PxVec3 mDelta; FeatureCode mFC; PxU32 mTriangleIndex; PxU32 mVRef[3]; }; struct CachedTriangleIndices { PxU32 mVRef[3]; }; static PX_FORCE_INLINE bool validateSquareDist(PxReal squareDist) { return squareDist>0.0001f; } static bool validateEdge(PxU32 vref0, PxU32 vref1, const CachedTriangleIndices* cachedTris, PxU32 nbCachedTris) { while(nbCachedTris--) { const CachedTriangleIndices& inds = *cachedTris++; const PxU32 vi0 = inds.mVRef[0]; const PxU32 vi1 = inds.mVRef[1]; const PxU32 vi2 = inds.mVRef[2]; if(vi0==vref0) { if(vi1==vref1 || vi2==vref1) return false; } else if(vi1==vref0) { if(vi0==vref1 || vi2==vref1) return false; } else if(vi2==vref0) { if(vi1==vref1 || vi0==vref1) return false; } } return true; } static bool validateVertex(PxU32 vref, const CachedTriangleIndices* cachedTris, PxU32 nbCachedTris) { while(nbCachedTris--) { const CachedTriangleIndices& inds = *cachedTris++; if(inds.mVRef[0]==vref || inds.mVRef[1]==vref || inds.mVRef[2]==vref) return false; } return true; } namespace { class NullAllocator { public: PX_FORCE_INLINE NullAllocator() { } PX_FORCE_INLINE void* allocate(size_t, const char*, int) { return NULL; } PX_FORCE_INLINE void deallocate(void*) { } }; struct SphereMeshContactGeneration { const PxSphereGeometry& mShapeSphere; const PxTransform& mTransform0; const PxTransform& mTransform1; PxContactBuffer& mContactBuffer; const PxVec3& mSphereCenterShape1Space; PxF32 mInflatedRadius2; PxU32 mNbDelayed; TriangleData mSavedData[PxContactBuffer::MAX_CONTACTS]; SortKey mSortKey[PxContactBuffer::MAX_CONTACTS]; PxU32 mNbCachedTris; CachedTriangleIndices mCachedTris[PxContactBuffer::MAX_CONTACTS]; PxRenderOutput* mRenderOutput; SphereMeshContactGeneration(const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput) : mShapeSphere (shapeSphere), mTransform0 (transform0), mTransform1 (transform1), mContactBuffer (contactBuffer), mSphereCenterShape1Space (sphereCenterShape1Space), mInflatedRadius2 (inflatedRadius*inflatedRadius), mNbDelayed (0), mNbCachedTris (0), mRenderOutput (renderOutput) { } PX_FORCE_INLINE void cacheTriangle(PxU32 ref0, PxU32 ref1, PxU32 ref2) { const PxU32 nb = mNbCachedTris++; mCachedTris[nb].mVRef[0] = ref0; mCachedTris[nb].mVRef[1] = ref1; mCachedTris[nb].mVRef[2] = ref2; } PX_FORCE_INLINE void addContact(const PxVec3& d, PxReal squareDist, PxU32 triangleIndex) { float dist; PxVec3 delta; if(validateSquareDist(squareDist)) { // PT: regular contact. Normalize 'delta'. dist = PxSqrt(squareDist); delta = d / dist; } else { // PT: singular contact: 'd' is the non-unit triangle's normal in this case. dist = 0.0f; delta = -d.getNormalized(); } const PxVec3 worldNormal = -mTransform1.rotate(delta); const PxVec3 localHit = mSphereCenterShape1Space + mShapeSphere.radius*delta; const PxVec3 hit = mTransform1.transform(localHit); if(!mContactBuffer.contact(hit, worldNormal, dist - mShapeSphere.radius, triangleIndex)) outputErrorMessage(); } void processTriangle(PxU32 triangleIndex, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxU32* vertInds) { // PT: compute closest point between sphere center and triangle PxReal u, v; FeatureCode fc; const PxVec3 cp = closestPtPointTriangle(mSphereCenterShape1Space, v0, v1, v2, u, v, fc); // PT: compute 'delta' vector between closest point and sphere center const PxVec3 delta = cp - mSphereCenterShape1Space; const PxReal squareDist = delta.magnitudeSquared(); if(squareDist >= mInflatedRadius2) return; // PT: backface culling without the normalize // PT: TODO: consider doing before the pt-triangle distance test if it's cheaper // PT: TODO: e0/e1 already computed in closestPtPointTriangle const PxVec3 e0 = v1 - v0; const PxVec3 e1 = v2 - v0; const PxVec3 planeNormal = e0.cross(e1); const PxF32 planeD = planeNormal.dot(v0); // PT: actually -d compared to PxcPlane if(planeNormal.dot(mSphereCenterShape1Space) < planeD) return; // PT: for a regular contact, 'delta' is non-zero (and so is 'squareDist'). However when the sphere's center exactly touches // the triangle, then both 'delta' and 'squareDist' become zero. This needs to be handled as a special case to avoid dividing // by zero. We will use the triangle's normal as a contact normal in this special case. // // 'validateSquareDist' is called twice because there are conflicting goals here. We could call it once now and already // compute the proper data for generating the contact. But this would mean doing a square-root and a division right here, // even when the contact is not actually needed in the end. We could also call it only once in "addContact', but the plane's // normal would not always be available (in case of delayed contacts), and thus it would need to be either recomputed (slower) // or stored within 'TriangleData' (using more memory). Calling 'validateSquareDist' twice is a better option overall. PxVec3 d; if(validateSquareDist(squareDist)) d = delta; else d = planeNormal; if(fc==FC_FACE) { addContact(d, squareDist, triangleIndex); if(mNbCachedTris<PxContactBuffer::MAX_CONTACTS) cacheTriangle(vertInds[0], vertInds[1], vertInds[2]); } else { if(mNbDelayed<PxContactBuffer::MAX_CONTACTS) { const PxU32 index = mNbDelayed++; mSortKey[index].mSquareDist = squareDist; mSortKey[index].mIndex = index; TriangleData* saved = mSavedData + index; saved->mDelta = d; saved->mVRef[0] = vertInds[0]; saved->mVRef[1] = vertInds[1]; saved->mVRef[2] = vertInds[2]; saved->mFC = fc; saved->mTriangleIndex = triangleIndex; } else outputErrorMessage(); } } void generateLastContacts() { const PxU32 count = mNbDelayed; if(!count) return; PxSort(mSortKey, count, PxLess<SortKey>(), NullAllocator(), PxContactBuffer::MAX_CONTACTS); TriangleData* touchedTris = mSavedData; for(PxU32 i=0;i<count;i++) { const TriangleData& data = touchedTris[mSortKey[i].mIndex]; const PxU32 ref0 = data.mVRef[0]; const PxU32 ref1 = data.mVRef[1]; const PxU32 ref2 = data.mVRef[2]; bool generateContact = false; switch(data.mFC) { case FC_VERTEX0: generateContact = ::validateVertex(ref0, mCachedTris, mNbCachedTris); break; case FC_VERTEX1: generateContact = ::validateVertex(ref1, mCachedTris, mNbCachedTris); break; case FC_VERTEX2: generateContact = ::validateVertex(ref2, mCachedTris, mNbCachedTris); break; case FC_EDGE01: generateContact = ::validateEdge(ref0, ref1, mCachedTris, mNbCachedTris); break; case FC_EDGE12: generateContact = ::validateEdge(ref1, ref2, mCachedTris, mNbCachedTris); break; case FC_EDGE20: generateContact = ::validateEdge(ref0, ref2, mCachedTris, mNbCachedTris); break; case FC_FACE: case FC_UNDEFINED: PX_ASSERT(0); // PT: should not be possible break; }; if(generateContact) addContact(data.mDelta, mSortKey[i].mSquareDist, data.mTriangleIndex); if(mNbCachedTris<PxContactBuffer::MAX_CONTACTS) cacheTriangle(ref0, ref1, ref2); else outputErrorMessage(); } } private: SphereMeshContactGeneration& operator=(const SphereMeshContactGeneration&); }; struct SphereMeshContactGenerationCallback_NoScale : MeshHitCallback<PxGeomRaycastHit> { SphereMeshContactGeneration mGeneration; const TriangleMesh& mMeshData; SphereMeshContactGenerationCallback_NoScale(const TriangleMesh& meshData, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (shapeSphere, transform0, transform1, contactBuffer, sphereCenterShape1Space, inflatedRadius, renderOutput), mMeshData (meshData) { } virtual ~SphereMeshContactGenerationCallback_NoScale() { mGeneration.generateLastContacts(); } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { if(gDrawTouchedTriangles) { (*mGeneration.mRenderOutput) << 0xffffffff; (*mGeneration.mRenderOutput) << PxMat44(PxIdentity); const PxVec3 wp0 = mGeneration.mTransform1.transform(v0); const PxVec3 wp1 = mGeneration.mTransform1.transform(v1); const PxVec3 wp2 = mGeneration.mTransform1.transform(v2); mGeneration.mRenderOutput->outputSegment(wp0, wp1); mGeneration.mRenderOutput->outputSegment(wp1, wp2); mGeneration.mRenderOutput->outputSegment(wp2, wp0); } mGeneration.processTriangle(hit.faceIndex, v0, v1, v2, vinds); return true; } protected: SphereMeshContactGenerationCallback_NoScale &operator=(const SphereMeshContactGenerationCallback_NoScale &); }; struct SphereMeshContactGenerationCallback_Scale : SphereMeshContactGenerationCallback_NoScale { const Cm::FastVertex2ShapeScaling& mMeshScaling; SphereMeshContactGenerationCallback_Scale(const TriangleMesh& meshData, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, const Cm::FastVertex2ShapeScaling& meshScaling, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : SphereMeshContactGenerationCallback_NoScale(meshData, shapeSphere, transform0, transform1, contactBuffer, sphereCenterShape1Space, inflatedRadius, renderOutput), mMeshScaling (meshScaling) { } virtual ~SphereMeshContactGenerationCallback_Scale() {} virtual PxAgain processHit(const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { PxVec3 verts[3]; getScaledVertices(verts, v0, v1, v2, false, mMeshScaling); const PxU32* vertexIndices = vinds; PxU32 localStorage[3]; if(mMeshScaling.flipsNormal()) { localStorage[0] = vinds[0]; localStorage[1] = vinds[2]; localStorage[2] = vinds[1]; vertexIndices = localStorage; } if(gDrawTouchedTriangles) { (*mGeneration.mRenderOutput) << 0xffffffff; (*mGeneration.mRenderOutput) << PxMat44(PxIdentity); const PxVec3 wp0 = mGeneration.mTransform1.transform(verts[0]); const PxVec3 wp1 = mGeneration.mTransform1.transform(verts[1]); const PxVec3 wp2 = mGeneration.mTransform1.transform(verts[2]); mGeneration.mRenderOutput->outputSegment(wp0, wp1); mGeneration.mRenderOutput->outputSegment(wp1, wp2); mGeneration.mRenderOutput->outputSegment(wp2, wp0); } mGeneration.processTriangle(hit.faceIndex, verts[0], verts[1], verts[2], vertexIndices); return true; } protected: SphereMeshContactGenerationCallback_Scale &operator=(const SphereMeshContactGenerationCallback_Scale &); }; } /////////////////////////////////////////////////////////////////////////////// bool Gu::contactSphereMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); // We must be in local space to use the cache const PxVec3 sphereCenterInMeshSpace = transform1.transformInv(transform0.p); const PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance; const TriangleMesh* meshData = _getMeshData(shapeMesh); // mesh scale is not baked into cached verts if(shapeMesh.scale.isIdentity()) { SphereMeshContactGenerationCallback_NoScale callback( *meshData, shapeSphere, transform0, transform1, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput); // PT: TODO: switch to sphere query here const Box obb(sphereCenterInMeshSpace, PxVec3(inflatedRadius), PxMat33(PxIdentity)); Midphase::intersectOBB(meshData, obb, callback, true); } else { const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale); SphereMeshContactGenerationCallback_Scale callback( *meshData, shapeSphere, transform0, transform1, meshScaling, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput); PxVec3 obbCenter = sphereCenterInMeshSpace; PxVec3 obbExtents = PxVec3(inflatedRadius); PxMat33 obbRot(PxIdentity); meshScaling.transformQueryBounds(obbCenter, obbExtents, obbRot); const Box obb(obbCenter, obbExtents, obbRot); Midphase::intersectOBB(meshData, obb, callback, true); } return contactBuffer.count > 0; } /////////////////////////////////////////////////////////////////////////////// namespace { struct SphereHeightfieldContactGenerationCallback : OverlapReport { SphereMeshContactGeneration mGeneration; HeightFieldUtil& mHfUtil; SphereHeightfieldContactGenerationCallback( HeightFieldUtil& hfUtil, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterInMeshSpace, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : mGeneration (shapeSphere, transform0, transform1, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput), mHfUtil (hfUtil) { } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTriangle currentTriangle; mHfUtil.getTriangle(mGeneration.mTransform1, currentTriangle, vertIndices, NULL, triangleIndex, false, false); mGeneration.processTriangle(triangleIndex, currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], vertIndices); } return true; } protected: SphereHeightfieldContactGenerationCallback &operator=(const SphereHeightfieldContactGenerationCallback &); }; } bool Gu::contactSphereHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); HeightFieldUtil hfUtil(shapeMesh); const PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance; PxBounds3 localBounds; const PxVec3 localSphereCenter = getLocalSphereData(localBounds, transform0, transform1, inflatedRadius); SphereHeightfieldContactGenerationCallback blockCallback(hfUtil, shapeSphere, transform0, transform1, contactBuffer, localSphereCenter, inflatedRadius, renderOutput); hfUtil.overlapAABBTriangles(localBounds, blockCallback); blockCallback.mGeneration.generateLastContacts(); return contactBuffer.count > 0; } ///////////////////////////////////////////////////////////////////////////////
19,978
C++
31.120579
167
0.719291
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactMethodImpl.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONTACTMETHODIMPL_H #define GU_CONTACTMETHODIMPL_H #include "foundation/PxAssert.h" #include "common/PxPhysXCommonConfig.h" #include "collision/PxCollisionDefs.h" #include "GuGeometryChecks.h" namespace physx { class PxGeometry; class PxRenderOutput; class PxContactBuffer; namespace Gu { class PersistentContactManifold; class MultiplePersistentContactManifold; struct NarrowPhaseParams { PX_FORCE_INLINE NarrowPhaseParams(PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength) : mContactDistance(contactDistance), mMeshContactMargin(meshContactMargin), mToleranceLength(toleranceLength) {} PxReal mContactDistance; const PxReal mMeshContactMargin; // PT: Margin used to generate mesh contacts. Temp & unclear, should be removed once GJK is default path. const PxReal mToleranceLength; // PT: copy of PxTolerancesScale::length }; enum ManifoldFlags { IS_MANIFOLD = (1<<0), IS_MULTI_MANIFOLD = (1<<1) }; struct Cache : public PxCache { Cache() { } PX_FORCE_INLINE void setManifold(void* manifold) { PX_ASSERT((size_t(manifold) & 0xF) == 0); mCachedData = reinterpret_cast<PxU8*>(manifold); mManifoldFlags |= IS_MANIFOLD; } PX_FORCE_INLINE void setMultiManifold(void* manifold) { PX_ASSERT((size_t(manifold) & 0xF) == 0); mCachedData = reinterpret_cast<PxU8*>(manifold); mManifoldFlags |= IS_MANIFOLD|IS_MULTI_MANIFOLD; } PX_FORCE_INLINE PxU8 isManifold() const { return PxU8(mManifoldFlags & IS_MANIFOLD); } PX_FORCE_INLINE PxU8 isMultiManifold() const { return PxU8(mManifoldFlags & IS_MULTI_MANIFOLD); } PX_FORCE_INLINE PersistentContactManifold& getManifold() { PX_ASSERT(isManifold()); PX_ASSERT(!isMultiManifold()); PX_ASSERT((uintptr_t(mCachedData) & 0xf) == 0); return *reinterpret_cast<PersistentContactManifold*>(mCachedData); } PX_FORCE_INLINE MultiplePersistentContactManifold& getMultipleManifold() { PX_ASSERT(isManifold()); PX_ASSERT(isMultiManifold()); PX_ASSERT((uintptr_t(mCachedData) & 0xf) == 0); return *reinterpret_cast<MultiplePersistentContactManifold*>(mCachedData); } }; } template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE const Geom& checkedCast(const PxGeometry& geom) { checkType<Geom>(geom); return static_cast<const Geom&>(geom); } #define GU_CONTACT_METHOD_ARGS \ const PxGeometry& shape0, \ const PxGeometry& shape1, \ const PxTransform32& transform0, \ const PxTransform32& transform1, \ const Gu::NarrowPhaseParams& params, \ Gu::Cache& cache, \ PxContactBuffer& contactBuffer, \ PxRenderOutput* renderOutput #define GU_CONTACT_METHOD_ARGS_UNUSED \ const PxGeometry&, \ const PxGeometry&, \ const PxTransform32&, \ const PxTransform32&, \ const Gu::NarrowPhaseParams&, \ Gu::Cache&, \ PxContactBuffer&, \ PxRenderOutput* namespace Gu { PX_PHYSX_COMMON_API bool contactSphereSphere(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSpherePlane(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereSphere(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSpherePlane(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS); } } #endif
7,987
C
38.544554
140
0.771504
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereCapsule.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuDistancePointSegment.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" using namespace physx; bool Gu::contactSphereCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom = checkedCast<PxSphereGeometry>(shape0); const PxCapsuleGeometry& capsuleGeom = checkedCast<PxCapsuleGeometry>(shape1); // PT: get capsule in local space const PxVec3 capsuleLocalSegment = getCapsuleHalfHeightVector(transform1, capsuleGeom); const Segment localSegment(capsuleLocalSegment, -capsuleLocalSegment); // PT: get sphere in capsule space const PxVec3 sphereCenterInCapsuleSpace = transform0.p - transform1.p; const PxReal radiusSum = sphereGeom.radius + capsuleGeom.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; // PT: compute distance between sphere center & capsule's segment PxReal u; const PxReal squareDist = distancePointSegmentSquared(localSegment, sphereCenterInCapsuleSpace, &u); if(squareDist >= inflatedSum*inflatedSum) return false; // PT: compute contact normal PxVec3 normal = sphereCenterInCapsuleSpace - localSegment.getPointAt(u); // We do a *manual* normalization to check for singularity condition const PxReal lenSq = normal.magnitudeSquared(); if(lenSq==0.0f) normal = PxVec3(1.0f, 0.0f, 0.0f); // PT: zero normal => pick up random one else normal *= PxRecipSqrt(lenSq); // PT: compute contact point const PxVec3 point = sphereCenterInCapsuleSpace + transform1.p - normal * sphereGeom.radius; // PT: output unique contact contactBuffer.contact(point, normal, PxSqrt(squareDist) - radiusSum); return true; }
3,397
C++
43.12987
101
0.771563
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactConvexConvex.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactPolygonPolygon.h" #include "GuConvexHelper.h" #include "GuInternal.h" #include "GuSeparatingAxes.h" #include "GuContactMethodImpl.h" #include "foundation/PxFPU.h" #include "foundation/PxAlloca.h" #include "CmMatrix34.h" // csigg: the single reference of gEnableOptims (below) has been // replaced with the actual value to prevent ios64 compiler crash. // static const int gEnableOptims = 1; #define CONVEX_CONVEX_ROUGH_FIRST_PASS #define TEST_INTERNAL_OBJECTS #ifdef TEST_INTERNAL_OBJECTS #define USE_BOX_DATA #endif using namespace physx; using namespace Gu; using namespace Cm; using namespace aos; using namespace intrinsics; #ifdef TEST_INTERNAL_OBJECTS #ifdef USE_BOX_DATA PX_FORCE_INLINE void BoxSupport(const float extents[3], const PxVec3& sv, float p[3]) { const PxU32* iextents = reinterpret_cast<const PxU32*>(extents); const PxU32* isv = reinterpret_cast<const PxU32*>(&sv); PxU32* ip = reinterpret_cast<PxU32*>(p); ip[0] = iextents[0]|(isv[0]&PX_SIGN_BITMASK); ip[1] = iextents[1]|(isv[1]&PX_SIGN_BITMASK); ip[2] = iextents[2]|(isv[2]&PX_SIGN_BITMASK); } #endif #if PX_DEBUG static const PxReal testInternalObjectsEpsilon = 1.0e-3f; #endif #ifdef DO_NOT_REMOVE PX_FORCE_INLINE void testInternalObjects_( const PxVec3& delta_c, const PxVec3& axis, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& tr0, const PxMat34& tr1, float& dmin, float contactDistance) { { /* float projected0 = axis.dot(tr0.p); float projected1 = axis.dot(tr1.p); float min0 = projected0 - polyData0.mInternal.mRadius; float max0 = projected0 + polyData0.mInternal.mRadius; float min1 = projected1 - polyData1.mInternal.mRadius; float max1 = projected1 + polyData1.mInternal.mRadius; */ float MinMaxRadius = polyData0.mInternal.mRadius + polyData1.mInternal.mRadius; PxVec3 delta = tr0.p - tr1.p; const PxReal dp = axis.dot(delta); // const PxReal dp2 = axis.dot(delta_c); // const PxReal d0 = max0 - min1; // const PxReal d0 = projected0 + polyData0.mInternal.mRadius - projected1 + polyData1.mInternal.mRadius; // const PxReal d0 = projected0 - projected1 + polyData0.mInternal.mRadius + polyData1.mInternal.mRadius; // const PxReal d0 = projected0 - projected1 + MinMaxRadius; // const PxReal d0 = axis.dot(tr0.p) - axis.dot(tr1.p) + MinMaxRadius; // const PxReal d0 = axis.dot(tr0.p - tr1.p) + MinMaxRadius; // const PxReal d0 = MinMaxRadius + axis.dot(delta); const PxReal d0 = MinMaxRadius + dp; // const PxReal d1 = max1 - min0; // const PxReal d1 = projected1 + polyData1.mInternal.mRadius - projected0 + polyData0.mInternal.mRadius; // const PxReal d1 = projected1 - projected0 + polyData1.mInternal.mRadius + polyData0.mInternal.mRadius; // const PxReal d1 = projected1 - projected0 + MinMaxRadius; // const PxReal d1 = axis.dot(tr1.p) - axis.dot(tr0.p) + MinMaxRadius; // const PxReal d1 = axis.dot(tr1.p - tr0.p) + MinMaxRadius; // const PxReal d1 = MinMaxRadius - axis.dot(delta); const PxReal d1 = MinMaxRadius - dp; dmin = selectMin(d0, d1); return; } #ifdef USE_BOX_DATA const PxVec3 localAxis0 = tr0.rotateTranspose(axis); const PxVec3 localAxis1 = tr1.rotateTranspose(axis); const float dp = delta_c.dot(axis); float p0[3]; BoxSupport(polyData0.mInternal.mExtents, localAxis0, p0); float p1[3]; BoxSupport(polyData1.mInternal.mExtents, localAxis1, p1); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float Radius1 = p1[0]*localAxis1.x + p1[1]*localAxis1.y + p1[2]*localAxis1.z; const float MinRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const float MaxRadius = selectMax(Radius1, polyData1.mInternal.mRadius); #else const float dp = delta_c.dot(axis); const float MinRadius = polyData0.mInternal.mRadius; const float MaxRadius = polyData1.mInternal.mRadius; #endif const float MinMaxRadius = MaxRadius + MinRadius; const float d0 = MinMaxRadius + dp; const float d1 = MinMaxRadius - dp; dmin = selectMin(d0, d1); } #endif static PX_FORCE_INLINE bool testInternalObjects( const PxVec3& delta_c, const PxVec3& axis, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& tr0, const PxMat34& tr1, float dmin) { #ifdef USE_BOX_DATA const PxVec3 localAxis0 = tr0.rotateTranspose(axis); const PxVec3 localAxis1 = tr1.rotateTranspose(axis); const float dp = delta_c.dot(axis); float p0[3]; BoxSupport(polyData0.mInternal.mExtents, localAxis0, p0); float p1[3]; BoxSupport(polyData1.mInternal.mExtents, localAxis1, p1); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float Radius1 = p1[0]*localAxis1.x + p1[1]*localAxis1.y + p1[2]*localAxis1.z; const float MinRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const float MaxRadius = selectMax(Radius1, polyData1.mInternal.mRadius); #else const float dp = delta_c.dot(axis); const float MinRadius = polyData0.mInternal.mRadius; const float MaxRadius = polyData1.mInternal.mRadius; #endif const float MinMaxRadius = MaxRadius + MinRadius; const float d0 = MinMaxRadius + dp; const float d1 = MinMaxRadius - dp; const float depth = selectMin(d0, d1); if(depth>dmin) return false; return true; } #endif PX_FORCE_INLINE float PxcMultiplyAdd3x4(PxU32 i, const PxVec3& p0, const PxVec3& p1, const PxMat34& world) { return (p1.x + p0.x) * world.m.column0[i] + (p1.y + p0.y) * world.m.column1[i] + (p1.z + p0.z) * world.m.column2[i] + 2.0f * world.p[i]; } PX_FORCE_INLINE float PxcMultiplySub3x4(PxU32 i, const PxVec3& p0, const PxVec3& p1, const PxMat34& world) { return (p1.x - p0.x) * world.m.column0[i] + (p1.y - p0.y) * world.m.column1[i] + (p1.z - p0.z) * world.m.column2[i]; } static PX_FORCE_INLINE bool testNormal( const PxVec3& axis, PxReal min0, PxReal max0, const PolygonalData& polyData1, const PxMat34& m1to0, const FastVertex2ShapeScaling& scaling1, PxReal& depth, PxReal contactDistance) { //The separating axis we want to test is a face normal of hull0 PxReal min1, max1; (polyData1.mProjectHull)(polyData1, axis, m1to0, scaling1, min1, max1); if(max0+contactDistance<min1 || max1+contactDistance<min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static PX_FORCE_INLINE bool testSeparatingAxis( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxVec3& axis, PxReal& depth, PxReal contactDistance) { PxReal min0, max0; (polyData0.mProjectHull)(polyData0, axis, world0, scaling0, min0, max0); return testNormal(axis, min0, max0, polyData1, world1, scaling1, depth, contactDistance); } static bool PxcSegmentAABBIntersect(const PxVec3& p0, const PxVec3& p1, const PxVec3& minimum, const PxVec3& maximum, const PxMat34& world) { PxVec3 boxExtent, diff, dir; PxReal fAWdU[3]; dir.x = PxcMultiplySub3x4(0, p0, p1, world); boxExtent.x = maximum.x - minimum.x; diff.x = (PxcMultiplyAdd3x4(0, p0, p1, world) - (maximum.x+minimum.x)); fAWdU[0] = PxAbs(dir.x); if(PxAbs(diff.x)> boxExtent.x + fAWdU[0]) return false; dir.y = PxcMultiplySub3x4(1, p0, p1, world); boxExtent.y = maximum.y - minimum.y; diff.y = (PxcMultiplyAdd3x4(1, p0, p1, world) - (maximum.y+minimum.y)); fAWdU[1] = PxAbs(dir.y); if(PxAbs(diff.y)> boxExtent.y + fAWdU[1]) return false; dir.z = PxcMultiplySub3x4(2, p0, p1, world); boxExtent.z = maximum.z - minimum.z; diff.z = (PxcMultiplyAdd3x4(2, p0, p1, world) - (maximum.z+minimum.z)); fAWdU[2] = PxAbs(dir.z); if(PxAbs(diff.z)> boxExtent.z + fAWdU[2]) return false; PxReal f; f = dir.y * diff.z - dir.z*diff.y; if(PxAbs(f)>boxExtent.y*fAWdU[2] + boxExtent.z*fAWdU[1]) return false; f = dir.z * diff.x - dir.x*diff.z; if(PxAbs(f)>boxExtent.x*fAWdU[2] + boxExtent.z*fAWdU[0]) return false; f = dir.x * diff.y - dir.y*diff.x; if(PxAbs(f)>boxExtent.x*fAWdU[1] + boxExtent.y*fAWdU[0]) return false; return true; } #define EXPERIMENT /* Edge culling can clearly be improved : in ConvexTest02 for example, edges don't even touch the other mesh sometimes. */ static void PxcFindSeparatingAxes( SeparatingAxes& sa, const PxU32* PX_RESTRICT indices, PxU32 numPolygons, const PolygonalData& polyData, const PxMat34& world0, const PxPlane& plane, const PxMat34& m0to1, const PxBounds3& aabb, PxReal contactDistance, const FastVertex2ShapeScaling& scaling) { // EdgeCache edgeCache; // PT: TODO: check this is actually useful const PxVec3* PX_RESTRICT vertices = polyData.mVerts; const HullPolygonData* PX_RESTRICT polygons = polyData.mPolygons; const PxU8* PX_RESTRICT vrefsBase = polyData.mPolygonVertexRefs; while(numPolygons--) { //Get current polygon const HullPolygonData& P = polygons[*indices++]; const PxU8* PX_RESTRICT VData = vrefsBase + P.mVRef8; // Loop through polygon vertices == polygon edges PxU32 numVerts = P.mNbVerts; #ifdef EXPERIMENT PxVec3 p0,p1; PxU8 VRef0 = VData[0]; p0 = scaling * vertices[VRef0]; bool b0 = plane.distance(p0) <= contactDistance; #endif for(PxU32 j = 0; j < numVerts; j++) { PxU32 j1 = j+1; if(j1 >= numVerts) j1 = 0; #ifndef EXPERIMENT PxU8 VRef0 = VData[j]; #endif PxU8 VRef1 = VData[j1]; // PxOrder(VRef0, VRef1); //make sure edge (a,b) == edge (b,a) // if (edgeCache.isInCache(VRef0, VRef1)) // continue; //transform points //TODO: once this works we could transform plan instead, that is more efficient!! #ifdef EXPERIMENT p1 = scaling * vertices[VRef1]; #else const PxVec3 p0 = scaling * vertices[VRef0]; const PxVec3 p1 = scaling * vertices[VRef1]; #endif // Cheap but effective culling! #ifdef EXPERIMENT bool b1 = plane.distance(p1) <= contactDistance; if(b0 || b1) #else if(plane.signedDistanceHessianNormalForm(p0) <= contactDistance || plane.signedDistanceHessianNormalForm(p1) <= contactDistance) #endif { if(PxcSegmentAABBIntersect(p0, p1, aabb.minimum, aabb.maximum, m0to1)) { // Create current edge. We're only interested in different edge directions so we normalize. const PxVec3 currentEdge = world0.rotate(p0 - p1).getNormalized(); sa.addAxis(currentEdge); } } #ifdef EXPERIMENT VRef0 = VRef1; p0 = p1; b0 = b1; #endif } } } static bool PxcTestFacesSepAxesBackface(const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m1to0, const PxVec3& delta, PxReal& dmin, PxVec3& sep, PxU32& id, PxU32* PX_RESTRICT indices_, PxU32& numIndices, PxReal contactDistance, float toleranceLength #ifdef TEST_INTERNAL_OBJECTS , const PxVec3& worldDelta #endif ) { PX_UNUSED(toleranceLength); // Only used in Debug id = PX_INVALID_U32; PxU32* indices = indices_; const PxU32 num = polyData0.mNbPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceDelta = scaling0 % delta; // PT: prefetch polygon data { const PxU32 dataSize = num*sizeof(HullPolygonData); for(PxU32 offset=0; offset < dataSize; offset+=128) PxPrefetchLine(polygons, offset); } for(PxU32 i=0; i < num; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; // Do backface-culling if(PL.n.dot(vertSpaceDelta) < 0.0f) continue; //normals transform by inverse transpose: (and transpose(skew) == skew as its symmetric) PxVec3 shapeSpaceNormal = scaling0 % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); // PT: We need to find a way to skip this normalize #ifdef TEST_INTERNAL_OBJECTS /* const PxVec3 worldNormal_ = world0.rotate(shapeSpaceNormal); PxReal d0; bool test0 = PxcTestSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, worldNormal_, d0, contactDistance); PxReal d1; const float invMagnitude0 = 1.0f / magnitude; bool test1 = PxcTestNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude0, P.getMax() * invMagnitude0, polyData1, m1to0, scaling1, d1, contactDistance); PxReal d2; testInternalObjects_(worldDelta, worldNormal_, polyData0, polyData1, world0, world1, d2, contactDistance); */ const PxVec3 worldNormal = world0.rotate(shapeSpaceNormal); if(!testInternalObjects(worldDelta, worldNormal, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; const float invMagnitude = 1.0f / magnitude; if(testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif *indices++ = i; //////////////////// /* //gotta transform minimum and maximum from vertex to shape space! //I think they transform like the 'd' of the plane, basically by magnitude division! //unfortunately I am not certain of that, so let's convert them to a point in vertex space, transform that, and then convert back to a plane d. //let's start by transforming the plane's d: //a point on the plane: PxVec3 vertSpaceDPoint = PL.normal * -PL.d; //make sure this is on the plane: PxReal distZero = PL.signedDistanceHessianNormalForm(vertSpaceDPoint); //should be zero //transform: PxVec3 shapeSpaceDPoint = cache.mVertex2ShapeSkew[skewIndex] * vertSpaceDPoint; //make into a d offset again by projecting along the plane: PxcPlane shapeSpacePlane(shapeSpaceNormal, shapeSpaceDPoint); //see what D is!! //NOTE: for boxes scale[0] is always id so this is all redundant. Hopefully for convex convex it will become useful! */ //////////////////// PxReal d; const float invMagnitude = 1.0f / magnitude; if(!testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. return false; if(d < dmin) { #ifdef TEST_INTERNAL_OBJECTS sep = worldNormal; #else sep = world0.rotate(shapeSpaceNormal); #endif dmin = d; id = i; } } numIndices = PxU32(indices - indices_); PX_ASSERT(id!=PX_INVALID_U32); //Should never happen with this version return true; } // PT: isolating this piece of code allows us to better see what happens in PIX. For some reason it looks // like isolating it creates *less* LHS than before, but I don't understand why. There's still a lot of // bad stuff there anyway //PX_FORCE_INLINE static void prepareData(PxPlane& witnessPlane0, PxPlane& witnessPlane1, PxBounds3& aabb0, PxBounds3& aabb1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxPlane& vertSpacePlane0, const PxPlane& vertSpacePlane1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, PxReal contactDistance ) { scaling0.transformPlaneToShapeSpace(vertSpacePlane0.n, vertSpacePlane0.d, witnessPlane0.n, witnessPlane0.d); scaling1.transformPlaneToShapeSpace(vertSpacePlane1.n, vertSpacePlane1.d, witnessPlane1.n, witnessPlane1.d); //witnessPlane0 = witnessPlane0.getTransformed(m0to1); //witnessPlane1 = witnessPlane1.getTransformed(m1to0); const PxVec3 newN0 = m0to1.rotate(witnessPlane0.n); witnessPlane0 = PxPlane(newN0, witnessPlane0.d - m0to1.p.dot(newN0)); const PxVec3 newN1 = m1to0.rotate(witnessPlane1.n); witnessPlane1 = PxPlane(newN1, witnessPlane1.d - m1to0.p.dot(newN1)); aabb0 = hullBounds0; aabb1 = hullBounds1; //gotta inflate // PT: perfect LHS recipe here.... const PxVec3 inflate(contactDistance); aabb0.minimum -= inflate; aabb1.minimum -= inflate; aabb0.maximum += inflate; aabb1.maximum += inflate; } static bool PxcBruteForceOverlapBackface( const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3& delta, PxU32& id0, PxU32& id1, PxReal& depth, PxVec3& sep, PxcSepAxisType& code, PxReal contactDistance, float toleranceLength) { const PxVec3 localDelta0 = world0.rotateTranspose(delta); PxU32* PX_RESTRICT indices0 = reinterpret_cast<PxU32*>(PxAlloca(polyData0.mNbPolygons*sizeof(PxU32))); PxU32 numIndices0; PxReal dmin0 = PX_MAX_REAL; PxVec3 vec0; if(!PxcTestFacesSepAxesBackface(polyData0, polyData1, world0, world1, scaling0, scaling1, m1to0, localDelta0, dmin0, vec0, id0, indices0, numIndices0, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , -delta #endif )) return false; const PxVec3 localDelta1 = world1.rotateTranspose(delta); PxU32* PX_RESTRICT indices1 = reinterpret_cast<PxU32*>(PxAlloca(polyData1.mNbPolygons*sizeof(PxU32))); PxU32 numIndices1; PxReal dmin1 = PX_MAX_REAL; PxVec3 vec1; if(!PxcTestFacesSepAxesBackface(polyData1, polyData0, world1, world0, scaling1, scaling0, m0to1, -localDelta1, dmin1, vec1, id1, indices1, numIndices1, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , delta #endif )) return false; PxReal dmin = dmin0; PxVec3 vec = vec0; code = SA_NORMAL0; if(dmin1 < dmin) { dmin = dmin1; vec = vec1; code = SA_NORMAL1; } PX_ASSERT(id0!=PX_INVALID_U32); PX_ASSERT(id1!=PX_INVALID_U32); // Brute-force find a separating axis SeparatingAxes mSA0; SeparatingAxes mSA1; mSA0.reset(); mSA1.reset(); PxPlane witnessPlane0; PxPlane witnessPlane1; PxBounds3 aabb0, aabb1; prepareData(witnessPlane0, witnessPlane1, aabb0, aabb1, hullBounds0, hullBounds1, polyData0.mPolygons[id0].mPlane, polyData1.mPolygons[id1].mPlane, scaling0, scaling1, m0to1, m1to0, contactDistance); // Find possibly separating axes PxcFindSeparatingAxes(mSA0, indices0, numIndices0, polyData0, world0, witnessPlane1, m0to1, aabb1, contactDistance, scaling0); PxcFindSeparatingAxes(mSA1, indices1, numIndices1, polyData1, world1, witnessPlane0, m1to0, aabb0, contactDistance, scaling1); // PxcFindSeparatingAxes(context.mSA0, &id0, 1, hull0, world0, witnessPlane1, m0to1, aabbMin1, aabbMax1); // PxcFindSeparatingAxes(context.mSA1, &id1, 1, hull1, world1, witnessPlane0, m1to0, aabbMin0, aabbMax0); const PxU32 numEdges0 = mSA0.getNumAxes(); const PxVec3* PX_RESTRICT edges0 = mSA0.getAxes(); const PxU32 numEdges1 = mSA1.getNumAxes(); const PxVec3* PX_RESTRICT edges1 = mSA1.getAxes(); // Worst case = convex test 02 with big meshes: 23 & 23 edges => 23*23 = 529 tests! // printf("%d - %d\n", NbEdges0, NbEdges1); // maximum = ~20 in test scenes. for(PxU32 i=0; i < numEdges0; i++) { const PxVec3& edge0 = edges0[i]; for(PxU32 j=0; j < numEdges1; j++) { const PxVec3& edge1 = edges1[j]; PxVec3 sepAxis = edge0.cross(edge1); if(!isAlmostZero(sepAxis)) { sepAxis = sepAxis.getNormalized(); #ifdef TEST_INTERNAL_OBJECTS if(!testInternalObjects(-delta, sepAxis, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; if(testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, sepAxis, d, contactDistance)) { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; if(!testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, sepAxis, d, contactDistance)) return false; if(d<dmin) { dmin = d; vec = sepAxis; code = SA_EE; } } } } depth = dmin; sep = vec; return true; } static bool GuTestFacesSepAxesBackfaceRoughPass( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m1to0, const PxVec3& /*witness*/, const PxVec3& delta, PxReal& dmin, PxVec3& sep, PxU32& id, PxReal contactDistance, float toleranceLength #ifdef TEST_INTERNAL_OBJECTS , const PxVec3& worldDelta #endif ) { PX_UNUSED(toleranceLength); // Only used in Debug id = PX_INVALID_U32; const PxU32 num = polyData0.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceDelta = scaling0 % delta; for(PxU32 i=0; i < num; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; if(PL.n.dot(vertSpaceDelta) < 0.0f) continue; //backface-cull PxVec3 shapeSpaceNormal = scaling0 % PL.n; //normals transform with inverse transpose //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); // PT: We need to find a way to skip this normalize #ifdef TEST_INTERNAL_OBJECTS const PxVec3 worldNormal = world0.rotate(shapeSpaceNormal); if(!testInternalObjects(worldDelta, worldNormal, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; const float invMagnitude = 1.0f / magnitude; if(testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, /*hull1,*/ polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; const float invMagnitude = 1.0f / magnitude; if(!testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, /*hull1,*/ polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. return false; if(d < dmin) { #ifdef TEST_INTERNAL_OBJECTS sep = worldNormal; #else sep = world0.rotate(shapeSpaceNormal); #endif dmin = d; id = i; } } PX_ASSERT(id!=PX_INVALID_U32); //Should never happen with this version return true; } static bool GuBruteForceOverlapBackfaceRoughPass( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3& delta, PxU32& id0, PxU32& id1, PxReal& depth, PxVec3& sep, PxcSepAxisType& code, PxReal contactDistance, PxReal toleranceLength) { PxReal dmin0 = PX_MAX_REAL; PxReal dmin1 = PX_MAX_REAL; PxVec3 vec0, vec1; const PxVec3 localDelta0 = world0.rotateTranspose(delta); const PxVec3 localCenter1in0 = m1to0.transform(polyData1.mCenter); if(!GuTestFacesSepAxesBackfaceRoughPass(polyData0, polyData1, world0, world1, scaling0, scaling1, m1to0, localCenter1in0, localDelta0, dmin0, vec0, id0, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , -delta #endif )) return false; const PxVec3 localDelta1 = world1.rotateTranspose(delta); const PxVec3 localCenter0in1 = m0to1.transform(polyData0.mCenter); if(!GuTestFacesSepAxesBackfaceRoughPass(polyData1, polyData0, world1, world0, scaling1, scaling0, m0to1, localCenter0in1, -localDelta1, dmin1, vec1, id1, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , delta #endif )) return false; PxReal dmin = dmin0; PxVec3 vec = vec0; code = SA_NORMAL0; if(dmin1 < dmin) { dmin = dmin1; vec = vec1; code = SA_NORMAL1; } PX_ASSERT(id0!=PX_INVALID_U32); PX_ASSERT(id1!=PX_INVALID_U32); depth = dmin; sep = vec; return true; } static bool GuContactHullHull( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, bool idtScale0, bool idtScale1); // Box-convex contact generation // this can no longer share code with convex-convex because that case needs scaling for both shapes, while this only needs it for one, which may be significant perf wise. // // PT: duplicating the full convex-vs-convex codepath is a lot worse. Look at it this way: if scaling is really "significant perf wise" then we made the whole convex-convex // codepath significantly slower, and this is a lot more important than just box-vs-convex. The proper approach is to share the code and make sure scaling is NOT a perf hit. // PT: please leave this function in the same translation unit as PxcContactHullHull. bool Gu::contactBoxConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); FastVertex2ShapeScaling idtScaling; const PxBounds3 boxBounds(-shapeBox.halfExtents, shapeBox.halfExtents); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); /////// FastVertex2ShapeScaling convexScaling; PxBounds3 convexBounds; PolygonalData polyData1; const bool idtScale = getConvexData(shapeConvex, convexScaling, convexBounds, polyData1); return GuContactHullHull( polyData0, polyData1, boxBounds, convexBounds, transform0, transform1, params, contactBuffer, idtScaling, convexScaling, true, idtScale); } // PT: please leave this function in the same translation unit as PxcContactHullHull. bool Gu::contactConvexConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxConvexMeshGeometry& shapeConvex0 = checkedCast<PxConvexMeshGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex1 = checkedCast<PxConvexMeshGeometry>(shape1); FastVertex2ShapeScaling scaling0, scaling1; PxBounds3 convexBounds0, convexBounds1; PolygonalData polyData0, polyData1; const bool idtScale0 = getConvexData(shapeConvex0, scaling0, convexBounds0, polyData0); const bool idtScale1 = getConvexData(shapeConvex1, scaling1, convexBounds1, polyData1); return GuContactHullHull( polyData0, polyData1, convexBounds0, convexBounds1, transform0, transform1, params, contactBuffer, scaling0, scaling1, idtScale0, idtScale1); } static bool GuContactHullHull( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, bool idtScale0, bool idtScale1) { // Compute matrices const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); const PxVec3 worldCenter0 = world0.transform(polyData0.mCenter); const PxVec3 worldCenter1 = world1.transform(polyData1.mCenter); const PxVec3 deltaC = worldCenter1 - worldCenter0; PxReal depth; /////////////////////////////////////////////////////////////////////////// // Early-exit test: quickly discard obviously non-colliding cases. // PT: we used to skip this when objects were touching, which provided a small speedup (saving 2 full hull projections). // We may want to add this back at some point in the future, if possible. if(true) //AM: now we definitely want to test the cached axis to get the depth value for the cached axis, even if we had a contact before. { if(!testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, deltaC, depth, params.mContactDistance)) //there was no contact previously and we reject using the same prev. axis. return false; } /////////////////////////////////////////////////////////////////////////// // Compute relative transforms PxTransform t0to1 = transform1.transformInv(transform0); PxTransform t1to0 = transform0.transformInv(transform1); PxU32 c0(0x7FFF); PxU32 c1(0x7FFF); PxVec3 worldNormal; const Matrix34FromTransform m0to1(t0to1); const Matrix34FromTransform m1to0(t1to0); #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS // PT: it is a bad idea to skip the rough pass, for two reasons: // 1) performance. The rough pass is obviously a lot faster. // 2) stability. The "skipIt" optimization relies on the rough pass being present to catch the cases where it fails. If you disable the rough pass // "skipIt" can skip the whole work, contacts get lost, and we never "try again" ==> explosions // bool TryRoughPass = (contactDistance == 0.0f); //Rough first pass doesn't work with dist based for some reason. for(int TryRoughPass = 1 /*gEnableOptims*/; 0 <= TryRoughPass; --TryRoughPass) { #endif { PxcSepAxisType code; PxU32 id0, id1; //PxReal depth; #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS bool Status; if(TryRoughPass) { Status = GuBruteForceOverlapBackfaceRoughPass(polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, params.mContactDistance, params.mToleranceLength); } else { Status = PxcBruteForceOverlapBackface( // hull0, hull1, hullBounds0, hullBounds1, polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, params.mContactDistance, params.mToleranceLength); } if(!Status) #else if(!PxcBruteForceOverlapBackface( // hull0, hull1, hullBounds0, hullBounds1, polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, contactDistance)) #endif return false; if(deltaC.dot(worldNormal) < 0.0f) worldNormal = -worldNormal; /* worldNormal = -partialSep; depth = -partialDepth; code = SA_EE; */ if(code==SA_NORMAL0) { c0 = id0; c1 = (polyData1.mSelectClosestEdgeCB)(polyData1, scaling1, world1.rotateTranspose(-worldNormal)); } else if(code==SA_NORMAL1) { c0 = (polyData0.mSelectClosestEdgeCB)(polyData0, scaling0, world0.rotateTranspose(worldNormal)); c1 = id1; } else if(code==SA_EE) { c0 = (polyData0.mSelectClosestEdgeCB)(polyData0, scaling0, world0.rotateTranspose(worldNormal)); c1 = (polyData1.mSelectClosestEdgeCB)(polyData1, scaling1, world1.rotateTranspose(-worldNormal)); } } const HullPolygonData& HP0 = polyData0.mPolygons[c0]; const HullPolygonData& HP1 = polyData1.mPolygons[c1]; // PT: prefetching those guys saves ~600.000 cycles in convex-convex benchmark PxPrefetchLine(&HP0.mPlane); PxPrefetchLine(&HP1.mPlane); //ok, we have a new depth value. convert to real distance. // PxReal separation = -depth; //depth was either computed in initial cached-axis check, or better, when skipIt was false, in sep axis search. // if (separation < 0.0f) // separation = 0.0f; //we don't want to store penetration values. const PxReal separation = fsel(depth, 0.0f, -depth); PxVec3 worldNormal0; PX_ALIGN(16, PxPlane) shapeSpacePlane0; if(idtScale0) { V4StoreA(V4LoadU(&HP0.mPlane.n.x), &shapeSpacePlane0.n.x); worldNormal0 = world0.rotate(HP0.mPlane.n); } else { scaling0.transformPlaneToShapeSpace(HP0.mPlane.n,HP0.mPlane.d,shapeSpacePlane0.n,shapeSpacePlane0.d); worldNormal0 = world0.rotate(shapeSpacePlane0.n); } PxVec3 worldNormal1; PX_ALIGN(16, PxPlane) shapeSpacePlane1; if(idtScale1) { V4StoreA(V4LoadU(&HP1.mPlane.n.x), &shapeSpacePlane1.n.x); worldNormal1 = world1.rotate(HP1.mPlane.n); } else { scaling1.transformPlaneToShapeSpace(HP1.mPlane.n,HP1.mPlane.d,shapeSpacePlane1.n,shapeSpacePlane1.d); worldNormal1 = world1.rotate(shapeSpacePlane1.n); } PxIntBool flag; { const PxReal d0 = PxAbs(worldNormal0.dot(worldNormal)); const PxReal d1 = PxAbs(worldNormal1.dot(worldNormal)); bool f = d0>d1; //which face normal is the separating axis closest to. flag = f; } ////////////////////NEW DIST HANDLING////////////////////// PX_ASSERT(separation >= 0.0f); //be sure this got fetched somewhere in the chaos above. const PxReal cCCDEpsilon = params.mMeshContactMargin; const PxReal contactGenPositionShift = separation + cCCDEpsilon; //if we're at a distance, shift so we're in penetration. const PxVec3 contactGenPositionShiftVec = worldNormal * -contactGenPositionShift; //shift one of the bodies this distance toward the other just for Pierre's contact generation. Then the bodies should be penetrating exactly by MIN_SEPARATION_FOR_PENALTY - ideal conditions for this contact generator. //note: for some reason this has to change sign! //this will make contact gen always generate contacts at about MSP. Shift them back to the true real distance, and then to a solver compliant distance given that //the solver converges to MSP penetration, while we want it to converge to 0 penetration. //to real distance: //The system: We always shift convex 0 (arbitrary). If the contact is attached to convex 0 then we will need to shift the contact point, otherwise not. const PxVec3 newp = world0.p - contactGenPositionShiftVec; const PxMat34 world0_Tweaked(world0.m.column0, world0.m.column1, world0.m.column2, newp); PxTransform shifted0(newp, transform0.q); t0to1 = transform1.transformInv(shifted0); t1to0 = shifted0.transformInv(transform1); const Matrix34FromTransform m0to1_Tweaked(t0to1); const Matrix34FromTransform m1to0_Tweaked(t1to0); ////////////////////////////////////////////////// //pretransform convex polygon if we have scaling! PxVec3* scaledVertices0; PxU8* stackIndices0; GET_SCALEX_CONVEX(scaledVertices0, stackIndices0, idtScale0, HP0.mNbVerts, scaling0, polyData0.mVerts, polyData0.getPolygonVertexRefs(HP0)) //pretransform convex polygon if we have scaling! PxVec3* scaledVertices1; PxU8* stackIndices1; GET_SCALEX_CONVEX(scaledVertices1, stackIndices1, idtScale1, HP1.mNbVerts, scaling1, polyData1.mVerts, polyData1.getPolygonVertexRefs(HP1)) // So we need to switch: // - HP0, HP1 // - scaledVertices0, scaledVertices1 // - stackIndices0, stackIndices1 // - world0, world1 // - shapeSpacePlane0, shapeSpacePlane1 // - worldNormal0, worldNormal1 // - m0to1, m1to0 // - true, false const PxMat33 RotT0 = findRotationMatrixFromZ(shapeSpacePlane0.n); const PxMat33 RotT1 = findRotationMatrixFromZ(shapeSpacePlane1.n); if(flag) { if(contactPolygonPolygonExt(HP0.mNbVerts, scaledVertices0, stackIndices0, world0_Tweaked, shapeSpacePlane0, RotT0, HP1.mNbVerts, scaledVertices1, stackIndices1, world1, shapeSpacePlane1, RotT1, worldNormal0, m0to1_Tweaked, m1to0_Tweaked, PXC_CONTACT_NO_FACE_INDEX, PXC_CONTACT_NO_FACE_INDEX, contactBuffer, true, contactGenPositionShiftVec, contactGenPositionShift)) return true; } else { if(contactPolygonPolygonExt(HP1.mNbVerts, scaledVertices1, stackIndices1, world1, shapeSpacePlane1, RotT1, HP0.mNbVerts, scaledVertices0, stackIndices0, world0_Tweaked, shapeSpacePlane0, RotT0, worldNormal1, m1to0_Tweaked, m0to1_Tweaked, PXC_CONTACT_NO_FACE_INDEX, PXC_CONTACT_NO_FACE_INDEX, contactBuffer, false, contactGenPositionShiftVec, contactGenPositionShift)) return true; } #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS } #endif return false; }
37,890
C++
35.751697
302
0.725996
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleBox.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuIntersectionRayBox.h" #include "GuDistanceSegmentBox.h" #include "GuInternal.h" #include "GuContactMethodImpl.h" #include "GuBoxConversion.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Gu; /*namespace Gu { const PxU8* getBoxEdges(); }*/ ///////// /*#include "common/PxRenderOutput.h" #include "PxsContext.h" static void gVisualizeBox(const Box& box, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat33 rot(box.base.column0, box.base.column1, box.base.column2); PxMat44 m(rot, box.origin); DebugBox db(box.extent); PxRenderOutput& out = context.mRenderOutput; out << color << m; out << db; } static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); RenderOutput& out = context.mRenderOutput; out << color << m << RenderOutput::LINES << a << b; }*/ ///////// static const PxReal fatBoxEdgeCoeff = 0.01f; static bool intersectEdgeEdgePreca(const PxVec3& p1, const PxVec3& p2, const PxVec3& v1, const PxPlane& plane, PxU32 i, PxU32 j, float coeff, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip) { // if colliding edge (p3,p4) does not cross plane return no collision // same as if p3 and p4 on same side of plane return 0 // // Derivation: // d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // if d3 and d4 have the same sign, they're on the same side of the plane => no collision // We test both sides at the same time by only testing Sign(d3 * d4). // ### put that in the Plane class // ### also check that code in the triangle class that might be similar const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp>0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision PxVec3 v2 = p4 - p3; temp = plane.n.dot(v2); if(temp==0.0f) return false; // ### epsilon would be better // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))*coeff; if(dist<0.0f) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; // no collision } static bool GuTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const Box& box, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project box PxReal Min1, Max1; { const PxReal BoxCen = box.center.dot(axis); const PxReal BoxExt = PxAbs(box.rot.column0.dot(axis)) * box.extents.x + PxAbs(box.rot.column1.dot(axis)) * box.extents.y + PxAbs(box.rot.column2.dot(axis)) * box.extents.z; Min1 = BoxCen - BoxExt; Max1 = BoxCen + BoxExt; } // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } static bool GuCapsuleOBBOverlap3(const Segment& segment, PxReal radius, const Box& box, PxReal* t=NULL, PxVec3* pp=NULL) { PxVec3 Sep(PxReal(0)); PxReal PenDepth = PX_MAX_REAL; // Test normals for(PxU32 i=0;i<3;i++) { PxReal d; if(!GuTestAxis(box.rot[i], segment, radius, box, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = box.rot[i]; } } // Test edges PxVec3 CapsuleAxis(segment.p1 - segment.p0); CapsuleAxis = CapsuleAxis.getNormalized(); for(PxU32 i=0;i<3;i++) { PxVec3 Cross = CapsuleAxis.cross(box.rot[i]); if(!isAlmostZero(Cross)) { Cross = Cross.getNormalized(); PxReal d; if(!GuTestAxis(Cross, segment, radius, box, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = Cross; } } } const PxVec3 Witness = segment.computeCenter() - box.center; if(Sep.dot(Witness) < 0.0f) Sep = -Sep; if(t) *t = PenDepth; if(pp) *pp = Sep; return true; } static void GuGenerateVFContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal, const PxReal contactDistance) { const PxVec3 Max = worldBox.extents; const PxVec3 Min = -worldBox.extents; const PxVec3 tmp2 = - worldBox.rot.transformTranspose(normal); const PxVec3* PX_RESTRICT Ptr = &segment.p0; for(PxU32 i=0;i<2;i++) { const PxVec3& Pos = Ptr[i]; const PxVec3 tmp = worldBox.rot.transformTranspose(Pos - worldBox.center); PxReal tnear, tfar; int Res = intersectRayAABB(Min, Max, tmp, tmp2, tnear, tfar); if(Res!=-1 && tnear < radius + contactDistance) { contactBuffer.contact(Pos - tnear * normal, normal, tnear - radius); } } } // PT: this looks similar to PxcGenerateEEContacts2 but it is mandatory to properly handle thin capsules. static void GuGenerateEEContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal) { const PxU8* PX_RESTRICT Indices = getBoxEdges(); PxVec3 Pts[8]; worldBox.computeBoxPoints(Pts); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = v1.cross(normal); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[ii]*normal[jj]-v1[jj]*normal[ii]); for(PxU32 i=0;i<12;i++) { // PxVec3 p1 = Pts[*Indices++]; // PxVec3 p2 = Pts[*Indices++]; // makeFatEdge(p1, p2, fatBoxEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3& p1 = Pts[*Indices++]; const PxVec3& p2 = Pts[*Indices++]; // PT: keep original code in case something goes wrong // PxReal dist; // PxVec3 ip; // if(intersectEdgeEdge(p1, p2, -normal, segment.p0, segment.p1, dist, ip)) // contactBuffer.contact(ip, normal, - (radius + dist)); PxReal dist; PxVec3 ip; if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) // if(intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) { contactBuffer.contact(ip-normal*dist, normal, - (radius + dist)); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } static void GuGenerateEEContacts2( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal, const PxReal contactDistance) { const PxU8* PX_RESTRICT Indices = getBoxEdges(); PxVec3 Pts[8]; worldBox.computeBoxPoints(Pts); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = -(v1.cross(normal)); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[jj]*normal[ii]-v1[ii]*normal[jj]); for(PxU32 i=0;i<12;i++) { // PxVec3 p1 = Pts[*Indices++]; // PxVec3 p2 = Pts[*Indices++]; // makeFatEdge(p1, p2, fatBoxEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3& p1 = Pts[*Indices++]; const PxVec3& p2 = Pts[*Indices++]; // PT: keep original code in case something goes wrong // PxReal dist; // PxVec3 ip; // bool contact = intersectEdgeEdge(p1, p2, normal, segment.p0, segment.p1, dist, ip); // if(contact && dist < radius + contactDistance) // contactBuffer.contact(ip, normal, dist - radius); PxReal dist; PxVec3 ip; // bool contact = intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); bool contact = intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); if(contact && dist < radius + contactDistance) { contactBuffer.contact(ip-normal*dist, normal, dist - radius); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } bool Gu::contactCapsuleBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); // Get actual shape data const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); // PT: TODO: move computations to local space // Capsule data Segment worldSegment; getCapsuleSegment(transform0, shapeCapsule, worldSegment); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; // Box data Box worldBox; buildFrom(worldBox, transform1.p, shapeBox.halfExtents, transform1.q); // Collision detection PxReal t; PxVec3 onBox; const PxReal squareDist = distanceSegmentBoxSquared(worldSegment.p0, worldSegment.p1, worldBox.center, worldBox.extents, worldBox.rot, &t, &onBox); if(squareDist >= inflatedRadius*inflatedRadius) return false; PX_ASSERT(contactBuffer.count==0); if(squareDist != 0.0f) { // PT: the capsule segment doesn't intersect the box => distance-based version const PxVec3 onSegment = worldSegment.getPointAt(t); onBox = worldBox.center + worldBox.rot.transform(onBox); PxVec3 normal = onSegment - onBox; PxReal normalLen = normal.magnitude(); if(normalLen > 0.0f) { normal *= 1.0f/normalLen; // PT: generate VF contacts for segment's vertices vs box GuGenerateVFContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, normal, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts GuGenerateEEContacts2(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, normal, params.mContactDistance); // PT: run VF case for box-vertex-vs-capsule only if we don't have any contact yet if(!contactBuffer.count) contactBuffer.contact(onBox, normal, sqrtf(squareDist) - shapeCapsule.radius); } else { // On linux we encountered the following: // For a case where a segment endpoint lies on the surface of a box, the squared distance between segment and box was tiny but still larger than 0. // However, the computation of the normal length was exactly 0. In that case we should have switched to the penetration based version so we do it now // instead. goto PenetrationBasedCode; } } else { PenetrationBasedCode: // PT: the capsule segment intersects the box => penetration-based version // PT: compute penetration vector (MTD) PxVec3 sepAxis; PxReal depth; if(!GuCapsuleOBBOverlap3(worldSegment, shapeCapsule.radius, worldBox, &depth, &sepAxis)) return false; // PT: generate VF contacts for segment's vertices vs box GuGenerateVFContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, sepAxis, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts GuGenerateEEContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, sepAxis); if(!contactBuffer.count) { contactBuffer.contact(worldSegment.computeCenter(), sepAxis, -(shapeCapsule.radius + depth)); return true; } } return true; }
13,856
C++
30.27991
222
0.694284
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactBoxBox.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "CmMatrix34.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Gu; using namespace Cm; #define MAX_NB_CTCS 8 + 12*5 + 6*4 #define ABS_GREATER(x, y) (PxAbs(x) > (y)) #define ABS_SMALLER_EQUAL(x, y) (PxAbs(x) <= (y)) //#define AIR(x) ((PxU32&)(x)&SIGN_BITMASK) //#define ABS_GREATER(x, y) (AIR(x) > IR(y)) //#define ABS_SMALLER_EQUAL(x, y) (AIR(x) <= IR(y)) #if PX_X86 && !PX_OSX // Some float optimizations ported over from novodex. //returns non zero if the value is negative. #define PXC_IS_NEGATIVE(x) (((PxU32&)(x)) & 0x80000000) #else //On most platforms using the integer rep is worse(produces LHSs) since the CPU has more registers. //returns non zero if the value is negative. #define PXC_IS_NEGATIVE(x) ((x) < 0.0f) #endif enum { AXIS_A0, AXIS_A1, AXIS_A2, AXIS_B0, AXIS_B1, AXIS_B2 }; struct VertexInfo { PxVec3 pos; bool penetrate; bool area; }; /*static PxI32 doBoxBoxContactGeneration(PxVec3 ctcPts[MAX_NB_CTCS], PxReal depths[MAX_NB_CTCS], PxVec3* ctcNrm, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance);*/ static PxI32 doBoxBoxContactGeneration(PxContactBuffer& contactBuffer, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance); bool Gu::contactBoxBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); // Get actual shape data const PxBoxGeometry& shapeBox0 = checkedCast<PxBoxGeometry>(shape0); const PxBoxGeometry& shapeBox1 = checkedCast<PxBoxGeometry>(shape1); PxU32 pd = PxU32(cache.mPairData); PxI32 Nb = doBoxBoxContactGeneration(contactBuffer, shapeBox0.halfExtents, shapeBox1.halfExtents, pd, Matrix34FromTransform(transform0), Matrix34FromTransform(transform1), params.mContactDistance); cache.mPairData = PxTo8(pd); if(!Nb) { cache.mPairData = 0; // Mark as separated for temporal coherence return false; // WARNING: the contact stream code below used to output stuff even for 0 contacts (!). Now we just return here. } return true; } // face => 4 vertices of a face of the cube (i.e. a quad) static PX_FORCE_INLINE PxReal IsInYZ(const PxReal y, const PxReal z, const VertexInfo** PX_RESTRICT face) { // Warning, indices have been remapped. We're now actually like this: // // 3+------+2 // | | | // | *--| // | (y,z)| // 0+------+1 PxReal PreviousY = face[3]->pos.y; PxReal PreviousZ = face[3]->pos.z; // Loop through quad vertices for(PxI32 i=0; i<4; i++) { const PxReal CurrentY = face[i]->pos.y; const PxReal CurrentZ = face[i]->pos.z; // |CurrentY - PreviousY y - PreviousY| // |CurrentZ - PreviousZ z - PreviousZ| // => similar to backface culling, check each one of the 4 triangles are consistent, in which case // the point is within the parallelogram. if((CurrentY - PreviousY)*(z - PreviousZ) - (CurrentZ - PreviousZ)*(y - PreviousY) >= 0.0f) return -1.0f; PreviousY = CurrentY; PreviousZ = CurrentZ; } PxReal x = face[0]->pos.x; { const PxReal ay = y - face[0]->pos.y; const PxReal az = z - face[0]->pos.z; PxVec3 b = face[1]->pos - face[0]->pos; // ### could be precomputed ? x += b.x * (ay*b.y + az*b.z) / b.magnitudeSquared(); // ### could be precomputed ? b = face[3]->pos - face[0]->pos; // ### could be precomputed ? x += b.x * (ay*b.y + az*b.z) / b.magnitudeSquared(); // ### could be precomputed ? } return x; } // Test with respect to the quad defined by (0,-y1,-z1) and (0,y1,z1) // +------+ y1 y // | | | // | * | | // | | | // +------+ -y1 *-----z static PxI32 generateContacts(//PxVec3 ctcPts[], PxReal depths[], PxContactBuffer& contactBuffer, const PxVec3& contactNormal, PxReal y1, PxReal z1, const PxVec3& box2, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance) { // PxI32 NbContacts=0; contactBuffer.reset(); y1 += contactDistance; z1 += contactDistance; const PxMat34 trans1to0 = transform0.getInverseRT() * transform1; VertexInfo vtx[8]; // The 8 cube vertices // PxI32 i; // 6+------+7 // /| /| // / | / | // / 4+---/--+5 // 2+------+3 / y z // | / | / | / // |/ |/ |/ // 0+------+1 *---x { const PxVec3 ex = trans1to0.m.column0 * box2.x; const PxVec3 ey = trans1to0.m.column1 * box2.y; const PxVec3 ez = trans1to0.m.column2 * box2.z; /* vtx[0].pos = mat.pos - ex - ey - ez; vtx[1].pos = mat.pos + ex - ey - ez; vtx[2].pos = mat.pos - ex + ey - ez; vtx[3].pos = mat.pos + ex + ey - ez; vtx[4].pos = mat.pos - ex - ey + ez; vtx[5].pos = mat.pos + ex - ey + ez; vtx[6].pos = mat.pos - ex + ey + ez; vtx[7].pos = mat.pos + ex + ey + ez; */ // 12 vector ops = 12*3 = 36 FPU ops vtx[0].pos = vtx[2].pos = vtx[4].pos = vtx[6].pos = trans1to0.p - ex; vtx[1].pos = vtx[3].pos = vtx[5].pos = vtx[7].pos = trans1to0.p + ex; PxVec3 e = ey+ez; vtx[0].pos -= e; vtx[1].pos -= e; vtx[6].pos += e; vtx[7].pos += e; e = ey-ez; vtx[2].pos += e; vtx[3].pos += e; vtx[4].pos -= e; vtx[5].pos -= e; } // Create vertex info for 8 vertices for(PxU32 i=0; i<8; i++) { // Vertex suivant VertexInfo& p = vtx[i]; // test the point with respect to the x = 0 plane // if(p.pos.x < 0) if(p.pos.x < -contactDistance) //if(PXC_IS_NEGATIVE(p.pos.x)) { p.area = false; p.penetrate = false; continue; } { // we penetrated the quad plane p.penetrate = true; // test to see if we are in the quad // PxAbs => thus we test Y with respect to -Y1 and +Y1 (same for Z) // if(PxAbs(p->pos.y) <= y1 && PxAbs(p->pos.z) <= z1) if(ABS_SMALLER_EQUAL(p.pos.y, y1) && ABS_SMALLER_EQUAL(p.pos.z, z1)) { // the point is inside the quad p.area=true; // Since we are testing with respect to x = 0, the penetration is directly the x coordinate. // depths[NbContacts] = p.pos.x; // We take the vertex as the impact point // ctcPts[NbContacts++] = p.pos; contactBuffer.contact(p.pos, contactNormal, -p.pos.x); } else { p.area=false; } } } // Teste 12 edges on the quad static const PxI32 indices[]={ 0,1, 1,3, 3,2, 2,0, 4,5, 5,7, 7,6, 6,4, 0,4, 1,5, 2,6, 3,7, }; const PxI32* runningLine = indices; const PxI32* endLine = runningLine+24; while(runningLine!=endLine) { // The two vertices of the current edge const VertexInfo* p1 = &vtx[*runningLine++]; const VertexInfo* p2 = &vtx[*runningLine++]; // Penetrate|Area|Penetrate|Area => 16 cases // We only take the edges that at least penetrated the quad's plane into account. if(p1->penetrate || p2->penetrate) // if(p1->penetrate + p2->penetrate) // One branch only { // If at least one of the two vertices is not in the quad... if(!p1->area || !p2->area) // if(!p1->area + !p2->area) // One branch only { // Test y if(p1->pos.y > p2->pos.y) { const VertexInfo* tmp=p1; p1=p2; p2=tmp; } // Impact on the +Y1 edge of the quad if(p1->pos.y < +y1 && p2->pos.y >= +y1) // => a point under Y1, the other above { // Case 1 PxReal a = (+y1 - p1->pos.y)/(p2->pos.y - p1->pos.y); PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y1, z); contactBuffer.contact(PxVec3(x, y1, z), contactNormal, -x); } } } // Impact on the edge -Y1 of the quad if(p1->pos.y < -y1 && p2->pos.y >= -y1) { // Case 2 PxReal a = (-y1 - p1->pos.y)/(p2->pos.y - p1->pos.y); PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, -y1, z); contactBuffer.contact(PxVec3(x, -y1, z), contactNormal, -x); } } } // Test z if(p1->pos.z > p2->pos.z) { const VertexInfo* tmp=p1; p1=p2; p2=tmp; } // Impact on the edge +Z1 of the quad if(p1->pos.z < +z1 && p2->pos.z >= +z1) { // Case 3 PxReal a = (+z1 - p1->pos.z)/(p2->pos.z - p1->pos.z); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y, z1); contactBuffer.contact(PxVec3(x, y, z1), contactNormal, -x); } } } // Impact on the edge -Z1 of the quad if(p1->pos.z < -z1 && p2->pos.z >= -z1) { // Case 4 PxReal a = (-z1 - p1->pos.z)/(p2->pos.z - p1->pos.z); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y, -z1); contactBuffer.contact(PxVec3(x, y, -z1), contactNormal, -x); } } } } // The case where one point penetrates the plane, and the other is not in the quad. if((!p1->penetrate && !p2->area) || (!p2->penetrate && !p1->area)) { // Case 5 PxReal a = (-p1->pos.x)/(p2->pos.x - p1->pos.x); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { // depths[NbContacts] = 0; // ctcPts[NbContacts++] = PxVec3(0, y, z); contactBuffer.contact(PxVec3(0, y, z), contactNormal, 0); } } } } } { // 6 quads => 6 faces of the cube static const PxI32 face[][4]={ {0,1,3,2}, {1,5,7,3}, {5,4,6,7}, {4,0,2,6}, {2,3,7,6}, {0,4,5,1} }; PxI32 addflg=0; for(PxU32 i=0; i<6 && addflg!=0x0f; i++) { const PxI32* p = face[i]; const VertexInfo* q[4]; if((q[0]=&vtx[p[0]])->penetrate && (q[1]=&vtx[p[1]])->penetrate && (q[2]=&vtx[p[2]])->penetrate && (q[3]=&vtx[p[3]])->penetrate) { if(!q[0]->area || !q[1]->area || !q[2]->area || !q[3]->area) { if(!(addflg&1)) { PxReal x = IsInYZ(-y1, -z1, q); if(x>=0.0f) { addflg|=1; contactBuffer.contact(PxVec3(x, -y1, -z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, -y1, -z1);*/ } } if(!(addflg&2)) { PxReal x = IsInYZ(+y1, -z1, q); if(x>=0.0f) { addflg|=2; contactBuffer.contact(PxVec3(x, +y1, -z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, +y1, -z1);*/ } } if(!(addflg&4)) { PxReal x = IsInYZ(-y1, +z1, q); if(x>=0.0f) { addflg|=4; contactBuffer.contact(PxVec3(x, -y1, +z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, -y1, +z1);*/ } } if(!(addflg&8)) { PxReal x = IsInYZ(+y1, +z1, q); if(x>=0.0f) { addflg|=8; contactBuffer.contact(PxVec3(x, +y1, +z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, +y1, +z1);*/ } } } } } } // for(i=0; i<NbContacts; i++) for(PxU32 i=0; i<contactBuffer.count; i++) // ctcPts[i] = transform0.transform(ctcPts[i]); // local to world contactBuffer.contacts[i].point = transform0.transform(contactBuffer.contacts[i].point); // local to world //PX_ASSERT(NbContacts); //if this did not make contacts then something went wrong in theory, but even the old code without distances had this flaw! // return NbContacts; return PxI32(contactBuffer.count); } //static PxI32 doBoxBoxContactGeneration(PxVec3 ctcPts[MAX_NB_CTCS], PxReal depths[MAX_NB_CTCS], PxVec3* ctcNrm, static PxI32 doBoxBoxContactGeneration(PxContactBuffer& contactBuffer, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance) { PxReal aafC[3][3]; // matrix C = A^T B, c_{ij} = Dot(A_i,B_j) PxReal aafAbsC[3][3]; // |c_{ij}| PxReal afAD[3]; // Dot(A_i,D) PxReal d1[6]; PxReal overlap[6]; PxVec3 kD = transform1.p - transform0.p; const PxVec3& axis00 = transform0.m.column0; const PxVec3& axis01 = transform0.m.column1; const PxVec3& axis02 = transform0.m.column2; const PxVec3& axis10 = transform1.m.column0; const PxVec3& axis11 = transform1.m.column1; const PxVec3& axis12 = transform1.m.column2; // Perform Class I tests aafC[0][0] = axis00.dot(axis10); aafC[0][1] = axis00.dot(axis11); aafC[0][2] = axis00.dot(axis12); afAD[0] = axis00.dot(kD); aafAbsC[0][0] = 1e-6f + PxAbs(aafC[0][0]); aafAbsC[0][1] = 1e-6f + PxAbs(aafC[0][1]); aafAbsC[0][2] = 1e-6f + PxAbs(aafC[0][2]); d1[AXIS_A0] = afAD[0]; PxReal d0 = extents0.x + extents1.x*aafAbsC[0][0] + extents1.y*aafAbsC[0][1] + extents1.z*aafAbsC[0][2]; overlap[AXIS_A0] = d0 - PxAbs(d1[AXIS_A0]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A0])) return 0; aafC[1][0] = axis01.dot(axis10); aafC[1][1] = axis01.dot(axis11); aafC[1][2] = axis01.dot(axis12); afAD[1] = axis01.dot(kD); aafAbsC[1][0] = 1e-6f + PxAbs(aafC[1][0]); aafAbsC[1][1] = 1e-6f + PxAbs(aafC[1][1]); aafAbsC[1][2] = 1e-6f + PxAbs(aafC[1][2]); d1[AXIS_A1] = afAD[1]; d0 = extents0.y + extents1.x*aafAbsC[1][0] + extents1.y*aafAbsC[1][1] + extents1.z*aafAbsC[1][2]; overlap[AXIS_A1] = d0 - PxAbs(d1[AXIS_A1]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A1])) return 0; aafC[2][0] = axis02.dot(axis10); aafC[2][1] = axis02.dot(axis11); aafC[2][2] = axis02.dot(axis12); afAD[2] = axis02.dot(kD); aafAbsC[2][0] = 1e-6f + PxAbs(aafC[2][0]); aafAbsC[2][1] = 1e-6f + PxAbs(aafC[2][1]); aafAbsC[2][2] = 1e-6f + PxAbs(aafC[2][2]); d1[AXIS_A2] = afAD[2]; d0 = extents0.z + extents1.x*aafAbsC[2][0] + extents1.y*aafAbsC[2][1] + extents1.z*aafAbsC[2][2]; overlap[AXIS_A2] = d0 - PxAbs(d1[AXIS_A2]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A2])) return 0; // Perform Class II tests d1[AXIS_B0] = axis10.dot(kD); d0 = extents1.x + extents0.x*aafAbsC[0][0] + extents0.y*aafAbsC[1][0] + extents0.z*aafAbsC[2][0]; overlap[AXIS_B0] = d0 - PxAbs(d1[AXIS_B0]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B0])) return 0; d1[AXIS_B1] = axis11.dot(kD); d0 = extents1.y + extents0.x*aafAbsC[0][1] + extents0.y*aafAbsC[1][1] + extents0.z*aafAbsC[2][1]; overlap[AXIS_B1] = d0 - PxAbs(d1[AXIS_B1]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B1])) return 0; d1[AXIS_B2] = axis12.dot(kD); d0 = extents1.z + extents0.x*aafAbsC[0][2] + extents0.y*aafAbsC[1][2] + extents0.z*aafAbsC[2][2]; overlap[AXIS_B2] = d0 - PxAbs(d1[AXIS_B2]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B2])) return 0; // Perform Class III tests - we don't need to store distances for those ones. // We only test those axes when objects are likely to be separated, i.e. when they where previously non-colliding. For stacks, we'll have // to do full contact generation anyway, and those tests are useless - so we skip them. This is similar to what I did in Opcode. if(!collisionData) // separated or first run { PxReal d = afAD[2]*aafC[1][0] - afAD[1]*aafC[2][0]; d0 = contactDistance + extents0.y*aafAbsC[2][0] + extents0.z*aafAbsC[1][0] + extents1.y*aafAbsC[0][2] + extents1.z*aafAbsC[0][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[2]*aafC[1][1] - afAD[1]*aafC[2][1]; d0 = contactDistance + extents0.y*aafAbsC[2][1] + extents0.z*aafAbsC[1][1] + extents1.x*aafAbsC[0][2] + extents1.z*aafAbsC[0][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[2]*aafC[1][2] - afAD[1]*aafC[2][2]; d0 = contactDistance + extents0.y*aafAbsC[2][2] + extents0.z*aafAbsC[1][2] + extents1.x*aafAbsC[0][1] + extents1.y*aafAbsC[0][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][0] - afAD[2]*aafC[0][0]; d0 = contactDistance + extents0.x*aafAbsC[2][0] + extents0.z*aafAbsC[0][0] + extents1.y*aafAbsC[1][2] + extents1.z*aafAbsC[1][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][1] - afAD[2]*aafC[0][1]; d0 = contactDistance + extents0.x*aafAbsC[2][1] + extents0.z*aafAbsC[0][1] + extents1.x*aafAbsC[1][2] + extents1.z*aafAbsC[1][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][2] - afAD[2]*aafC[0][2]; d0 = contactDistance + extents0.x*aafAbsC[2][2] + extents0.z*aafAbsC[0][2] + extents1.x*aafAbsC[1][1] + extents1.y*aafAbsC[1][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][0] - afAD[0]*aafC[1][0]; d0 = contactDistance + extents0.x*aafAbsC[1][0] + extents0.y*aafAbsC[0][0] + extents1.y*aafAbsC[2][2] + extents1.z*aafAbsC[2][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][1] - afAD[0]*aafC[1][1]; d0 = contactDistance + extents0.x*aafAbsC[1][1] + extents0.y*aafAbsC[0][1] + extents1.x*aafAbsC[2][2] + extents1.z*aafAbsC[2][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][2] - afAD[0]*aafC[1][2]; d0 = contactDistance + extents0.x*aafAbsC[1][2] + extents0.y*aafAbsC[0][2] + extents1.x*aafAbsC[2][1] + extents1.y*aafAbsC[2][0]; if(ABS_GREATER(d, d0)) return 0; } /* djs - tempUserData can be zero when it gets here - maybe if there was no previous axis? - which causes stack corruption, and thence a crash, in .NET PT: right! At first tempUserData wasn't ever supposed to be zero, but then I used that value to mark separation of boxes, and forgot to update the code below. Now I think the test is redundant with the one performed above, and the line could eventually be merged in the previous block. I'll do that later when removing all the #defines. */ // NB: the "16" here has nothing to do with MAX_NB_CTCS. Don't touch. if(collisionData) // if initialized & not previously separated overlap[collisionData-1] *= 0.999f; // Favorise previous axis .999 is too little. PxReal minimum = PX_MAX_REAL; PxI32 minIndex = 0; for(PxU32 i=AXIS_A0; i<6; i++) { PxReal d = overlap[i]; if(d>=0.0f && d<minimum) { minimum=d; minIndex=PxI32(i); } // >=0 !! otherwise bug at sep = 0 } collisionData = PxU32(minIndex + 1); // Leave "0" for separation #if PX_X86 const PxU32 sign = PXC_IS_NEGATIVE(d1[minIndex]); #else const PxU32 sign = PxU32(PXC_IS_NEGATIVE(d1[minIndex])); #endif PxMat34 trs; PxVec3 ctcNrm; switch(minIndex) { default: return 0; case AXIS_A0: // *ctcNrm = axis00; if(sign) { ctcNrm = axis00; trs.m = transform0.m; trs.p = transform0.p - extents0.x*axis00; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis00; trs.m.column0 = -axis00; trs.m.column1 = -axis01; trs.m.column2 = axis02; trs.p = transform0.p + extents0.x*axis00; } // return generateContacts(ctcPts, depths, extents0.y, extents0.z, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.y, extents0.z, extents1, trs, transform1, contactDistance); case AXIS_A1: // *ctcNrm = axis01; trs.m.column2 = axis00; // Factored out if(sign) { ctcNrm = axis01; trs.m.column0 = axis01; trs.m.column1 = axis02; trs.p = transform0.p - extents0.y*axis01; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis01; trs.m.column0 = -axis01; trs.m.column1 = -axis02; trs.p = transform0.p + extents0.y*axis01; } // return generateContacts(ctcPts, depths, extents0.z, extents0.x, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.z, extents0.x, extents1, trs, transform1, contactDistance); case AXIS_A2: // *ctcNrm = axis02; trs.m.column2 = axis01; // Factored out if(sign) { ctcNrm = axis02; trs.m.column0 = axis02; trs.m.column1 = axis00; trs.p = transform0.p - extents0.z*axis02; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis02; trs.m.column0 = -axis02; trs.m.column1 = -axis00; trs.p = transform0.p + extents0.z*axis02; } // return generateContacts(ctcPts, depths, extents0.x, extents0.y, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.x, extents0.y, extents1, trs, transform1, contactDistance); case AXIS_B0: // *ctcNrm = axis10; if(sign) { ctcNrm = axis10; trs.m.column0 = -axis10; trs.m.column1 = -axis11; trs.m.column2 = axis12; trs.p = transform1.p + extents1.x*axis10; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis10; trs.m = transform1.m; trs.p = transform1.p - extents1.x*axis10; } // return generateContacts(ctcPts, depths, extents1.y, extents1.z, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.y, extents1.z, extents0, trs, transform0, contactDistance); case AXIS_B1: // *ctcNrm = axis11; trs.m.column2 = axis10; // Factored out if(sign) { ctcNrm = axis11; trs.m.column0 = -axis11; trs.m.column1 = -axis12; trs.p = transform1.p + extents1.y*axis11; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis11; trs.m.column0 = axis11; trs.m.column1 = axis12; trs.m.column2 = axis10; trs.p = transform1.p - extents1.y*axis11; } // return generateContacts(ctcPts, depths, extents1.z, extents1.x, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.z, extents1.x, extents0, trs, transform0, contactDistance); case AXIS_B2: // *ctcNrm = axis12; trs.m.column2 = axis11; // Factored out if(sign) { ctcNrm = axis12; trs.m.column0 = -axis12; trs.m.column1 = -axis10; trs.p = transform1.p + extents1.z*axis12; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis12; trs.m.column0 = axis12; trs.m.column1 = axis10; trs.p = transform1.p - extents1.z*axis12; } // return generateContacts(ctcPts, depths, extents1.x, extents1.y, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.x, extents1.y, extents0, trs, transform0, contactDistance); } }
23,913
C++
33.359195
216
0.626145
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCustomGeometry.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; bool Gu::contactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxCustomGeometry& customGeom = checkedCast<PxCustomGeometry>(shape0); const PxGeometry& otherGeom = shape1; customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1, params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength, contactBuffer); return true; } bool Gu::contactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS) { bool res = contactCustomGeometryGeometry(shape1, shape0, transform1, transform0, params, cache, contactBuffer, renderOutput); for (PxU32 i = 0; i < contactBuffer.count; ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; return res; }
2,572
C++
44.14035
126
0.769051
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPolygonPolygon.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxMemory.h" #include "geomutils/PxContactBuffer.h" #include "GuContactPolygonPolygon.h" #include "GuShapeConvex.h" #include "GuInternal.h" #include "foundation/PxAlloca.h" #include "foundation/PxFPU.h" using namespace physx; using namespace Gu; #define CONTACT_REDUCTION /* void gVisualizeLocalLine(const PxVec3& a, const PxVec3& b, const PxMat34& m, PxsContactManager& manager) //temp debug { RenderOutput out = manager.getContext()->getRenderOutput(); out << 0xffffff << m << RenderOutput::LINES << a << b; } */ #ifdef CONTACT_REDUCTION static PX_FORCE_INLINE PxReal dot2D(const PxVec3& v0, const PxVec3& v1) { return v0.x * v1.x + v0.y * v1.y; } static void ContactReductionAllIn( PxContactBuffer& contactBuffer, PxU32 nbExistingContacts, PxU32 numIn, const PxMat33& rotT, const PxVec3* PX_RESTRICT vertices, const PxU8* PX_RESTRICT indices) { // Number of contacts created by current call const PxU32 nbNewContacts = contactBuffer.count - nbExistingContacts; if(nbNewContacts<=4) return; // no reduction for less than 4 verts // We have 3 different numbers here: // - numVerts = number of vertices in the convex polygon we're dealing with // - numIn = number of those that were "inside" the other convex polygon (should be <= numVerts) // - contactBuffer.count = total number of contacts *from both polygons* (that's the catch here) // The fast path can only be chosen when the contact buffer contains all the verts from current polygon, // i.e. when contactBuffer.count == numIn == numVerts PxContactPoint* PX_RESTRICT ctcs = contactBuffer.contacts + nbExistingContacts; if(numIn == nbNewContacts) { // Codepath 1: all vertices generated a contact PxReal deepestSeparation = ctcs[0].separation; PxU32 deepestIndex = 0; for(PxU32 i=1; i<nbNewContacts; ++i) { if(deepestSeparation > ctcs[i].separation) { deepestSeparation = ctcs[i].separation; deepestIndex = i; } } PxU32 index = 0; const PxU32 step = (numIn<<16)>>2; // Fixed point math, don't use floats here please bool needsExtraPoint = true; for(PxU32 i=0;i<4;i++) { const PxU32 contactIndex = index>>16; ctcs[i] = ctcs[contactIndex]; if(contactIndex==deepestIndex) needsExtraPoint = false; index += step; } if(needsExtraPoint) { ctcs[4] = ctcs[deepestIndex]; contactBuffer.count = nbExistingContacts + 5; } else { contactBuffer.count = nbExistingContacts + 4; } /* PT: TODO: investigate why this one does not work PxU32 index = deepestIndex<<16; const PxU32 step = (numIn<<16)>>2; // Fixed point math, don't use floats here please for(PxU32 i=0;i<4;i++) { PxU32 contactIndex = index>>16; if(contactIndex>=numIn) contactIndex -= numIn; ctcs[i] = ctcs[contactIndex]; index += step; } contactBuffer.count = nbExistingContacts + 4;*/ } else { // Codepath 2: all vertices are "in" but only some of them generated a contact // WARNING: this path doesn't work when the buffer contains vertices from both polys. // TODO: precompute those axes const PxU32 nbAxes = 8; PxVec3 dirs[nbAxes]; float angle = 0.0f; const float angleStep = PxDegToRad(180.0f/float(nbAxes)); for(PxU32 i=0;i<nbAxes;i++) { dirs[i] = PxVec3(cosf(angle), sinf(angle), 0.0f); angle += angleStep; } float dpmin[nbAxes]; float dpmax[nbAxes]; for(PxU32 i=0;i<nbAxes;i++) { dpmin[i] = PX_MAX_F32; dpmax[i] = -PX_MAX_F32; } for(PxU32 i=0;i<nbNewContacts;i++) { const PxVec3& p = vertices[indices[i]]; // Transform to 2D const PxVec3 p2d = rotT.transform(p); for(PxU32 j=0;j<nbAxes;j++) { const float dp = dot2D(dirs[j], p2d); dpmin[j] = physx::intrinsics::selectMin(dpmin[j], dp); dpmax[j] = physx::intrinsics::selectMax(dpmax[j], dp); } } PxU32 bestAxis = 0; float maxVariance = dpmax[0] - dpmin[0]; for(PxU32 i=1;i<nbAxes;i++) { const float variance = dpmax[i] - dpmin[i]; if(variance>maxVariance) { maxVariance = variance; bestAxis = i; } } const PxVec3 u = dirs[bestAxis]; const PxVec3 v = PxVec3(-u.y, u.x, 0.0f); // PxVec3(1.0f, 0.0f, 0.0f) => PxVec3(0.0f, 1.0f, 0.0f) // PxVec3(0.0f, 1.0f, 0.0f) => PxVec3(-1.0f, 0.0f, 0.0f) // PxVec3(-1.0f, 1.0f, 0.0f) => PxVec3(-1.0f, -1.0f, 0.0f) // PxVec3(1.0f, 1.0f, 0.0f) => PxVec3(-1.0f, 1.0f, 0.0f) float dpminu = PX_MAX_F32; float dpmaxu = -PX_MAX_F32; float dpminv = PX_MAX_F32; float dpmaxv = -PX_MAX_F32; PxU32 indexMinU = 0; PxU32 indexMaxU = 0; PxU32 indexMinV = 0; PxU32 indexMaxV = 0; for(PxU32 i=0;i<nbNewContacts;i++) { const PxVec3& p = vertices[indices[i]]; // Transform to 2D const PxVec3 p2d = rotT.transform(p); const float dpu = dot2D(u, p2d); const float dpv = dot2D(v, p2d); if(dpu<dpminu) { dpminu=dpu; indexMinU = i; } if(dpu>dpmaxu) { dpmaxu=dpu; indexMaxU = i; } if(dpv<dpminv) { dpminv=dpv; indexMinV = i; } if(dpv>dpmaxv) { dpmaxv=dpv; indexMaxV = i; } } if(indexMaxU == indexMinU) indexMaxU = 0xffffffff; if(indexMinV == indexMinU || indexMinV == indexMaxU) indexMinV = 0xffffffff; if(indexMaxV == indexMinU || indexMaxV == indexMaxU || indexMaxV == indexMinV) indexMaxV = 0xffffffff; PxU32 newCount = 0; for(PxU32 i=0;i<nbNewContacts;i++) { if( i==indexMinU || i==indexMaxU || i==indexMinV || i==indexMaxV) { ctcs[newCount++] = ctcs[i]; } } contactBuffer.count = nbExistingContacts + newCount; } } #endif // PT: please leave that function in the same translation unit as the calling code /*static*/ PxMat33 Gu::findRotationMatrixFromZ(const PxVec3& to) { PxMat33 result; const PxReal e = to.z; const PxReal f = PxAbs(e); if(f <= 0.9999f) { // PT: please keep the normal case first for PS3 branch prediction // Normal case, to and from are not parallel or anti-parallel const PxVec3 v = cross001(to); const PxReal h = 1.0f/(1.0f + e); /* optimization by Gottfried Chen */ const PxReal hvx = h * v.x; const PxReal hvz = h * v.z; const PxReal hvxy = hvx * v.y; const PxReal hvxz = hvx * v.z; const PxReal hvyz = hvz * v.y; result(0,0) = e + hvx*v.x; result(0,1) = hvxy - v.z; result(0,2) = hvxz + v.y; result(1,0) = hvxy + v.z; result(1,1) = e + h*v.y*v.y; result(1,2) = hvyz - v.x; result(2,0) = hvxz - v.y; result(2,1) = hvyz + v.x; result(2,2) = e + hvz*v.z; } else { //Vectors almost parallel // PT: TODO: simplify code below PxVec3 from(0.0f, 0.0f, 1.0f); PxVec3 absFrom(0.0f, 0.0f, 1.0f); if(absFrom.x < absFrom.y) { if(absFrom.x < absFrom.z) absFrom = PxVec3(1.0f, 0.0f, 0.0f); else absFrom = PxVec3(0.0f, 0.0f, 1.0f); } else { if(absFrom.y < absFrom.z) absFrom = PxVec3(0.0f, 1.0f, 0.0f); else absFrom = PxVec3(0.0f, 0.0f, 1.0f); } PxVec3 u, v; u.x = absFrom.x - from.x; u.y = absFrom.y - from.y; u.z = absFrom.z - from.z; v.x = absFrom.x - to.x; v.y = absFrom.y - to.y; v.z = absFrom.z - to.z; const PxReal c1 = 2.0f / u.dot(u); const PxReal c2 = 2.0f / v.dot(v); const PxReal c3 = c1 * c2 * u.dot(v); for(unsigned int i = 0; i < 3; i++) { for(unsigned int j = 0; j < 3; j++) { result(i,j) = - c1*u[i]*u[j] - c2*v[i]*v[j] + c3*v[i]*u[j]; } result(i,i) += 1.0f; } } return result; } // PT: using this specialized version avoids doing an explicit transpose, which reduces LHS PX_FORCE_INLINE PxMat34 transformTranspose(const PxMat33& a, const PxMat34& b) { return PxMat34(a.transformTranspose(b.m.column0), a.transformTranspose(b.m.column1), a.transformTranspose(b.m.column2), a.transformTranspose(b.p)); } // Helper function to transform x/y coordinate of point. PX_FORCE_INLINE void transform2D(float& x, float& y, const PxVec3& src, const PxMat34& mat) { x = src.x * mat.m.column0.x + src.y * mat.m.column1.x + src.z * mat.m.column2.x + mat.p.x; y = src.x * mat.m.column0.y + src.y * mat.m.column1.y + src.z * mat.m.column2.y + mat.p.y; } // Helper function to transform x/y coordinate of point. Use transposed matrix PX_FORCE_INLINE void transform2DT(float& x, float& y, const PxVec3& src, const PxMat33& mat) { x = mat.column0.dot(src); y = mat.column1.dot(src); } // Helper function to transform z coordinate of point. PX_FORCE_INLINE PxReal transformZ(const PxVec3& src, const PxMat34& mat) { return src.x * mat.m.column0.z + src.y * mat.m.column1.z + src.z * mat.m.column2.z + mat.p.z; } static void transformVertices( float& minX, float& minY, float& maxX, float& maxY, float* PX_RESTRICT verts2D, PxU32 nb, const PxVec3* PX_RESTRICT vertices, const PxU8* PX_RESTRICT indices, const PxMat33& RotT) { // PT: using local variables is important to reduce LHS. float lminX = FLT_MAX; float lminY = FLT_MAX; float lmaxX = -FLT_MAX; float lmaxY = -FLT_MAX; // PT: project points, compute min & max at the same time for(PxU32 i=0; i<nb; i++) { float x,y; transform2DT(x, y, vertices[indices[i]], RotT); lminX = physx::intrinsics::selectMin(lminX, x); lminY = physx::intrinsics::selectMin(lminY, y); lmaxX = physx::intrinsics::selectMax(lmaxX, x); lmaxY = physx::intrinsics::selectMax(lmaxY, y); verts2D[i*2+0] = x; verts2D[i*2+1] = y; } // DE702 // Compute center of polygon const float cx = (lminX + lmaxX)*0.5f; const float cy = (lminY + lmaxY)*0.5f; // We'll scale the polygon by epsilon const float epsilon = 1.e-6f; // Adjust bounds to take care of scaling lminX -= epsilon; lminY -= epsilon; lmaxX += epsilon; lmaxY += epsilon; //~DE702 // PT: relocate polygon to positive quadrant for(PxU32 i=0; i<nb; i++) { const float x = verts2D[i*2+0]; const float y = verts2D[i*2+1]; // PT: original code suffering from DE702 (relocation) // verts2D[i*2+0] = x - lminX; // verts2D[i*2+1] = y - lminY; // PT: theoretically proper DE702 fix (relocation + scaling) const float dx = x - cx; const float dy = y - cy; // const float coeff = epsilon * physx::intrinsics::recipSqrt(dx*dx+dy*dy); // verts2D[i*2+0] = x - lminX + dx * coeff; // verts2D[i*2+1] = y - lminY + dy * coeff; // PT: approximate but faster DE702 fix. We multiply by epsilon so this is good enough. verts2D[i*2+0] = x - lminX + physx::intrinsics::fsel(dx, epsilon, -epsilon); verts2D[i*2+1] = y - lminY + physx::intrinsics::fsel(dy, epsilon, -epsilon); } lmaxX -= lminX; lmaxY -= lminY; minX = lminX; minY = lminY; maxX = lmaxX; maxY = lmaxY; } //! Dedicated triangle version PX_FORCE_INLINE bool pointInTriangle2D( float px, float pz, float p0x, float p0z, float e10x, float e10z, float e20x, float e20z) { const float a = e10x*e10x + e10z*e10z; const float b = e10x*e20x + e10z*e20z; const float c = e20x*e20x + e20z*e20z; const float ac_bb = (a*c)-(b*b); const float vpx = px - p0x; const float vpz = pz - p0z; const float d = vpx*e10x + vpz*e10z; const float e = vpx*e20x + vpz*e20z; const float x = (d*c) - (e*b); const float y = (e*a) - (d*b); const float z = x + y - ac_bb; // Same as: if(x>0.0f && y>0.0f && z<0.0f) return TRUE; // else return FALSE; // return (( IR(z) & ~(IR(x)|IR(y)) ) & SIGN_BITMASK) != 0; if(x>0.0f && y>0.0f && z<0.0f) return true; else return false; } enum OutCode { OUT_XP = (1<<0), OUT_XN = (1<<1), OUT_YP = (1<<2), OUT_YN = (1<<3) }; static //PX_FORCE_INLINE bool PointInConvexPolygon2D_OutCodes(const float* PX_RESTRICT pgon2D, PxU32 numVerts, const PxReal tx, const PxReal ty, const PxReal maxX, const PxReal maxY, PxU8& outCodes) { PxU32 out = 0; if(tx<0.0f) out |= OUT_XN; if(ty<0.0f) out |= OUT_YN; if(tx>maxX) out |= OUT_XP; if(ty>maxY) out |= OUT_YP; outCodes = PxU8(out); if(out) return false; if(numVerts==3) return pointInTriangle2D( tx, ty, pgon2D[0], pgon2D[1], pgon2D[2] - pgon2D[0], pgon2D[3] - pgon2D[1], pgon2D[4] - pgon2D[0], pgon2D[5] - pgon2D[1]); #define X 0 #define Y 1 const PxReal* PX_RESTRICT vtx0_ = pgon2D + (numVerts-1)*2; const PxReal* PX_RESTRICT vtx1_ = pgon2D; const int* PX_RESTRICT ivtx0 = reinterpret_cast<const int*>(vtx0_); const int* PX_RESTRICT ivtx1 = reinterpret_cast<const int*>(vtx1_); //const int itx = (int&)tx; //const int ity = (int&)ty; // const int ity = PX_SIR(ty); const int* tmp = reinterpret_cast<const int*>(&ty); const int ity = *tmp; // get test bit for above/below X axis int yflag0 = ivtx0[Y] >= ity; int InsideFlag = 0; while(numVerts--) { const int yflag1 = ivtx1[Y] >= ity; if(yflag0 != yflag1) { const PxReal* PX_RESTRICT vtx0 = reinterpret_cast<const PxReal*>(ivtx0); const PxReal* PX_RESTRICT vtx1 = reinterpret_cast<const PxReal*>(ivtx1); if( ((vtx1[Y]-ty) * (vtx0[X]-vtx1[X]) > (vtx1[X]-tx) * (vtx0[Y]-vtx1[Y])) == yflag1 ) { if(InsideFlag == 1) return false; InsideFlag++; } } yflag0 = yflag1; ivtx0 = ivtx1; ivtx1 += 2; } #undef X #undef Y return InsideFlag & 1; } // Helper function to detect contact between two edges PX_FORCE_INLINE bool EdgeEdgeContactSpecial(const PxVec3& v1, const PxPlane& plane, const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip, unsigned int i, unsigned int j, float coeff) { const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp > 0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision const PxVec3 v2 = (p4-p3); temp = plane.n.dot(v2); if(temp == 0.0f) // ### epsilon would be better return false; // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i])) * coeff; if(dist < 0.0f) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; //no collision } //This one can also handle 2 vertex 'polygons' (useful for capsule surface segments) and can shift the results before contact generation. bool Gu::contactPolygonPolygonExt( PxU32 numVerts0, const PxVec3* vertices0, const PxU8* indices0, //polygon 0 const PxMat34& world0, const PxPlane& localPlane0, //xform of polygon 0, plane of polygon const PxMat33& rotT0, // PxU32 numVerts1, const PxVec3* PX_RESTRICT vertices1, const PxU8* PX_RESTRICT indices1, //polygon 1 const PxMat34& world1, const PxPlane& localPlane1, //xform of polygon 1, plane of polygon const PxMat33& rotT1, // const PxVec3& worldSepAxis, //world normal of separating plane - this is the world space normal of polygon0!! const PxMat34& transform0to1, const PxMat34& transform1to0, //transforms between polygons PxU32 /*polyIndex0*/, PxU32 polyIndex1, //feature indices for contact callback PxContactBuffer& contactBuffer, bool flipNormal, const PxVec3& posShift, PxReal sepShift) // shape order, result shift { const PxVec3 n = flipNormal ? -worldSepAxis : worldSepAxis; PX_ASSERT(indices0 != NULL && indices1 != NULL); // - optimize "from to" computation // - do the raycast case && EE tests in same space as 2D case... // - project all edges at the same time ? PxU32 NumIn = 0; bool status = false; void* PX_RESTRICT stackMemory; { const PxU32 maxNumVert = PxMax(numVerts0, numVerts1); stackMemory = PxAlloca(maxNumVert * sizeof(PxVec3)); } const PxU32 size0 = numVerts0 * sizeof(bool); bool* PX_RESTRICT flags0 = reinterpret_cast<bool*>(PxAlloca(size0)); PxU8* PX_RESTRICT outCodes0 = reinterpret_cast<PxU8*>(PxAlloca(size0)); // PxMemZero(flags0, size0); // PxMemZero(outCodes0, size0); const PxU32 size1 = numVerts1 * sizeof(bool); bool* PX_RESTRICT flags1 = reinterpret_cast<bool*>(PxAlloca(size1)); PxU8* PX_RESTRICT outCodes1 = reinterpret_cast<PxU8*>(PxAlloca(size1)); // PxMemZero(flags1, size1); // PxMemZero(outCodes1, size1); #ifdef CONTACT_REDUCTION // We want to do contact reduction on newly created contacts, not on all the already existing ones... PxU32 nbExistingContacts = contactBuffer.count; PxU32 nbCurrentContacts=0; PxU8 indices[PxContactBuffer::MAX_CONTACTS]; #endif { //polygon 1 float* PX_RESTRICT verts2D = NULL; float minX=0, minY=0; float maxX=0, maxY=0; const PxVec3 localDir = -world1.rotateTranspose(worldSepAxis); //contactNormal in hull1 space //that's redundant, its equal to -localPlane1.d const PxMat34 t0to2D = transformTranspose(rotT1, transform0to1); //transform from hull0 to RotT PxReal dn = localDir.dot(localPlane1.n); //if the contactNormal == +-(normal of poly0) is NOT orthogonal to poly1 ...this is just to protect the division below. // PT: TODO: if "numVerts1>2" we may skip more if (numVerts1 > 2 //no need to test whether we're 'inside' ignore capsule segments and points // if(!(-1E-7 < dn && dn < 1E-7)) && dn >= 1E-7f) // PT: it should never be negative so this unique test is enough { dn = 1.0f / dn; const float ld1 = -localPlane1.d; // PT: unavoidable "int-to-float" LHS here, so we only want to read it once! // Lazy-transform vertices if(!verts2D) { verts2D = reinterpret_cast<float*>(stackMemory); //Project points transformVertices( minX, minY, maxX, maxY, verts2D, numVerts1, vertices1, indices1, rotT1); } for(PxU32 i=0; i < numVerts0; i++) //for all vertices of poly0 { const PxVec3& p = vertices0[indices0[i]]; const float p0_z = transformZ(p, t0to2D); //transform ith vertex of poly0 to RotT const PxVec3 pIn1 = transform0to1.transform(p); //transform vertex to hull1 space, in which we have the poly1 vertices. const PxReal dd = (p0_z - ld1) * dn; //(p0_z + localPlane1.d) is the depth of the vertex behind the triangle measured along the triangle's normal. //we convert this to being measured along the 'contact normal' using the division. // if(dd < 0.0f) //if the penetrating vertex will have a penetration along the contact normal: // PX_ASSERT(dd <= 0.0f); // PT: dn is always positive, so dd is always negative { float px, py; transform2DT(px, py, pIn1 - dd*localDir, rotT1); //project vertex into poly1 plane along CONTACT NORMAL - not the polygon's normal. const bool res = PointInConvexPolygon2D_OutCodes(verts2D, numVerts1, px-minX, py-minY, maxX, maxY, outCodes0[i]); flags0[i] = res; if(res) { NumIn++; if(p0_z < ld1) { status = true; // PT: keep this first to avoid an LHS when leaving the function PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { #ifdef CONTACT_REDUCTION indices[nbCurrentContacts++] = indices0[i]; #endif ctc->normal = n; ctc->point = world0.transform(p) + (flipNormal ? posShift : PxVec3(0.0f)); ctc->separation = dd + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } } } else { PxMemZero(flags0, size0); PxMemZero(outCodes0, size0); } if(NumIn == numVerts0) { //All vertices0 are inside polygon 1 #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT0, vertices0, indices); #endif return status; } #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT0, vertices0, indices); #endif #ifdef CONTACT_REDUCTION nbExistingContacts = contactBuffer.count; nbCurrentContacts = 0; #endif NumIn = 0; verts2D = NULL; //Polygon 0 const PxMat34 t1to2D = transformTranspose(rotT0, transform1to0); if (numVerts0 > 2) //no need to test whether we're 'inside' ignore capsule segments and points { const float ld0 = -localPlane0.d; // PT: unavoidable "int-to-float" LHS here, so we only want to read it once! // Lazy-transform vertices if(!verts2D) { verts2D = reinterpret_cast<float*>(stackMemory); //Project vertices transformVertices( minX, minY, maxX, maxY, verts2D, numVerts0, vertices0, indices0, rotT0); } for(PxU32 i=0; i < numVerts1; i++) { const PxVec3& p = vertices1[indices1[i]]; float px, py; transform2D(px, py, p, t1to2D); const bool res = PointInConvexPolygon2D_OutCodes(verts2D, numVerts0, px-minX, py-minY, maxX, maxY, outCodes1[i]); flags1[i] = res; if(res) { NumIn++; const float pz = transformZ(p, t1to2D); if(pz < ld0) { status = true; // PT: keep this first to avoid an LHS when leaving the function // PT: in theory, with this contact point we should use "worldSepAxis" as a contact normal. // However we want to output the same normal for all contact points not to break friction // patches!!! In theory again, it should be exactly the same since the contact point at // time of impact is supposed to be the same on both bodies. In practice however, and with // a depth-based engine, this is not the case. So the contact point here is not exactly // right, but preserving the friction patch seems more important. PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { #ifdef CONTACT_REDUCTION indices[nbCurrentContacts++] = indices1[i]; #endif ctc->normal = n; ctc->point = world1.transform(p) + (flipNormal ? PxVec3(0.0f) : posShift); ctc->separation = (pz - ld0) + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } if(NumIn == numVerts1) { //all vertices 1 are inside polygon 0 #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT1, vertices1, indices); #endif return status; } #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT1, vertices1, indices); #endif } else { PxMemZero(flags1, size1); PxMemZero(outCodes1, size1); } } //Edge/edge case //Calculation done in space 0 PxVec3* PX_RESTRICT verts1in0 = reinterpret_cast<PxVec3*>(stackMemory); for(PxU32 i=0; i<numVerts1; i++) { verts1in0[i] = transform1to0.transform(vertices1[indices1[i]]); } if (numVerts0 >= 2 && numVerts1 >= 2)//useless if one of them is degenerate. for(PxU32 j=0; j<numVerts1; j++) { PxU32 j1 = j+1; if(j1 >= numVerts1) j1 = 0; // if(!(flags1[j] ^ flags1[j1])) // continue; if(flags1[j] && flags1[j1]) continue; if(outCodes1[j]&outCodes1[j1]) continue; const PxVec3& p0 = verts1in0[j]; const PxVec3& p1 = verts1in0[j1]; // gVisualizeLocalLine(vertices1[indices1[j]], vertices1[indices1[j1]], world1, callback.getManager()); const PxVec3 v1 = p1-p0; const PxVec3 planeNormal = v1.cross(localPlane0.n); const PxPlane plane(planeNormal, -(planeNormal.dot(p0))); // find largest 2D plane projection PxU32 _i, _j; closestAxis(planeNormal, _i, _j); const PxReal coeff = 1.0f / (v1[_i]*localPlane0.n[_j]-v1[_j]*localPlane0.n[_i]); for(PxU32 i=0; i<numVerts0; i++) { PxU32 i1 = i+1; if(i1 >= numVerts0) i1 = 0; // if(!(flags0[i] ^ flags0[i1])) // continue; if(flags0[i] && flags0[i1]) continue; if(outCodes0[i]&outCodes0[i1]) continue; const PxVec3& p0b = vertices0[indices0[i]]; const PxVec3& p1b = vertices0[indices0[i1]]; // gVisualizeLocalLine(p0b, p1b, world0, callback.getManager()); PxReal dist; PxVec3 p; if(EdgeEdgeContactSpecial(v1, plane, p0, p1, localPlane0.n, p0b, p1b, dist, p, _i, _j, coeff)) { status = true; // PT: keep this first to avoid an LHS when leaving the function /* p = world0.transform(p); //contacts are generated on the edges of polygon 1 //we only have to shift the position of polygon 1 if flipNormal is false, because //in this case convex 0 gets passed as polygon 1, and it is convex 0 that was shifted. if (!flipNormal) p += posShift; contactBuffer.contact(p, n, -dist + sepShift, polyIndex0, polyIndex1, convexID);*/ PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { ctc->normal = n; ctc->point = world0.transform(p) + (flipNormal ? PxVec3(0.0f) : posShift); ctc->separation = -dist + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } return status; }
26,369
C++
29.591647
173
0.65888
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuQuantizer.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuQuantizer.h" #include "foundation/PxVec3.h" #include "foundation/PxBounds3.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxAllocator.h" #include "foundation/PxArray.h" using namespace physx; using namespace Gu; PxU32 kmeans_cluster3d(const PxVec3* input, // an array of input 3d data points. PxU32 inputSize, // the number of input data points. PxU32 clumpCount, // the number of clumps you wish to product. PxVec3* outputClusters, // The output array of clumps 3d vectors, should be at least 'clumpCount' in size. PxU32* outputIndices, // A set of indices which remaps the input vertices to clumps; should be at least 'inputSize' float errorThreshold=0.01f, // The error threshold to converge towards before giving up. float collapseDistance=0.01f); // distance so small it is not worth bothering to create a new clump. template <class Vec,class Type > PxU32 kmeans_cluster(const Vec* input, PxU32 inputCount, PxU32 clumpCount, Vec* clusters, PxU32* outputIndices, Type threshold, // controls how long it works to converge towards a least errors solution. Type collapseDistance) // distance between clumps to consider them to be essentially equal. { PxU32 convergeCount = 64; // maximum number of iterations attempting to converge to a solution.. PxU32* counts = PX_ALLOCATE(PxU32, clumpCount, "PxU32"); Type error=0; if ( inputCount <= clumpCount ) // if the number of input points is less than our clumping size, just return the input points. { clumpCount = inputCount; for (PxU32 i=0; i<inputCount; i++) { if ( outputIndices ) { outputIndices[i] = i; } clusters[i] = input[i]; counts[i] = 1; } } else { PxVec3* centroids = PX_ALLOCATE(PxVec3, clumpCount, "PxVec3"); // Take a sampling of the input points as initial centroid estimates. for (PxU32 i=0; i<clumpCount; i++) { PxU32 index = (i*inputCount)/clumpCount; PX_ASSERT( index < inputCount ); clusters[i] = input[index]; } // Here is the main convergence loop Type old_error = FLT_MAX; // old and initial error estimates are max Type error = FLT_MAX; do { old_error = error; // preserve the old error // reset the counts and centroids to current cluster location for (PxU32 i=0; i<clumpCount; i++) { counts[i] = 0; centroids[i] = PxVec3(PxZero); } error = 0; // For each input data point, figure out which cluster it is closest too and add it to that cluster. for (PxU32 i=0; i<inputCount; i++) { Type min_distance = FLT_MAX; // find the nearest clump to this point. for (PxU32 j=0; j<clumpCount; j++) { const Type distance = (input[i] - clusters[j]).magnitudeSquared(); if ( distance < min_distance ) { min_distance = distance; outputIndices[i] = j; // save which clump this point indexes } } const PxU32 index = outputIndices[i]; // which clump was nearest to this point. centroids[index]+=input[i]; counts[index]++; // increment the counter indicating how many points are in this clump. error+=min_distance; // save the error accumulation } // Now, for each clump, compute the mean and store the result. for (PxU32 i=0; i<clumpCount; i++) { if ( counts[i] ) // if this clump got any points added to it... { const Type recip = 1.0f / Type(counts[i]); // compute the average (center of those points) centroids[i]*=recip; // compute the average center of the points in this clump. clusters[i] = centroids[i]; // store it as the new cluster. } } // decrement the convergence counter and bail if it is taking too long to converge to a solution. convergeCount--; if (convergeCount == 0 ) { break; } if ( error < threshold ) // early exit if our first guess is already good enough (if all input points are the same) break; } while ( PxAbs(error - old_error) > threshold ); // keep going until the error is reduced by this threshold amount. PX_FREE(centroids); } // ok..now we prune the clumps if necessary. // The rules are; first, if a clump has no 'counts' then we prune it as it's unused. // The second, is if the centroid of this clump is essentially the same (based on the distance tolerance) // as an existing clump, then it is pruned and all indices which used to point to it, now point to the one // it is closest too. PxU32 outCount = 0; // number of clumps output after pruning performed. Type d2 = collapseDistance*collapseDistance; // squared collapse distance. for (PxU32 i=0; i<clumpCount; i++) { if ( counts[i] == 0 ) // if no points ended up in this clump, eliminate it. continue; // see if this clump is too close to any already accepted clump. bool add = true; PxU32 remapIndex = outCount; // by default this clump will be remapped to its current index. for (PxU32 j=0; j<outCount; j++) { Type distance = (clusters[i] - clusters[j]).magnitudeSquared(); if ( distance < d2 ) { remapIndex = j; add = false; // we do not add this clump break; } } // If we have fewer output clumps than input clumps so far, then we need to remap the old indices to the new ones. if ( outputIndices ) { if ( outCount != i || !add ) // we need to remap indices! everything that was index 'i' now needs to be remapped to 'outCount' { for (PxU32 j=0; j<inputCount; j++) { if ( outputIndices[j] == i ) { outputIndices[j] = remapIndex; // } } } } if ( add ) { clusters[outCount] = clusters[i]; outCount++; } } PX_FREE(counts); clumpCount = outCount; return clumpCount; } PxU32 kmeans_cluster3d( const PxVec3* input, // an array of input 3d data points. PxU32 inputSize, // the number of input data points. PxU32 clumpCount, // the number of clumps you wish to produce PxVec3* outputClusters, // The output array of clumps 3d vectors, should be at least 'clumpCount' in size. PxU32* outputIndices, // A set of indices which remaps the input vertices to clumps; should be at least 'inputSize' float errorThreshold, // The error threshold to converge towards before giving up. float collapseDistance) // distance so small it is not worth bothering to create a new clump. { return kmeans_cluster< PxVec3, float >(input, inputSize, clumpCount, outputClusters, outputIndices, errorThreshold, collapseDistance); } class QuantizerImpl : public Quantizer, public PxUserAllocated { public: QuantizerImpl(void) { mScale = PxVec3(1.0f, 1.0f, 1.0f); mCenter = PxVec3(0.0f, 0.0f, 0.0f); } // Use the k-means quantizer, similar results, but much slower. virtual const PxVec3* kmeansQuantize3D(PxU32 vcount, const PxVec3* vertices, PxU32 stride, bool denormalizeResults, PxU32 maxVertices, PxU32& outVertsCount) { const PxVec3* ret = NULL; outVertsCount = 0; mNormalizedInput.clear(); mQuantizedOutput.clear(); if ( vcount > 0 ) { normalizeInput(vcount,vertices, stride); PxVec3* quantizedOutput = PX_ALLOCATE(PxVec3, vcount, "PxVec3"); PxU32* quantizedIndices = PX_ALLOCATE(PxU32, vcount, "PxU32"); outVertsCount = kmeans_cluster3d(&mNormalizedInput[0], vcount, maxVertices, quantizedOutput, quantizedIndices, 0.01f, 0.0001f ); if ( outVertsCount > 0 ) { if ( denormalizeResults ) { for (PxU32 i=0; i<outVertsCount; i++) { PxVec3 v( quantizedOutput[i] ); v = v.multiply(mScale) + mCenter; mQuantizedOutput.pushBack(v); } } else { for (PxU32 i=0; i<outVertsCount; i++) { const PxVec3& v( quantizedOutput[i] ); mQuantizedOutput.pushBack(v); } } ret = &mQuantizedOutput[0]; } PX_FREE(quantizedOutput); PX_FREE(quantizedIndices); } return ret; } virtual void release(void) { PX_DELETE_THIS; } virtual const PxVec3& getDenormalizeScale(void) const { return mScale; } virtual const PxVec3& getDenormalizeCenter(void) const { return mCenter; } private: void normalizeInput(PxU32 vcount, const PxVec3* vertices, PxU32 stride) { const char* vtx = reinterpret_cast<const char *> (vertices); mNormalizedInput.clear(); mQuantizedOutput.clear(); PxBounds3 bounds; bounds.setEmpty(); for (PxU32 i=0; i<vcount; i++) { const PxVec3& v = *reinterpret_cast<const PxVec3 *> (vtx); vtx += stride; bounds.include(v); } mCenter = bounds.getCenter(); PxVec3 dim = bounds.getDimensions(); dim *= 1.001f; mScale = dim*0.5f; for (PxU32 i = 0; i < 3; i++) { if(dim[i] == 0) mScale[i] = 1.0f; } PxVec3 recip; recip.x = 1.0f / mScale.x; recip.y = 1.0f / mScale.y; recip.z = 1.0f / mScale.z; vtx = reinterpret_cast<const char *> (vertices); for (PxU32 i=0; i<vcount; i++) { PxVec3 v = *reinterpret_cast<const PxVec3 *> (vtx); vtx += stride; v = (v - mCenter).multiply(recip); mNormalizedInput.pushBack(v); } } virtual ~QuantizerImpl() { } private: PxVec3 mScale; PxVec3 mCenter; PxArray<PxVec3> mNormalizedInput; PxArray<PxVec3> mQuantizedOutput; }; Quantizer* physx::Gu::createQuantizer() { return PX_NEW(QuantizerImpl); }
10,947
C++
31.876877
135
0.6811
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuVertexReducer.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuVertexReducer.h" #include "foundation/PxAllocator.h" #include "CmRadixSort.h" using namespace physx; using namespace Gu; using namespace Cm; // PT: code archeology: this initially came from ICE (IceVertexCloud.h/cpp). Consider dropping it. ReducedVertexCloud::ReducedVertexCloud(const PxVec3* verts, PxU32 nb_verts) : mNbRVerts(0), mRVerts(NULL), mXRef(NULL) { mVerts = verts; mNbVerts = nb_verts; } ReducedVertexCloud::~ReducedVertexCloud() { clean(); } ReducedVertexCloud& ReducedVertexCloud::clean() { PX_FREE(mXRef); PX_FREE(mRVerts); return *this; } /** * Reduction method. Use this to create a minimal vertex cloud. * \param rc [out] result structure * \return true if success * \warning This is not about welding nearby vertices, here we look for real redundant ones. */ bool ReducedVertexCloud::reduce(REDUCEDCLOUD* rc) { clean(); mXRef = PX_ALLOCATE(PxU32, mNbVerts, "mXRef"); float* f = PX_ALLOCATE(float, mNbVerts, "tmp"); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].x; RadixSortBuffered Radix; Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].y; Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].z; const PxU32* Sorted = Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED).GetRanks(); PX_FREE(f); mNbRVerts = 0; const PxU32 Junk[] = {PX_INVALID_U32, PX_INVALID_U32, PX_INVALID_U32}; const PxU32* Previous = Junk; mRVerts = PX_ALLOCATE(PxVec3, mNbVerts, "PxVec3"); PxU32 Nb = mNbVerts; while(Nb--) { const PxU32 Vertex = *Sorted++; // Vertex number const PxU32* current = reinterpret_cast<const PxU32*>(&mVerts[Vertex]); if(current[0]!=Previous[0] || current[1]!=Previous[1] || current[2]!=Previous[2]) mRVerts[mNbRVerts++] = mVerts[Vertex]; Previous = current; mXRef[Vertex] = mNbRVerts-1; } if(rc) { rc->CrossRef = mXRef; rc->NbRVerts = mNbRVerts; rc->RVerts = mRVerts; } return true; }
3,751
C++
32.20354
118
0.728339
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuBarycentricCoordinates.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBarycentricCoordinates.h" using namespace physx; using namespace aos; void Gu::barycentricCoordinates(const Vec3VArg p, const Vec3VArg a, const Vec3VArg b, FloatV& v) { const Vec3V v0 = V3Sub(a, p); const Vec3V v1 = V3Sub(b, p); const Vec3V d = V3Sub(v1, v0); const FloatV denominator = V3Dot(d, d); const FloatV numerator = V3Dot(V3Neg(v0), d); const FloatV zero = FZero(); const FloatV denom = FSel(FIsGrtr(denominator, zero), FRecip(denominator), zero); v = FMul(numerator, denom); } void Gu::barycentricCoordinates(const aos::Vec3VArg p, const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c, aos::FloatV& v, aos::FloatV& w) { const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V n = V3Cross(ab, ac); const VecCrossV crossA = V3PrepareCross(V3Sub(a, p)); const VecCrossV crossB = V3PrepareCross(V3Sub(b, p)); const VecCrossV crossC = V3PrepareCross(V3Sub(c, p)); const Vec3V bCrossC = V3Cross(crossB, crossC); const Vec3V cCrossA = V3Cross(crossC, crossA); const Vec3V aCrossB = V3Cross(crossA, crossB); const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c const FloatV totalArea =FAdd(va, FAdd(vb, vc)); const FloatV zero = FZero(); const FloatV denom = FSel(FIsEq(totalArea, zero), zero, FRecip(totalArea)); v = FMul(vb, denom); w = FMul(vc, denom); } // v0 = b - a; // v1 = c - a; // v2 = p - a; void Gu::barycentricCoordinates(const Vec3VArg v0, const Vec3VArg v1, const Vec3VArg v2, FloatV& v, FloatV& w) { const FloatV d00 = V3Dot(v0, v0); const FloatV d01 = V3Dot(v0, v1); const FloatV d11 = V3Dot(v1, v1); const FloatV d20 = V3Dot(v2, v0); const FloatV d21 = V3Dot(v2, v1); const FloatV denom = FRecip(FSub(FMul(d00,d11), FMul(d01, d01))); v = FMul(FSub(FMul(d11, d20), FMul(d01, d21)), denom); w = FMul(FSub(FMul(d00, d21), FMul(d01, d20)), denom); }
3,790
C++
43.599999
155
0.7219
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuAdjacencies.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxMemory.h" #include "GuEdgeList.h" #include "GuAdjacencies.h" #include "CmSerialize.h" #include "CmRadixSort.h" // PT: code archeology: this initially came from ICE (IceAdjacencies.h/cpp). Consider putting it back the way it was initially. using namespace physx; using namespace Gu; using namespace Cm; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// /** * Flips the winding. */ void AdjTriangle::Flip() { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY // Call the Triangle method IndexedTriangle::Flip(); #endif // Flip links. We flipped vertex references 1 & 2, i.e. links 0 & 1. physx::PxSwap(mATri[0], mATri[1]); } /** * Computes the number of boundary edges in a triangle. * \return the number of boundary edges. (0 => 3) */ PxU32 AdjTriangle::ComputeNbBoundaryEdges() const { // Look for boundary edges PxU32 Nb = 0; if(IS_BOUNDARY(mATri[0])) Nb++; if(IS_BOUNDARY(mATri[1])) Nb++; if(IS_BOUNDARY(mATri[2])) Nb++; return Nb; } /** * Computes the number of valid neighbors. * \return the number of neighbors. (0 => 3) */ PxU32 AdjTriangle::ComputeNbNeighbors() const { PxU32 Nb = 0; if(!IS_BOUNDARY(mATri[0])) Nb++; if(!IS_BOUNDARY(mATri[1])) Nb++; if(!IS_BOUNDARY(mATri[2])) Nb++; return Nb; } /** * Checks whether the triangle has a particular neighbor or not. * \param tref [in] the triangle reference to look for * \param index [out] the corresponding index in the triangle (NULL if not needed) * \return true if the triangle has the given neighbor */ bool AdjTriangle::HasNeighbor(PxU32 tref, PxU32* index) const { // ### could be optimized if(!IS_BOUNDARY(mATri[0]) && MAKE_ADJ_TRI(mATri[0])==tref) { if(index) *index = 0; return true; } if(!IS_BOUNDARY(mATri[1]) && MAKE_ADJ_TRI(mATri[1])==tref) { if(index) *index = 1; return true; } if(!IS_BOUNDARY(mATri[2]) && MAKE_ADJ_TRI(mATri[2])==tref) { if(index) *index = 2; return true; } return false; } Adjacencies::Adjacencies() : mNbFaces(0), mFaces(NULL) { } Adjacencies::~Adjacencies() { PX_DELETE_ARRAY(mFaces); } /** * Computes the number of boundary edges. * \return the number of boundary edges. */ PxU32 Adjacencies::ComputeNbBoundaryEdges() const { if(!mFaces) return 0; // Look for boundary edges PxU32 Nb = 0; for(PxU32 i=0;i<mNbFaces;i++) { AdjTriangle* CurTri = &mFaces[i]; Nb+=CurTri->ComputeNbBoundaryEdges(); } return Nb; } /** * Computes the boundary vertices. A boundary vertex is defined as a vertex shared by at least one boundary edge. * \param nb_verts [in] the number of vertices * \param bound_status [out] a user-provided array of bool * \return true if success. The user-array is filled with true or false (boundary vertex / not boundary vertex) */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Adjacencies::GetBoundaryVertices(PxU32 nb_verts, bool* bound_status) const #else bool Adjacencies::GetBoundaryVertices(PxU32 nb_verts, bool* bound_status, const IndexedTriangle32* faces) const #endif { // We need the adjacencies if(!mFaces || !bound_status || !nb_verts) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::GetBoundaryVertices: NULL parameter!"); #ifndef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!faces) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::GetBoundaryVertices: NULL parameter!"); #endif // Init PxMemZero(bound_status, nb_verts*sizeof(bool)); // Loop through faces for(PxU32 i=0;i<mNbFaces;i++) { AdjTriangle* CurTri = &mFaces[i]; if(IS_BOUNDARY(CurTri->mATri[0])) { // Two boundary vertices: 0 - 1 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[1]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[1]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } if(IS_BOUNDARY(CurTri->mATri[1])) { // Two boundary vertices: 0 - 2 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } if(IS_BOUNDARY(CurTri->mATri[2])) { // Two boundary vertices: 1 - 2 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[1]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[1]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } } return true; } /** * Assigns a new edge code to the counterpart link of a given link. * \param link [in] the link to modify - shouldn't be a boundary link * \param edge_nb [in] the new edge number */ void Adjacencies::AssignNewEdgeCode(PxU32 link, PxU8 edge_nb) { if(!IS_BOUNDARY(link)) { PxU32 Id = MAKE_ADJ_TRI(link); // Triangle ID PxU32 Edge = GET_EDGE_NB(link); // Counterpart edge ID AdjTriangle* Tri = &mFaces[Id]; // Adjacent triangle // Get link whose edge code is invalid PxU32 AdjLink = Tri->mATri[Edge]; // Link to ourself (i.e. to 'link') SET_EDGE_NB(AdjLink, edge_nb); // Assign new edge code Tri->mATri[Edge] = AdjLink; // Put link back } } /** * Modifies the existing database so that reference 'vref' of triangle 'curtri' becomes the last one. * Provided reference must already exist in provided triangle. * \param cur_tri [in] the triangle * \param vref [in] the reference * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Adjacencies::MakeLastRef(AdjTriangle& cur_tri, PxU32 vref) #else bool Adjacencies::MakeLastRef(AdjTriangle& cur_tri, PxU32 vref, IndexedTriangle32* cur_topo) #endif { #ifndef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!cur_topo) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::MakeLastRef: NULL parameter!"); #endif // We want pattern (x y vref) // Edge 0-1 is (x y) // Edge 0-2 is (x vref) // Edge 1-2 is (y vref) // First thing is to scroll the existing references in order for vref to become the last one. Scrolling assures winding order is conserved. // Edge code need fixing as well: // The two MSB for each link encode the counterpart edge in adjacent triangle. We swap the link positions, but adjacent triangles remain the // same. In other words, edge codes are still valid for current triangle since counterpart edges have not been swapped. *BUT* edge codes of // the three possible adjacent triangles *are* now invalid. We need to fix edge codes, but for adjacent triangles... #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(cur_tri.v[0]==vref) #else if(cur_topo->mRef[0]==vref) #endif { // Pattern is (vref x y) // Edge 0-1 is (vref x) // Edge 0-2 is (vref y) // Edge 1-2 is (x y) // Catch original data #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 Ref0 = cur_tri.v[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_tri.v[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_tri.v[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_tri.v[0] = Ref1; cur_tri.v[1] = Ref2; cur_tri.v[2] = Ref0; #else PxU32 Ref0 = cur_topo->mRef[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_topo->mRef[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_topo->mRef[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_topo->mRef[0] = Ref1; cur_topo->mRef[1] = Ref2; cur_topo->mRef[2] = Ref0; #endif cur_tri.mATri[0] = Link12; // Edge 0-1 now encodes Ref1-Ref2, i.e. previous Link12 cur_tri.mATri[1] = Link01; // Edge 0-2 now encodes Ref1-Ref0, i.e. previous Link01 cur_tri.mATri[2] = Link02; // Edge 1-2 now encodes Ref2-Ref0, i.e. previous Link02 // Fix edge codes AssignNewEdgeCode(Link01, 1); AssignNewEdgeCode(Link02, 2); AssignNewEdgeCode(Link12, 0); return true; } #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY else if(cur_tri.v[1]==vref) #else else if(cur_topo->mRef[1]==vref) #endif { // Pattern is (x vref y) // Edge 0-1 is (x vref) // Edge 0-2 is (x y) // Edge 1-2 is (vref y) // Catch original data #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 Ref0 = cur_tri.v[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_tri.v[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_tri.v[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_tri.v[0] = Ref2; cur_tri.v[1] = Ref0; cur_tri.v[2] = Ref1; #else PxU32 Ref0 = cur_topo->mRef[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_topo->mRef[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_topo->mRef[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_topo->mRef[0] = Ref2; cur_topo->mRef[1] = Ref0; cur_topo->mRef[2] = Ref1; #endif cur_tri.mATri[0] = Link02; // Edge 0-1 now encodes Ref2-Ref0, i.e. previous Link02 cur_tri.mATri[1] = Link12; // Edge 0-2 now encodes Ref2-Ref1, i.e. previous Link12 cur_tri.mATri[2] = Link01; // Edge 1-2 now encodes Ref0-Ref1, i.e. previous Link01 // Fix edge codes AssignNewEdgeCode(Link01, 2); AssignNewEdgeCode(Link02, 0); AssignNewEdgeCode(Link12, 1); return true; } #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY else if(cur_tri.v[2]==vref) #else else if(cur_topo->mRef[2]==vref) #endif { // Nothing to do, provided reference already is the last one return true; } // Here the provided reference doesn't belong to the provided triangle. return false; } bool Adjacencies::Load(PxInputStream& stream) { // Import header PxU32 Version; bool Mismatch; if(!ReadHeader('A', 'D', 'J', 'A', Version, Mismatch, stream)) return false; // Import adjacencies mNbFaces = readDword(Mismatch, stream); mFaces = PX_NEW(AdjTriangle)[mNbFaces]; stream.read(mFaces, sizeof(AdjTriangle)*mNbFaces); return true; } //#ifdef PX_COOKING //! An edge class used to compute the adjacency structures. class AdjEdge : public EdgeData, public PxUserAllocated { public: PX_INLINE AdjEdge() {} PX_INLINE ~AdjEdge() {} PxU32 mFaceNb; //!< Owner face }; /** * Adds a new edge to the database. * \param ref0 [in] vertex reference for the new edge * \param ref1 [in] vertex reference for the new edge * \param face [in] owner face */ static void AddEdge(PxU32 ref0, PxU32 ref1, PxU32 face, PxU32& nb_edges, AdjEdge* edges) { // Store edge data edges[nb_edges].Ref0 = ref0; edges[nb_edges].Ref1 = ref1; edges[nb_edges].mFaceNb = face; nb_edges++; } /** * Adds a new triangle to the database. * \param ref0 [in] vertex reference for the new triangle * \param ref1 [in] vertex reference for the new triangle * \param ref2 [in] vertex reference for the new triangle * \param id [in] triangle index */ static void AddTriangle(PxU32 ref0, PxU32 ref1, PxU32 ref2, PxU32 id, AdjTriangle* faces, PxU32& nb_edges, AdjEdge* edges) { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY // Store vertex-references faces[id].v[0] = ref0; faces[id].v[1] = ref1; faces[id].v[2] = ref2; #endif // Reset links faces[id].mATri[0] = PX_INVALID_U32; faces[id].mATri[1] = PX_INVALID_U32; faces[id].mATri[2] = PX_INVALID_U32; // Add edge 01 to database if(ref0<ref1) AddEdge(ref0, ref1, id, nb_edges, edges); else AddEdge(ref1, ref0, id, nb_edges, edges); // Add edge 02 to database if(ref0<ref2) AddEdge(ref0, ref2, id, nb_edges, edges); else AddEdge(ref2, ref0, id, nb_edges, edges); // Add edge 12 to database if(ref1<ref2) AddEdge(ref1, ref2, id, nb_edges, edges); else AddEdge(ref2, ref1, id, nb_edges, edges); } /** * Updates the links in two adjacent triangles. * \param first_tri [in] index of the first triangle * \param second_tri [in] index of the second triangle * \param ref0 [in] the common edge's first vertex reference * \param ref1 [in] the common edge's second vertex reference * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY static bool UpdateLink(PxU32 first_tri, PxU32 second_tri, PxU32 ref0, PxU32 ref1, AdjTriangle* faces) #else static bool UpdateLink(PxU32 first_tri, PxU32 second_tri, PxU32 ref0, PxU32 ref1, AdjTriangle* faces, const ADJACENCIESCREATE& create) #endif { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY AdjTriangle& Tri0 = faces[first_tri]; // Catch the first triangle AdjTriangle& Tri1 = faces[second_tri]; // Catch the second triangle // Get the edge IDs. 0xff means input references are wrong. PxU8 EdgeNb0 = Tri0.FindEdge(ref0, ref1); if(EdgeNb0==0xff) return SetIceError("Adjacencies::UpdateLink: invalid edge reference in first triangle"); PxU8 EdgeNb1 = Tri1.FindEdge(ref0, ref1); if(EdgeNb1==0xff) return SetIceError("Adjacencies::UpdateLink: invalid edge reference in second triangle"); // Update links. The two most significant bits contain the counterpart edge's ID. Tri0.mATri[EdgeNb0] = second_tri |(PxU32(EdgeNb1)<<30); Tri1.mATri[EdgeNb1] = first_tri |(PxU32(EdgeNb0)<<30); #else IndexedTriangle32 FirstTri, SecondTri; if(create.DFaces) { FirstTri.mRef[0] = create.DFaces[first_tri*3+0]; FirstTri.mRef[1] = create.DFaces[first_tri*3+1]; FirstTri.mRef[2] = create.DFaces[first_tri*3+2]; SecondTri.mRef[0] = create.DFaces[second_tri*3+0]; SecondTri.mRef[1] = create.DFaces[second_tri*3+1]; SecondTri.mRef[2] = create.DFaces[second_tri*3+2]; } if(create.WFaces) { FirstTri.mRef[0] = create.WFaces[first_tri*3+0]; FirstTri.mRef[1] = create.WFaces[first_tri*3+1]; FirstTri.mRef[2] = create.WFaces[first_tri*3+2]; SecondTri.mRef[0] = create.WFaces[second_tri*3+0]; SecondTri.mRef[1] = create.WFaces[second_tri*3+1]; SecondTri.mRef[2] = create.WFaces[second_tri*3+2]; } // Get the edge IDs. 0xff means input references are wrong. const PxU8 EdgeNb0 = FirstTri.findEdge(ref0, ref1); const PxU8 EdgeNb1 = SecondTri.findEdge(ref0, ref1); if(EdgeNb0==0xff || EdgeNb1==0xff) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::UpdateLink: invalid edge reference"); // Update links. The two most significant bits contain the counterpart edge's ID. faces[first_tri].mATri[EdgeNb0] = second_tri |(PxU32(EdgeNb1)<<30); faces[second_tri].mATri[EdgeNb1] = first_tri |(PxU32(EdgeNb0)<<30); #endif return true; } /** * Creates the adjacency structures. * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY static bool CreateDatabase(AdjTriangle* faces, PxU32 nb_edges, const AdjEdge* edges) #else static bool CreateDatabase(AdjTriangle* faces, PxU32 nb_edges, const AdjEdge* edges, const ADJACENCIESCREATE& create) #endif { RadixSortBuffered Core; { // Multiple sorts - this rewritten version uses less ram // PT: TTP 2994: the mesh has 343000+ edges, so yeah, sure, allocating more than 1mb on the stack causes overflow... PxU32* VRefs = PX_ALLOCATE(PxU32, nb_edges, "tmp"); // Sort according to mRef0, then mRef1 PxU32 i; for(i=0;i<nb_edges;i++) VRefs[i] = edges[i].Ref0; Core.Sort(VRefs, nb_edges); for(i=0;i<nb_edges;i++) VRefs[i] = edges[i].Ref1; Core.Sort(VRefs, nb_edges); PX_FREE(VRefs); } const PxU32* Sorted = Core.GetRanks(); // Read the list in sorted order, look for similar edges PxU32 LastRef0 = edges[Sorted[0]].Ref0; PxU32 LastRef1 = edges[Sorted[0]].Ref1; PxU32 Count = 0; PxU32 TmpBuffer[3]; while(nb_edges--) { PxU32 SortedIndex = *Sorted++; PxU32 Face = edges[SortedIndex].mFaceNb; // Owner face PxU32 Ref0 = edges[SortedIndex].Ref0; // Vertex ref #1 PxU32 Ref1 = edges[SortedIndex].Ref1; // Vertex ref #2 if(Ref0==LastRef0 && Ref1==LastRef1) { // Current edge is the same as last one TmpBuffer[Count++] = Face; // Store face number // Only works with manifold meshes (i.e. an edge is not shared by more than 2 triangles) if(Count==3) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::CreateDatabase: can't work on non-manifold meshes."); } else { // Here we have a new edge (LastRef0, LastRef1) shared by Count triangles stored in TmpBuffer if(Count==2) { // if Count==1 => edge is a boundary edge: it belongs to a single triangle. // Hence there's no need to update a link to an adjacent triangle. #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces)) return false; #else if(!UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces, create)) return false; #endif } // Reset for next edge Count = 0; TmpBuffer[Count++] = Face; LastRef0 = Ref0; LastRef1 = Ref1; } } bool Status = true; #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(Count==2) Status = UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces); #else if(Count==2) Status = UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces, create); #endif return Status; } AdjacenciesBuilder::AdjacenciesBuilder() { } AdjacenciesBuilder::~AdjacenciesBuilder() { } /** * Initializes the component. * \param create [in] the creation structure * \return true if success. */ bool AdjacenciesBuilder::Init(const ADJACENCIESCREATE& create) { if(!create.NbFaces) return false; // Get some bytes mNbFaces = create.NbFaces; mFaces = PX_NEW(AdjTriangle)[mNbFaces]; AdjEdge* Edges = PX_NEW(AdjEdge)[mNbFaces*3]; PxU32 NbEdges=0; // Feed me with triangles..... for(PxU32 i=0;i<mNbFaces;i++) { // Get correct vertex references const PxU32 Ref0 = create.DFaces ? create.DFaces[i*3+0] : create.WFaces ? create.WFaces[i*3+0] : 0; const PxU32 Ref1 = create.DFaces ? create.DFaces[i*3+1] : create.WFaces ? create.WFaces[i*3+1] : 1; const PxU32 Ref2 = create.DFaces ? create.DFaces[i*3+2] : create.WFaces ? create.WFaces[i*3+2] : 2; // Add a triangle to the database AddTriangle(Ref0, Ref1, Ref2, i, mFaces, NbEdges, Edges); } // At this point of the process we have mFaces & Edges filled with input data. That is: // - a list of triangles with 3 NULL links (i.e. PX_INVALID_U32) // - a list of mNbFaces*3 edges, each edge having 2 vertex references and an owner face. // Here NbEdges should be equal to mNbFaces*3. PX_ASSERT(NbEdges==mNbFaces*3); #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Status = CreateDatabase(mFaces, NbEdges, Edges); #else bool Status = CreateDatabase(mFaces, NbEdges, Edges, create); #endif // We don't need the edges anymore PX_DELETE_ARRAY(Edges); #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS // Now create convex information. This creates coupling between adjacencies & edge-list but in this case it's actually the goal: // mixing the two structures to save memory. if(Status && create.Verts) { EDGELISTCREATE ELC; ELC.NbFaces = create.NbFaces; ELC.DFaces = create.DFaces; // That's where I like having a unified way to do things... We ELC.WFaces = create.WFaces; // can just directly copy the same pointers. ELC.FacesToEdges = true; ELC.Verts = create.Verts; ELC.Epsilon = create.Epsilon; EdgeList EL; if(EL.init(ELC)) { for(PxU32 i=0;i<mNbFaces;i++) { const EdgeTriangleData& ET = EL.getEdgeTriangle(i); if(EdgeTriangleAC::HasActiveEdge01(ET)) mFaces[i].mATri[EDGE01] |= 0x20000000; else mFaces[i].mATri[EDGE01] &= ~0x20000000; if(EdgeTriangleAC::HasActiveEdge20(ET)) mFaces[i].mATri[EDGE02] |= 0x20000000; else mFaces[i].mATri[EDGE02] &= ~0x20000000; if(EdgeTriangleAC::HasActiveEdge12(ET)) mFaces[i].mATri[EDGE12] |= 0x20000000; else mFaces[i].mATri[EDGE12] &= ~0x20000000; PX_ASSERT((EdgeTriangleAC::HasActiveEdge01(ET) && mFaces[i].HasActiveEdge01()) || (!EdgeTriangleAC::HasActiveEdge01(ET) && !mFaces[i].HasActiveEdge01())); PX_ASSERT((EdgeTriangleAC::HasActiveEdge20(ET) && mFaces[i].HasActiveEdge20()) || (!EdgeTriangleAC::HasActiveEdge20(ET) && !mFaces[i].HasActiveEdge20())); PX_ASSERT((EdgeTriangleAC::HasActiveEdge12(ET) && mFaces[i].HasActiveEdge12()) || (!EdgeTriangleAC::HasActiveEdge12(ET) && !mFaces[i].HasActiveEdge12())); } } } #endif return Status; } /* bool AdjacenciesBuilder::Save(Stream& stream) const { bool PlatformMismatch = PxPlatformMismatch(); // Export header if(!WriteHeader('A', 'D', 'J', 'A', gVersion, PlatformMismatch, stream)) return false; // Export adjacencies // stream.StoreDword(mNbFaces); WriteDword(mNbFaces, PlatformMismatch, stream); // stream.StoreBuffer(mFaces, sizeof(AdjTriangle)*mNbFaces); WriteDwordBuffer((const PxU32*)mFaces, mNbFaces*3, PlatformMismatch, stream); return true; }*/ //#endif
22,841
C++
33.452489
158
0.690381
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuMeshAnalysis.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxVec3.h" #include "foundation/PxArray.h" #include "GuMeshAnalysis.h" using namespace physx; using namespace Gu; PX_FORCE_INLINE PxU64 key(PxI32 a, PxI32 b) { if (a < b) return ((PxU64(a)) << 32) | (PxU64(b)); else return ((PxU64(b)) << 32) | (PxU64(a)); } #define INITIAL_VALUE -3 const static PxU32 neighborEdges[3][2] = { { 0, 1 }, { 2, 0 }, { 1, 2 } }; //const static PxU32 triTip[3] = { 2, 1, 0 }; bool MeshAnalyzer::buildTriangleAdjacency(const Triangle* tris, PxU32 numTriangles, PxArray<PxI32>& result, PxHashMap<PxU64, PxI32>& edges) { PxU32 l = 4 * numTriangles; //Still factor 4 - waste one entry per triangle to get a power of 2 which allows for bit shift usage instead of modulo result.clear(); result.resize(l, -1); for (PxU32 i = 3; i < l; i += 4) result[i] = INITIAL_VALUE; //Mark the fields that get never accessed because they are just not used, this is useful for debugging edges.clear(); for (PxU32 i = 0; i < numTriangles; ++i) { const Triangle& tri = tris[i]; if (tri[0] < 0) continue; for (PxU32 j = 0; j < 3; ++j) { PxU64 edge = key(tri[neighborEdges[j][0]], tri[neighborEdges[j][1]]); if (const PxPair<const PxU64, PxI32>* ptr = edges.find(edge)) { if (ptr->second < 0) return false; //Edge shared by more than 2 triangles if (result[4 * i + j] == -4 || result[ptr->second] == -4) { result[4 * i + j] = -4; //Mark as non-manifold edge result[ptr->second] = -4; } else { if (result[4 * i + j] != -1 || result[ptr->second] != -1) { result[4 * i + j] = -4; //Mark as non-manifold edge result[ptr->second] = -4; } result[4 * i + j] = ptr->second; result[ptr->second] = 4 * i + j; } edges.erase(ptr->first); edges.insert(edge, -1); //Mark as processed } else edges.insert(edge, 4 * i + j); } } return true; } PxI32 indexOf(const Triangle& tri, PxI32 node) { if (tri[0] == node) return 0; if (tri[1] == node) return 1; if (tri[2] == node) return 2; return 0xFFFFFFFF; } bool MeshAnalyzer::checkConsistentTriangleOrientation(const Triangle* tris, PxU32 numTriangles) { PxArray<bool> flip; PxHashMap<PxU64, PxI32> edges; PxArray<PxArray<PxU32>> connectedTriangleGroups; if (!buildConsistentTriangleOrientationMap(tris, numTriangles, flip, edges, connectedTriangleGroups)) return false; for (PxU32 i = 0; i < flip.size(); ++i) { if (flip[i]) return false; } return true; } bool MeshAnalyzer::buildConsistentTriangleOrientationMap(const Triangle* tris, PxU32 numTriangles, PxArray<bool>& flip, PxHashMap<PxU64, PxI32>& edges, PxArray<PxArray<PxU32>>& connectedTriangleGroups) { PxArray<PxI32> adj; if (!buildTriangleAdjacency(tris, numTriangles, adj, edges)) return false; PxU32 l = numTriangles; PxArray<bool> done; done.resize(l, false); flip.clear(); flip.resize(l, false); PxU32 seedIndex = 0; PxArray<PxI32> stack; while (true) { if (stack.size() == 0) { while (seedIndex < done.size() && done[seedIndex]) ++seedIndex; if (seedIndex == done.size()) break; done[seedIndex] = true; flip[seedIndex] = false; stack.pushBack(seedIndex); PxArray<PxU32> currentGroup; currentGroup.pushBack(seedIndex); connectedTriangleGroups.pushBack(currentGroup); } PxI32 index = stack.popBack(); bool f = flip[index]; const Triangle& tri = tris[index]; for (PxU32 i = 0; i < 3; ++i) { if (adj[4 * index + i] >= 0 && !done[adj[4 * index + i] >> 2]) { PxI32 neighborTriIndex = adj[4 * index + i] >> 2; done[neighborTriIndex] = true; connectedTriangleGroups[connectedTriangleGroups.size() - 1].pushBack(neighborTriIndex); const Triangle& neighborTri = tris[neighborTriIndex]; PxI32 j = indexOf(neighborTri, tri[neighborEdges[i][0]]); flip[neighborTriIndex] = (neighborTri[(j + 1) % 3] == tri[neighborEdges[i][1]]) != f; stack.pushBack(neighborTriIndex); } } } return true; } bool MeshAnalyzer::makeTriOrientationConsistent(Triangle* tris, PxU32 numTriangles, bool invertOrientation) { PxHashMap<PxU64, PxI32> edges; PxArray<bool> flipTriangle; PxArray<PxArray<PxU32>> connectedTriangleGroups; if (!buildConsistentTriangleOrientationMap(tris, numTriangles, flipTriangle, edges, connectedTriangleGroups)) return false; for (PxU32 i = 0; i < flipTriangle.size(); ++i) { Triangle& t = tris[i]; if (flipTriangle[i] != invertOrientation) PxSwap(t[0], t[1]); } return true; } bool MeshAnalyzer::checkMeshWatertightness(const Triangle* tris, PxU32 numTriangles, bool treatInconsistentWindingAsNonWatertight) { PxArray<bool> flip; PxHashMap<PxU64, PxI32> edges; PxArray<PxArray<PxU32>> connectedTriangleGroups; if (!MeshAnalyzer::buildConsistentTriangleOrientationMap(tris, numTriangles, flip, edges, connectedTriangleGroups)) return false; if (treatInconsistentWindingAsNonWatertight) { for (PxU32 i = 0; i < flip.size(); ++i) { if (flip[i]) return false; } } for (PxHashMap<PxU64, PxI32>::Iterator iter = edges.getIterator(); !iter.done(); ++iter) { if (iter->second >= 0) return false; } return true; }
6,854
C++
29.878378
147
0.687919
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuVertexReducer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VERTEX_REDUCER_H #define GU_VERTEX_REDUCER_H #include "foundation/PxVec3.h" #include "common/PxPhysXCommonConfig.h" namespace physx { namespace Gu { //! Vertex cloud reduction result structure struct REDUCEDCLOUD { // Out PxVec3* RVerts; //!< Reduced list PxU32 NbRVerts; //!< Reduced number of vertices PxU32* CrossRef; //!< nb_verts remapped indices }; class ReducedVertexCloud { public: ReducedVertexCloud(const PxVec3* verts, PxU32 nb_verts); ~ReducedVertexCloud(); ReducedVertexCloud& clean(); bool reduce(REDUCEDCLOUD* rc=NULL); PX_FORCE_INLINE PxU32 getNbVerts() const { return mNbVerts; } PX_FORCE_INLINE PxU32 getNbReducedVerts() const { return mNbRVerts; } PX_FORCE_INLINE const PxVec3* getReducedVerts() const { return mRVerts; } PX_FORCE_INLINE const PxVec3& getReducedVertex(PxU32 i) const { return mRVerts[i]; } PX_FORCE_INLINE const PxU32* getCrossRefTable() const { return mXRef; } private: // Original vertex cloud PxU32 mNbVerts; //!< Number of vertices const PxVec3* mVerts; //!< List of vertices (pointer copy) // Reduced vertex cloud PxU32 mNbRVerts; //!< Reduced number of vertices PxVec3* mRVerts; //!< Reduced list of vertices PxU32* mXRef; //!< Cross-reference table (used to remap topologies) }; } } #endif
3,091
C
38.641025
87
0.725008
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuAdjacencies.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_ADJACENCIES_H #define GU_ADJACENCIES_H #define MSH_ADJACENCIES_INCLUDE_CONVEX_BITS #include "foundation/Px.h" #include "GuTriangle.h" #include "common/PxPhysXCommonConfig.h" namespace physx { namespace Gu { #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS #define ADJ_TRIREF_MASK 0x1fffffff //!< Masks 3 bits #define IS_CONVEX_EDGE(x) (x & 0x20000000) //!< Returns true for convex edges #else #define ADJ_TRIREF_MASK 0x3fffffff //!< Masks 2 bits #endif #define MAKE_ADJ_TRI(x) (x & ADJ_TRIREF_MASK) //!< Transforms a link into a triangle reference. #define GET_EDGE_NB(x) (x>>30) //!< Transforms a link into a counterpart edge ID. // #define IS_BOUNDARY(x) (x==PX_INVALID_U32) //!< Returns true for boundary edges. #define IS_BOUNDARY(x) ((x & ADJ_TRIREF_MASK)==ADJ_TRIREF_MASK) //!< Returns true for boundary edges. // Forward declarations class Adjacencies; enum SharedEdgeIndex { EDGE01 = 0, EDGE02 = 1, EDGE12 = 2 }; /* PX_INLINE void GetEdgeIndices(SharedEdgeIndex edge_index, PxU32& id0, PxU32& id1) { if(edge_index==0) { id0 = 0; id1 = 1; } else if(edge_index==1) { id0 = 0; id1 = 2; } else if(edge_index==2) { id0 = 1; id1 = 2; } }*/ //! Sets a new edge code #define SET_EDGE_NB(link, code) \ link&=ADJ_TRIREF_MASK; \ link|=code<<30; \ //! A triangle class used to compute the adjacency structures. class AdjTriangle #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY : public IndexedTriangle #else : public PxUserAllocated #endif { public: //! Constructor PX_INLINE AdjTriangle() {} //! Destructor PX_INLINE ~AdjTriangle() {} /** * Computes the number of boundary edges in a triangle. * \return the number of boundary edges. (0 => 3) */ PxU32 ComputeNbBoundaryEdges() const; /** * Computes the number of valid neighbors. * \return the number of neighbors. (0 => 3) */ PxU32 ComputeNbNeighbors() const; /** * Checks whether the triangle has a particular neighbor or not. * \param tref [in] the triangle reference to look for * \param index [out] the corresponding index in the triangle (NULL if not needed) * \return true if the triangle has the given neighbor */ bool HasNeighbor(PxU32 tref, PxU32* index=NULL) const; /** * Flips the winding. */ void Flip(); // Data access PX_INLINE PxU32 GetLink(SharedEdgeIndex edge_index) const { return mATri[edge_index]; } PX_INLINE PxU32 GetAdjTri(SharedEdgeIndex edge_index) const { return MAKE_ADJ_TRI(mATri[edge_index]); } PX_INLINE PxU32 GetAdjEdge(SharedEdgeIndex edge_index) const { return GET_EDGE_NB(mATri[edge_index]); } PX_INLINE PxIntBool IsBoundaryEdge(SharedEdgeIndex edge_index) const { return IS_BOUNDARY(mATri[edge_index]); } #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS PX_INLINE PxIntBool HasActiveEdge01() const { return PxIntBool(IS_CONVEX_EDGE(mATri[EDGE01])); } PX_INLINE PxIntBool HasActiveEdge20() const { return PxIntBool(IS_CONVEX_EDGE(mATri[EDGE02])); } PX_INLINE PxIntBool HasActiveEdge12() const { return PxIntBool(IS_CONVEX_EDGE(mATri[EDGE12])); } PX_INLINE PxIntBool HasActiveEdge(PxU32 i) const { return PxIntBool(IS_CONVEX_EDGE(mATri[i])); } #endif // private: //! Links/References of adjacent triangles. The 2 most significant bits contains the counterpart edge in the adjacent triangle. //! mATri[0] refers to edge 0-1 //! mATri[1] refers to edge 0-2 //! mATri[2] refers to edge 1-2 PxU32 mATri[3]; }; //! The adjacencies creation structure. struct ADJACENCIESCREATE { //! Constructor ADJACENCIESCREATE() : NbFaces(0), DFaces(NULL), WFaces(NULL) { #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS Verts = NULL; Epsilon = 0.1f; // Epsilon = 0.001f; #endif } PxU32 NbFaces; //!< Number of faces in source topo const PxU32* DFaces; //!< List of faces (dwords) or NULL const PxU16* WFaces; //!< List of faces (words) or NULL #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS const PxVec3* Verts; float Epsilon; #endif }; class Adjacencies : public PxUserAllocated { public: Adjacencies(); ~Adjacencies(); PxU32 mNbFaces; //!< Number of faces involved in the computation. AdjTriangle* mFaces; //!< A list of AdjTriangles (one/face) bool Load(PxInputStream& stream); // Basic mesh walking PX_INLINE const AdjTriangle* GetAdjacentFace(const AdjTriangle& current_tri, SharedEdgeIndex edge_nb) const { // No checkings here, make sure mFaces has been created // Catch the link PxU32 Link = current_tri.GetLink(edge_nb); // Returns NULL for boundary edges if(IS_BOUNDARY(Link)) return NULL; // Else transform into face index PxU32 Id = MAKE_ADJ_TRI(Link); // Possible counterpart edge is: // PxU32 Edge = GET_EDGE_NB(Link); // And returns adjacent triangle return &mFaces[Id]; } // Helpers PxU32 ComputeNbBoundaryEdges() const; #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool GetBoundaryVertices(PxU32 nb_verts, bool* bound_status) const; #else bool GetBoundaryVertices(PxU32 nb_verts, bool* bound_status, const IndexedTriangle32* faces) const; #endif // #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool MakeLastRef(AdjTriangle& cur_tri, PxU32 vref); #else bool MakeLastRef(AdjTriangle& cur_tri, PxU32 vref, IndexedTriangle32* cur_topo); #endif private: // New edge codes assignment void AssignNewEdgeCode(PxU32 link, PxU8 edge_nb); }; //#ifdef PX_COOKING class AdjacenciesBuilder : public Adjacencies { public: AdjacenciesBuilder(); ~AdjacenciesBuilder(); bool Init(const ADJACENCIESCREATE& create); // bool Save(Stream& stream) const; }; //#endif } } #endif
7,670
C
32.352174
129
0.683051
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuEdgeCache.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_EDGECACHE_H #define GU_EDGECACHE_H #include "foundation/PxMemory.h" #include "foundation/PxAllocator.h" #include "foundation/PxHash.h" namespace physx { namespace Gu { class EdgeCache { #define NUM_EDGES_IN_CACHE 64 //must be power of 2. 32 lines result in 10% extra work (due to cache misses), 64 lines in 6% extra work, 128 lines in 4%. public: EdgeCache() { PxMemZero(cacheLines, NUM_EDGES_IN_CACHE*sizeof(CacheLine)); } PxU32 hash(PxU32 key) const { return (NUM_EDGES_IN_CACHE - 1) & PxComputeHash(key); //Only a 16 bit hash would be needed here. } bool isInCache(PxU8 vertex0, PxU8 vertex1) { PX_ASSERT(vertex1 >= vertex0); PxU16 key = PxU16((vertex0 << 8) | vertex1); PxU32 h = hash(key); CacheLine& cl = cacheLines[h]; if (cl.fullKey == key) { return true; } else //cache the line now as it's about to be processed { cl.fullKey = key; return false; } } private: struct CacheLine { PxU16 fullKey; }; CacheLine cacheLines[NUM_EDGES_IN_CACHE]; #undef NUM_EDGES_IN_CACHE }; } } #endif
2,789
C
31.823529
153
0.724632
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuBarycentricCoordinates.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BARYCENTRIC_COORDINATES_H #define GU_BARYCENTRIC_COORDINATES_H #include "common/PxPhysXCommonConfig.h" #include "foundation/PxVecMath.h" namespace physx { namespace Gu { //calculate the barycentric coorinates for a point in a segment void barycentricCoordinates(const aos::Vec3VArg p, const aos::Vec3VArg a, const aos::Vec3VArg b, aos::FloatV& v); //calculate the barycentric coorinates for a point in a triangle void barycentricCoordinates(const aos::Vec3VArg p, const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c, aos::FloatV& v, aos::FloatV& w); void barycentricCoordinates(const aos::Vec3VArg v0, const aos::Vec3VArg v1, const aos::Vec3VArg v2, aos::FloatV& v, aos::FloatV& w); PX_INLINE aos::BoolV isValidTriangleBarycentricCoord(const aos::FloatVArg v, const aos::FloatVArg w) { using namespace aos; const FloatV zero = FNeg(FEps()); const FloatV one = FAdd(FOne(), FEps()); const BoolV con0 = BAnd(FIsGrtrOrEq(v, zero), FIsGrtrOrEq(one, v)); const BoolV con1 = BAnd(FIsGrtrOrEq(w, zero), FIsGrtrOrEq(one, w)); const BoolV con2 = FIsGrtr(one, FAdd(v, w)); return BAnd(con0, BAnd(con1, con2)); } PX_INLINE aos::BoolV isValidTriangleBarycentricCoord2(const aos::Vec4VArg vwvw) { using namespace aos; const Vec4V eps = V4Splat(FEps()); const Vec4V zero =V4Neg(eps); const Vec4V one = V4Add(V4One(), eps); const Vec4V v0v1v0v1 = V4PermXZXZ(vwvw); const Vec4V w0w1w0w1 = V4PermYWYW(vwvw); const BoolV con0 = BAnd(V4IsGrtrOrEq(v0v1v0v1, zero), V4IsGrtrOrEq(one, v0v1v0v1)); const BoolV con1 = BAnd(V4IsGrtrOrEq(w0w1w0w1, zero), V4IsGrtrOrEq(one, w0w1w0w1)); const BoolV con2 = V4IsGrtr(one, V4Add(v0v1v0v1, w0w1w0w1)); return BAnd(con0, BAnd(con1, con2)); } } // namespace Gu } #endif
3,505
C
37.108695
101
0.740656
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuMeshAnalysis.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_MESH_ANALYSIS_H #define GU_MESH_ANALYSIS_H #include "foundation/Px.h" #include "common/PxPhysXCommonConfig.h" #include "GuTriangle.h" #include "foundation/PxHashMap.h" #include "foundation/PxSort.h" namespace physx { namespace Gu { using Triangle = Gu::IndexedTriangleT<PxI32>; class MeshAnalyzer { struct Range { PxI32 start; PxI32 end; //Exclusive Range(PxI32 start_, PxI32 end_) { start = start_; end = end_; } PxI32 Length() const { return end - start; } }; template<typename T, typename S> static void splitRanges(PxArray<Range>& mergeRanges, const PxArray<PxI32>& indexer, const T* points, PxI32 dimIndex, S tol) { PxArray<Range> newMergeRanges; for (PxU32 i = 0; i < mergeRanges.size(); ++i) { const Range& r = mergeRanges[i]; PxI32 start = r.start; for (PxI32 j = r.start + 1; j < r.end; ++j) { //PxF64 delta = PxAbs(points[start][dimIndex] - points[j - 1][dimIndex]); S delta = PxAbs(points[indexer[j]][dimIndex] - points[indexer[j - 1]][dimIndex]); if (delta > tol) { if (j - start > 1) newMergeRanges.pushBack(Range(start, j)); start = j; } } if (r.end - start > 1) newMergeRanges.pushBack(Range(start, r.end)); } mergeRanges.clear(); for (PxU32 i = 0; i < newMergeRanges.size(); ++i) mergeRanges.pushBack(newMergeRanges[i]); } template<typename T> struct Comparer { const T* points; PxU32 dimension; Comparer(const T* points_, const PxU32 dimension_) : points(points_), dimension(dimension_) {} bool operator()(const PxI32& a, const PxI32& b) const { return points[a][dimension] > points[b][dimension]; } private: PX_NOCOPY(Comparer) }; public: template<typename T, typename S> static void mapDuplicatePoints(const T* points, const PxU32 nbPoints, PxArray<PxI32>& result, S duplicateDistanceManhattanMetric = static_cast<S>(1e-6)) { result.reserve(nbPoints); result.forceSize_Unsafe(nbPoints); PxArray<PxI32> indexer; indexer.reserve(nbPoints); indexer.forceSize_Unsafe(nbPoints); for (PxU32 i = 0; i < nbPoints; ++i) { indexer[i] = i; result[i] = i; } Comparer<T> comparer(points, 0); PxSort(indexer.begin(), indexer.size(), comparer); PxArray<Range> mergeRanges; mergeRanges.pushBack(Range(0, nbPoints)); splitRanges<T>(mergeRanges, indexer, points, 0, duplicateDistanceManhattanMetric); comparer.dimension = 1; for (PxU32 i = 0; i < mergeRanges.size(); ++i) { const Range& r = mergeRanges[i]; PxSort(indexer.begin() + r.start, r.Length(), comparer); } splitRanges<T>(mergeRanges, indexer, points, 1, duplicateDistanceManhattanMetric); comparer.dimension = 2; for (PxU32 i = 0; i < mergeRanges.size(); ++i) { const Range& r = mergeRanges[i]; PxSort(indexer.begin() + r.start, r.Length(), comparer); } splitRanges<T>(mergeRanges, indexer, points, 2, duplicateDistanceManhattanMetric); //Merge the ranges for (PxU32 i = 0; i < mergeRanges.size(); ++i) { const Range& r = mergeRanges[i]; PxSort(indexer.begin() + r.start, r.Length()); for (PxI32 j = r.start + 1; j < r.end; ++j) result[indexer[j]] = result[indexer[r.start]]; } } PX_PHYSX_COMMON_API static bool buildTriangleAdjacency(const Triangle* tris, PxU32 numTriangles, PxArray<PxI32>& result, PxHashMap<PxU64, PxI32>& edges); PX_PHYSX_COMMON_API static bool checkConsistentTriangleOrientation(const Triangle* tris, PxU32 numTriangles); PX_PHYSX_COMMON_API static bool buildConsistentTriangleOrientationMap(const Triangle* tris, PxU32 numTriangles, PxArray<bool>& flipMap, PxHashMap<PxU64, PxI32>& edges, PxArray<PxArray<PxU32>>& connectedTriangleGroups); PX_PHYSX_COMMON_API static bool makeTriOrientationConsistent(Triangle* tris, PxU32 numTriangles, bool invertOrientation = false); PX_PHYSX_COMMON_API static bool checkMeshWatertightness(const Triangle* tris, PxU32 numTriangles, bool treatInconsistentWindingAsNonWatertight = true); }; } } #endif
5,777
C
33.392857
155
0.700883
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuEdgeList.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxMemory.h" #include "geometry/PxTriangle.h" #include "GuEdgeList.h" #include "foundation/PxMathUtils.h" #include "foundation/PxPlane.h" #include "CmRadixSort.h" #include "CmSerialize.h" // PT: code archeology: this initially came from ICE (IceEdgeList.h/cpp). Consider putting it back the way it was initially. // It makes little sense that something like EdgeList is in GeomUtils but some equivalent class like Adjacencies in is Cooking. using namespace physx; using namespace Gu; using namespace Cm; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// EdgeList::EdgeList() : mNbEdges (0), mEdges (NULL), mNbFaces (0), mEdgeFaces (NULL), mEdgeToTriangles (NULL), mFacesByEdges (NULL) { } EdgeList::~EdgeList() { PX_FREE(mFacesByEdges); PX_FREE(mEdgeToTriangles); PX_FREE(mEdges); PX_FREE(mEdgeFaces); } bool EdgeList::load(PxInputStream& stream) { // Import header PxU32 Version; bool Mismatch; if(!ReadHeader('E', 'D', 'G', 'E', Version, Mismatch, stream)) return false; // Import edges mNbEdges = readDword(Mismatch, stream); mEdges = PX_ALLOCATE(EdgeData, mNbEdges, "EdgeData"); stream.read(mEdges, sizeof(EdgeData)*mNbEdges); mNbFaces = readDword(Mismatch, stream); mEdgeFaces = PX_ALLOCATE(EdgeTriangleData, mNbFaces, "EdgeTriangleData"); stream.read(mEdgeFaces, sizeof(EdgeTriangleData)*mNbFaces); mEdgeToTriangles = PX_ALLOCATE(EdgeDescData, mNbEdges, "EdgeDescData"); stream.read(mEdgeToTriangles, sizeof(EdgeDescData)*mNbEdges); PxU32 LastOffset = mEdgeToTriangles[mNbEdges-1].Offset + mEdgeToTriangles[mNbEdges-1].Count; mFacesByEdges = PX_ALLOCATE(PxU32, LastOffset, "EdgeList FacesByEdges"); stream.read(mFacesByEdges, sizeof(PxU32)*LastOffset); return true; } /** * Initializes the edge-list. * \param create [in] edge-list creation structure * \return true if success. */ bool EdgeList::init(const EDGELISTCREATE& create) { const bool FacesToEdges = create.Verts ? true : create.FacesToEdges; const bool EdgesToFaces = create.Verts ? true : create.EdgesToFaces; // "FacesToEdges" maps each face to three edges. if(FacesToEdges && !createFacesToEdges(create.NbFaces, create.DFaces, create.WFaces)) return false; // "EdgesToFaces" maps each edge to the set of faces sharing this edge if(EdgesToFaces && !createEdgesToFaces(create.NbFaces, create.DFaces, create.WFaces)) return false; // Create active edges if(create.Verts && !computeActiveEdges(create.NbFaces, create.DFaces, create.WFaces, create.Verts, create.Epsilon)) return false; // Get rid of useless data if(!create.FacesToEdges) PX_FREE(mEdgeFaces); if(!create.EdgesToFaces) { PX_FREE(mEdgeToTriangles); PX_FREE(mFacesByEdges); } return true; } /** * Computes FacesToEdges. * After the call: * - mNbEdges is updated with the number of non-redundant edges * - mEdges is a list of mNbEdges edges (one edge is 2 vertex-references) * - mEdgesRef is a list of nbfaces structures with 3 indexes in mEdges for each face * * \param nb_faces [in] a number of triangles * \param dfaces [in] list of triangles with PxU32 vertex references (or NULL) * \param wfaces [in] list of triangles with PxU16 vertex references (or NULL) * \return true if success. */ bool EdgeList::createFacesToEdges(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces) { if(!nb_faces || (!dfaces && !wfaces)) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "EdgeList::CreateFacesToEdges: NULL parameter!"); if(mEdgeFaces) return true; // Already computed! // 1) Get some bytes: I need one EdgesRefs for each face, and some temp buffers mEdgeFaces = PX_ALLOCATE(EdgeTriangleData, nb_faces, "mEdgeFaces"); // Link faces to edges PxU32* VRefs0 = PX_ALLOCATE(PxU32, nb_faces*3, "Tmp"); // Temp storage PxU32* VRefs1 = PX_ALLOCATE(PxU32, nb_faces*3, "Tmp"); // Temp storage EdgeData* Buffer = PX_ALLOCATE(EdgeData, nb_faces*3, "Tmp"); // Temp storage // 2) Create a full redundant list of 3 edges / face. for(PxU32 i=0;i<nb_faces;i++) { // Get right vertex-references const PxU32 Ref0 = dfaces ? dfaces[i*3+0] : wfaces ? wfaces[i*3+0] : 0; const PxU32 Ref1 = dfaces ? dfaces[i*3+1] : wfaces ? wfaces[i*3+1] : 1; const PxU32 Ref2 = dfaces ? dfaces[i*3+2] : wfaces ? wfaces[i*3+2] : 2; // Pre-Sort vertex-references and put them in the lists if(Ref0<Ref1) { VRefs0[i*3+0] = Ref0; VRefs1[i*3+0] = Ref1; } // Edge 0-1 maps (i%3) else { VRefs0[i*3+0] = Ref1; VRefs1[i*3+0] = Ref0; } // Edge 0-1 maps (i%3) if(Ref1<Ref2) { VRefs0[i*3+1] = Ref1; VRefs1[i*3+1] = Ref2; } // Edge 1-2 maps (i%3)+1 else { VRefs0[i*3+1] = Ref2; VRefs1[i*3+1] = Ref1; } // Edge 1-2 maps (i%3)+1 if(Ref2<Ref0) { VRefs0[i*3+2] = Ref2; VRefs1[i*3+2] = Ref0; } // Edge 2-0 maps (i%3)+2 else { VRefs0[i*3+2] = Ref0; VRefs1[i*3+2] = Ref2; } // Edge 2-0 maps (i%3)+2 } // 3) Sort the list according to both keys (VRefs0 and VRefs1) Cm::RadixSortBuffered Sorter; const PxU32* Sorted = Sorter.Sort(VRefs1, nb_faces*3).Sort(VRefs0, nb_faces*3).GetRanks(); // 4) Loop through all possible edges // - clean edges list by removing redundant edges // - create EdgesRef list mNbEdges = 0; // #non-redundant edges mNbFaces = nb_faces; PxU32 PreviousRef0 = PX_INVALID_U32; PxU32 PreviousRef1 = PX_INVALID_U32; for(PxU32 i=0;i<nb_faces*3;i++) { PxU32 Face = Sorted[i]; // Between 0 and nbfaces*3 PxU32 ID = Face % 3; // Get edge ID back. PxU32 SortedRef0 = VRefs0[Face]; // (SortedRef0, SortedRef1) is the sorted edge PxU32 SortedRef1 = VRefs1[Face]; if(SortedRef0!=PreviousRef0 || SortedRef1!=PreviousRef1) { // New edge found! => stored in temp buffer Buffer[mNbEdges].Ref0 = SortedRef0; Buffer[mNbEdges].Ref1 = SortedRef1; mNbEdges++; } PreviousRef0 = SortedRef0; PreviousRef1 = SortedRef1; // Create mEdgesRef on the fly mEdgeFaces[Face/3].mLink[ID] = mNbEdges-1; } // 5) Here, mNbEdges==#non redundant edges mEdges = PX_ALLOCATE(EdgeData, mNbEdges, "EdgeData"); // Create real edges-list. PxMemCopy(mEdges, Buffer, mNbEdges*sizeof(EdgeData)); // 6) Free ram and exit PX_FREE(Buffer); PX_FREE(VRefs1); PX_FREE(VRefs0); return true; } /** * Computes EdgesToFaces. * After the call: * - mEdgeToTriangles is created * - mFacesByEdges is created * * \param nb_faces [in] a number of triangles * \param dfaces [in] list of triangles with PxU32 vertex references (or NULL) * \param wfaces [in] list of triangles with PxU16 vertex references (or NULL) * \return true if success. */ bool EdgeList::createEdgesToFaces(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces) { // 1) I need FacesToEdges ! if(!createFacesToEdges(nb_faces, dfaces, wfaces)) return false; // 2) Get some bytes: one Pair structure / edge mEdgeToTriangles = PX_ALLOCATE(EdgeDescData, mNbEdges, "EdgeDescData"); PxMemZero(mEdgeToTriangles, sizeof(EdgeDescData)*mNbEdges); // 3) Create Counters, ie compute the #faces sharing each edge for(PxU32 i=0;i<nb_faces;i++) { mEdgeToTriangles[mEdgeFaces[i].mLink[0]].Count++; mEdgeToTriangles[mEdgeFaces[i].mLink[1]].Count++; mEdgeToTriangles[mEdgeFaces[i].mLink[2]].Count++; } // 3) Create Radix-like Offsets mEdgeToTriangles[0].Offset=0; for(PxU32 i=1;i<mNbEdges;i++) mEdgeToTriangles[i].Offset = mEdgeToTriangles[i-1].Offset + mEdgeToTriangles[i-1].Count; const PxU32 LastOffset = mEdgeToTriangles[mNbEdges-1].Offset + mEdgeToTriangles[mNbEdges-1].Count; // 4) Get some bytes for mFacesByEdges. LastOffset is the number of indices needed. mFacesByEdges = PX_ALLOCATE(PxU32, LastOffset, "EdgeList FacesByEdges"); // 5) Create mFacesByEdges for(PxU32 i=0;i<nb_faces;i++) { mFacesByEdges[mEdgeToTriangles[mEdgeFaces[i].mLink[0]].Offset++] = i; mFacesByEdges[mEdgeToTriangles[mEdgeFaces[i].mLink[1]].Offset++] = i; mFacesByEdges[mEdgeToTriangles[mEdgeFaces[i].mLink[2]].Offset++] = i; } // 6) Recompute offsets wasted by 5) mEdgeToTriangles[0].Offset=0; for(PxU32 i=1;i<mNbEdges;i++) mEdgeToTriangles[i].Offset = mEdgeToTriangles[i-1].Offset + mEdgeToTriangles[i-1].Count; return true; } static PX_INLINE PxU32 OppositeVertex(PxU32 r0, PxU32 r1, PxU32 r2, PxU32 vref0, PxU32 vref1) { if(vref0==r0) { if (vref1==r1) return r2; else if(vref1==r2) return r1; } else if(vref0==r1) { if (vref1==r0) return r2; else if(vref1==r2) return r0; } else if(vref0==r2) { if (vref1==r1) return r0; else if(vref1==r0) return r1; } return PX_INVALID_U32; } bool EdgeList::computeActiveEdges(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces, const PxVec3* verts, float epsilon) { if(!verts || (!dfaces && !wfaces)) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "EdgeList::ComputeActiveEdges: NULL parameter!"); PxU32 NbEdges = getNbEdges(); if(!NbEdges) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ActiveEdges::ComputeConvexEdges: no edges in edge list!"); const EdgeData* Edges = getEdges(); if(!Edges) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ActiveEdges::ComputeConvexEdges: no edge data in edge list!"); const EdgeDescData* ED = getEdgeToTriangles(); if(!ED) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ActiveEdges::ComputeConvexEdges: no edge-to-triangle in edge list!"); const PxU32* FBE = getFacesByEdges(); if(!FBE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ActiveEdges::ComputeConvexEdges: no faces-by-edges in edge list!"); // We first create active edges in a temporaray buffer. We have one bool / edge. bool* ActiveEdges = PX_ALLOCATE(bool, NbEdges, "bool"); // Loop through edges and look for convex ones bool* CurrentMark = ActiveEdges; while(NbEdges--) { // Get number of triangles sharing current edge const PxU32 Count = ED->Count; // Boundary edges are active => keep them (actually they're silhouette edges directly) // Internal edges can be active => test them // Singular edges ? => discard them bool Active = false; if(Count==1) { Active = true; } else if(Count==2) { const PxU32 FaceIndex0 = FBE[ED->Offset+0]*3; const PxU32 FaceIndex1 = FBE[ED->Offset+1]*3; PxU32 VRef00, VRef01, VRef02; PxU32 VRef10, VRef11, VRef12; if(dfaces) { VRef00 = dfaces[FaceIndex0+0]; VRef01 = dfaces[FaceIndex0+1]; VRef02 = dfaces[FaceIndex0+2]; VRef10 = dfaces[FaceIndex1+0]; VRef11 = dfaces[FaceIndex1+1]; VRef12 = dfaces[FaceIndex1+2]; } else //if(wfaces) { PX_ASSERT(wfaces); VRef00 = wfaces[FaceIndex0+0]; VRef01 = wfaces[FaceIndex0+1]; VRef02 = wfaces[FaceIndex0+2]; VRef10 = wfaces[FaceIndex1+0]; VRef11 = wfaces[FaceIndex1+1]; VRef12 = wfaces[FaceIndex1+2]; } { // We first check the opposite vertex against the plane const PxU32 Op = OppositeVertex(VRef00, VRef01, VRef02, Edges->Ref0, Edges->Ref1); const PxPlane PL1(verts[VRef10], verts[VRef11], verts[VRef12]); if(PL1.distance(verts[Op])<0.0f) // If opposite vertex is below the plane, i.e. we discard concave edges { const PxTriangle T0(verts[VRef00], verts[VRef01], verts[VRef02]); const PxTriangle T1(verts[VRef10], verts[VRef11], verts[VRef12]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); const float a = PxComputeAngle(N0, N1); if(fabsf(a)>epsilon) Active = true; } else { const PxTriangle T0(verts[VRef00], verts[VRef01], verts[VRef02]); const PxTriangle T1(verts[VRef10], verts[VRef11], verts[VRef12]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); if(N0.dot(N1) < -0.999f) Active = true; } //Active = true; } } else { //Connected to more than 2 //We need to loop through the triangles and count the number of unique triangles (considering back-face triangles as non-unique). If we end up with more than 2 unique triangles, //then by definition this is an inactive edge. However, if we end up with 2 unique triangles (say like a double-sided tesselated surface), then it depends on the same rules as above const PxU32 FaceInd0 = FBE[ED->Offset]*3; PxU32 VRef00, VRef01, VRef02; PxU32 VRef10=0, VRef11=0, VRef12=0; if(dfaces) { VRef00 = dfaces[FaceInd0+0]; VRef01 = dfaces[FaceInd0+1]; VRef02 = dfaces[FaceInd0+2]; } else //if(wfaces) { PX_ASSERT(wfaces); VRef00 = wfaces[FaceInd0+0]; VRef01 = wfaces[FaceInd0+1]; VRef02 = wfaces[FaceInd0+2]; } PxU32 numUniqueTriangles = 1; bool doubleSided0 = false; bool doubleSided1 = 0; for(PxU32 a = 1; a < Count; ++a) { const PxU32 FaceInd = FBE[ED->Offset+a]*3; PxU32 VRef0, VRef1, VRef2; if(dfaces) { VRef0 = dfaces[FaceInd+0]; VRef1 = dfaces[FaceInd+1]; VRef2 = dfaces[FaceInd+2]; } else //if(wfaces) { PX_ASSERT(wfaces); VRef0 = wfaces[FaceInd+0]; VRef1 = wfaces[FaceInd+1]; VRef2 = wfaces[FaceInd+2]; } if(((VRef0 != VRef00) && (VRef0 != VRef01) && (VRef0 != VRef02)) || ((VRef1 != VRef00) && (VRef1 != VRef01) && (VRef1 != VRef02)) || ((VRef2 != VRef00) && (VRef2 != VRef01) && (VRef2 != VRef02))) { //Not the same as trig 0 if(numUniqueTriangles == 2) { if(((VRef0 != VRef10) && (VRef0 != VRef11) && (VRef0 != VRef12)) || ((VRef1 != VRef10) && (VRef1 != VRef11) && (VRef1 != VRef12)) || ((VRef2 != VRef10) && (VRef2 != VRef11) && (VRef2 != VRef12))) { //Too many unique triangles - terminate and mark as inactive numUniqueTriangles++; break; } else { const PxTriangle T0(verts[VRef10], verts[VRef11], verts[VRef12]); const PxTriangle T1(verts[VRef0], verts[VRef1], verts[VRef2]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); if(N0.dot(N1) < -0.999f) doubleSided1 = true; } } else { VRef10 = VRef0; VRef11 = VRef1; VRef12 = VRef2; numUniqueTriangles++; } } else { //Check for double sided... const PxTriangle T0(verts[VRef00], verts[VRef01], verts[VRef02]); const PxTriangle T1(verts[VRef0], verts[VRef1], verts[VRef2]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); if(N0.dot(N1) < -0.999f) doubleSided0 = true; } } if(numUniqueTriangles == 1) Active = true; if(numUniqueTriangles == 2) { //Potentially active. Let's check the angles between the surfaces... if(doubleSided0 || doubleSided1) { // Plane PL1 = faces[FBE[ED->Offset+1]].PlaneEquation(verts); const PxPlane PL1(verts[VRef10], verts[VRef11], verts[VRef12]); // if(PL1.Distance(verts[Op])<-epsilon) Active = true; //if(PL1.distance(verts[Op])<0.0f) // If opposite vertex is below the plane, i.e. we discard concave edges //KS - can't test signed distance for concave edges. This is a double-sided poly { const PxTriangle T0(verts[VRef00], verts[VRef01], verts[VRef02]); const PxTriangle T1(verts[VRef10], verts[VRef11], verts[VRef12]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); const float a = PxComputeAngle(N0, N1); if(fabsf(a)>epsilon) Active = true; } } else { //Not double sided...must have had a bunch of duplicate triangles!!!! //Treat as normal const PxU32 Op = OppositeVertex(VRef00, VRef01, VRef02, Edges->Ref0, Edges->Ref1); // Plane PL1 = faces[FBE[ED->Offset+1]].PlaneEquation(verts); const PxPlane PL1(verts[VRef10], verts[VRef11], verts[VRef12]); // if(PL1.Distance(verts[Op])<-epsilon) Active = true; if(PL1.distance(verts[Op])<0.0f) // If opposite vertex is below the plane, i.e. we discard concave edges { const PxTriangle T0(verts[VRef00], verts[VRef01], verts[VRef02]); const PxTriangle T1(verts[VRef10], verts[VRef11], verts[VRef12]); PxVec3 N0, N1; T0.normal(N0); T1.normal(N1); const float a = PxComputeAngle(N0, N1); if(fabsf(a)>epsilon) Active = true; } } } else { //Lots of triangles all smooshed together. Just activate the edge in this case Active = true; } } *CurrentMark++ = Active; ED++; Edges++; } // Now copy bits back into already existing edge structures // - first in edge triangles for(PxU32 i=0;i<mNbFaces;i++) { EdgeTriangleData& ET = mEdgeFaces[i]; for(PxU32 j=0;j<3;j++) { const PxU32 Link = ET.mLink[j]; if(!(Link & MSH_ACTIVE_EDGE_MASK)) // else already active { if(ActiveEdges[Link & MSH_EDGE_LINK_MASK]) ET.mLink[j] |= MSH_ACTIVE_EDGE_MASK; // Mark as active } } } // - then in edge-to-faces for(PxU32 i=0;i<mNbEdges;i++) { if(ActiveEdges[i]) mEdgeToTriangles[i].Flags |= PX_EDGE_ACTIVE; } // Free & exit PX_FREE(ActiveEdges); if(0) // PT: this is not needed anymore { //initially all vertices are flagged to ignore them. (we assume them to be flat) //for all NONFLAT edges, incl boundary //unflag 2 vertices in up to 2 trigs as perhaps interesting //for all CONCAVE edges //flag 2 vertices in up to 2 trigs to ignore them. // Handle active vertices PxU32 MaxIndex = 0; for(PxU32 i=0;i<nb_faces;i++) { PxU32 VRef0, VRef1, VRef2; if(dfaces) { VRef0 = dfaces[i*3+0]; VRef1 = dfaces[i*3+1]; VRef2 = dfaces[i*3+2]; } else //if(wfaces) { PX_ASSERT(wfaces); VRef0 = wfaces[i*3+0]; VRef1 = wfaces[i*3+1]; VRef2 = wfaces[i*3+2]; } if(VRef0>MaxIndex) MaxIndex = VRef0; if(VRef1>MaxIndex) MaxIndex = VRef1; if(VRef2>MaxIndex) MaxIndex = VRef2; } MaxIndex++; bool* ActiveVerts = PX_ALLOCATE(bool, MaxIndex, "bool"); PxMemZero(ActiveVerts, MaxIndex*sizeof(bool)); PX_ASSERT(dfaces || wfaces); for(PxU32 i=0;i<mNbFaces;i++) { PxU32 VRef[3]; if(dfaces) { VRef[0] = dfaces[i*3+0]; VRef[1] = dfaces[i*3+1]; VRef[2] = dfaces[i*3+2]; } else if(wfaces) { VRef[0] = wfaces[i*3+0]; VRef[1] = wfaces[i*3+1]; VRef[2] = wfaces[i*3+2]; } const EdgeTriangleData& ET = mEdgeFaces[i]; for(PxU32 j=0;j<3;j++) { PxU32 Link = ET.mLink[j]; if(Link & MSH_ACTIVE_EDGE_MASK) { // Active edge => mark edge vertices as active PxU32 r0, r1; if(j==0) { r0=0; r1=1; } else if(j==1) { r0=1; r1=2; } else /*if(j==2)*/ { PX_ASSERT(j==2); r0=0; r1=2; } ActiveVerts[VRef[r0]] = ActiveVerts[VRef[r1]] = true; } } } /* for(PxU32 i=0;i<mNbFaces;i++) { PxU32 VRef[3]; if(dfaces) { VRef[0] = dfaces[i*3+0]; VRef[1] = dfaces[i*3+1]; VRef[2] = dfaces[i*3+2]; } else if(wfaces) { VRef[0] = wfaces[i*3+0]; VRef[1] = wfaces[i*3+1]; VRef[2] = wfaces[i*3+2]; } const EdgeTriangle& ET = mEdgeFaces[i]; for(PxU32 j=0;j<3;j++) { PxU32 Link = ET.mLink[j]; if(!(Link & MSH_ACTIVE_EDGE_MASK)) { // Inactive edge => mark edge vertices as inactive PxU32 r0, r1; if(j==0) { r0=0; r1=1; } if(j==1) { r0=1; r1=2; } if(j==2) { r0=0; r1=2; } ActiveVerts[VRef[r0]] = ActiveVerts[VRef[r1]] = false; } } }*/ // Now stuff this into the structure for(PxU32 i=0;i<mNbFaces;i++) { PxU32 VRef[3]; if(dfaces) { VRef[0] = dfaces[i*3+0]; VRef[1] = dfaces[i*3+1]; VRef[2] = dfaces[i*3+2]; } else if(wfaces) { VRef[0] = wfaces[i*3+0]; VRef[1] = wfaces[i*3+1]; VRef[2] = wfaces[i*3+2]; } EdgeTriangleData& ET = mEdgeFaces[i]; for(PxU32 j=0;j<3;j++) { const PxU32 Link = ET.mLink[j]; if(!(Link & MSH_ACTIVE_VERTEX_MASK)) // else already active { if(ActiveVerts[VRef[j]]) ET.mLink[j] |= MSH_ACTIVE_VERTEX_MASK; // Mark as active } } } PX_FREE(ActiveVerts); } return true; }
21,776
C++
29.245833
184
0.65067
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuBoxConversion.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BOX_CONVERSION_H #define GU_BOX_CONVERSION_H #include "GuBox.h" #include "foundation/PxMathUtils.h" #include "foundation/PxMat34.h" #include "foundation/PxVecMath.h" namespace physx { // PT: builds rot from quat. WARNING: writes 4 bytes after 'dst.rot'. PX_FORCE_INLINE void buildFrom(Gu::Box& dst, const PxQuat& q) { using namespace aos; const QuatV qV = V4LoadU(&q.x); Vec3V column0, column1, column2; QuatGetMat33V(qV, column0, column1, column2); // PT: TODO: investigate if these overlapping stores are a problem V4StoreU(Vec4V_From_Vec3V(column0), &dst.rot.column0.x); V4StoreU(Vec4V_From_Vec3V(column1), &dst.rot.column1.x); V4StoreU(Vec4V_From_Vec3V(column2), &dst.rot.column2.x); } PX_FORCE_INLINE void buildFrom(Gu::Box& dst, const PxVec3& center, const PxVec3& extents, const PxQuat& q) { using namespace aos; // PT: writes 4 bytes after 'rot' but it's safe since we then write 'center' just afterwards buildFrom(dst, q); dst.center = center; dst.extents = extents; } PX_FORCE_INLINE void buildMatrixFromBox(PxMat34& mat34, const Gu::Box& box) { mat34.m = box.rot; mat34.p = box.center; } // SD: function is now the same as FastVertex2ShapeScaling::transformQueryBounds // PT: lots of LHS in that one. TODO: revisit... PX_INLINE Gu::Box transform(const PxMat34& transfo, const Gu::Box& box) { Gu::Box ret; PxMat33& obbBasis = ret.rot; obbBasis.column0 = transfo.rotate(box.rot.column0 * box.extents.x); obbBasis.column1 = transfo.rotate(box.rot.column1 * box.extents.y); obbBasis.column2 = transfo.rotate(box.rot.column2 * box.extents.z); ret.center = transfo.transform(box.center); ret.extents = PxOptimizeBoundingBox(obbBasis); return ret; } PX_INLINE Gu::Box transformBoxOrthonormal(const Gu::Box& box, const PxTransform& t) { Gu::Box ret; PxMat33& obbBasis = ret.rot; obbBasis.column0 = t.rotate(box.rot.column0); obbBasis.column1 = t.rotate(box.rot.column1); obbBasis.column2 = t.rotate(box.rot.column2); ret.center = t.transform(box.center); ret.extents = box.extents; return ret; } /** \brief recomputes the OBB after an arbitrary transform by a 4x4 matrix. \param mtx [in] the transform matrix \param obb [out] the transformed OBB */ PX_INLINE void rotate(const Gu::Box& src, const PxMat34& mtx, Gu::Box& obb) { // The extents remain constant obb.extents = src.extents; // The center gets x-formed obb.center = mtx.transform(src.center); // Combine rotations obb.rot = mtx.m * src.rot; } // PT: TODO: move this to a better place PX_FORCE_INLINE void getInverse(PxMat33& dstRot, PxVec3& dstTrans, const PxMat33& srcRot, const PxVec3& srcTrans) { const PxMat33 invRot = srcRot.getInverse(); dstTrans = invRot.transform(-srcTrans); dstRot = invRot; } } #endif
4,507
C
36.256198
114
0.731751
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuEdgeList.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_EDGE_LIST_H #define GU_EDGE_LIST_H #include "foundation/PxSimpleTypes.h" #include "common/PxPhysXCommonConfig.h" #include "foundation/Px.h" #include "foundation/PxUserAllocated.h" namespace physx { namespace Gu { enum EdgeType { PX_EDGE_UNDEFINED, PX_EDGE_BOUNDARY, //!< Edge belongs to a single triangle PX_EDGE_INTERNAL, //!< Edge belongs to exactly two triangles PX_EDGE_SINGULAR, //!< Edge belongs to three or more triangles PX_EDGE_FORCE_DWORD = 0x7fffffff }; enum EdgeFlag { PX_EDGE_ACTIVE = (1<<0) }; //! Basic edge-data struct EdgeData { PxU32 Ref0; //!< First vertex reference PxU32 Ref1; //!< Second vertex reference }; PX_COMPILE_TIME_ASSERT(sizeof(EdgeData) == 8); //! Basic edge-data using 8-bit references struct Edge8Data { PxU8 Ref0; //!< First vertex reference PxU8 Ref1; //!< Second vertex reference }; PX_COMPILE_TIME_ASSERT(sizeof(Edge8Data) == 2); //! A count/offset pair = an edge descriptor struct EdgeDescData { PxU16 Flags; PxU16 Count; PxU32 Offset; }; PX_COMPILE_TIME_ASSERT(sizeof(EdgeDescData) == 8); //! Edge<->triangle mapping struct EdgeTriangleData { PxU32 mLink[3]; }; PX_COMPILE_TIME_ASSERT(sizeof(EdgeTriangleData) == 12); enum { MSH_EDGE_LINK_MASK = 0x0fffffff, MSH_ACTIVE_EDGE_MASK = 0x80000000, MSH_ACTIVE_VERTEX_MASK = 0x40000000 }; class EdgeTriangleAC { public: PX_INLINE static PxU32 GetEdge01(const EdgeTriangleData& data) { return data.mLink[0] & MSH_EDGE_LINK_MASK; } PX_INLINE static PxU32 GetEdge12(const EdgeTriangleData& data) { return data.mLink[1] & MSH_EDGE_LINK_MASK; } PX_INLINE static PxU32 GetEdge20(const EdgeTriangleData& data) { return data.mLink[2] & MSH_EDGE_LINK_MASK; } PX_INLINE static PxU32 GetEdge(const EdgeTriangleData& data, PxU32 i) { return data.mLink[i] & MSH_EDGE_LINK_MASK; } PX_INLINE static PxIntBool HasActiveEdge01(const EdgeTriangleData& data) { return PxIntBool(data.mLink[0] & MSH_ACTIVE_EDGE_MASK); } PX_INLINE static PxIntBool HasActiveEdge12(const EdgeTriangleData& data) { return PxIntBool(data.mLink[1] & MSH_ACTIVE_EDGE_MASK); } PX_INLINE static PxIntBool HasActiveEdge20(const EdgeTriangleData& data) { return PxIntBool(data.mLink[2] & MSH_ACTIVE_EDGE_MASK); } PX_INLINE static PxIntBool HasActiveEdge(const EdgeTriangleData& data, PxU32 i) { return PxIntBool(data.mLink[i] & MSH_ACTIVE_EDGE_MASK); } }; //! The edge-list creation structure. struct EDGELISTCREATE { EDGELISTCREATE() : NbFaces (0), DFaces (NULL), WFaces (NULL), FacesToEdges (false), EdgesToFaces (false), Verts (NULL), Epsilon (0.1f) {} PxU32 NbFaces; //!< Number of faces in source topo const PxU32* DFaces; //!< List of faces (dwords) or NULL const PxU16* WFaces; //!< List of faces (words) or NULL bool FacesToEdges; bool EdgesToFaces; const PxVec3* Verts; float Epsilon; }; class EdgeList : public PxUserAllocated { public: PX_PHYSX_COMMON_API EdgeList(); PX_PHYSX_COMMON_API ~EdgeList(); PX_PHYSX_COMMON_API bool init(const EDGELISTCREATE& create); bool load(PxInputStream& stream); PX_FORCE_INLINE PxU32 getNbEdges() const { return mNbEdges; } PX_FORCE_INLINE const EdgeData* getEdges() const { return mEdges; } PX_FORCE_INLINE const EdgeData& getEdge(PxU32 edge_index) const { return mEdges[edge_index]; } PX_FORCE_INLINE PxU32 getNbFaces() const { return mNbFaces; } PX_FORCE_INLINE const EdgeTriangleData* getEdgeTriangles() const { return mEdgeFaces; } PX_FORCE_INLINE const EdgeTriangleData& getEdgeTriangle(PxU32 face_index) const { return mEdgeFaces[face_index]; } PX_FORCE_INLINE const EdgeDescData* getEdgeToTriangles() const { return mEdgeToTriangles; } PX_FORCE_INLINE const EdgeDescData& getEdgeToTriangles(PxU32 edge_index) const { return mEdgeToTriangles[edge_index]; } PX_FORCE_INLINE const PxU32* getFacesByEdges() const { return mFacesByEdges; } PX_FORCE_INLINE PxU32 getFacesByEdges(PxU32 face_index) const { return mFacesByEdges[face_index]; } private: // The edge list PxU32 mNbEdges; //!< Number of edges in the list EdgeData* mEdges; //!< List of edges // Faces to edges PxU32 mNbFaces; //!< Number of faces for which we have data EdgeTriangleData* mEdgeFaces; //!< Array of edge-triangles referencing mEdges // Edges to faces EdgeDescData* mEdgeToTriangles; //!< An EdgeDesc structure for each edge PxU32* mFacesByEdges; //!< A pool of face indices bool createFacesToEdges(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces); bool createEdgesToFaces(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces); bool computeActiveEdges(PxU32 nb_faces, const PxU32* dfaces, const PxU16* wfaces, const PxVec3* verts, float epsilon); }; } // namespace Gu } #endif
6,772
C
37.050562
141
0.703042
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuMeshCleaner.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxVec3.h" #include "foundation/PxMemory.h" #include "foundation/PxAllocator.h" #include "foundation/PxBitUtils.h" #include "GuMeshCleaner.h" using namespace physx; using namespace Gu; struct Indices { PxU32 mRef[3]; PX_FORCE_INLINE bool operator!=(const Indices&v) const { return mRef[0] != v.mRef[0] || mRef[1] != v.mRef[1] || mRef[2] != v.mRef[2]; } }; static PX_FORCE_INLINE PxU32 getHashValue(const PxVec3& v) { const PxU32* h = reinterpret_cast<const PxU32*>(&v.x); const PxU32 f = (h[0]+h[1]*11-(h[2]*17)) & 0x7fffffff; // avoid problems with +-0 return (f>>22)^(f>>12)^(f); } static PX_FORCE_INLINE PxU32 getHashValue(const Indices& v) { // const PxU32* h = v.mRef; // const PxU32 f = (h[0]+h[1]*11-(h[2]*17)) & 0x7fffffff; // avoid problems with +-0 // return (f>>22)^(f>>12)^(f); PxU32 a = v.mRef[0]; PxU32 b = v.mRef[1]; PxU32 c = v.mRef[2]; a=a-b; a=a-c; a=a^(c >> 13); b=b-c; b=b-a; b=b^(a << 8); c=c-a; c=c-b; c=c^(b >> 13); a=a-b; a=a-c; a=a^(c >> 12); b=b-c; b=b-a; b=b^(a << 16); c=c-a; c=c-b; c=c^(b >> 5); a=a-b; a=a-c; a=a^(c >> 3); b=b-c; b=b-a; b=b^(a << 10); c=c-a; c=c-b; c=c^(b >> 15); return c; } MeshCleaner::MeshCleaner(PxU32 nbVerts, const PxVec3* srcVerts, PxU32 nbTris, const PxU32* srcIndices, PxF32 meshWeldTolerance, PxF32 areaLimit) { PxVec3* cleanVerts = PX_ALLOCATE(PxVec3, nbVerts, "MeshCleaner"); PX_ASSERT(cleanVerts); PxU32* indices = PX_ALLOCATE(PxU32, (nbTris*3), "MeshCleaner"); PxU32* remapTriangles = PX_ALLOCATE(PxU32, nbTris, "MeshCleaner"); PxU32* vertexIndices = NULL; if(meshWeldTolerance!=0.0f) { vertexIndices = PX_ALLOCATE(PxU32, nbVerts, "MeshCleaner"); const PxF32 weldTolerance = 1.0f / meshWeldTolerance; // snap to grid for(PxU32 i=0; i<nbVerts; i++) { vertexIndices[i] = i; cleanVerts[i] = PxVec3( PxFloor(srcVerts[i].x*weldTolerance + 0.5f), PxFloor(srcVerts[i].y*weldTolerance + 0.5f), PxFloor(srcVerts[i].z*weldTolerance + 0.5f)); } } else { PxMemCopy(cleanVerts, srcVerts, nbVerts*sizeof(PxVec3)); } const PxU32 maxNbElems = PxMax(nbTris, nbVerts); const PxU32 hashSize = PxNextPowerOfTwo(maxNbElems); const PxU32 hashMask = hashSize-1; PxU32* hashTable = PX_ALLOCATE(PxU32, (hashSize + maxNbElems), "MeshCleaner"); PX_ASSERT(hashTable); PxMemSet(hashTable, 0xff, hashSize * sizeof(PxU32)); PxU32* const next = hashTable + hashSize; PxU32* remapVerts = PX_ALLOCATE(PxU32, nbVerts, "MeshCleaner"); PxMemSet(remapVerts, 0xff, nbVerts * sizeof(PxU32)); for(PxU32 i=0;i<nbTris*3;i++) { const PxU32 vref = srcIndices[i]; if(vref<nbVerts) remapVerts[vref] = 0; } PxU32 nbCleanedVerts = 0; for(PxU32 i=0;i<nbVerts;i++) { if(remapVerts[i]==0xffffffff) continue; const PxVec3& v = cleanVerts[i]; const PxU32 hashValue = getHashValue(v) & hashMask; PxU32 offset = hashTable[hashValue]; while(offset!=0xffffffff && cleanVerts[offset]!=v) offset = next[offset]; if(offset==0xffffffff) { remapVerts[i] = nbCleanedVerts; cleanVerts[nbCleanedVerts] = v; if(vertexIndices) vertexIndices[nbCleanedVerts] = i; next[nbCleanedVerts] = hashTable[hashValue]; hashTable[hashValue] = nbCleanedVerts++; } else remapVerts[i] = offset; } // PT: area = ((p0 - p1).cross(p0 - p2)).magnitude() * 0.5 // area < areaLimit // <=> ((p0 - p1).cross(p0 - p2)).magnitude() < areaLimit * 2.0 // <=> ((p0 - p1).cross(p0 - p2)).magnitudeSquared() < (areaLimit * 2.0)^2 const PxF32 limit = areaLimit * areaLimit * 4.0f; PxU32 nbCleanedTris = 0; for(PxU32 i=0;i<nbTris;i++) { PxU32 vref0 = *srcIndices++; PxU32 vref1 = *srcIndices++; PxU32 vref2 = *srcIndices++; if(vref0>=nbVerts || vref1>=nbVerts || vref2>=nbVerts) continue; // PT: you can still get zero-area faces when the 3 vertices are perfectly aligned const PxVec3& p0 = srcVerts[vref0]; const PxVec3& p1 = srcVerts[vref1]; const PxVec3& p2 = srcVerts[vref2]; const float area2 = ((p0 - p1).cross(p0 - p2)).magnitudeSquared(); if(area2<=limit) continue; vref0 = remapVerts[vref0]; vref1 = remapVerts[vref1]; vref2 = remapVerts[vref2]; if(vref0==vref1 || vref1==vref2 || vref2==vref0) continue; indices[nbCleanedTris*3+0] = vref0; indices[nbCleanedTris*3+1] = vref1; indices[nbCleanedTris*3+2] = vref2; remapTriangles[nbCleanedTris] = i; nbCleanedTris++; } PX_FREE(remapVerts); PxU32 nbToGo = nbCleanedTris; nbCleanedTris = 0; PxMemSet(hashTable, 0xff, hashSize * sizeof(PxU32)); Indices* const I = reinterpret_cast<Indices*>(indices); bool idtRemap = true; for(PxU32 i=0;i<nbToGo;i++) { const Indices& v = I[i]; const PxU32 hashValue = getHashValue(v) & hashMask; PxU32 offset = hashTable[hashValue]; while(offset!=0xffffffff && I[offset]!=v) offset = next[offset]; if(offset==0xffffffff) { const PxU32 originalIndex = remapTriangles[i]; PX_ASSERT(nbCleanedTris<=i); remapTriangles[nbCleanedTris] = originalIndex; if(originalIndex!=nbCleanedTris) idtRemap = false; I[nbCleanedTris] = v; next[nbCleanedTris] = hashTable[hashValue]; hashTable[hashValue] = nbCleanedTris++; } } PX_FREE(hashTable); if(vertexIndices) { for(PxU32 i=0;i<nbCleanedVerts;i++) cleanVerts[i] = srcVerts[vertexIndices[i]]; PX_FREE(vertexIndices); } mNbVerts = nbCleanedVerts; mNbTris = nbCleanedTris; mVerts = cleanVerts; mIndices = indices; if(idtRemap) { PX_FREE(remapTriangles); mRemap = NULL; } else { mRemap = remapTriangles; } } MeshCleaner::~MeshCleaner() { PX_FREE(mRemap); PX_FREE(mIndices); PX_FREE(mVerts); }
7,311
C++
29.722689
144
0.685132
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuSeparatingAxes.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_SEPARATINGAXES_H #define GU_SEPARATINGAXES_H #include "foundation/PxVec3.h" #include "common/PxPhysXCommonConfig.h" namespace physx { namespace Gu { // PT: this is a number of axes. Multiply by sizeof(PxVec3) for size in bytes. #define SEP_AXIS_FIXED_MEMORY 256 // This class holds a list of potential separating axes. // - the orientation is irrelevant so V and -V should be the same vector // - the scale is irrelevant so V and n*V should be the same vector // - a given separating axis should appear only once in the class #if PX_VC #pragma warning(push) #pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class #endif class PX_PHYSX_COMMON_API SeparatingAxes { public: PX_INLINE SeparatingAxes() : mNbAxes(0) {} bool addAxis(const PxVec3& axis); PX_FORCE_INLINE const PxVec3* getAxes() const { return mAxes; } PX_FORCE_INLINE PxU32 getNumAxes() const { return mNbAxes; } PX_FORCE_INLINE void reset() { mNbAxes = 0; } private: PxU32 mNbAxes; PxVec3 mAxes[SEP_AXIS_FIXED_MEMORY]; }; #if PX_VC #pragma warning(pop) #endif enum PxcSepAxisType { SA_NORMAL0, // Normal of object 0 SA_NORMAL1, // Normal of object 1 SA_EE // Cross product of edges }; } } #endif
2,996
C
31.934066
102
0.735314
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV32.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxMemory.h" #include "GuBV32.h" #include "CmSerialize.h" #include "CmUtils.h" #include "foundation/PxUtilities.h" #include "foundation/PxVecMath.h" using namespace physx; using namespace Gu; using namespace Cm; BV32Tree::BV32Tree(SourceMesh* meshInterface, const PxBounds3& localBounds) { reset(); init(meshInterface, localBounds); } BV32Tree::BV32Tree() { reset(); } void BV32Tree::release() { if (!mUserAllocated) { PX_DELETE_ARRAY(mNodes); PX_FREE(mPackedNodes); PX_FREE(mTreeDepthInfo); PX_FREE(mRemapPackedNodeIndexWithDepth); } mNodes = NULL; mNbNodes = 0; mMaxTreeDepth = 0; } BV32Tree::~BV32Tree() { release(); } void BV32Tree::reset() { mMeshInterface = NULL; mNbNodes = 0; mNodes = NULL; mNbPackedNodes = 0; mPackedNodes = NULL; mMaxTreeDepth = 0; mTreeDepthInfo = NULL; mRemapPackedNodeIndexWithDepth = NULL; mInitData = 0; mUserAllocated = false; } void BV32Tree::operator=(BV32Tree& v) { mMeshInterface = v.mMeshInterface; mLocalBounds = v.mLocalBounds; mNbNodes = v.mNbNodes; mNodes = v.mNodes; mInitData = v.mInitData; mUserAllocated = v.mUserAllocated; v.reset(); } bool BV32Tree::init(SourceMeshBase* meshInterface, const PxBounds3& localBounds) { mMeshInterface = meshInterface; mLocalBounds.init(localBounds); return true; } // PX_SERIALIZATION BV32Tree::BV32Tree(const PxEMPTY) { mUserAllocated = true; } void BV32Tree::exportExtraData(PxSerializationContext& stream) { stream.alignData(16); stream.writeData(mPackedNodes, mNbPackedNodes*sizeof(BV32DataPacked)); } void BV32Tree::importExtraData(PxDeserializationContext& context) { context.alignExtraData(16); mPackedNodes = context.readExtraData<BV32DataPacked>(mNbPackedNodes); } //~PX_SERIALIZATION bool BV32Tree::load(PxInputStream& stream, bool mismatch_) { PX_ASSERT(!mUserAllocated); release(); PxI8 a, b, c, d; readChunk(a, b, c, d, stream); if(a != 'B' || b != 'V' || c != '3' || d != '2') return false; bool mismatch; PxU32 fileVersion; if(!readBigEndianVersionNumber(stream, mismatch_, fileVersion, mismatch)) return false; mLocalBounds.mCenter.x = readFloat(mismatch, stream); mLocalBounds.mCenter.y = readFloat(mismatch, stream); mLocalBounds.mCenter.z = readFloat(mismatch, stream); mLocalBounds.mExtentsMagnitude = readFloat(mismatch, stream); mInitData = readDword(mismatch, stream); /*const PxU32 nbNodes = readDword(mismatch, stream); mNbNodes = nbNodes; if (nbNodes) { BV32Data* nodes = PX_NEW(BV32Data)[nbNodes]; mNodes = nodes; PxMarkSerializedMemory(nodes, sizeof(BV32Data)*nbNodes); for (PxU32 i = 0; i<nbNodes; i++) { BV32Data& node = nodes[i]; readFloatBuffer(&node.mCenter.x, 3, mismatch, stream); node.mData = readDword(mismatch, stream); readFloatBuffer(&node.mExtents.x, 3, mismatch, stream); } }*/ //read SOA format node data const PxU32 nbPackedNodes = readDword(mismatch, stream); mNbPackedNodes = nbPackedNodes; if (nbPackedNodes) { mPackedNodes = reinterpret_cast<BV32DataPacked*>(PX_ALLOC(sizeof(BV32DataPacked)*nbPackedNodes, "BV32DataPacked")); PxMarkSerializedMemory(mPackedNodes, sizeof(BV32DataPacked)*nbPackedNodes); for (PxU32 i = 0; i < nbPackedNodes; ++i) { BV32DataPacked& node = mPackedNodes[i]; node.mNbNodes = readDword(mismatch, stream); PX_ASSERT(node.mNbNodes > 0); node.mDepth = readDword(mismatch, stream); ReadDwordBuffer(node.mData, node.mNbNodes, mismatch, stream); const PxU32 nbElements = 4 * node.mNbNodes; readFloatBuffer(&node.mMin[0].x, nbElements, mismatch, stream); readFloatBuffer(&node.mMax[0].x, nbElements, mismatch, stream); } } const PxU32 maxTreeDepth = readDword(mismatch, stream); mMaxTreeDepth = maxTreeDepth; if (maxTreeDepth > 0) { mTreeDepthInfo = reinterpret_cast<BV32DataDepthInfo*>(PX_ALLOC(sizeof(BV32DataDepthInfo)*maxTreeDepth, "BV32DataDepthInfo")); for (PxU32 i = 0; i < maxTreeDepth; ++i) { BV32DataDepthInfo& info = mTreeDepthInfo[i]; info.offset = readDword(mismatch, stream); info.count = readDword(mismatch, stream); } mRemapPackedNodeIndexWithDepth = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32)*nbPackedNodes, "PxU32")); ReadDwordBuffer(mRemapPackedNodeIndexWithDepth, nbPackedNodes, mismatch, stream); } return true; } void BV32Tree::createSOAformatNode(BV32DataPacked& packedData, const BV32Data& node, const PxU32 childOffset, PxU32& currentIndex, PxU32& nbPackedNodes) { //found the next 32 nodes and fill it in SOA format const PxU32 nbChildren = node.getNbChildren(); const PxU32 offset = node.getChildOffset(); packedData.mDepth = node.mDepth; for (PxU32 i = 0; i < nbChildren; ++i) { BV32Data& child = mNodes[offset + i]; packedData.mMin[i] = PxVec4(child.mMin, 0.f); packedData.mMax[i] = PxVec4(child.mMax, 0.f); packedData.mData[i] = PxU32(child.mData); } packedData.mNbNodes = nbChildren; PxU32 NbToGo = 0; PxU32 NextIDs[32]; PxMemSet(NextIDs, PX_INVALID_U32, sizeof(PxU32) * 32); const BV32Data* ChildNodes[32]; PxMemSet(ChildNodes, 0, sizeof(BV32Data*) * 32); for (PxU32 i = 0; i< nbChildren; i++) { BV32Data& child = mNodes[offset + i]; if (!child.isLeaf()) { const PxU32 NextID = currentIndex; const PxU32 ChildSize = child.getNbChildren() - child.mNbLeafNodes; currentIndex += ChildSize; //packedData.mData[i] = (packedData.mData[i] & ((1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT) - 1)) | (NextID << GU_BV4_CHILD_OFFSET_SHIFT_COUNT); packedData.mData[i] = (packedData.mData[i] & ((1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT) - 1)) | ((childOffset + NbToGo) << GU_BV4_CHILD_OFFSET_SHIFT_COUNT); NextIDs[NbToGo] = NextID; ChildNodes[NbToGo] = &child; NbToGo++; } } nbPackedNodes += NbToGo; for (PxU32 i = 0; i < NbToGo; ++i) { const BV32Data& child = *ChildNodes[i]; BV32DataPacked& childData = mPackedNodes[childOffset+i]; createSOAformatNode(childData, child, NextIDs[i], currentIndex, nbPackedNodes); } } bool BV32Tree::refit(float epsilon) { using namespace physx::aos; if (!mPackedNodes) { PxBounds3 bounds; bounds.setEmpty(); if (mMeshInterface) { PxU32 nbVerts = mMeshInterface->getNbVertices(); const PxVec3* verts = mMeshInterface->getVerts(); while (nbVerts--) bounds.include(*verts++); mLocalBounds.init(bounds); } return true; } class PxBounds3Padded : public PxBounds3 { public: PX_FORCE_INLINE PxBounds3Padded() {} PX_FORCE_INLINE ~PxBounds3Padded() {} PxU32 padding; }; PxU32 nb = mNbPackedNodes; while (nb--) { BV32DataPacked* PX_RESTRICT current = mPackedNodes + nb; const PxU32 nbChildren = current->mNbNodes; for (PxU32 j = 0; j< nbChildren; j++) { if (current->isLeaf(j)) { PxU32 nbTets = current->getNbReferencedPrimitives(j); PxU32 primIndex = current->getPrimitiveStartIndex(j); Vec4V minV = V4Load(FLT_MAX); Vec4V maxV = V4Load(-FLT_MAX); //TetrahedronPointers do { PX_ASSERT(primIndex< mMeshInterface->getNbPrimitives()); //meshInterface->getTriangle(VP, primIndex); Vec4V tMin, tMax; mMeshInterface->getPrimitiveBox(primIndex, tMin, tMax); minV = V4Min(minV, tMin); maxV = V4Max(maxV, tMax); primIndex++; } while (--nbTets); const Vec4V epsilonV = V4Load(epsilon); minV = V4Sub(minV, epsilonV); maxV = V4Add(maxV, epsilonV); PxBounds3Padded refitBox; V4StoreU_Safe(minV, &refitBox.minimum.x); V4StoreU_Safe(maxV, &refitBox.maximum.x); current->mMin[j].x = refitBox.minimum.x; current->mMin[j].y = refitBox.minimum.y; current->mMin[j].z = refitBox.minimum.z; current->mMax[j].x = refitBox.maximum.x; current->mMax[j].y = refitBox.maximum.y; current->mMax[j].z = refitBox.maximum.z; } else { PxU32 childOffset = current->getChildOffset(j); PX_ASSERT(childOffset < mNbPackedNodes); BV32DataPacked* next = mPackedNodes + childOffset; const PxU32 nextNbChilds = next->mNbNodes; Vec4V minV = V4Load(FLT_MAX); Vec4V maxV = V4Load(-FLT_MAX); for (PxU32 a = 0; a < nextNbChilds; ++a) { const Vec4V tMin = V4LoadU(&next->mMin[a].x); const Vec4V tMax = V4LoadU(&next->mMax[a].x); minV = V4Min(minV, tMin); maxV = V4Max(maxV, tMax); } PxBounds3Padded refitBox; V4StoreU_Safe(minV, &refitBox.minimum.x); V4StoreU_Safe(maxV, &refitBox.maximum.x); current->mMin[j].x = refitBox.minimum.x; current->mMin[j].y = refitBox.minimum.y; current->mMin[j].z = refitBox.minimum.z; current->mMax[j].x = refitBox.maximum.x; current->mMax[j].y = refitBox.maximum.y; current->mMax[j].z = refitBox.maximum.z; } } } BV32DataPacked* root = mPackedNodes; { PxBounds3 globalBounds; globalBounds.setEmpty(); const PxU32 nbChildren = root->mNbNodes; Vec4V minV = V4Load(FLT_MAX); Vec4V maxV = V4Load(-FLT_MAX); for (PxU32 a = 0; a < nbChildren; ++a) { const Vec4V tMin = V4LoadU(&root->mMin[a].x); const Vec4V tMax = V4LoadU(&root->mMax[a].x); minV = V4Min(minV, tMin); maxV = V4Max(maxV, tMax); } PxBounds3Padded refitBox; V4StoreU_Safe(minV, &refitBox.minimum.x); V4StoreU_Safe(maxV, &refitBox.maximum.x); globalBounds.minimum.x = refitBox.minimum.x; globalBounds.minimum.y = refitBox.minimum.y; globalBounds.minimum.z = refitBox.minimum.z; globalBounds.maximum.x = refitBox.maximum.x; globalBounds.maximum.y = refitBox.maximum.y; globalBounds.maximum.z = refitBox.maximum.z; mLocalBounds.init(globalBounds); } return true; }
11,253
C++
26.315534
156
0.706034
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Raycast.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" using namespace physx; using namespace Gu; #include "PxQueryReport.h" #include "GuInternal.h" #include "GuIntersectionRayTriangle.h" #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuBV4_Common.h" class RaycastHitInternalUV : public RaycastHitInternal { public: PX_FORCE_INLINE RaycastHitInternalUV() {} PX_FORCE_INLINE ~RaycastHitInternalUV() {} float mU, mV; }; // PT: this makes a UT fail - to investigate #ifdef TO_SEE PX_FORCE_INLINE __m128 DotV(const __m128 a, const __m128 b) { const __m128 t0 = _mm_mul_ps(a, b); // aw*bw | az*bz | ay*by | ax*bx const __m128 t1 = _mm_shuffle_ps(t0, t0, _MM_SHUFFLE(1,0,3,2)); // ay*by | ax*bx | aw*bw | az*bz const __m128 t2 = _mm_add_ps(t0, t1); // ay*by + aw*bw | ax*bx + az*bz | aw*bw + ay*by | az*bz + ax*bx const __m128 t3 = _mm_shuffle_ps(t2, t2, _MM_SHUFFLE(2,3,0,1)); // ax*bx + az*bz | ay*by + aw*bw | az*bz + ax*bx | aw*bw + ay*by return _mm_add_ps(t3, t2); // ax*bx + az*bz + ay*by + aw*bw // ay*by + aw*bw + ax*bx + az*bz // az*bz + ax*bx + aw*bw + ay*by // aw*bw + ay*by + az*bz + ax*bx } #endif template<class T> PX_FORCE_INLINE PxIntBool RayTriOverlapT(PxGeomRaycastHit& mStabbedFace, const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, const T* PX_RESTRICT params) { #ifdef TO_SEE if(0) { const Vec4V vert0V = V4LoadU(&vert0.x); const Vec4V edge1V = V4Sub(V4LoadU(&vert1.x), vert0V); const Vec4V edge2V = V4Sub(V4LoadU(&vert2.x), vert0V); const Vec4V localDirV = V4LoadU(&params->mLocalDir_Padded.x); const Vec4V pvecV = V4Cross(localDirV, edge2V); const __m128 detV = DotV(edge1V, pvecV); if(params->mBackfaceCulling) { const Vec4V tvecV = V4Sub(V4LoadU(&params->mOrigin_Padded.x), vert0V); const Vec4V qvecV = V4Cross(tvecV, edge1V); const __m128 uV = DotV(tvecV, pvecV); const __m128 vV = DotV(localDirV, qvecV); const __m128 dV = DotV(edge2V, qvecV); if(1) // best so far, alt impl, looks like it's exactly the same speed, might be better for platforms that don't have good movemask { const float localEpsilon = GU_CULLING_EPSILON_RAY_TRIANGLE; const __m128 localEpsilonV = _mm_load1_ps(&localEpsilon); __m128 res = (_mm_cmpgt_ps(localEpsilonV, detV)); const __m128 geomEpsilonV = _mm_load1_ps(&params->mGeomEpsilon); // PT: strange. PhysX version not the same as usual. One more mul needed here :( const __m128 enlargeCoeffV = _mm_mul_ps(detV, geomEpsilonV); // res = _mm_or_ps(res, _mm_min_ps(dV, _mm_min_ps(_mm_add_ps(uV, geomEpsilonV), _mm_add_ps(vV, geomEpsilonV)))); // res = _mm_or_ps(res, _mm_cmpgt_ps(_mm_max_ps(uV, _mm_add_ps(uV, vV)), _mm_add_ps(detV, geomEpsilonV))); res = _mm_or_ps(res, _mm_min_ps(dV, _mm_min_ps(_mm_add_ps(uV, enlargeCoeffV), _mm_add_ps(vV, enlargeCoeffV)))); res = _mm_or_ps(res, _mm_cmpgt_ps(_mm_max_ps(uV, _mm_add_ps(uV, vV)), _mm_add_ps(detV, enlargeCoeffV))); const int cndt = _mm_movemask_ps(res); if(cndt) return 0; } const float one = 1.0f; const __m128 oneV = _mm_load1_ps(&one); const __m128 OneOverDetV = _mm_div_ps(oneV, detV); _mm_store_ss(&mStabbedFace.distance, _mm_mul_ps(dV, OneOverDetV)); _mm_store_ss(&mStabbedFace.u, _mm_mul_ps(uV, OneOverDetV)); _mm_store_ss(&mStabbedFace.v, _mm_mul_ps(vV, OneOverDetV)); return 1; } else { const __m128 tvecV = V4Sub(V4LoadU(&params->mOrigin_Padded.x), vert0V); // const Point tvec = params->mOrigin - vert0; const __m128 qvecV = V4Cross(tvecV, edge1V); // const Point qvec = tvec^edge1; const float localEpsilon = GU_CULLING_EPSILON_RAY_TRIANGLE; const __m128 localEpsilonV = _mm_load1_ps(&localEpsilon); const __m128 absDet = _mm_max_ps(detV, V4Sub(_mm_setzero_ps(), detV)); const int cndt = _mm_movemask_ps(_mm_cmpgt_ps(localEpsilonV, absDet)); const float one = 1.0f; const __m128 oneV = _mm_load1_ps(&one); const __m128 OneOverDetV = _mm_div_ps(oneV, detV); const __m128 uV = _mm_mul_ps(DotV(tvecV, pvecV), OneOverDetV); const __m128 vV = _mm_mul_ps(DotV(localDirV, qvecV), OneOverDetV); const __m128 dV = _mm_mul_ps(DotV(edge2V, qvecV), OneOverDetV); const __m128 geomEpsilonV = _mm_load1_ps(&params->mGeomEpsilon); const int cndt2 = _mm_movemask_ps(_mm_min_ps(dV, _mm_min_ps(_mm_add_ps(uV, geomEpsilonV), _mm_add_ps(vV, geomEpsilonV)))); const int cndt3 = _mm_movemask_ps(_mm_cmpgt_ps(_mm_max_ps(uV, _mm_add_ps(uV, vV)), _mm_add_ps(oneV, geomEpsilonV))); if(cndt|cndt3|cndt2) return 0; _mm_store_ss(&mStabbedFace.distance, dV); _mm_store_ss(&mStabbedFace.u, uV); _mm_store_ss(&mStabbedFace.v, vV); return 1; } } else #endif { // Find vectors for two edges sharing vert0 const PxVec3 edge1 = vert1 - vert0; const PxVec3 edge2 = vert2 - vert0; // Begin calculating determinant - also used to calculate U parameter const PxVec3 pvec = params->mLocalDir_Padded.cross(edge2); // If determinant is near zero, ray lies in plane of triangle const float det = edge1.dot(pvec); if(params->mBackfaceCulling) { if(det<GU_CULLING_EPSILON_RAY_TRIANGLE) return 0; // Calculate distance from vert0 to ray origin const PxVec3 tvec = params->mOrigin_Padded - vert0; // Calculate U parameter and test bounds const float u = tvec.dot(pvec); const PxReal enlargeCoeff = params->mGeomEpsilon*det; const PxReal uvlimit = -enlargeCoeff; const PxReal uvlimit2 = det + enlargeCoeff; if(u < uvlimit || u > uvlimit2) return 0; // Prepare to test V parameter const PxVec3 qvec = tvec.cross(edge1); // Calculate V parameter and test bounds const float v = params->mLocalDir_Padded.dot(qvec); if(v < uvlimit || (u + v) > uvlimit2) return 0; // Calculate t, scale parameters, ray intersects triangle const float d = edge2.dot(qvec); // Det > 0 so we can early exit here // Intersection point is valid if distance is positive (else it can just be a face behind the orig point) if(d<0.0f) return 0; // Else go on const float OneOverDet = 1.0f / det; mStabbedFace.distance = d * OneOverDet; mStabbedFace.u = u * OneOverDet; mStabbedFace.v = v * OneOverDet; } else { if(PxAbs(det)<GU_CULLING_EPSILON_RAY_TRIANGLE) return 0; const float OneOverDet = 1.0f / det; const PxVec3 tvec = params->mOrigin_Padded - vert0; const float u = tvec.dot(pvec) * OneOverDet; if(u<-params->mGeomEpsilon || u>1.0f+params->mGeomEpsilon) return 0; // prepare to test V parameter const PxVec3 qvec = tvec.cross(edge1); // Calculate V parameter and test bounds const float v = params->mLocalDir_Padded.dot(qvec) * OneOverDet; if(v < -params->mGeomEpsilon || (u + v) > 1.0f + params->mGeomEpsilon) return 0; // Calculate t, ray intersects triangle const float d = edge2.dot(qvec) * OneOverDet; // Intersection point is valid if distance is positive (else it can just be a face behind the orig point) if(d<0.0f) return 0; mStabbedFace.distance = d; mStabbedFace.u = u; mStabbedFace.v = v; } return 1; } } #if PX_VC #pragma warning ( disable : 4324 ) #endif namespace { struct RayParams { BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); // Organized in the order they are accessed #ifndef GU_BV4_USE_SLABS BV4_ALIGN16(PxVec3p mData2_PaddedAligned); BV4_ALIGN16(PxVec3p mFDir_PaddedAligned); BV4_ALIGN16(PxVec3p mData_PaddedAligned); #endif const IndTri32* PX_RESTRICT mTris32; const IndTri16* PX_RESTRICT mTris16; const PxVec3* PX_RESTRICT mVerts; PxVec3 mLocalDir_Padded; PxVec3 mOrigin_Padded; float mGeomEpsilon; PxU32 mBackfaceCulling; RaycastHitInternalUV mStabbedFace; PxU32 mEarlyExit; PxVec3 mOriginalExtents_Padded; // Added to please the slabs code BV4_ALIGN16(PxVec3p mP0_PaddedAligned); BV4_ALIGN16(PxVec3p mP1_PaddedAligned); BV4_ALIGN16(PxVec3p mP2_PaddedAligned); }; } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE void updateParamsAfterImpact(RayParams* PX_RESTRICT params, PxU32 primIndex, PxU32 VRef0, PxU32 VRef1, PxU32 VRef2, const PxGeomRaycastHit& StabbedFace) { V4StoreA_Safe(V4LoadU_Safe(&params->mVerts[VRef0].x), &params->mP0_PaddedAligned.x); V4StoreA_Safe(V4LoadU_Safe(&params->mVerts[VRef1].x), &params->mP1_PaddedAligned.x); V4StoreA_Safe(V4LoadU_Safe(&params->mVerts[VRef2].x), &params->mP2_PaddedAligned.x); params->mStabbedFace.mTriangleID = primIndex; params->mStabbedFace.mDistance = StabbedFace.distance; params->mStabbedFace.mU = StabbedFace.u; params->mStabbedFace.mV = StabbedFace.v; } namespace { class LeafFunction_RaycastClosest { public: static /*PX_FORCE_INLINE*/ PxIntBool doLeafTest(RayParams* PX_RESTRICT params, PxU32 primIndex) { PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& StabbedFace = reinterpret_cast<PxGeomRaycastHit&>(buffer); PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); if(RayTriOverlapT<RayParams>(StabbedFace, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params)) { if(StabbedFace.distance<params->mStabbedFace.mDistance) //### just for a corner case UT in PhysX :( { updateParamsAfterImpact(params, primIndex, VRef0, VRef1, VRef2, StabbedFace); #ifndef GU_BV4_USE_SLABS setupRayData(params, StabbedFace.distance, params->mOrigin_Padded, params->mLocalDir_Padded); #endif } } primIndex++; }while(nbToGo--); return 0; } }; class LeafFunction_RaycastAny { public: static /*PX_FORCE_INLINE*/ PxIntBool doLeafTest(RayParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& StabbedFace = reinterpret_cast<PxGeomRaycastHit&>(buffer); if(RayTriOverlapT<RayParams>(StabbedFace, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params)) { if(StabbedFace.distance<params->mStabbedFace.mDistance) //### just for a corner case UT in PhysX :( { updateParamsAfterImpact(params, primIndex, VRef0, VRef1, VRef2, StabbedFace); return 1; } } primIndex++; }while(nbToGo--); return 0; } }; } static PX_FORCE_INLINE Vec4V multiply3x3V_Aligned(const Vec4V p, const PxMat44* PX_RESTRICT mat) { const FloatV xxxV = V4GetX(p); const FloatV yyyV = V4GetY(p); const FloatV zzzV = V4GetZ(p); Vec4V ResV = V4Scale(V4LoadA(&mat->column0.x), xxxV); ResV = V4Add(ResV, V4Scale(V4LoadA(&mat->column1.x), yyyV)); ResV = V4Add(ResV, V4Scale(V4LoadA(&mat->column2.x), zzzV)); return ResV; } static PX_FORCE_INLINE PxIntBool computeImpactData(PxGeomRaycastHit* PX_RESTRICT hit, const RayParams* PX_RESTRICT params, const PxMat44* PX_RESTRICT worldm_Aligned, PxHitFlags /*hitFlags*/) { if(params->mStabbedFace.mTriangleID!=PX_INVALID_U32 /*&& !params->mEarlyExit*/) //### PhysX needs the raycast data even for "any hit" :( { const float u = params->mStabbedFace.mU; const float v = params->mStabbedFace.mV; const float d = params->mStabbedFace.mDistance; const PxU32 id = params->mStabbedFace.mTriangleID; hit->u = u; hit->v = v; hit->distance = d; hit->faceIndex = id; { const Vec4V P0V = V4LoadA_Safe(&params->mP0_PaddedAligned.x); const Vec4V P1V = V4LoadA_Safe(&params->mP1_PaddedAligned.x); const Vec4V P2V = V4LoadA_Safe(&params->mP2_PaddedAligned.x); const FloatV uV = FLoad(params->mStabbedFace.mU); const FloatV vV = FLoad(params->mStabbedFace.mV); const float w = 1.0f - params->mStabbedFace.mU - params->mStabbedFace.mV; const FloatV wV = FLoad(w); //pt = (1.0f - u - v)*p0 + u*p1 + v*p2; Vec4V LocalPtV = V4Scale(P1V, uV); LocalPtV = V4Add(LocalPtV, V4Scale(P2V, vV)); LocalPtV = V4Add(LocalPtV, V4Scale(P0V, wV)); const Vec4V LocalNormalV = V4Cross(V4Sub(P0V, P1V), V4Sub(P0V, P2V)); BV4_ALIGN16(PxVec3p tmp_PaddedAligned); if(worldm_Aligned) { const Vec4V TransV = V4LoadA(&worldm_Aligned->column3.x); V4StoreU_Safe(V4Add(multiply3x3V_Aligned(LocalPtV, worldm_Aligned), TransV), &hit->position.x); V4StoreA_Safe(multiply3x3V_Aligned(LocalNormalV, worldm_Aligned), &tmp_PaddedAligned.x); } else { V4StoreU_Safe(LocalPtV, &hit->position.x); V4StoreA_Safe(LocalNormalV, &tmp_PaddedAligned.x); } tmp_PaddedAligned.normalize(); hit->normal = tmp_PaddedAligned; // PT: TODO: check asm here (TA34704) } } return params->mStabbedFace.mTriangleID!=PX_INVALID_U32; } static PX_FORCE_INLINE float clipRay(const PxVec3& ray_orig, const PxVec3& ray_dir, const LocalBounds& local_bounds) { const float dpc = local_bounds.mCenter.dot(ray_dir); const float dpMin = dpc - local_bounds.mExtentsMagnitude; const float dpMax = dpc + local_bounds.mExtentsMagnitude; const float dpO = ray_orig.dot(ray_dir); const float boxLength = local_bounds.mExtentsMagnitude * 2.0f; const float distToBox = PxMin(fabsf(dpMin - dpO), fabsf(dpMax - dpO)); return distToBox + boxLength * 2.0f; } template<class ParamsT> static PX_FORCE_INLINE void setupRayParams(ParamsT* PX_RESTRICT params, const PxVec3& origin, const PxVec3& dir, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT world, const SourceMesh* PX_RESTRICT mesh, float maxDist, float geomEpsilon, PxU32 flags) { params->mGeomEpsilon = geomEpsilon; setupParamsFlags(params, flags); computeLocalRay(params->mLocalDir_Padded, params->mOrigin_Padded, dir, origin, world); // PT: TODO: clipRay may not be needed with GU_BV4_USE_SLABS (TA34704) const float MaxDist = clipRay(params->mOrigin_Padded, params->mLocalDir_Padded, tree->mLocalBounds); maxDist = PxMin(maxDist, MaxDist); params->mStabbedFace.mDistance = maxDist; params->mStabbedFace.mTriangleID = PX_INVALID_U32; setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); #ifndef GU_BV4_USE_SLABS setupRayData(params, maxDist, params->mOrigin_Padded, params->mLocalDir_Padded); #endif } #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamOrdered_SegmentAABB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_KajiyaNoOrder.h" #include "GuBV4_Slabs_KajiyaOrdered.h" #endif #define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER #define GU_BV4_PROCESS_STREAM_RAY_ORDERED #include "GuBV4_Internal.h" #ifndef GU_BV4_USE_SLABS #ifdef GU_BV4_QUANTIZED_TREE // A.B. enable new version only for intel non simd path #if PX_INTEL_FAMILY && !defined(PX_SIMD_DISABLED) // #define NEW_VERSION #endif // PX_INTEL_FAMILY && !PX_SIMD_DISABLED static PX_FORCE_INLINE /*PX_NOINLINE*/ PxIntBool BV4_SegmentAABBOverlap(const BVDataPacked* PX_RESTRICT node, const RayParams* PX_RESTRICT params) { #ifdef NEW_VERSION SSE_CONST4(maskV, 0x7fffffff); SSE_CONST4(maskQV, 0x0000ffff); #endif #ifdef NEW_VERSION Vec4V centerV = V4LoadA((float*)node->mAABB.mData); __m128 extentsV = _mm_castsi128_ps(_mm_and_si128(_mm_castps_si128(centerV), SSE_CONST(maskQV))); extentsV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(extentsV)), V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x)); centerV = _mm_castsi128_ps(_mm_srai_epi32(_mm_castps_si128(centerV), 16)); centerV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(centerV)), V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x)); #else const VecI32V centerVI = I4LoadA((PxI32*)node->mAABB.mData); const VecI32V extentsVI = VecI32V_And(centerVI, I4Load(0x0000ffff)); const Vec4V extentsV = V4Mul(Vec4V_From_VecI32V(extentsVI), V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x)); const VecI32V centerVShift = VecI32V_RightShift(centerVI, 16); const Vec4V centerV = V4Mul(Vec4V_From_VecI32V(centerVShift), V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x)); #endif const Vec4V fdirV = V4LoadA_Safe(&params->mFDir_PaddedAligned.x); const Vec4V DV = V4Sub(V4LoadA_Safe(&params->mData2_PaddedAligned.x), centerV); #ifdef NEW_VERSION __m128 absDV = _mm_and_ps(DV, SSE_CONSTF(maskV)); #else Vec4V absDV = V4Abs(DV); #endif const BoolV resDV = V4IsGrtr(absDV, V4Add(extentsV, fdirV)); const PxU32 test = BGetBitMask(resDV); if(test&7) return 0; if(1) { const Vec4V dataZYX_V = V4LoadA_Safe(&params->mData_PaddedAligned.x); const Vec4V dataXZY_V = V4Perm<1, 2, 0, 3>(dataZYX_V); const Vec4V DXZY_V = V4Perm<1, 2, 0, 3>(DV); const Vec4V fV = V4Sub(V4Mul(dataZYX_V, DXZY_V), V4Mul(dataXZY_V, DV)); const Vec4V fdirZYX_V = V4LoadA_Safe(&params->mFDir_PaddedAligned.x); const Vec4V fdirXZY_V = V4Perm<1, 2, 0, 3>(fdirZYX_V); const Vec4V extentsXZY_V = V4Perm<1, 2, 0, 3>(extentsV); // PT: TODO: use V4MulAdd here (TA34704) const Vec4V fg = V4Add(V4Mul(extentsV, fdirXZY_V), V4Mul(extentsXZY_V, fdirZYX_V)); #ifdef NEW_VERSION __m128 absfV = _mm_and_ps(fV, SSE_CONSTF(maskV)); #else Vec4V absfV = V4Abs(fV); #endif const BoolV resfV = V4IsGrtr(absfV, fg); const PxU32 test2 = BGetBitMask(resfV); if(test2&7) return 0; return 1; } } #else static PX_FORCE_INLINE /*PX_NOINLINE*/ PxIntBool BV4_SegmentAABBOverlap(const PxVec3& center, const PxVec3& extents, const RayParams* PX_RESTRICT params) { const PxU32 maskI = 0x7fffffff; const Vec4V fdirV = V4LoadA_Safe(&params->mFDir_PaddedAligned.x); const Vec4V extentsV = V4LoadU(&extents.x); const Vec4V DV = V4Sub(V4LoadA_Safe(&params->mData2_PaddedAligned.x), V4LoadU(&center.x)); //###center should be aligned __m128 absDV = _mm_and_ps(DV, _mm_load1_ps((float*)&maskI)); absDV = _mm_cmpgt_ps(absDV, V4Add(extentsV, fdirV)); const PxU32 test = (PxU32)_mm_movemask_ps(absDV); if(test&7) return 0; if(1) { const Vec4V dataZYX_V = V4LoadA_Safe(&params->mData_PaddedAligned.x); const __m128 dataXZY_V = _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(dataZYX_V), _MM_SHUFFLE(3,0,2,1))); const __m128 DXZY_V = _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(DV), _MM_SHUFFLE(3,0,2,1))); const Vec4V fV = V4Sub(V4Mul(dataZYX_V, DXZY_V), V4Mul(dataXZY_V, DV)); const Vec4V fdirZYX_V = V4LoadA_Safe(&params->mFDir_PaddedAligned.x); const __m128 fdirXZY_V = _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(fdirZYX_V), _MM_SHUFFLE(3,0,2,1))); const __m128 extentsXZY_V = _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(extentsV), _MM_SHUFFLE(3,0,2,1))); // PT: TODO: use V4MulAdd here (TA34704) const Vec4V fg = V4Add(V4Mul(extentsV, fdirXZY_V), V4Mul(extentsXZY_V, fdirZYX_V)); __m128 absfV = _mm_and_ps(fV, _mm_load1_ps((float*)&maskI)); absfV = _mm_cmpgt_ps(absfV, fg); const PxU32 test2 = (PxU32)_mm_movemask_ps(absfV); if(test2&7) return 0; return 1; } } #endif #endif PxIntBool BV4_RaycastSingle(const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxGeomRaycastHit* PX_RESTRICT hit, float maxDist, float geomEpsilon, PxU32 flags, PxHitFlags hitFlags) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); RayParams Params; setupRayParams(&Params, origin, dir, &tree, worldm_Aligned, mesh, maxDist, geomEpsilon, flags); if(tree.mNodes) { if(Params.mEarlyExit) processStreamRayNoOrder<0, LeafFunction_RaycastAny>(tree, &Params); else processStreamRayOrdered<0, LeafFunction_RaycastClosest>(tree, &Params); } else doBruteForceTests<LeafFunction_RaycastAny, LeafFunction_RaycastClosest>(mesh->getNbTriangles(), &Params); return computeImpactData(hit, &Params, worldm_Aligned, hitFlags); } // Callback-based version namespace { struct RayParamsCB : RayParams { MeshRayCallback mCallback; void* mUserData; }; class LeafFunction_RaycastCB { public: static PxIntBool doLeafTest(RayParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& StabbedFace = reinterpret_cast<PxGeomRaycastHit&>(buffer); if(RayTriOverlapT<RayParams>(StabbedFace, p0, p1, p2, params)) { if(StabbedFace.distance<params->mStabbedFace.mDistance) { HitCode Code = (params->mCallback)(params->mUserData, p0, p1, p2, primIndex, StabbedFace.distance, StabbedFace.u, StabbedFace.v); if(Code==HIT_EXIT) return 1; } // PT: TODO: no shrinking here? (TA34704) } primIndex++; }while(nbToGo--); return 0; } }; } #include "GuBV4_ProcessStreamNoOrder_SegmentAABB.h" void BV4_RaycastCB(const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, float maxDist, float geomEpsilon, PxU32 flags, MeshRayCallback callback, void* userData) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); //### beware, some parameters in the struct aren't used RayParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupRayParams(&Params, origin, dir, &tree, worldm_Aligned, mesh, maxDist, geomEpsilon, flags); if(tree.mNodes) processStreamRayNoOrder<0, LeafFunction_RaycastCB>(tree, &Params); else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); // if(Params.mEarlyExit) // LeafFunction_BoxSweepAnyCB::doLeafTest(&Params, nbTris); // else LeafFunction_RaycastCB::doLeafTest(&Params, nbTris); } } // Raycast all namespace { struct RayParamsAll : RayParams { PX_FORCE_INLINE RayParamsAll(PxGeomRaycastHit* hits, PxU32 maxNbHits, PxU32 stride, const PxMat44* mat, PxHitFlags hitFlags) : mHits (reinterpret_cast<PxU8*>(hits)), mNbHits (0), mMaxNbHits (maxNbHits), mStride (stride), mWorld_Aligned (mat), mHitFlags (hitFlags) { } PxU8* mHits; PxU32 mNbHits; const PxU32 mMaxNbHits; const PxU32 mStride; const PxMat44* mWorld_Aligned; const PxHitFlags mHitFlags; PX_NOCOPY(RayParamsAll) }; class LeafFunction_RaycastAll { public: static /*PX_FORCE_INLINE*/ PxIntBool doLeafTest(RayParams* PX_RESTRICT p, PxU32 primIndex) { RayParamsAll* params = static_cast<RayParamsAll*>(p); PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); PxGeomRaycastHit& StabbedFace = *reinterpret_cast<PxGeomRaycastHit*>(params->mHits); if(RayTriOverlapT<RayParams>(StabbedFace, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params)) { if(StabbedFace.distance<params->mStabbedFace.mDistance) { updateParamsAfterImpact(params, primIndex, VRef0, VRef1, VRef2, StabbedFace); computeImpactData(&StabbedFace, params, params->mWorld_Aligned, params->mHitFlags); params->mNbHits++; params->mHits += params->mStride; if(params->mNbHits==params->mMaxNbHits) return 1; } } primIndex++; }while(nbToGo--); return 0; } }; } // PT: this function is not used yet, but eventually it should be PxU32 BV4_RaycastAll(const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 maxNbHits, PxU32 stride, float maxDist, float geomEpsilon, PxU32 flags, PxHitFlags hitFlags) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); RayParamsAll Params(hits, maxNbHits, stride, worldm_Aligned, hitFlags); setupRayParams(&Params, origin, dir, &tree, worldm_Aligned, mesh, maxDist, geomEpsilon, flags); if(tree.mNodes) processStreamRayNoOrder<0, LeafFunction_RaycastAll>(tree, &Params); else { PX_ASSERT(0); } return Params.mNbHits; }
25,830
C++
33.953992
262
0.707898
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuRTree.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #define RTREE_TEXT_DUMP_ENABLE 0 #if PX_P64_FAMILY #define RTREE_PAGES_PER_POOL_SLAB 16384 // preallocate all pages in first batch to make sure we stay within 32 bits for relative pointers.. this is 2 megs #else #define RTREE_PAGES_PER_POOL_SLAB 128 #endif #define INSERT_SCAN_LOOKAHEAD 1 // enable one level lookahead scan for determining which child page is best to insert a node into #define RTREE_INFLATION_EPSILON 5e-4f #include "GuRTree.h" #include "foundation/PxSort.h" #include "CmSerialize.h" #include "CmUtils.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace aos; using namespace Gu; using namespace Cm; namespace physx { namespace Gu { bool RTree::load(PxInputStream& stream, PxU32 meshVersion, bool mismatch_) // PT: 'meshVersion' is the PX_MESH_VERSION from cooked file { PX_UNUSED(meshVersion); release(); PxI8 a, b, c, d; readChunk(a, b, c, d, stream); if(a!='R' || b!='T' || c!='R' || d!='E') return false; bool mismatch; PxU32 fileVersion; if(!readBigEndianVersionNumber(stream, mismatch_, fileVersion, mismatch)) return false; readFloatBuffer(&mBoundsMin.x, 4, mismatch, stream); readFloatBuffer(&mBoundsMax.x, 4, mismatch, stream); readFloatBuffer(&mInvDiagonal.x, 4, mismatch, stream); readFloatBuffer(&mDiagonalScaler.x, 4, mismatch, stream); mPageSize = readDword(mismatch, stream); mNumRootPages = readDword(mismatch, stream); mNumLevels = readDword(mismatch, stream); mTotalNodes = readDword(mismatch, stream); mTotalPages = readDword(mismatch, stream); PxU32 unused = readDword(mismatch, stream); PX_UNUSED(unused); // backwards compatibility mPages = static_cast<RTreePage*>(PxAlignedAllocator<128>().allocate(sizeof(RTreePage)*mTotalPages, PX_FL)); PxMarkSerializedMemory(mPages, sizeof(RTreePage)*mTotalPages); for(PxU32 j=0; j<mTotalPages; j++) { readFloatBuffer(mPages[j].minx, RTREE_N, mismatch, stream); readFloatBuffer(mPages[j].miny, RTREE_N, mismatch, stream); readFloatBuffer(mPages[j].minz, RTREE_N, mismatch, stream); readFloatBuffer(mPages[j].maxx, RTREE_N, mismatch, stream); readFloatBuffer(mPages[j].maxy, RTREE_N, mismatch, stream); readFloatBuffer(mPages[j].maxz, RTREE_N, mismatch, stream); ReadDwordBuffer(mPages[j].ptrs, RTREE_N, mismatch, stream); } return true; } ///////////////////////////////////////////////////////////////////////// PxU32 RTree::computeBottomLevelCount(PxU32 multiplier) const { PxU32 topCount = 0, curCount = mNumRootPages; const RTreePage* rightMostPage = &mPages[mNumRootPages-1]; PX_ASSERT(rightMostPage); for (PxU32 level = 0; level < mNumLevels-1; level++) { topCount += curCount; PxU32 nc = rightMostPage->nodeCount(); PX_ASSERT(nc > 0 && nc <= RTREE_N); // old version pointer, up to PX_MESH_VERSION 8 PxU32 ptr = (rightMostPage->ptrs[nc-1]) * multiplier; PX_ASSERT(ptr % sizeof(RTreePage) == 0); const RTreePage* rightMostPageNext = mPages + (ptr / sizeof(RTreePage)); curCount = PxU32(rightMostPageNext - rightMostPage); rightMostPage = rightMostPageNext; } return mTotalPages - topCount; } ///////////////////////////////////////////////////////////////////////// RTree::RTree(const PxEMPTY) { mFlags |= USER_ALLOCATED; } // PX_SERIALIZATION ///////////////////////////////////////////////////////////////////////// void RTree::exportExtraData(PxSerializationContext& stream) { stream.alignData(128); stream.writeData(mPages, mTotalPages*sizeof(RTreePage)); } ///////////////////////////////////////////////////////////////////////// void RTree::importExtraData(PxDeserializationContext& context) { context.alignExtraData(128); mPages = context.readExtraData<RTreePage>(mTotalPages); } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE PxU32 RTreePage::nodeCount() const { for (int j = 0; j < RTREE_N; j ++) if (minx[j] == MX) return PxU32(j); return RTREE_N; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::clearNode(PxU32 nodeIndex) { PX_ASSERT(nodeIndex < RTREE_N); minx[nodeIndex] = miny[nodeIndex] = minz[nodeIndex] = MX; // initialize empty node with sentinels maxx[nodeIndex] = maxy[nodeIndex] = maxz[nodeIndex] = MN; ptrs[nodeIndex] = 0; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::getNode(const PxU32 nodeIndex, RTreeNodeQ& r) const { PX_ASSERT(nodeIndex < RTREE_N); r.minx = minx[nodeIndex]; r.miny = miny[nodeIndex]; r.minz = minz[nodeIndex]; r.maxx = maxx[nodeIndex]; r.maxy = maxy[nodeIndex]; r.maxz = maxz[nodeIndex]; r.ptr = ptrs[nodeIndex]; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::setEmpty(PxU32 startIndex) { PX_ASSERT(startIndex < RTREE_N); for (PxU32 j = startIndex; j < RTREE_N; j ++) clearNode(j); } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::computeBounds(RTreeNodeQ& newBounds) { RTreeValue _minx = MX, _miny = MX, _minz = MX, _maxx = MN, _maxy = MN, _maxz = MN; for (PxU32 j = 0; j < RTREE_N; j++) { if (isEmpty(j)) continue; _minx = PxMin(_minx, minx[j]); _miny = PxMin(_miny, miny[j]); _minz = PxMin(_minz, minz[j]); _maxx = PxMax(_maxx, maxx[j]); _maxy = PxMax(_maxy, maxy[j]); _maxz = PxMax(_maxz, maxz[j]); } newBounds.minx = _minx; newBounds.miny = _miny; newBounds.minz = _minz; newBounds.maxx = _maxx; newBounds.maxy = _maxy; newBounds.maxz = _maxz; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::adjustChildBounds(PxU32 index, const RTreeNodeQ& adjChild) { PX_ASSERT(index < RTREE_N); minx[index] = adjChild.minx; miny[index] = adjChild.miny; minz[index] = adjChild.minz; maxx[index] = adjChild.maxx; maxy[index] = adjChild.maxy; maxz[index] = adjChild.maxz; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::growChildBounds(PxU32 index, const RTreeNodeQ& child) { PX_ASSERT(index < RTREE_N); minx[index] = PxMin(minx[index], child.minx); miny[index] = PxMin(miny[index], child.miny); minz[index] = PxMin(minz[index], child.minz); maxx[index] = PxMax(maxx[index], child.maxx); maxy[index] = PxMax(maxy[index], child.maxy); maxz[index] = PxMax(maxz[index], child.maxz); } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::copyNode(PxU32 targetIndex, const RTreePage& sourcePage, PxU32 sourceIndex) { PX_ASSERT(targetIndex < RTREE_N); PX_ASSERT(sourceIndex < RTREE_N); minx[targetIndex] = sourcePage.minx[sourceIndex]; miny[targetIndex] = sourcePage.miny[sourceIndex]; minz[targetIndex] = sourcePage.minz[sourceIndex]; maxx[targetIndex] = sourcePage.maxx[sourceIndex]; maxy[targetIndex] = sourcePage.maxy[sourceIndex]; maxz[targetIndex] = sourcePage.maxz[sourceIndex]; ptrs[targetIndex] = sourcePage.ptrs[sourceIndex]; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreePage::setNode(PxU32 targetIndex, const RTreeNodeQ& sourceNode) { PX_ASSERT(targetIndex < RTREE_N); minx[targetIndex] = sourceNode.minx; miny[targetIndex] = sourceNode.miny; minz[targetIndex] = sourceNode.minz; maxx[targetIndex] = sourceNode.maxx; maxy[targetIndex] = sourceNode.maxy; maxz[targetIndex] = sourceNode.maxz; ptrs[targetIndex] = sourceNode.ptr; } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreeNodeQ::grow(const RTreePage& page, int nodeIndex) { PX_ASSERT(nodeIndex < RTREE_N); minx = PxMin(minx, page.minx[nodeIndex]); miny = PxMin(miny, page.miny[nodeIndex]); minz = PxMin(minz, page.minz[nodeIndex]); maxx = PxMax(maxx, page.maxx[nodeIndex]); maxy = PxMax(maxy, page.maxy[nodeIndex]); maxz = PxMax(maxz, page.maxz[nodeIndex]); } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreeNodeQ::grow(const RTreeNodeQ& node) { minx = PxMin(minx, node.minx); miny = PxMin(miny, node.miny); minz = PxMin(minz, node.minz); maxx = PxMax(maxx, node.maxx); maxy = PxMax(maxy, node.maxy); maxz = PxMax(maxz, node.maxz); } ///////////////////////////////////////////////////////////////////////// void RTree::validateRecursive(PxU32 level, RTreeNodeQ parentBounds, RTreePage* page, CallbackRefit* cbLeaf) { PX_UNUSED(parentBounds); static PxU32 validateCounter = 0; // this is to suppress a warning that recursive call has no side effects validateCounter++; RTreeNodeQ n; PxU32 pageNodeCount = page->nodeCount(); for (PxU32 j = 0; j < pageNodeCount; j++) { page->getNode(j, n); if (page->isEmpty(j)) continue; PX_ASSERT(n.minx >= parentBounds.minx); PX_ASSERT(n.miny >= parentBounds.miny); PX_ASSERT(n.minz >= parentBounds.minz); PX_ASSERT(n.maxx <= parentBounds.maxx); PX_ASSERT(n.maxy <= parentBounds.maxy); PX_ASSERT(n.maxz <= parentBounds.maxz); if (!n.isLeaf()) { PX_ASSERT((n.ptr&1) == 0); RTreePage* childPage = reinterpret_cast<RTreePage*>(size_t(mPages) + n.ptr); validateRecursive(level+1, n, childPage, cbLeaf); } else if (cbLeaf) { Vec3V mnv, mxv; cbLeaf->recomputeBounds(page->ptrs[j] & ~1, mnv, mxv); PxVec3 mn3, mx3; V3StoreU(mnv, mn3); V3StoreU(mxv, mx3); const PxBounds3 lb(mn3, mx3); const PxVec3& mn = lb.minimum; const PxVec3& mx = lb.maximum; PX_UNUSED(mn); PX_UNUSED(mx); PX_ASSERT(mn.x >= n.minx); PX_ASSERT(mn.y >= n.miny); PX_ASSERT(mn.z >= n.minz); PX_ASSERT(mx.x <= n.maxx); PX_ASSERT(mx.y <= n.maxy); PX_ASSERT(mx.z <= n.maxz); } } RTreeNodeQ recomputedBounds; page->computeBounds(recomputedBounds); PX_ASSERT((recomputedBounds.minx - parentBounds.minx)<=RTREE_INFLATION_EPSILON); PX_ASSERT((recomputedBounds.miny - parentBounds.miny)<=RTREE_INFLATION_EPSILON); PX_ASSERT((recomputedBounds.minz - parentBounds.minz)<=RTREE_INFLATION_EPSILON); PX_ASSERT((recomputedBounds.maxx - parentBounds.maxx)<=RTREE_INFLATION_EPSILON); PX_ASSERT((recomputedBounds.maxy - parentBounds.maxy)<=RTREE_INFLATION_EPSILON); PX_ASSERT((recomputedBounds.maxz - parentBounds.maxz)<=RTREE_INFLATION_EPSILON); } ///////////////////////////////////////////////////////////////////////// void RTree::validate(CallbackRefit* cbLeaf) { for (PxU32 j = 0; j < mNumRootPages; j++) { RTreeNodeQ rootBounds; mPages[j].computeBounds(rootBounds); validateRecursive(0, rootBounds, mPages+j, cbLeaf); } } void RTree::refitAllStaticTree(CallbackRefit& cb, PxBounds3* retBounds) { PxU8* treeNodes8 = reinterpret_cast<PxU8*>(mPages); // since pages are ordered we can scan back to front and the hierarchy will be updated for (PxI32 iPage = PxI32(mTotalPages)-1; iPage>=0; iPage--) { RTreePage& page = mPages[iPage]; for (PxU32 j = 0; j < RTREE_N; j++) { if (page.isEmpty(j)) continue; if (page.isLeaf(j)) { Vec3V childMn, childMx; cb.recomputeBounds(page.ptrs[j]-1, childMn, childMx); // compute the bound around triangles PxVec3 mn3, mx3; V3StoreU(childMn, mn3); V3StoreU(childMx, mx3); page.minx[j] = mn3.x; page.miny[j] = mn3.y; page.minz[j] = mn3.z; page.maxx[j] = mx3.x; page.maxy[j] = mx3.y; page.maxz[j] = mx3.z; } else { const RTreePage* child = reinterpret_cast<const RTreePage*>(treeNodes8 + page.ptrs[j]); PX_COMPILE_TIME_ASSERT(RTREE_N == 4); bool first = true; for (PxU32 k = 0; k < RTREE_N; k++) { if (child->isEmpty(k)) continue; if (first) { page.minx[j] = child->minx[k]; page.miny[j] = child->miny[k]; page.minz[j] = child->minz[k]; page.maxx[j] = child->maxx[k]; page.maxy[j] = child->maxy[k]; page.maxz[j] = child->maxz[k]; first = false; } else { page.minx[j] = PxMin(page.minx[j], child->minx[k]); page.miny[j] = PxMin(page.miny[j], child->miny[k]); page.minz[j] = PxMin(page.minz[j], child->minz[k]); page.maxx[j] = PxMax(page.maxx[j], child->maxx[k]); page.maxy[j] = PxMax(page.maxy[j], child->maxy[k]); page.maxz[j] = PxMax(page.maxz[j], child->maxz[k]); } } } } } if (retBounds) { RTreeNodeQ bound1; for (PxU32 ii = 0; ii<mNumRootPages; ii++) { mPages[ii].computeBounds(bound1); if (ii == 0) { retBounds->minimum = PxVec3(bound1.minx, bound1.miny, bound1.minz); retBounds->maximum = PxVec3(bound1.maxx, bound1.maxy, bound1.maxz); } else { retBounds->minimum = retBounds->minimum.minimum(PxVec3(bound1.minx, bound1.miny, bound1.minz)); retBounds->maximum = retBounds->maximum.maximum(PxVec3(bound1.maxx, bound1.maxy, bound1.maxz)); } } } #if PX_CHECKED validate(&cb); #endif } //~PX_SERIALIZATION const RTreeValue RTreePage::MN = -PX_MAX_F32; const RTreeValue RTreePage::MX = PX_MAX_F32; } // namespace Gu }
14,595
C++
34.77451
154
0.645221
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_OBBSweep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuBV4_BoxSweep_Internal.h" PxIntBool Sweep_AABB_BV4(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags); void GenericSweep_AABB_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, MeshSweepCallback callback, void* userData, PxU32 flags); void Sweep_AABB_BV4_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting); // PT: TODO: optimize this (TA34704) static PX_FORCE_INLINE void computeLocalData(Box& localBox, PxVec3& localDir, const Box& box, const PxVec3& dir, const PxMat44* PX_RESTRICT worldm_Aligned) { if(worldm_Aligned) { PxMat44 IWM; invertPRMatrix(&IWM, worldm_Aligned); localDir = IWM.rotate(dir); rotateBox(localBox, IWM, box); } else { localDir = dir; localBox = box; // PT: TODO: check asm for operator= (TA34704) } } static PX_FORCE_INLINE bool isAxisAligned(const PxVec3& axis) { const PxReal minLimit = 1e-3f; const PxReal maxLimit = 1.0f - 1e-3f; const PxReal absX = PxAbs(axis.x); if(absX>minLimit && absX<maxLimit) return false; const PxReal absY = PxAbs(axis.y); if(absY>minLimit && absY<maxLimit) return false; const PxReal absZ = PxAbs(axis.z); if(absZ>minLimit && absZ<maxLimit) return false; return true; } static PX_FORCE_INLINE bool isAABB(const Box& box) { if(!isAxisAligned(box.rot.column0)) return false; if(!isAxisAligned(box.rot.column1)) return false; if(!isAxisAligned(box.rot.column2)) return false; return true; } PxIntBool BV4_BoxSweepSingle(const Box& box, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepHit* PX_RESTRICT hit, PxU32 flags) { Box localBox; PxVec3 localDir; computeLocalData(localBox, localDir, box, dir, worldm_Aligned); PxIntBool Status; if(isAABB(localBox)) Status = Sweep_AABB_BV4(localBox, localDir, maxDist, tree, hit, flags); else Status = Sweep_OBB_BV4(localBox, localDir, maxDist, tree, hit, flags); if(Status && worldm_Aligned) { // Move to world space // PT: TODO: optimize (TA34704) hit->mPos = worldm_Aligned->transform(hit->mPos); hit->mNormal = worldm_Aligned->rotate(hit->mNormal); } return Status; } // PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB(). void BV4_BoxSweepCB(const Box& box, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting) { Box localBox; PxVec3 localDir; computeLocalData(localBox, localDir, box, dir, worldm_Aligned); if(isAABB(localBox)) Sweep_AABB_BV4_CB(localBox, localDir, maxDist, tree, worldm_Aligned, callback, userData, flags, nodeSorting); else Sweep_OBB_BV4_CB(localBox, localDir, maxDist, tree, worldm_Aligned, callback, userData, flags, nodeSorting); } // PT: this generic sweep uses an OBB because this is the most versatile volume, but it does not mean this function is // a "box sweep function" per-se. In fact it could be used all alone to implement all sweeps in the SDK (but that would // have an impact on performance). // // So the idea here is simply to provide and use a generic function for everything that the BV4 code does not support directly. // In particular this should be used: // - for convex sweeps (where the OBB is the box around the swept convex) // - for non-trivial sphere/capsule/box sweeps where mesh scaling or inflation // // By design we don't do leaf tests inside the BV4 traversal code here (because we don't support them, e.g. convex // sweeps. If we could do them inside the BV4 traversal code, like we do for regular sweeps, then this would not be a generic // sweep function, but instead a built-in, natively supported query). So the leaf tests are performed outside of BV4, in the // client code, through MeshSweepCallback. This has a direct impact on the design & parameters of MeshSweepCallback. // // On the other hand this is used for "regular sweeps with shapes we don't natively support", i.e. SweepSingle kind of queries. // This means that we need to support an early-exit codepath (without node-sorting) and a regular sweep single codepath (with // node sorting) for this generic function. The leaf tests are external, but everything traversal-related should be exactly the // same as the regular box-sweep function otherwise. // // As a consequence, this function is not well-suited to implement "unlimited results" kind of queries, a.k.a. "sweep all": // // - for regular sphere/capsule/box "sweep all" queries, the leaf tests should be internal (same as sweep single queries). This // means the existing MeshSweepCallback can't be reused. // // - there is no need to support "sweep any" (it is already supported by the other sweep functions). // // - there may be no need for ordered traversal/node sorting/ray shrinking, since we want to return all results anyway. But this // may not be true if the "sweep all" function is used to emulate the Epic Tweak. In that case we still want to shrink the ray // and use node sorting. Since both versions are useful, we should probably have a bool param to enable/disable node sorting. // // - we are interested in all hits so we can't delay the computation of impact data (computing it only once in the end, for the // closest hit). We actually need to compute the data for all hits, possibly within the traversal code. void BV4_GenericSweepCB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, MeshSweepCallback callback, void* userData, bool anyHit) { const PxU32 flags = anyHit ? PxU32(QUERY_MODIFIER_ANY_HIT) : 0; if(isAABB(localBox)) GenericSweep_AABB_CB(localBox, localDir, maxDist, tree, callback, userData, flags); else GenericSweep_OBB_CB(localBox, localDir, maxDist, tree, callback, userData, flags); }
7,852
C++
45.744047
227
0.752674
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuMidphaseInterface.h" #include "GuTetrahedronMesh.h" #include "GuBox.h" using namespace physx; using namespace Gu; void TetrahedronMesh::onRefCountZero() { if (mMeshFactory) { ::onRefCountZero(this, mMeshFactory, false, "PxTetrahedronMesh::release: double deletion detected!"); } } void SoftBodyMesh::onRefCountZero() { if (mMeshFactory) { ::onRefCountZero(this, mMeshFactory, false, "PxSoftBodyMesh::release: double deletion detected!"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SoftBodyAuxData::SoftBodyAuxData(SoftBodySimulationData& d, SoftBodyCollisionData& c, CollisionMeshMappingData& e) : PxSoftBodyAuxData(PxType(PxConcreteType::eSOFT_BODY_STATE), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mGridModelInvMass(d.mGridModelInvMass) , mGridModelTetraRestPoses(d.mGridModelTetraRestPoses) , mGridModelOrderedTetrahedrons(d.mGridModelOrderedTetrahedrons) , mGMNbPartitions(d.mGridModelNbPartitions) , mGMMaxMaxTetsPerPartitions(d.mGridModelMaxTetsPerPartitions) , mGMRemapOutputSize(d.mGMRemapOutputSize) , mGMRemapOutputCP(d.mGMRemapOutputCP) , mGMAccumulatedPartitionsCP(d.mGMAccumulatedPartitionsCP) , mGMAccumulatedCopiesCP(d.mGMAccumulatedCopiesCP) , mCollisionAccumulatedTetrahedronsRef(e.mCollisionAccumulatedTetrahedronsRef) , mCollisionTetrahedronsReferences(e.mCollisionTetrahedronsReferences) , mCollisionNbTetrahedronsReferences(e.mCollisionNbTetrahedronsReferences) , mCollisionSurfaceVertsHint(e.mCollisionSurfaceVertsHint) , mCollisionSurfaceVertToTetRemap(e.mCollisionSurfaceVertToTetRemap) , mVertsBarycentricInGridModel(e.mVertsBarycentricInGridModel) , mVertsRemapInGridModel(e.mVertsRemapInGridModel) , mTetsRemapColToSim(e.mTetsRemapColToSim) , mTetsRemapSize(e.mTetsRemapSize) , mTetsAccumulatedRemapColToSim(e.mTetsAccumulatedRemapColToSim) , mGMPullIndices(d.mGMPullIndices) , mTetraRestPoses(c.mTetraRestPoses) , mNumTetsPerElement(d.mNumTetsPerElement) { // this constructor takes ownership of memory from the data object d.mGridModelInvMass = 0; d.mGridModelTetraRestPoses = 0; d.mGridModelOrderedTetrahedrons = 0; d.mGMRemapOutputCP = 0; d.mGMAccumulatedPartitionsCP = 0; d.mGMAccumulatedCopiesCP = 0; e.mCollisionAccumulatedTetrahedronsRef = 0; e.mCollisionTetrahedronsReferences = 0; e.mCollisionSurfaceVertsHint = 0; e.mCollisionSurfaceVertToTetRemap = 0; d.mGMPullIndices = 0; e.mVertsBarycentricInGridModel = 0; e.mVertsRemapInGridModel = 0; e.mTetsRemapColToSim = 0; e.mTetsAccumulatedRemapColToSim = 0; c.mTetraRestPoses = 0; } SoftBodyAuxData::~SoftBodyAuxData() { PX_FREE(mGridModelInvMass); PX_FREE(mGridModelTetraRestPoses); PX_FREE(mGridModelOrderedTetrahedrons); PX_FREE(mGMRemapOutputCP); PX_FREE(mGMAccumulatedPartitionsCP); PX_FREE(mGMAccumulatedCopiesCP); PX_FREE(mCollisionAccumulatedTetrahedronsRef); PX_FREE(mCollisionTetrahedronsReferences); PX_FREE(mCollisionSurfaceVertsHint); PX_FREE(mCollisionSurfaceVertToTetRemap); PX_FREE(mVertsBarycentricInGridModel); PX_FREE(mVertsRemapInGridModel); PX_FREE(mTetsRemapColToSim); PX_FREE(mTetsAccumulatedRemapColToSim); PX_FREE(mGMPullIndices); PX_FREE(mTetraRestPoses); } TetrahedronMesh::TetrahedronMesh(PxU32 nbVertices, PxVec3* vertices, PxU32 nbTetrahedrons, void* tetrahedrons, PxU8 flags, PxBounds3 aabb, PxReal geomEpsilon) : PxTetrahedronMesh(PxType(PxConcreteType::eTETRAHEDRON_MESH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mNbVertices(nbVertices) , mVertices(vertices) , mNbTetrahedrons(nbTetrahedrons) , mTetrahedrons(tetrahedrons) , mFlags(flags) , mMaterialIndices(NULL) , mAABB(aabb) , mGeomEpsilon(geomEpsilon) { } TetrahedronMesh::TetrahedronMesh(TetrahedronMeshData& mesh) : PxTetrahedronMesh(PxType(PxConcreteType::eTETRAHEDRON_MESH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mNbVertices(mesh.mNbVertices) , mVertices(mesh.mVertices) , mNbTetrahedrons(mesh.mNbTetrahedrons) , mTetrahedrons(mesh.mTetrahedrons) , mFlags(mesh.mFlags) , mMaterialIndices(mesh.mMaterialIndices) , mAABB(mesh.mAABB) , mGeomEpsilon(mesh.mGeomEpsilon) { // this constructor takes ownership of memory from the data object mesh.mVertices = 0; mesh.mTetrahedrons = 0; mesh.mMaterialIndices = 0; } TetrahedronMesh::TetrahedronMesh(MeshFactory* meshFactory, TetrahedronMeshData& mesh) : PxTetrahedronMesh(PxType(PxConcreteType::eTETRAHEDRON_MESH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mNbVertices(mesh.mNbVertices) , mVertices(mesh.mVertices) , mNbTetrahedrons(mesh.mNbTetrahedrons) , mTetrahedrons(mesh.mTetrahedrons) , mFlags(mesh.mFlags) , mMaterialIndices(mesh.mMaterialIndices) , mAABB(mesh.mAABB) , mGeomEpsilon(mesh.mGeomEpsilon) , mMeshFactory(meshFactory) { // this constructor takes ownership of memory from the data object mesh.mVertices = 0; mesh.mTetrahedrons = 0; mesh.mMaterialIndices = 0; } TetrahedronMesh::~TetrahedronMesh() { PX_FREE(mTetrahedrons); PX_FREE(mVertices); PX_FREE(mMaterialIndices); } BVTetrahedronMesh::BVTetrahedronMesh(TetrahedronMeshData& mesh, SoftBodyCollisionData& d, MeshFactory* factory) : TetrahedronMesh(mesh) , mFaceRemap(d.mFaceRemap) , mGRB_tetraIndices(d.mGRB_primIndices) , mGRB_tetraSurfaceHint(d.mGRB_tetraSurfaceHint) , mGRB_faceRemap(d.mGRB_faceRemap) , mGRB_faceRemapInverse(d.mGRB_faceRemapInverse) , mGRB_BV32Tree(d.mGRB_BV32Tree) { mMeshFactory = factory; bool has16BitIndices = (mesh.mFlags & PxMeshFlag::e16_BIT_INDICES) ? true : false; mMeshInterface4.mVerts = mVertices; // mesh.mVertices; mMeshInterface4.mNbVerts = mesh.mNbVertices; mMeshInterface4.mNbTetrahedrons = mesh.mNbTetrahedrons; mMeshInterface4.mTetrahedrons16 = has16BitIndices ? reinterpret_cast<IndTetrahedron16*>(mTetrahedrons/*mesh.mTetrahedrons*/) : NULL; mMeshInterface4.mTetrahedrons32 = has16BitIndices ? NULL : reinterpret_cast<IndTetrahedron32*>(mTetrahedrons/*mesh.mTetrahedrons*/); mBV4Tree = d.mBV4Tree; mBV4Tree.mMeshInterface = &mMeshInterface4; if (mGRB_BV32Tree) { mMeshInterface32.mVerts = mVertices; // mesh.mVertices; mMeshInterface32.mNbVerts = mesh.mNbVertices; mMeshInterface32.mNbTetrahedrons = mesh.mNbTetrahedrons; mMeshInterface32.mTetrahedrons16 = has16BitIndices ? reinterpret_cast<IndTetrahedron16*>(d.mGRB_primIndices) : NULL; mMeshInterface32.mTetrahedrons32 = has16BitIndices ? NULL : reinterpret_cast<IndTetrahedron32*>(d.mGRB_primIndices); mGRB_BV32Tree->mMeshInterface = &mMeshInterface32; } // this constructor takes ownership of memory from the data object d.mGRB_tetraSurfaceHint = NULL; d.mFaceRemap = NULL; d.mGRB_primIndices = NULL; d.mGRB_faceRemap = NULL; d.mGRB_faceRemapInverse = NULL; d.mGRB_BV32Tree = NULL; mesh.mVertices = NULL; mesh.mTetrahedrons = NULL; } SoftBodyMesh::SoftBodyMesh(MeshFactory* factory, SoftBodyMeshData& d) : PxSoftBodyMesh(PxType(PxConcreteType::eSOFTBODY_MESH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mMeshFactory(factory) { mSoftBodyAuxData = PX_NEW(SoftBodyAuxData)(d.mSimulationData, d.mCollisionData, d.mMappingData); mCollisionMesh = PX_NEW(BVTetrahedronMesh)(d.mCollisionMesh, d.mCollisionData, factory); mSimulationMesh = PX_NEW(TetrahedronMesh)(factory, d.mSimulationMesh); } SoftBodyMesh::~SoftBodyMesh() { if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { PX_DELETE(mSoftBodyAuxData); PX_DELETE(mCollisionMesh); PX_DELETE(mSimulationMesh); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PT: used to be automatic but making it manual saves bytes in the internal mesh void SoftBodyMesh::exportExtraData(PxSerializationContext& stream) { //PX_DEFINE_DYNAMIC_ARRAY(TriangleMesh, mVertices, PxField::eVEC3, mNbVertices, Ps::PxFieldFlag::eSERIALIZE), if (getCollisionMeshFast()->mVertices) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(getCollisionMeshFast()->mVertices, getCollisionMeshFast()->mNbVertices * sizeof(PxVec3)); } /*if (mSurfaceTriangles) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mSurfaceTriangles, mNbTriangles * 3 * sizeof(PxU32)); }*/ if (getCollisionMeshFast()->mTetrahedrons) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(getCollisionMeshFast()->mTetrahedrons, getCollisionMeshFast()->mNbTetrahedrons * 4 * sizeof(PxU32)); } /*if (mTetSurfaceHint) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mTetSurfaceHint, mNbTetrahedrons * sizeof(PxU8)); }*/ if (getCollisionMeshFast()->mMaterialIndices) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(getCollisionMeshFast()->mMaterialIndices, getCollisionMeshFast()->mNbTetrahedrons * sizeof(PxU16)); } if (getCollisionMeshFast()->mFaceRemap) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(getCollisionMeshFast()->mFaceRemap, getCollisionMeshFast()->mNbTetrahedrons * sizeof(PxU32)); } } void SoftBodyMesh::importExtraData(PxDeserializationContext& context) { // PT: vertices are followed by indices, so it will be safe to V4Load vertices from a deserialized binary file if (getCollisionMeshFast()->mVertices) getCollisionMeshFast()->mVertices = context.readExtraData<PxVec3, PX_SERIAL_ALIGN>(getCollisionMeshFast()->mNbVertices); if (getCollisionMeshFast()->mTetrahedrons) getCollisionMeshFast()->mTetrahedrons = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(4 * getCollisionMeshFast()->mNbTetrahedrons); if (getCollisionMeshFast()->mFaceRemap) getCollisionMeshFast()->mFaceRemap = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(getCollisionMeshFast()->mNbTetrahedrons); getCollisionMeshFast()->mGRB_tetraIndices = NULL; getCollisionMeshFast()->mGRB_tetraSurfaceHint = NULL; getCollisionMeshFast()->mGRB_faceRemap = NULL; getCollisionMeshFast()->mGRB_faceRemapInverse = NULL; getCollisionMeshFast()->mGRB_BV32Tree = NULL; } void SoftBodyMesh::release() { Cm::RefCountable_decRefCount(*this); } //PxVec3* TetrahedronMesh::getVerticesForModification() //{ // PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxSoftBodyMesh::getVerticesForModification() is not currently supported."); // // return NULL; //} //PxBounds3 BVTetrahedronMesh::refitBVH() //{ // PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxSoftBodyMesh::refitBVH() is not currently supported."); // // return PxBounds3(mAABB.getMin(), mAABB.getMax()); //}
12,332
C++
36.947692
199
0.761596
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuOverlapTestsMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxSphereGeometry.h" #include "GuMidphaseInterface.h" #include "CmScaling.h" #include "GuSphere.h" #include "GuInternal.h" #include "GuConvexUtilsInternal.h" #include "GuVecTriangle.h" #include "GuVecConvexHull.h" #include "GuConvexMesh.h" #include "GuGJK.h" #include "GuSweepSharedTests.h" #include "CmMatrix34.h" using namespace physx; using namespace Cm; using namespace Gu; using namespace physx::aos; bool GeomOverlapCallback_SphereMesh(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eSPHERE); PX_ASSERT(geom1.getType()==PxGeometryType::eTRIANGLEMESH); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom1); const Sphere worldSphere(pose0.p, sphereGeom.radius); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); return Midphase::intersectSphereVsMesh(worldSphere, *meshData, pose1, meshGeom.scale, NULL); } bool GeomOverlapCallback_CapsuleMesh(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eCAPSULE); PX_ASSERT(geom1.getType()==PxGeometryType::eTRIANGLEMESH); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom0); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom1); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); Capsule capsule; getCapsule(capsule, capsuleGeom, pose0); return Midphase::intersectCapsuleVsMesh(capsule, *meshData, pose1, meshGeom.scale, NULL); } bool GeomOverlapCallback_BoxMesh(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eBOX); PX_ASSERT(geom1.getType()==PxGeometryType::eTRIANGLEMESH); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom0); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom1); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); Box box; buildFrom(box, pose0.p, boxGeom.halfExtents, pose0.q); return Midphase::intersectBoxVsMesh(box, *meshData, pose1, meshGeom.scale, NULL); } /////////////////////////////////////////////////////////////////////////////// namespace { struct ConvexVsMeshOverlapCallback : MeshHitCallback<PxGeomRaycastHit> { PxMatTransformV MeshToBoxV; Vec3V boxExtents; ConvexVsMeshOverlapCallback( const ConvexMesh& cm, const PxMeshScale& convexScale, const FastVertex2ShapeScaling& meshScale, const PxTransform& tr0, const PxTransform& tr1, bool identityScale, const Box& meshSpaceOBB) : MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE), mAnyHit (false), mIdentityScale (identityScale) { if (!identityScale) // not done in initializer list for performance mMeshScale = aos::Mat33V( V3LoadU(meshScale.getVertex2ShapeSkew().column0), V3LoadU(meshScale.getVertex2ShapeSkew().column1), V3LoadU(meshScale.getVertex2ShapeSkew().column2) ); using namespace aos; const ConvexHullData* hullData = &cm.getHull(); const Vec3V vScale0 = V3LoadU_SafeReadW(convexScale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat0 = QuatVLoadU(&convexScale.rotation.x); mConvex = ConvexHullV(hullData, V3Zero(), vScale0, vQuat0, convexScale.isIdentity()); aToB = PxMatTransformV(tr0.transformInv(tr1)); { // Move to AABB space PxMat34 MeshToBox; computeWorldToBoxMatrix(MeshToBox, meshSpaceOBB); const Vec3V base0 = V3LoadU(MeshToBox.m.column0); const Vec3V base1 = V3LoadU(MeshToBox.m.column1); const Vec3V base2 = V3LoadU(MeshToBox.m.column2); const Mat33V matV(base0, base1, base2); const Vec3V p = V3LoadU(MeshToBox.p); MeshToBoxV = PxMatTransformV(p, matV); boxExtents = V3LoadU(meshSpaceOBB.extents+PxVec3(0.001f)); } } virtual ~ConvexVsMeshOverlapCallback() {} virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit&, const PxVec3& v0a, const PxVec3& v1a, const PxVec3& v2a, PxReal&, const PxU32*) { using namespace aos; Vec3V v0 = V3LoadU(v0a); Vec3V v1 = V3LoadU(v1a); Vec3V v2 = V3LoadU(v2a); // test triangle AABB in box space vs box AABB in box local space { const Vec3V triV0 = MeshToBoxV.transform(v0); // AP: MeshToBoxV already includes mesh scale so we have to use unscaled verts here const Vec3V triV1 = MeshToBoxV.transform(v1); const Vec3V triV2 = MeshToBoxV.transform(v2); const Vec3V triMn = V3Min(V3Min(triV0, triV1), triV2); const Vec3V triMx = V3Max(V3Max(triV0, triV1), triV2); const Vec3V negExtents = V3Neg(boxExtents); const BoolV minSeparated = V3IsGrtr(triMn, boxExtents), maxSeparated = V3IsGrtr(negExtents, triMx); const BoolV bSeparated = BAnyTrue3(BOr(minSeparated, maxSeparated)); if(BAllEqTTTT(bSeparated)) return true; // continue traversal } if(!mIdentityScale) { v0 = M33MulV3(mMeshScale, v0); v1 = M33MulV3(mMeshScale, v1); v2 = M33MulV3(mMeshScale, v2); } TriangleV triangle(v0, v1, v2); Vec3V contactA, contactB, normal; FloatV dist; const RelativeConvex<TriangleV> convexA(triangle, aToB); const LocalConvex<ConvexHullV> convexB(mConvex); const GjkStatus status = gjk(convexA, convexB, aToB.p, FZero(), contactA, contactB, normal, dist); if(status == GJK_CONTACT || status == GJK_CLOSE)// || FAllGrtrOrEq(mSqTolerance, sqDist)) { mAnyHit = true; return false; // abort traversal } return true; // continue traversal } ConvexHullV mConvex; PxMatTransformV aToB; aos::Mat33V mMeshScale; bool mAnyHit; const bool mIdentityScale; private: ConvexVsMeshOverlapCallback& operator=(const ConvexVsMeshOverlapCallback&); }; } // PT: TODO: refactor bits of this with convex-vs-mesh code bool GeomOverlapCallback_ConvexMesh(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eCONVEXMESH); PX_ASSERT(geom1.getType()==PxGeometryType::eTRIANGLEMESH); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom1); ConvexMesh* cm = static_cast<ConvexMesh*>(convexGeom.convexMesh); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); const bool idtScaleConvex = convexGeom.scale.isIdentity(); const bool idtScaleMesh = meshGeom.scale.isIdentity(); FastVertex2ShapeScaling convexScaling; if (!idtScaleConvex) convexScaling.init(convexGeom.scale); FastVertex2ShapeScaling meshScaling; if (!idtScaleMesh) meshScaling.init(meshGeom.scale); PX_ASSERT(!cm->getLocalBoundsFast().isEmpty()); const PxBounds3 hullAABB = cm->getLocalBoundsFast().transformFast(convexScaling.getVertex2ShapeSkew()); Box hullOBB; { const Matrix34FromTransform world0(pose0); const Matrix34FromTransform world1(pose1); computeHullOBB(hullOBB, hullAABB, 0.0f, world0, world1, meshScaling, idtScaleMesh); } ConvexVsMeshOverlapCallback cb(*cm, convexGeom.scale, meshScaling, pose0, pose1, idtScaleMesh, hullOBB); Midphase::intersectOBB(meshData, hullOBB, cb, true, false); return cb.mAnyHit; } /////////////////////////////////////////////////////////////////////////////// bool GeomOverlapCallback_MeshMesh(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eTRIANGLEMESH); PX_ASSERT(geom1.getType()==PxGeometryType::eTRIANGLEMESH); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxTriangleMeshGeometry& meshGeom0 = static_cast<const PxTriangleMeshGeometry&>(geom0); const PxTriangleMeshGeometry& meshGeom1 = static_cast<const PxTriangleMeshGeometry&>(geom1); const TriangleMesh* tm0 = static_cast<const TriangleMesh*>(meshGeom0.triangleMesh); const TriangleMesh* tm1 = static_cast<const TriangleMesh*>(meshGeom1.triangleMesh); // PT: only implemented for BV4 if(!tm0 || !tm1 || tm0->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34 || tm1->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34) return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxGeometryQuery::overlap(): only available between two BVH34 triangles meshes."); class AnyHitReportCallback : public PxReportCallback<PxGeomIndexPair> { public: AnyHitReportCallback() { mCapacity = 1; } virtual bool flushResults(PxU32, const PxGeomIndexPair*) { return false; } }; AnyHitReportCallback callback; // PT: ...so we don't need a table like for the other ops, just go straight to BV4 return intersectMeshVsMesh_BV4(callback, *tm0, pose0, meshGeom0.scale, *tm1, pose1, meshGeom1.scale, PxMeshMeshQueryFlag::eDEFAULT, 0.0f); }
10,568
C++
37.017985
155
0.75123
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuSweepsMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuSweepTests.h" #include "GuSweepMesh.h" #include "GuInternal.h" #include "GuConvexUtilsInternal.h" #include "CmScaling.h" #include "GuSweepMTD.h" #include "GuVecBox.h" #include "GuVecCapsule.h" #include "GuSweepBoxTriangle_SAT.h" #include "GuSweepCapsuleTriangle.h" #include "GuSweepSphereTriangle.h" #include "GuDistancePointTriangle.h" #include "GuCapsule.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace physx::aos; #include "GuSweepConvexTri.h" /////////////////////////////////////////////////////////////////////////////// static bool sweepSphereTriangle(const PxTriangle& tri, const PxVec3& center, PxReal radius, const PxVec3& unitDir, const PxReal distance, PxGeomSweepHit& hit, PxVec3& triNormalOut, PxHitFlags hitFlags, bool isDoubleSided) { const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; if(!(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP)) { const bool doBackfaceCulling = !isDoubleSided && !meshBothSides; // PT: test if shapes initially overlap // PT: add culling here for now, but could be made more efficiently... // Create triangle normal PxVec3 denormalizedNormal; tri.denormalizedNormal(denormalizedNormal); // Backface culling if(doBackfaceCulling && (denormalizedNormal.dot(unitDir) > 0.0f)) return false; float s_unused, t_unused; const PxVec3 cp = closestPtPointTriangle(center, tri.verts[0], tri.verts[1], tri.verts[2], s_unused, t_unused); const PxReal dist2 = (cp - center).magnitudeSquared(); if(dist2<=radius*radius) { triNormalOut = denormalizedNormal.getNormalized(); return setInitialOverlapResults(hit, unitDir, 0); } } return sweepSphereTriangles(1, &tri, center, radius, unitDir, distance, NULL, hit, triNormalOut, isDoubleSided, meshBothSides, false, false); } /////////////////////////////////////////////////////////////////////////////// SweepShapeMeshHitCallback::SweepShapeMeshHitCallback(CallbackMode::Enum inMode, const PxHitFlags& hitFlags, bool flipNormal, float distCoef) : MeshHitCallback<PxGeomRaycastHit> (inMode), mHitFlags (hitFlags), mStatus (false), mInitialOverlap (false), mFlipNormal (flipNormal), mDistCoeff (distCoef) { } /////////////////////////////////////////////////////////////////////////////// SweepCapsuleMeshHitCallback::SweepCapsuleMeshHitCallback( PxGeomSweepHit& sweepHit, const PxMat34& worldMatrix, PxReal distance, bool meshDoubleSided, const Capsule& capsule, const PxVec3& unitDir, const PxHitFlags& hitFlags, bool flipNormal, float distCoef) : SweepShapeMeshHitCallback (CallbackMode::eMULTIPLE, hitFlags, flipNormal, distCoef), mSweepHit (sweepHit), mVertexToWorldSkew (worldMatrix), mTrueSweepDistance (distance), mBestAlignmentValue (2.0f), mBestDist (distance + GU_EPSILON_SAME_DISTANCE), mCapsule (capsule), mUnitDir (unitDir), mMeshDoubleSided (meshDoubleSided), mIsSphere (capsule.p0 == capsule.p1) { mSweepHit.distance = mTrueSweepDistance; } PxAgain SweepCapsuleMeshHitCallback::processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& aHit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal& shrunkMaxT, const PxU32*) { const PxTriangle tmpt( mVertexToWorldSkew.transform(v0), mVertexToWorldSkew.transform(mFlipNormal ? v2 : v1), mVertexToWorldSkew.transform(mFlipNormal ? v1 : v2)); PxGeomSweepHit localHit; // PT: TODO: ctor! PxVec3 triNormal; // pick a farther hit within distEpsilon that is more opposing than the previous closest hit // make it a relative epsilon to make sure it still works with large distances const PxReal distEpsilon = GU_EPSILON_SAME_DISTANCE * PxMax(1.0f, mSweepHit.distance); const float minD = mSweepHit.distance + distEpsilon; if(mIsSphere) { if(!::sweepSphereTriangle( tmpt, mCapsule.p0, mCapsule.radius, mUnitDir, minD, localHit, triNormal, mHitFlags, mMeshDoubleSided)) return true; } else { // PT: this one is safe because cullbox is NULL (no need to allocate one more triangle) if(!sweepCapsuleTriangles_Precise( 1, &tmpt, mCapsule, mUnitDir, minD, NULL, localHit, triNormal, mHitFlags, mMeshDoubleSided, NULL)) return true; } const PxReal alignmentValue = computeAlignmentValue(triNormal, mUnitDir); if(keepTriangle(localHit.distance, alignmentValue, mBestDist, mBestAlignmentValue, mTrueSweepDistance)) { mBestAlignmentValue = alignmentValue; // AP: need to shrink the sweep distance passed into sweepCapsuleTriangles for correctness so that next sweep is closer shrunkMaxT = localHit.distance * mDistCoeff; // shrunkMaxT is scaled mBestDist = PxMin(mBestDist, localHit.distance); // exact lower bound mSweepHit.flags = localHit.flags; mSweepHit.distance = localHit.distance; mSweepHit.normal = localHit.normal; mSweepHit.position = localHit.position; mSweepHit.faceIndex = aHit.faceIndex; mStatus = true; //ML:this is the initial overlap condition if(localHit.distance == 0.0f) { mInitialOverlap = true; return false; } if(mHitFlags & PxHitFlag::eMESH_ANY) return false; // abort traversal } /// else if(keepTriangleBasic(localHit.distance, mBestDist, mTrueSweepDistance)) { mSweepHit.distance = localHit.distance; mBestDist = PxMin(mBestDist, localHit.distance); // exact lower bound } /// return true; } bool SweepCapsuleMeshHitCallback::finalizeHit( PxGeomSweepHit& sweepHit, const Capsule& lss, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, bool isDoubleSided) const { if(!mStatus) return false; if(mInitialOverlap) { // PT: TODO: consider using 'setInitialOverlapResults' here bool hasContacts = false; if(mHitFlags & PxHitFlag::eMTD) { const Vec3V p0 = V3LoadU(mCapsule.p0); const Vec3V p1 = V3LoadU(mCapsule.p1); const FloatV radius = FLoad(lss.radius); CapsuleV capsuleV; capsuleV.initialize(p0, p1, radius); //we need to calculate the MTD hasContacts = computeCapsule_TriangleMeshMTD(triMeshGeom, pose, capsuleV, mCapsule.radius, isDoubleSided, sweepHit); } setupSweepHitForMTD(sweepHit, hasContacts, mUnitDir); } else { mSweepHit.distance = mBestDist; sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::ePOSITION | PxHitFlag::eFACE_INDEX; } return true; } /////////////////////////////////////////////////////////////////////////////// bool sweepCapsule_MeshGeom(GU_CAPSULE_SWEEP_FUNC_PARAMS) { PX_UNUSED(threadContext); PX_UNUSED(capsuleGeom_); PX_UNUSED(capsulePose_); PX_ASSERT(geom.getType() == PxGeometryType::eTRIANGLEMESH); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); return Midphase::sweepCapsuleVsMesh(meshData, meshGeom, pose, lss, unitDir, distance, sweepHit, hitFlags, inflation); } /////////////////////////////////////////////////////////////////////////////// // same as 'mat.transform(p)' but using SIMD static PX_FORCE_INLINE Vec4V transformV(const Vec4V p, const PxMat34Padded& mat) { Vec4V ResV = V4Scale(V4LoadU(&mat.m.column0.x), V4GetX(p)); ResV = V4ScaleAdd(V4LoadU(&mat.m.column1.x), V4GetY(p), ResV); ResV = V4ScaleAdd(V4LoadU(&mat.m.column2.x), V4GetZ(p), ResV); ResV = V4Add(ResV, V4LoadU(&mat.p.x)); // PT: this load is safe thanks to padding return ResV; } /////////////////////////////////////////////////////////////////////////////// SweepBoxMeshHitCallback::SweepBoxMeshHitCallback( CallbackMode::Enum mode_, const PxMat34Padded& meshToBox, PxReal distance, bool bothTriangleSidesCollide, const Box& box, const PxVec3& localMotion, const PxVec3& localDir, const PxVec3& unitDir, const PxHitFlags& hitFlags, const PxReal inflation, bool flipNormal, float distCoef) : SweepShapeMeshHitCallback (mode_, hitFlags, flipNormal,distCoef), mMeshToBox (meshToBox), mDist (distance), mBox (box), mLocalDir (localDir), mWorldUnitDir (unitDir), mInflation (inflation), mBothTriangleSidesCollide (bothTriangleSidesCollide) { mLocalMotionV = V3LoadU(localMotion); mDistV = FLoad(distance); mDist0 = distance; mOneOverDir = PxVec3( mLocalDir.x!=0.0f ? 1.0f/mLocalDir.x : 0.0f, mLocalDir.y!=0.0f ? 1.0f/mLocalDir.y : 0.0f, mLocalDir.z!=0.0f ? 1.0f/mLocalDir.z : 0.0f); } PxAgain SweepBoxMeshHitCallback::processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& meshHit, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxReal& shrinkMaxT, const PxU32*) { if(mHitFlags & PxHitFlag::ePRECISE_SWEEP) { const PxTriangle currentTriangle( mMeshToBox.transform(lp0), mMeshToBox.transform(mFlipNormal ? lp2 : lp1), mMeshToBox.transform(mFlipNormal ? lp1 : lp2)); PxF32 t = PX_MAX_REAL; // PT: could be better! if(!triBoxSweepTestBoxSpace(currentTriangle, mBox.extents, mLocalDir, mOneOverDir, mDist, t, !mBothTriangleSidesCollide)) return true; if(t <= mDist) { // PT: test if shapes initially overlap mDist = t; shrinkMaxT = t * mDistCoeff; // shrunkMaxT is scaled mMinClosestA = V3LoadU(currentTriangle.verts[0]); // PT: this is arbitrary mMinNormal = V3LoadU(-mWorldUnitDir); mStatus = true; mMinTriangleIndex = meshHit.faceIndex; mHitTriangle = currentTriangle; if(t == 0.0f) { mInitialOverlap = true; return false; // abort traversal } } } else { const FloatV zero = FZero(); // PT: SIMD code similar to: // const Vec3V triV0 = V3LoadU(mMeshToBox.transform(lp0)); // const Vec3V triV1 = V3LoadU(mMeshToBox.transform(lp1)); // const Vec3V triV2 = V3LoadU(mMeshToBox.transform(lp2)); // // SIMD version works but we need to ensure all loads are safe. // For incoming vertices they should either come from the vertex array or from a binary deserialized file. // For the vertex array we can just allocate one more vertex. For the binary file it should be ok as soon // as vertices aren't the last thing serialized in the file. // For the matrix only the last column is a problem, and we can easily solve that with some padding in the local class. const Vec3V triV0 = Vec3V_From_Vec4V(transformV(V4LoadU(&lp0.x), mMeshToBox)); const Vec3V triV1 = Vec3V_From_Vec4V(transformV(V4LoadU(mFlipNormal ? &lp2.x : &lp1.x), mMeshToBox)); const Vec3V triV2 = Vec3V_From_Vec4V(transformV(V4LoadU(mFlipNormal ? &lp1.x : &lp2.x), mMeshToBox)); if(!mBothTriangleSidesCollide) { const Vec3V triNormal = V3Cross(V3Sub(triV2, triV1),V3Sub(triV0, triV1)); if(FAllGrtrOrEq(V3Dot(triNormal, mLocalMotionV), zero)) return true; } const Vec3V zeroV = V3Zero(); const Vec3V boxExtents = V3LoadU(mBox.extents); const BoxV boxV(zeroV, boxExtents); const TriangleV triangleV(triV0, triV1, triV2); FloatV lambda; Vec3V closestA, normal;//closestA and normal is in the local space of convex hull const LocalConvex<TriangleV> convexA(triangleV); const LocalConvex<BoxV> convexB(boxV); const Vec3V initialSearchDir = V3Sub(triangleV.getCenter(), boxV.getCenter()); if(!gjkRaycastPenetration<LocalConvex<TriangleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, zero, zeroV, mLocalMotionV, lambda, normal, closestA, mInflation, false)) return true; mStatus = true; mMinClosestA = closestA; mMinTriangleIndex = meshHit.faceIndex; if(FAllGrtrOrEq(zero, lambda)) // lambda < 0? => initial overlap { mInitialOverlap = true; shrinkMaxT = 0.0f; mDistV = zero; mDist = 0.0f; mMinNormal = V3LoadU(-mWorldUnitDir); return false; } PxF32 f; FStore(lambda, &f); mDist = f*mDist; // shrink dist mLocalMotionV = V3Scale(mLocalMotionV, lambda); // shrink localMotion mDistV = FMul(mDistV, lambda); // shrink distV mMinNormal = normal; if(mDist * mDistCoeff < shrinkMaxT) // shrink shrinkMaxT shrinkMaxT = mDist * mDistCoeff; // shrunkMaxT is scaled //mHitTriangle = currentTriangle; V3StoreU(triV0, mHitTriangle.verts[0]); V3StoreU(triV1, mHitTriangle.verts[1]); V3StoreU(triV2, mHitTriangle.verts[2]); } return true; } bool SweepBoxMeshHitCallback::finalizeHit( PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const PxTransform& boxTransform, const PxVec3& localDir, bool meshBothSides, bool isDoubleSided) const { if(!mStatus) return false; Vec3V minClosestA = mMinClosestA; Vec3V minNormal = mMinNormal; sweepHit.faceIndex = mMinTriangleIndex; if(mInitialOverlap) { bool hasContacts = false; if(mHitFlags & PxHitFlag::eMTD) hasContacts = computeBox_TriangleMeshMTD(triMeshGeom, pose, mBox, boxTransform, mInflation, mBothTriangleSidesCollide, sweepHit); setupSweepHitForMTD(sweepHit, hasContacts, mWorldUnitDir); } else { sweepHit.distance = mDist; sweepHit.flags = PxHitFlag::eFACE_INDEX; // PT: we need the "best triangle" normal in order to call 'shouldFlipNormal'. We stored the best // triangle in both GJK & precise codepaths (in box space). We use a dedicated 'shouldFlipNormal' // function that delays computing the triangle normal. // TODO: would still be more efficient to store the best normal directly, it's already computed at least // in the GJK codepath. const Vec3V p0 = V3LoadU(&boxTransform.p.x); const QuatV q0 = QuatVLoadU(&boxTransform.q.x); const PxTransformV boxPos(p0, q0); if(mHitFlags & PxHitFlag::ePRECISE_SWEEP) { computeBoxLocalImpact(sweepHit.position, sweepHit.normal, sweepHit.flags, mBox, localDir, mHitTriangle, mHitFlags, isDoubleSided, meshBothSides, mDist); } else { sweepHit.flags |= PxHitFlag::eNORMAL|PxHitFlag::ePOSITION; // PT: now for the GJK path, we must first always negate the returned normal. Similar to what happens in the precise path, // we can't delay this anymore: our normal must be properly oriented in order to call 'shouldFlipNormal'. minNormal = V3Neg(minNormal); // PT: this one is to ensure the normal respects the mesh-both-sides/double-sided convention PxVec3 tmp; V3StoreU(minNormal, tmp); if(shouldFlipNormal(tmp, meshBothSides, isDoubleSided, mHitTriangle, localDir, NULL)) minNormal = V3Neg(minNormal); // PT: finally, this moves everything back to world space V3StoreU(boxPos.rotate(minNormal), sweepHit.normal); V3StoreU(boxPos.transform(minClosestA), sweepHit.position); } } return true; } /////////////////////////////////////////////////////////////////////////////// bool sweepBox_MeshGeom(GU_BOX_SWEEP_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eTRIANGLEMESH); PX_UNUSED(threadContext); PX_UNUSED(boxPose_); PX_UNUSED(boxGeom_); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); return Midphase::sweepBoxVsMesh(meshData, meshGeom, pose, box, unitDir, distance, sweepHit, hitFlags, inflation); } /////////////////////////////////////////////////////////////////////////////// SweepConvexMeshHitCallback::SweepConvexMeshHitCallback( const ConvexHullData& hull, const PxMeshScale& convexScale, const FastVertex2ShapeScaling& meshScale, const PxTransform& convexPose, const PxTransform& meshPose, const PxVec3& unitDir, const PxReal distance, PxHitFlags hitFlags, const bool bothTriangleSidesCollide, const PxReal inflation, const bool anyHit, float distCoef) : SweepShapeMeshHitCallback (CallbackMode::eMULTIPLE, hitFlags, meshScale.flipsNormal(), distCoef), mMeshScale (meshScale), mUnitDir (unitDir), mInflation (inflation), mAnyHit (anyHit), mBothTriangleSidesCollide (bothTriangleSidesCollide) { mSweepHit.distance = distance; // this will be shrinking progressively as we sweep and clip the sweep length mSweepHit.faceIndex = 0xFFFFFFFF; mMeshSpaceUnitDir = meshPose.rotateInv(unitDir); const Vec3V worldDir = V3LoadU(unitDir); const FloatV dist = FLoad(distance); const QuatV q0 = QuatVLoadU(&meshPose.q.x); const Vec3V p0 = V3LoadU(&meshPose.p.x); const QuatV q1 = QuatVLoadU(&convexPose.q.x); const Vec3V p1 = V3LoadU(&convexPose.p.x); const PxTransformV meshPoseV(p0, q0); const PxTransformV convexPoseV(p1, q1); mMeshToConvex = convexPoseV.transformInv(meshPoseV); mConvexPoseV = convexPoseV; mConvexSpaceDir = convexPoseV.rotateInv(V3Neg(V3Scale(worldDir, dist))); mInitialDistance = dist; const Vec3V vScale = V3LoadU_SafeReadW(convexScale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat = QuatVLoadU(&convexScale.rotation.x); mConvexHull.initialize(&hull, V3Zero(), vScale, vQuat, convexScale.isIdentity()); } PxAgain SweepConvexMeshHitCallback::processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& hit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal& shrunkMaxT, const PxU32*) { const PxVec3 v0 = mMeshScale * av0; const PxVec3 v1 = mMeshScale * (mFlipNormal ? av2 : av1); const PxVec3 v2 = mMeshScale * (mFlipNormal ? av1 : av2); // mSweepHit will be updated if sweep distance is < input mSweepHit.distance const PxReal oldDist = mSweepHit.distance; if(sweepConvexVsTriangle( v0, v1, v2, mConvexHull, mMeshToConvex, mConvexPoseV, mConvexSpaceDir, mUnitDir, mMeshSpaceUnitDir, mInitialDistance, oldDist, mSweepHit, mBothTriangleSidesCollide, mInflation, mInitialOverlap, hit.faceIndex)) { mStatus = true; shrunkMaxT = mSweepHit.distance * mDistCoeff; // shrunkMaxT is scaled // PT: added for 'shouldFlipNormal' mHitTriangle.verts[0] = v0; mHitTriangle.verts[1] = v1; mHitTriangle.verts[2] = v2; if(mAnyHit) return false; // abort traversal if(mSweepHit.distance == 0.0f) return false; } return true; // continue traversal } bool SweepConvexMeshHitCallback::finalizeHit( PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose, const PxVec3& unitDir, PxReal inflation, bool isMtd, bool meshBothSides, bool isDoubleSided, bool bothTriangleSidesCollide) { if(!mStatus) return false; if(mInitialOverlap) { bool hasContacts = false; if(isMtd) hasContacts = computeConvex_TriangleMeshMTD(meshGeom, pose, convexGeom, convexPose, inflation, bothTriangleSidesCollide, sweepHit); setupSweepHitForMTD(sweepHit, hasContacts, unitDir); sweepHit.faceIndex = mSweepHit.faceIndex; } else { sweepHit = mSweepHit; //sweepHit.position += unitDir * sweepHit.distance; sweepHit.normal = -sweepHit.normal; sweepHit.normal.normalize(); // PT: this one is to ensure the normal respects the mesh-both-sides/double-sided convention // PT: beware, the best triangle is in mesh-space, but the impact data is in world-space already if(shouldFlipNormal(sweepHit.normal, meshBothSides, isDoubleSided, mHitTriangle, unitDir, &pose)) sweepHit.normal = -sweepHit.normal; } return true; } /////////////////////////////////////////////////////////////////////////////// bool sweepConvex_MeshGeom(GU_CONVEX_SWEEP_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eTRIANGLEMESH); PX_UNUSED(threadContext); const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom); ConvexMesh* convexMesh = static_cast<ConvexMesh*>(convexGeom.convexMesh); TriangleMesh* meshData = static_cast<TriangleMesh*>(meshGeom.triangleMesh); const bool idtScaleConvex = convexGeom.scale.isIdentity(); const bool idtScaleMesh = meshGeom.scale.isIdentity(); FastVertex2ShapeScaling convexScaling; if(!idtScaleConvex) convexScaling.init(convexGeom.scale); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(meshGeom.scale); PX_ASSERT(!convexMesh->getLocalBoundsFast().isEmpty()); const PxBounds3 hullAABB = convexMesh->getLocalBoundsFast().transformFast(convexScaling.getVertex2ShapeSkew()); Box hullOBB; computeHullOBB(hullOBB, hullAABB, 0.0f, Matrix34FromTransform(convexPose), Matrix34FromTransform(pose), meshScaling, idtScaleMesh); hullOBB.extents.x += inflation; hullOBB.extents.y += inflation; hullOBB.extents.z += inflation; const PxVec3 localDir = pose.rotateInv(unitDir); // inverse transform the sweep direction and distance to mesh space PxVec3 meshSpaceSweepVector = meshScaling.getShape2VertexSkew().transform(localDir*distance); const PxReal meshSpaceSweepDist = meshSpaceSweepVector.normalize(); PxReal distCoeff = 1.0f; if (!idtScaleMesh) distCoeff = meshSpaceSweepDist / distance; const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; const bool isDoubleSided = meshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED; const bool bothTriangleSidesCollide = isDoubleSided || meshBothSides; const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY; SweepConvexMeshHitCallback callback( convexMesh->getHull(), convexGeom.scale, meshScaling, convexPose, pose, -unitDir, distance, hitFlags, bothTriangleSidesCollide, inflation, anyHit, distCoeff); Midphase::sweepConvexVsMesh(meshData, hullOBB, meshSpaceSweepVector, meshSpaceSweepDist, callback, anyHit); const bool isMtd = hitFlags & PxHitFlag::eMTD; return callback.finalizeHit(sweepHit, meshGeom, pose, convexGeom, convexPose, unitDir, inflation, isMtd, meshBothSides, isDoubleSided, bothTriangleSidesCollide); } ///////////////////////////////////////////////////////////////////////////////
23,554
C++
37.363192
181
0.71733
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMeshData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_MESH_DATA_H #define GU_MESH_DATA_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec4.h" #include "foundation/PxBounds3.h" #include "geometry/PxTriangleMesh.h" #include "geometry/PxTetrahedronMesh.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxAllocator.h" #include "GuRTree.h" #include "GuBV4.h" #include "GuBV32.h" #include "GuSDF.h" namespace physx { namespace Gu { // 1: support stackless collision trees for non-recursive collision queries // 2: height field functionality not supported anymore // 3: mass struct removed // 4: bounding sphere removed // 5: RTree added, opcode tree still in the binary image, physx 3.0 // 6: opcode tree removed from binary image // 7: convex decomposition is out // 8: adjacency information added // 9: removed leaf triangles and most of opcode data, changed rtree layout // 10: float rtrees // 11: new build, isLeaf added to page // 12: isLeaf is now the lowest bit in ptrs // 13: TA30159 removed deprecated convexEdgeThreshold and bumped version // 14: added midphase ID // 15: GPU data simplification // 16: vertex2Face mapping enabled by default if using GPU #define PX_MESH_VERSION 16 #define PX_TET_MESH_VERSION 1 #define PX_SOFTBODY_MESH_VERSION 2 // these flags are used to indicate/validate the contents of a cooked mesh file enum InternalMeshSerialFlag { IMSF_MATERIALS = (1<<0), //!< if set, the cooked mesh file contains per-triangle material indices IMSF_FACE_REMAP = (1<<1), //!< if set, the cooked mesh file contains a remap table IMSF_8BIT_INDICES = (1<<2), //!< if set, the cooked mesh file contains 8bit indices (topology) IMSF_16BIT_INDICES = (1<<3), //!< if set, the cooked mesh file contains 16bit indices (topology) IMSF_ADJACENCIES = (1<<4), //!< if set, the cooked mesh file contains adjacency structures IMSF_GRB_DATA = (1<<5), //!< if set, the cooked mesh file contains GRB data structures IMSF_SDF = (1<<6), //!< if set, the cooked mesh file contains SDF data structures IMSF_VERT_MAPPING = (1<<7), //!< if set, the cooked mesh file contains vertex mapping information IMSF_GRB_INV_REMAP = (1<<8), //!< if set, the cooked mesh file contains vertex inv mapping information. Required for cloth IMSF_INERTIA = (1<<9) //!< if set, the cooked mesh file contains inertia tensor for the mesh }; #if PX_VC #pragma warning(push) #pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class MeshDataBase : public PxUserAllocated { public: PxMeshMidPhase::Enum mType; PxU8 mFlags; PxU32 mNbVertices; PxVec3* mVertices; PxReal mMass; //this is mass assuming a unit density that can be scaled by instances! PxMat33 mInertia; //in local space of mesh! PxVec3 mLocalCenterOfMass; //local space com PxBounds3 mAABB; PxReal mGeomEpsilon; PxU32* mFaceRemap; // GRB data ------------------------- void* mGRB_primIndices; //!< GRB: GPU-friendly primitive indices(either triangle or tetrahedron) PxU32* mGRB_faceRemap; //!< GRB: this remap the GPU triangle indices to CPU triangle indices PxU32* mGRB_faceRemapInverse; // // End of GRB data ------------------ // SDF data SDF mSdfData; //Cloth data : each vert has a list of associated triangles in the mesh, this is for attachement constraints to enable default filtering PxU32* mAccumulatedTrianglesRef;//runsum PxU32* mTrianglesReferences; PxU32 mNbTrianglesReferences; MeshDataBase() : mFlags (0), mNbVertices (0), mVertices (NULL), mMass (0.f), mInertia (PxZero), mLocalCenterOfMass (0.f), mAABB (PxBounds3::empty()), mGeomEpsilon (0.0f), mFaceRemap (NULL), mGRB_primIndices (NULL), mGRB_faceRemap (NULL), mGRB_faceRemapInverse (NULL), mSdfData (PxZero), mAccumulatedTrianglesRef(NULL), mTrianglesReferences (NULL), mNbTrianglesReferences (0) { } virtual ~MeshDataBase() { PX_FREE(mVertices); PX_FREE(mFaceRemap); PX_FREE(mGRB_primIndices); PX_FREE(mGRB_faceRemap); PX_FREE(mGRB_faceRemapInverse); PX_FREE(mAccumulatedTrianglesRef); PX_FREE(mTrianglesReferences); } PX_NOINLINE PxVec3* allocateVertices(PxU32 nbVertices) { PX_ASSERT(!mVertices); // PT: we allocate one more vertex to make sure it's safe to V4Load the last one const PxU32 nbAllocatedVerts = nbVertices + 1; mVertices = PX_ALLOCATE(PxVec3, nbAllocatedVerts, "PxVec3"); mNbVertices = nbVertices; return mVertices; } PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) ? true : false; } }; class TriangleMeshData : public MeshDataBase { public: PxU32 mNbTriangles; void* mTriangles; PxU32* mAdjacencies; PxU8* mExtraTrigData; PxU16* mMaterialIndices; // GRB data ------------------------- void* mGRB_primAdjacencies; //!< GRB: adjacency data, with BOUNDARY and NONCONVEX flags (flags replace adj indices where applicable) [uin4] Gu::BV32Tree* mGRB_BV32Tree; // End of GRB data ------------------ TriangleMeshData() : mNbTriangles (0), mTriangles (NULL), mAdjacencies (NULL), mExtraTrigData (NULL), mMaterialIndices (NULL), mGRB_primAdjacencies (NULL), mGRB_BV32Tree (NULL) { } virtual ~TriangleMeshData() { PX_FREE(mTriangles); PX_FREE(mAdjacencies); PX_FREE(mMaterialIndices); PX_FREE(mExtraTrigData); PX_FREE(mGRB_primAdjacencies); PX_DELETE(mGRB_BV32Tree); } PX_NOINLINE PxU32* allocateAdjacencies() { PX_ASSERT(mNbTriangles); PX_ASSERT(!mAdjacencies); mAdjacencies = PX_ALLOCATE(PxU32, mNbTriangles * 3, "mAdjacencies"); mFlags |= PxTriangleMeshFlag::eADJACENCY_INFO; return mAdjacencies; } PX_NOINLINE PxU32* allocateFaceRemap() { PX_ASSERT(mNbTriangles); PX_ASSERT(!mFaceRemap); mFaceRemap = PX_ALLOCATE(PxU32, mNbTriangles, "mFaceRemap"); return mFaceRemap; } PX_NOINLINE void* allocateTriangles(PxU32 nbTriangles, bool force32Bit, PxU32 allocateGPUData = 0) { PX_ASSERT(mNbVertices); PX_ASSERT(!mTriangles); bool index16 = mNbVertices <= 0xffff && !force32Bit; if(index16) mFlags |= PxTriangleMeshFlag::e16_BIT_INDICES; mTriangles = PX_ALLOC(nbTriangles * (index16 ? sizeof(PxU16) : sizeof(PxU32)) * 3, "mTriangles"); if (allocateGPUData) mGRB_primIndices = PX_ALLOC(nbTriangles * (index16 ? sizeof(PxU16) : sizeof(PxU32)) * 3, "mGRB_triIndices"); mNbTriangles = nbTriangles; return mTriangles; } PX_NOINLINE PxU16* allocateMaterials() { PX_ASSERT(mNbTriangles); PX_ASSERT(!mMaterialIndices); mMaterialIndices = PX_ALLOCATE(PxU16, mNbTriangles, "mMaterialIndices"); return mMaterialIndices; } PX_NOINLINE PxU8* allocateExtraTrigData() { PX_ASSERT(mNbTriangles); PX_ASSERT(!mExtraTrigData); mExtraTrigData = PX_ALLOCATE(PxU8, mNbTriangles, "mExtraTrigData"); return mExtraTrigData; } PX_FORCE_INLINE void setTriangleAdjacency(PxU32 triangleIndex, PxU32 adjacency, PxU32 offset) { PX_ASSERT(mAdjacencies); mAdjacencies[triangleIndex*3 + offset] = adjacency; } }; class RTreeTriangleData : public TriangleMeshData { public: RTreeTriangleData() { mType = PxMeshMidPhase::eBVH33; } virtual ~RTreeTriangleData() {} Gu::RTree mRTree; }; class BV4TriangleData : public TriangleMeshData { public: BV4TriangleData() { mType = PxMeshMidPhase::eBVH34; } virtual ~BV4TriangleData() {} Gu::SourceMesh mMeshInterface; Gu::BV4Tree mBV4Tree; }; // PT: TODO: the following classes should probably be in their own specific files (e.g. GuTetrahedronMeshData.h, GuSoftBodyMeshData.h) class TetrahedronMeshData : public PxTetrahedronMeshData { public: PxU32 mNbVertices; PxVec3* mVertices; PxU16* mMaterialIndices; //each tetrahedron should have a material index PxU32 mNbTetrahedrons; void* mTetrahedrons; //IndTetrahedron32 PxU8 mFlags; PxReal mGeomEpsilon; PxBounds3 mAABB; TetrahedronMeshData() : mNbVertices(0), mVertices(NULL), mMaterialIndices(NULL), mNbTetrahedrons(0), mTetrahedrons(NULL), mFlags(0), mGeomEpsilon(0.0f), mAABB(PxBounds3::empty()) {} TetrahedronMeshData(PxVec3* vertices, PxU32 nbVertices, void* tetrahedrons, PxU32 nbTetrahedrons, PxU8 flags, PxReal geomEpsilon, PxBounds3 aabb) : mNbVertices(nbVertices), mVertices(vertices), mNbTetrahedrons(nbTetrahedrons), mTetrahedrons(tetrahedrons), mFlags(flags), mGeomEpsilon(geomEpsilon), mAABB(aabb) {} void allocateTetrahedrons(const PxU32 nbGridTetrahedrons, const PxU32 allocateGPUData = 0) { if (allocateGPUData) { mTetrahedrons = PX_ALLOC(nbGridTetrahedrons * sizeof(PxU32) * 4, "mGridModelTetrahedrons"); } mNbTetrahedrons = nbGridTetrahedrons; } PxVec3* allocateVertices(PxU32 nbVertices, const PxU32 allocateGPUData = 1) { PX_ASSERT(!mVertices); // PT: we allocate one more vertex to make sure it's safe to V4Load the last one if (allocateGPUData) { const PxU32 nbAllocatedVerts = nbVertices + 1; mVertices = PX_ALLOCATE(PxVec3, nbAllocatedVerts, "PxVec3"); } mNbVertices = nbVertices; return mVertices; } PxU16* allocateMaterials() { PX_ASSERT(mNbTetrahedrons); PX_ASSERT(!mMaterialIndices); mMaterialIndices = PX_ALLOCATE(PxU16, mNbTetrahedrons, "mMaterialIndices"); return mMaterialIndices; } PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) ? true : false; } ~TetrahedronMeshData() { PX_FREE(mTetrahedrons); PX_FREE(mVertices); PX_FREE(mMaterialIndices) } }; class SoftBodyCollisionData : public PxSoftBodyCollisionData { public: PxU32* mFaceRemap; // GRB data ------------------------- void * mGRB_primIndices; //!< GRB: GPU-friendly primitive indices(either triangle or tetrahedron) PxU32* mGRB_faceRemap; //!< GRB: this remap the GPU triangle indices to CPU triangle indices PxU32* mGRB_faceRemapInverse; Gu::BV32Tree* mGRB_BV32Tree; PxU8* mGRB_tetraSurfaceHint; // End of GRB data ------------------ Gu::TetrahedronSourceMesh mMeshInterface; Gu::BV4Tree mBV4Tree; PxMat33* mTetraRestPoses; SoftBodyCollisionData() : mFaceRemap(NULL), mGRB_primIndices(NULL), mGRB_faceRemap(NULL), mGRB_faceRemapInverse(NULL), mGRB_BV32Tree(NULL), mGRB_tetraSurfaceHint(NULL), mTetraRestPoses(NULL) {} virtual ~SoftBodyCollisionData() { PX_FREE(mGRB_tetraSurfaceHint); PX_DELETE(mGRB_BV32Tree); PX_FREE(mFaceRemap); PX_FREE(mGRB_primIndices); PX_FREE(mGRB_faceRemap); PX_FREE(mGRB_faceRemapInverse); PX_FREE(mTetraRestPoses); } PxU32* allocateFaceRemap(PxU32 nbTetrahedrons) { PX_ASSERT(nbTetrahedrons); PX_ASSERT(!mFaceRemap); mFaceRemap = PX_ALLOCATE(PxU32, nbTetrahedrons, "mFaceRemap"); return mFaceRemap; } void allocateCollisionData(PxU32 nbTetrahedrons) { mGRB_primIndices = PX_ALLOC(nbTetrahedrons * 4 * sizeof(PxU32), "mGRB_primIndices"); mGRB_tetraSurfaceHint = PX_ALLOCATE(PxU8, nbTetrahedrons, "mGRB_tetraSurfaceHint"); mTetraRestPoses = PX_ALLOCATE(PxMat33, nbTetrahedrons, "mTetraRestPoses"); } }; class CollisionMeshMappingData : public PxCollisionMeshMappingData { public: PxReal* mVertsBarycentricInGridModel; PxU32* mVertsRemapInGridModel; PxU32* mTetsRemapColToSim; PxU32 mTetsRemapSize; PxU32* mTetsAccumulatedRemapColToSim; //runsum, size of number of tetrahedrons in collision mesh //in the collision model, each vert has a list of associated simulation tetrahedrons, this is for attachement constraints to enable default filtering PxU32* mCollisionAccumulatedTetrahedronsRef;//runsum PxU32* mCollisionTetrahedronsReferences; PxU32 mCollisionNbTetrahedronsReferences; PxU32* mCollisionSurfaceVertToTetRemap; PxU8* mCollisionSurfaceVertsHint; CollisionMeshMappingData() : mVertsBarycentricInGridModel(NULL), mVertsRemapInGridModel(NULL), mTetsRemapColToSim(NULL), mTetsRemapSize(0), mTetsAccumulatedRemapColToSim(NULL), mCollisionAccumulatedTetrahedronsRef(NULL), mCollisionTetrahedronsReferences(NULL), mCollisionNbTetrahedronsReferences(0), mCollisionSurfaceVertToTetRemap(NULL), mCollisionSurfaceVertsHint(NULL) { } virtual ~CollisionMeshMappingData() { PX_FREE(mVertsBarycentricInGridModel); PX_FREE(mVertsRemapInGridModel); PX_FREE(mTetsRemapColToSim); PX_FREE(mTetsAccumulatedRemapColToSim); PX_FREE(mCollisionAccumulatedTetrahedronsRef); PX_FREE(mCollisionTetrahedronsReferences); PX_FREE(mCollisionSurfaceVertsHint); PX_FREE(mCollisionSurfaceVertToTetRemap); } void allocatemappingData(const PxU32 nbVerts, const PxU32 tetRemapSize, const PxU32 nbColTetrahedrons, const PxU32 allocateGPUData = 0) { if (allocateGPUData) { mVertsBarycentricInGridModel = reinterpret_cast<PxReal*>(PX_ALLOC(nbVerts * sizeof(PxReal) * 4, "mVertsBarycentricInGridModel")); mVertsRemapInGridModel = reinterpret_cast<PxU32*>(PX_ALLOC(nbVerts * sizeof(PxU32), "mVertsRemapInGridModel")); mTetsRemapColToSim = reinterpret_cast<PxU32*>(PX_ALLOC(tetRemapSize * sizeof(PxU32), "mTetsRemapInSimModel")); mTetsAccumulatedRemapColToSim = reinterpret_cast<PxU32*>(PX_ALLOC(nbColTetrahedrons * sizeof(PxU32), "mTetsAccumulatedRemapInSimModel")); mCollisionSurfaceVertsHint = reinterpret_cast<PxU8*>(PX_ALLOC(nbVerts * sizeof(PxU8), "mCollisionSurfaceVertsHint")); mCollisionSurfaceVertToTetRemap = reinterpret_cast<PxU32*>(PX_ALLOC(nbVerts * sizeof(PxU32), "mCollisionSurfaceVertToTetRemap")); } mTetsRemapSize = tetRemapSize; } void allocateTetRefData(const PxU32 totalTetReference, const PxU32 nbCollisionVerts, const PxU32 allocateGPUData /*= 0*/) { if (allocateGPUData) { mCollisionAccumulatedTetrahedronsRef = reinterpret_cast<PxU32*>(PX_ALLOC(nbCollisionVerts * sizeof(PxU32), "mGMAccumulatedTetrahedronsRef")); mCollisionTetrahedronsReferences = reinterpret_cast<PxU32*>(PX_ALLOC(totalTetReference * sizeof(PxU32), "mGMTetrahedronsReferences")); } mCollisionNbTetrahedronsReferences = totalTetReference; } virtual void release() { PX_DELETE_THIS; } }; class SoftBodySimulationData : public PxSoftBodySimulationData { public: PxReal* mGridModelInvMass; PxMat33* mGridModelTetraRestPoses; PxU32 mGridModelNbPartitions; PxU32 mGridModelMaxTetsPerPartitions; PxU32* mGridModelOrderedTetrahedrons; // the corresponding tetrahedron index for the runsum PxU32* mGMRemapOutputCP; PxU32* mGMAccumulatedPartitionsCP; //runsum for the combined partition PxU32* mGMAccumulatedCopiesCP; //runsum for the vert copies in combined partitions PxU32 mGMRemapOutputSize; PxU32* mGMPullIndices; PxU32 mNumTetsPerElement; SoftBodySimulationData() : mGridModelInvMass(NULL), mGridModelTetraRestPoses(NULL), mGridModelNbPartitions(0), mGridModelOrderedTetrahedrons(NULL), mGMRemapOutputCP(NULL), mGMAccumulatedPartitionsCP(NULL), mGMAccumulatedCopiesCP(NULL), mGMRemapOutputSize(0), mGMPullIndices(NULL) {} virtual ~SoftBodySimulationData() { PX_FREE(mGridModelInvMass); PX_FREE(mGridModelTetraRestPoses); PX_FREE(mGridModelOrderedTetrahedrons); PX_FREE(mGMRemapOutputCP); PX_FREE(mGMAccumulatedPartitionsCP); PX_FREE(mGMAccumulatedCopiesCP); PX_FREE(mGMPullIndices); } void allocateGridModelData(const PxU32 nbGridTetrahedrons, const PxU32 nbGridVerts, const PxU32 nbVerts, const PxU32 nbPartitions, const PxU32 remapOutputSize, const PxU32 numTetsPerElement, const PxU32 allocateGPUData = 0) { PX_UNUSED(nbVerts); if (allocateGPUData) { const PxU32 numElements = nbGridTetrahedrons / numTetsPerElement; const PxU32 numVertsPerElement = (numTetsPerElement == 6 || numTetsPerElement == 5) ? 8 : 4; mGridModelInvMass = reinterpret_cast<float*>(PX_ALLOC(nbGridVerts * sizeof(float), "mGridModelInvMass")); mGridModelTetraRestPoses = reinterpret_cast<PxMat33*>(PX_ALLOC(nbGridTetrahedrons * sizeof(PxMat33), "mGridModelTetraRestPoses")); mGridModelOrderedTetrahedrons = reinterpret_cast<PxU32*>(PX_ALLOC(numElements * sizeof(PxU32), "mGridModelOrderedTetrahedrons")); mGMRemapOutputCP = reinterpret_cast<PxU32*>(PX_ALLOC(remapOutputSize * sizeof(PxU32), "mGMRemapOutputCP")); mGMAccumulatedPartitionsCP = reinterpret_cast<PxU32*>(PX_ALLOC(nbPartitions * sizeof(PxU32), "mGMAccumulatedPartitionsCP")); mGMAccumulatedCopiesCP = reinterpret_cast<PxU32*>(PX_ALLOC(nbGridVerts * sizeof(PxU32), "mGMAccumulatedCopiesCP")); mGMPullIndices = reinterpret_cast<PxU32*>(PX_ALLOC(numElements * numVertsPerElement * sizeof(PxU32) , "mGMPullIndices")); } mGridModelNbPartitions = nbPartitions; mGMRemapOutputSize = remapOutputSize; } }; class CollisionTetrahedronMeshData : public PxCollisionTetrahedronMeshData { public: TetrahedronMeshData* mMesh; SoftBodyCollisionData* mCollisionData; virtual PxTetrahedronMeshData* getMesh() { return mMesh; } virtual const PxTetrahedronMeshData* getMesh() const { return mMesh; } virtual PxSoftBodyCollisionData* getData() { return mCollisionData; } virtual const PxSoftBodyCollisionData* getData() const { return mCollisionData; } virtual ~CollisionTetrahedronMeshData() { PX_FREE(mMesh); PX_FREE(mCollisionData); } virtual void release() { PX_DELETE_THIS; } }; class SimulationTetrahedronMeshData : public PxSimulationTetrahedronMeshData { public: TetrahedronMeshData* mMesh; SoftBodySimulationData* mSimulationData; virtual PxTetrahedronMeshData* getMesh() { return mMesh; } virtual PxSoftBodySimulationData* getData() { return mSimulationData; } virtual ~SimulationTetrahedronMeshData() { PX_FREE(mMesh); PX_FREE(mSimulationData); } virtual void release() { PX_DELETE_THIS; } }; class SoftBodyMeshData : public PxUserAllocated { PX_NOCOPY(SoftBodyMeshData) public: TetrahedronMeshData& mSimulationMesh; SoftBodySimulationData& mSimulationData; TetrahedronMeshData& mCollisionMesh; SoftBodyCollisionData& mCollisionData; CollisionMeshMappingData& mMappingData; SoftBodyMeshData(TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData, TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, CollisionMeshMappingData& mappingData) : mSimulationMesh(simulationMesh), mSimulationData(simulationData), mCollisionMesh(collisionMesh), mCollisionData(collisionData), mMappingData(mappingData) { } }; #if PX_VC #pragma warning(pop) #endif } // namespace Gu } #endif // #ifdef GU_MESH_DATA_H
20,736
C
31.150388
151
0.727238
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMidphaseBV4.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxTriangleMeshGeometry.h" #include "GuBV4.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuSweepMesh.h" #include "GuBV4Build.h" #include "GuBV4_Common.h" #include "GuSphere.h" #include "GuCapsule.h" #include "GuBoxConversion.h" #include "GuConvexUtilsInternal.h" #include "GuVecTriangle.h" #include "GuIntersectionTriangleBox.h" #include "GuIntersectionCapsuleTriangle.h" #include "GuIntersectionRayBox.h" #include "GuTriangleMeshBV4.h" #include "CmScaling.h" #include "CmMatrix34.h" // This file contains code specific to the BV4 midphase. // PT: TODO: revisit/inline static sweep functions (TA34704) using namespace physx; using namespace Gu; using namespace Cm; PxIntBool BV4_RaycastSingle (const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxGeomRaycastHit* PX_RESTRICT hit, float maxDist, float geomEpsilon, PxU32 flags, PxHitFlags hitFlags); PxU32 BV4_RaycastAll (const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 maxNbHits, float maxDist, PxU32 stride, float geomEpsilon, PxU32 flags, PxHitFlags hitFlags); void BV4_RaycastCB (const PxVec3& origin, const PxVec3& dir, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, float maxDist, float geomEpsilon, PxU32 flags, MeshRayCallback callback, void* userData); PxIntBool BV4_OverlapSphereAny (const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned); PxU32 BV4_OverlapSphereAll (const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow); void BV4_OverlapSphereCB (const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData); PxIntBool BV4_OverlapBoxAny (const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned); PxU32 BV4_OverlapBoxAll (const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow); void BV4_OverlapBoxCB (const Box& box, const BV4Tree& tree, MeshOverlapCallback callback, void* userData); void BV4_OverlapBoxCB (const Box& box, const BV4Tree& tree, TetMeshOverlapCallback callback, void* userData); PxIntBool BV4_OverlapCapsuleAny (const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned); PxU32 BV4_OverlapCapsuleAll (const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow); void BV4_OverlapCapsuleCB (const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData); PxIntBool BV4_SphereSweepSingle (const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepHit* PX_RESTRICT hit, PxU32 flags); void BV4_SphereSweepCB (const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting); PxIntBool BV4_BoxSweepSingle (const Box& box, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepHit* PX_RESTRICT hit, PxU32 flags); void BV4_BoxSweepCB (const Box& box, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting); PxIntBool BV4_CapsuleSweepSingle (const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags); PxIntBool BV4_CapsuleSweepSingleAA(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags); void BV4_CapsuleSweepCB (const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags); void BV4_CapsuleSweepAACB (const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags); void BV4_GenericSweepCB_Old (const PxVec3& origin, const PxVec3& extents, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshSweepCallback callback, void* userData); void BV4_GenericSweepCB (const Box& box, const PxVec3& dir, float maxDist, const BV4Tree& tree, MeshSweepCallback callback, void* userData, bool anyHit); static PX_FORCE_INLINE void setIdentity(PxMat44& m) { m.column0 = PxVec4(1.0f, 0.0f, 0.0f, 0.0f); m.column1 = PxVec4(0.0f, 1.0f, 0.0f, 0.0f); m.column2 = PxVec4(0.0f, 0.0f, 1.0f, 0.0f); m.column3 = PxVec4(0.0f, 0.0f, 0.0f, 1.0f); } // PT: TODO: PX-566 static PX_FORCE_INLINE void setRotation(PxMat44& m, const PxQuat& q) { const PxReal x = q.x; const PxReal y = q.y; const PxReal z = q.z; const PxReal w = q.w; const PxReal x2 = x + x; const PxReal y2 = y + y; const PxReal z2 = z + z; const PxReal xx = x2*x; const PxReal yy = y2*y; const PxReal zz = z2*z; const PxReal xy = x2*y; const PxReal xz = x2*z; const PxReal xw = x2*w; const PxReal yz = y2*z; const PxReal yw = y2*w; const PxReal zw = z2*w; m.column0 = PxVec4(1.0f - yy - zz, xy + zw, xz - yw, 0.0f); m.column1 = PxVec4(xy - zw, 1.0f - xx - zz, yz + xw, 0.0f); m.column2 = PxVec4(xz + yw, yz - xw, 1.0f - xx - yy, 0.0f); } #define IEEE_1_0 0x3f800000 //!< integer representation of 1.0 static PX_FORCE_INLINE const PxMat44* setupWorldMatrix(PxMat44& world, const float* meshPos, const float* meshRot) { // world = PxMat44(PxIdentity); setIdentity(world); bool isIdt = true; if(meshRot) { const PxU32* Bin = reinterpret_cast<const PxU32*>(meshRot); if(Bin[0]!=0 || Bin[1]!=0 || Bin[2]!=0 || Bin[3]!=IEEE_1_0) { // const PxQuat Q(meshRot[0], meshRot[1], meshRot[2], meshRot[3]); // world = PxMat44(Q); setRotation(world, PxQuat(meshRot[0], meshRot[1], meshRot[2], meshRot[3])); isIdt = false; } } if(meshPos) { const PxU32* Bin = reinterpret_cast<const PxU32*>(meshPos); if(Bin[0]!=0 || Bin[1]!=0 || Bin[2]!=0) { // world.setPosition(PxVec3(meshPos[0], meshPos[1], meshPos[2])); world.column3.x = meshPos[0]; world.column3.y = meshPos[1]; world.column3.z = meshPos[2]; isIdt = false; } } return isIdt ? NULL : &world; } static PX_FORCE_INLINE PxU32 setupFlags(bool anyHit, bool doubleSided, bool meshBothSides) { PxU32 flags = 0; if(anyHit) flags |= QUERY_MODIFIER_ANY_HIT; if(doubleSided) flags |= QUERY_MODIFIER_DOUBLE_SIDED; if(meshBothSides) flags |= QUERY_MODIFIER_MESH_BOTH_SIDES; return flags; } static PxIntBool boxSweepVsMesh(SweepHit& h, const BV4Tree& tree, const float* meshPos, const float* meshRot, const Box& box, const PxVec3& dir, float maxDist, bool anyHit, bool doubleSided, bool meshBothSides) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, meshPos, meshRot); const PxU32 flags = setupFlags(anyHit, doubleSided, meshBothSides); return BV4_BoxSweepSingle(box, dir, maxDist, tree, TM, &h, flags); } static PxIntBool sphereSweepVsMesh(SweepHit& h, const BV4Tree& tree, const PxVec3& center, float radius, const PxVec3& dir, float maxDist, const PxMat44* TM, const PxU32 flags) { // PT: TODO: avoid this copy (TA34704) const Sphere tmp(center, radius); return BV4_SphereSweepSingle(tmp, dir, maxDist, tree, TM, &h, flags); } static bool capsuleSweepVsMesh(SweepHit& h, const BV4Tree& tree, const Capsule& capsule, const PxVec3& dir, float maxDist, const PxMat44* TM, const PxU32 flags) { Capsule localCapsule; computeLocalCapsule(localCapsule, capsule, TM); // PT: TODO: optimize PxVec3 localDir, unused; computeLocalRay(localDir, unused, dir, dir, TM); const PxVec3 capsuleDir = localCapsule.p1 - localCapsule.p0; PxU32 nbNullComponents = 0; const float epsilon = 1e-3f; if(PxAbs(capsuleDir.x)<epsilon) nbNullComponents++; if(PxAbs(capsuleDir.y)<epsilon) nbNullComponents++; if(PxAbs(capsuleDir.z)<epsilon) nbNullComponents++; // PT: TODO: consider passing TM to BV4_CapsuleSweepSingleXX just to do the final transforms there instead // of below. It would make the parameters slightly inconsistent (local input + world TM) but it might make // the code better overall, more aligned with the "unlimited results" version. PxIntBool status; if(nbNullComponents==2) { status = BV4_CapsuleSweepSingleAA(localCapsule, localDir, maxDist, tree, &h, flags); } else { status = BV4_CapsuleSweepSingle(localCapsule, localDir, maxDist, tree, &h, flags); } if(status && TM) { h.mPos = TM->transform(h.mPos); h.mNormal = TM->rotate(h.mNormal); } return status!=0; } static PX_FORCE_INLINE void boxSweepVsMeshCBOld(const BV4Tree& tree, const float* meshPos, const float* meshRot, const PxVec3& center, const PxVec3& extents, const PxVec3& dir, float maxDist, MeshSweepCallback callback, void* userData) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, meshPos, meshRot); BV4_GenericSweepCB_Old(center, extents, dir, maxDist, tree, TM, callback, userData); } // static PX_FORCE_INLINE bool raycastVsMesh(PxGeomRaycastHit& hitData, const BV4Tree& tree, const float* meshPos, const float* meshRot, const PxVec3& orig, const PxVec3& dir, float maxDist, float geomEpsilon, bool doubleSided, PxHitFlags hitFlags) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, meshPos, meshRot); const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY; const PxU32 flags = setupFlags(anyHit, doubleSided, false); if(!BV4_RaycastSingle(orig, dir, tree, TM, &hitData, maxDist, geomEpsilon, flags, hitFlags)) return false; return true; } /*static PX_FORCE_INLINE PxU32 raycastVsMeshAll(PxRaycastHit* hits, PxU32 maxNbHits, const BV4Tree& tree, const float* meshPos, const float* meshRot, const PxVec3& orig, const PxVec3& dir, float maxDist, float geomEpsilon, bool doubleSided, PxHitFlags hitFlags) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, meshPos, meshRot); const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY; const PxU32 flags = setupFlags(anyHit, doubleSided, false); return BV4_RaycastAll(orig, dir, tree, TM, hits, maxNbHits, maxDist, geomEpsilon, flags, hitFlags); }*/ static PX_FORCE_INLINE void raycastVsMeshCB(const BV4Tree& tree, const PxVec3& orig, const PxVec3& dir, float maxDist, float geomEpsilon, bool doubleSided, MeshRayCallback callback, void* userData) { const PxU32 flags = setupFlags(false, doubleSided, false); BV4_RaycastCB(orig, dir, tree, NULL, maxDist, geomEpsilon, flags, callback, userData); } struct BV4RaycastCBParams { PX_FORCE_INLINE BV4RaycastCBParams( PxGeomRaycastHit* hits, PxU32 maxHits, PxU32 stride, const PxMeshScale* scale, const PxTransform* pose, const PxMat34* world2vertexSkew, PxU32 hitFlags, const PxVec3& rayDir, bool isDoubleSided, float distCoeff) : mDstBase (reinterpret_cast<PxU8*>(hits)), mHitNum (0), mMaxHits (maxHits), mStride (stride), mScale (scale), mPose (pose), mWorld2vertexSkew (world2vertexSkew), mHitFlags (hitFlags), mRayDir (rayDir), mIsDoubleSided (isDoubleSided), mDistCoeff (distCoeff) { } PxU8* mDstBase; PxU32 mHitNum; const PxU32 mMaxHits; const PxU32 mStride; const PxMeshScale* mScale; const PxTransform* mPose; const PxMat34* mWorld2vertexSkew; const PxU32 mHitFlags; const PxVec3& mRayDir; const bool mIsDoubleSided; float mDistCoeff; private: BV4RaycastCBParams& operator=(const BV4RaycastCBParams&); }; static PX_FORCE_INLINE PxVec3 processLocalNormal(const PxMat34* PX_RESTRICT world2vertexSkew, const PxTransform* PX_RESTRICT pose, const PxVec3& localNormal, const PxVec3& rayDir, const bool isDoubleSided) { PxVec3 normal; if(world2vertexSkew) normal = world2vertexSkew->rotateTranspose(localNormal); else normal = pose->rotate(localNormal); normal.normalize(); // PT: figure out correct normal orientation (DE7458) // - if the mesh is single-sided the normal should be the regular triangle normal N, regardless of eMESH_BOTH_SIDES. // - if the mesh is double-sided the correct normal can be either N or -N. We take the one opposed to ray direction. if(isDoubleSided && normal.dot(rayDir) > 0.0f) normal = -normal; return normal; } static HitCode gRayCallback(void* userData, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxU32 triangleIndex, float dist, float u, float v) { BV4RaycastCBParams* params = reinterpret_cast<BV4RaycastCBParams*>(userData); if(params->mHitNum == params->mMaxHits) return HIT_EXIT; PxGeomRaycastHit& hit = *reinterpret_cast<PxGeomRaycastHit*>(params->mDstBase); hit.distance = dist * params->mDistCoeff; hit.u = u; hit.v = v; hit.faceIndex = triangleIndex; PxVec3 localImpact = (1.0f - u - v)*lp0 + u*lp1 + v*lp2; if(params->mWorld2vertexSkew) { localImpact = params->mScale->transform(localImpact); if(params->mScale->hasNegativeDeterminant()) PxSwap<PxReal>(hit.u, hit.v); // have to swap the UVs though since they were computed in mesh local space } hit.position = params->mPose->transform(localImpact); hit.flags = PxHitFlag::ePOSITION|PxHitFlag::eUV|PxHitFlag::eFACE_INDEX; PxVec3 normal(0.0f); // Compute additional information if needed if(params->mHitFlags & PxHitFlag::eNORMAL) { const PxVec3 localNormal = (lp1 - lp0).cross(lp2 - lp0); normal = processLocalNormal(params->mWorld2vertexSkew, params->mPose, localNormal, params->mRayDir, params->mIsDoubleSided); hit.flags |= PxHitFlag::eNORMAL; } hit.normal = normal; params->mHitNum++; params->mDstBase += params->mStride; return HIT_NONE; } PxU32 physx::Gu::raycast_triangleMesh_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4TriangleMesh* meshData = static_cast<const BV4TriangleMesh*>(mesh); const bool multipleHits = hitFlags & PxHitFlag::eMESH_MULTIPLE; const bool idtScale = meshGeom.scale.isIdentity(); const bool isDoubleSided = meshGeom.meshFlags.isSet(PxMeshGeometryFlag::eDOUBLE_SIDED); const bool bothSides = isDoubleSided || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES); const BV4Tree& tree = static_cast<const BV4TriangleMesh*>(meshData)->getBV4Tree(); if(idtScale && !multipleHits) { bool b = raycastVsMesh(*hits, tree, &pose.p.x, &pose.q.x, rayOrigin, rayDir, maxDist, meshData->getGeomEpsilon(), bothSides, hitFlags); if(b) { PxHitFlags dstFlags = PxHitFlag::ePOSITION|PxHitFlag::eUV|PxHitFlag::eFACE_INDEX; // PT: TODO: pass flags to BV4 code (TA34704) if(hitFlags & PxHitFlag::eNORMAL) { dstFlags |= PxHitFlag::eNORMAL; if(isDoubleSided) { PxVec3 normal = hits->normal; // PT: figure out correct normal orientation (DE7458) // - if the mesh is single-sided the normal should be the regular triangle normal N, regardless of eMESH_BOTH_SIDES. // - if the mesh is double-sided the correct normal can be either N or -N. We take the one opposed to ray direction. if(normal.dot(rayDir) > 0.0f) normal = -normal; hits->normal = normal; } } else { hits->normal = PxVec3(0.0f); } hits->flags = dstFlags; } return PxU32(b); } /* if(idtScale && multipleHits) { PxU32 nbHits = raycastVsMeshAll(hits, maxHits, tree, &pose.p.x, &pose.q.x, rayOrigin, rayDir, maxDist, meshData->getGeomEpsilon(), bothSides, hitFlags); return nbHits; } */ //scaling: transform the ray to vertex space PxVec3 orig, dir; PxMat34 world2vertexSkew; PxMat34* world2vertexSkewP = NULL; PxReal distCoeff = 1.0f; if(idtScale) { orig = pose.transformInv(rayOrigin); dir = pose.rotateInv(rayDir); } else { world2vertexSkew = meshGeom.scale.getInverse() * pose.getInverse(); world2vertexSkewP = &world2vertexSkew; orig = world2vertexSkew.transform(rayOrigin); dir = world2vertexSkew.rotate(rayDir); { distCoeff = dir.normalize(); maxDist *= distCoeff; maxDist += 1e-3f; distCoeff = 1.0f/distCoeff; } } if(!multipleHits) { bool b = raycastVsMesh(*hits, tree, NULL, NULL, orig, dir, maxDist, meshData->getGeomEpsilon(), bothSides, hitFlags); if(b) { hits->distance *= distCoeff; hits->position = pose.transform(meshGeom.scale.transform(hits->position)); PxHitFlags dstFlags = PxHitFlag::ePOSITION|PxHitFlag::eUV|PxHitFlag::eFACE_INDEX; if(meshGeom.scale.hasNegativeDeterminant()) PxSwap<PxReal>(hits->u, hits->v); // have to swap the UVs though since they were computed in mesh local space // PT: TODO: pass flags to BV4 code (TA34704) // Compute additional information if needed if(hitFlags & PxHitFlag::eNORMAL) { dstFlags |= PxHitFlag::eNORMAL; hits->normal = processLocalNormal(world2vertexSkewP, &pose, hits->normal, rayDir, isDoubleSided); } else { hits->normal = PxVec3(0.0f); } hits->flags = dstFlags; } return PxU32(b); } BV4RaycastCBParams callback(hits, maxHits, stride, &meshGeom.scale, &pose, world2vertexSkewP, hitFlags, rayDir, isDoubleSided, distCoeff); raycastVsMeshCB( tree, orig, dir, maxDist, meshData->getGeomEpsilon(), bothSides, gRayCallback, &callback); return callback.mHitNum; } namespace { struct IntersectShapeVsMeshCallback { IntersectShapeVsMeshCallback(LimitedResults* results, bool flipNormal) : mResults(results), mAnyHits(false), mFlipNormal(flipNormal) {} LimitedResults* mResults; bool mAnyHits; bool mFlipNormal; PX_FORCE_INLINE bool recordHit(PxU32 faceIndex, PxIntBool hit) { if(hit) { mAnyHits = true; if(mResults) mResults->add(faceIndex); else return false; // abort traversal if we are only interested in firstContact (mResults is NULL) } return true; // if we are here, either no triangles were hit or multiple results are expected => continue traversal } }; // PT: TODO: get rid of this (TA34704) struct IntersectSphereVsMeshCallback : IntersectShapeVsMeshCallback { PX_FORCE_INLINE IntersectSphereVsMeshCallback(const PxMeshScale& meshScale, const PxTransform& meshTransform, const Sphere& sphere, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(r, flipNormal) { mVertexToShapeSkew = toMat33(meshScale); mLocalCenter = meshTransform.transformInv(sphere.center); // sphereCenterInMeshSpace mSphereRadius2 = sphere.radius*sphere.radius; } PxMat33 mVertexToShapeSkew; PxVec3 mLocalCenter; // PT: sphere center in local/mesh space PxF32 mSphereRadius2; PX_FORCE_INLINE PxAgain processHit(PxU32 faceIndex, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2) { const Vec3V v0 = V3LoadU(mVertexToShapeSkew * av0); const Vec3V v1 = V3LoadU(mVertexToShapeSkew * (mFlipNormal ? av2 : av1)); const Vec3V v2 = V3LoadU(mVertexToShapeSkew * (mFlipNormal ? av1 : av2)); FloatV dummy1, dummy2; Vec3V closestP; PxReal dist2; FStore(distancePointTriangleSquared(V3LoadU(mLocalCenter), v0, v1, v2, dummy1, dummy2, closestP), &dist2); return recordHit(faceIndex, dist2 <= mSphereRadius2); } }; // PT: TODO: get rid of this (TA34704) struct IntersectCapsuleVsMeshCallback : IntersectShapeVsMeshCallback { PX_FORCE_INLINE IntersectCapsuleVsMeshCallback(const PxMeshScale& meshScale, const PxTransform& meshTransform, const Capsule& capsule, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(r, flipNormal) { mVertexToShapeSkew = toMat33(meshScale); // transform world capsule to mesh shape space mLocalCapsule.p0 = meshTransform.transformInv(capsule.p0); mLocalCapsule.p1 = meshTransform.transformInv(capsule.p1); mLocalCapsule.radius = capsule.radius; mParams.init(mLocalCapsule); } PxMat33 mVertexToShapeSkew; Capsule mLocalCapsule; // PT: capsule in mesh/local space CapsuleTriangleOverlapData mParams; PX_FORCE_INLINE PxAgain processHit(PxU32 faceIndex, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2) { const PxVec3 v0 = mVertexToShapeSkew * av0; const PxVec3 v1 = mVertexToShapeSkew * (mFlipNormal ? av2 : av1); const PxVec3 v2 = mVertexToShapeSkew * (mFlipNormal ? av1 : av2); const PxVec3 normal = (v0 - v1).cross(v0 - v2); bool hit = intersectCapsuleTriangle(normal, v0, v1, v2, mLocalCapsule, mParams); return recordHit(faceIndex, hit); } }; // PT: TODO: get rid of this (TA34704) struct IntersectBoxVsMeshCallback : IntersectShapeVsMeshCallback { PX_FORCE_INLINE IntersectBoxVsMeshCallback(const PxMeshScale& meshScale, const PxTransform& meshTransform, const Box& box, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(r, flipNormal) { const PxMat33 vertexToShapeSkew = toMat33(meshScale); // mesh scale needs to be included - inverse transform and optimize the box const PxMat33 vertexToWorldSkew_Rot = PxMat33Padded(meshTransform.q) * vertexToShapeSkew; const PxVec3& vertexToWorldSkew_Trans = meshTransform.p; PxMat34 tmp; buildMatrixFromBox(tmp, box); const PxMat34 inv = tmp.getInverseRT(); const PxMat34 _vertexToWorldSkew(vertexToWorldSkew_Rot, vertexToWorldSkew_Trans); mVertexToBox = inv * _vertexToWorldSkew; mBoxCenter = PxVec3(0.0f); mBoxExtents = box.extents; // extents do not change } PxMat34 mVertexToBox; PxVec3p mBoxExtents, mBoxCenter; PX_FORCE_INLINE PxAgain processHit(PxU32 faceIndex, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2) { const PxVec3p v0 = mVertexToBox.transform(av0); const PxVec3p v1 = mVertexToBox.transform(mFlipNormal ? av2 : av1); const PxVec3p v2 = mVertexToBox.transform(mFlipNormal ? av1 : av2); // PT: this one is safe because we're using PxVec3p for all parameters const PxIntBool hit = intersectTriangleBox_Unsafe(mBoxCenter, mBoxExtents, v0, v1, v2); return recordHit(faceIndex, hit); } }; } static bool gSphereVsMeshCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* /*vertexIndices*/) { IntersectSphereVsMeshCallback* callback = reinterpret_cast<IntersectSphereVsMeshCallback*>(userData); return !callback->processHit(triangleIndex, p0, p1, p2); } static bool gCapsuleVsMeshCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* /*vertexIndices*/) { IntersectCapsuleVsMeshCallback* callback = reinterpret_cast<IntersectCapsuleVsMeshCallback*>(userData); return !callback->processHit(triangleIndex, p0, p1, p2); } static bool gBoxVsMeshCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* /*vertexIndices*/) { IntersectBoxVsMeshCallback* callback = reinterpret_cast<IntersectBoxVsMeshCallback*>(userData); return !callback->processHit(triangleIndex, p0, p1, p2); } bool physx::Gu::intersectSphereVsMesh_BV4(const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { PX_ASSERT(triMesh.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4Tree& tree = static_cast<const BV4TriangleMesh&>(triMesh).getBV4Tree(); if(meshScale.isIdentity()) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, &meshTransform.p.x, &meshTransform.q.x); if(results) { const PxU32 nbResults = BV4_OverlapSphereAll(sphere, tree, TM, results->mResults, results->mMaxResults, results->mOverflow); results->mNbResults = nbResults; return nbResults!=0; } else { return BV4_OverlapSphereAny(sphere, tree, TM)!=0; } } else { // PT: TODO: we don't need to use this callback here (TA34704) IntersectSphereVsMeshCallback callback(meshScale, meshTransform, sphere, results, meshScale.hasNegativeDeterminant()); const Box worldOBB_(sphere.center, PxVec3(sphere.radius), PxMat33(PxIdentity)); Box vertexOBB; computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale); BV4_OverlapBoxCB(vertexOBB, tree, gSphereVsMeshCallback, &callback); return callback.mAnyHits; } } bool physx::Gu::intersectBoxVsMesh_BV4(const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { PX_ASSERT(triMesh.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4Tree& tree = static_cast<const BV4TriangleMesh&>(triMesh).getBV4Tree(); if(meshScale.isIdentity()) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, &meshTransform.p.x, &meshTransform.q.x); if(results) { const PxU32 nbResults = BV4_OverlapBoxAll(box, tree, TM, results->mResults, results->mMaxResults, results->mOverflow); results->mNbResults = nbResults; return nbResults!=0; } else { return BV4_OverlapBoxAny(box, tree, TM)!=0; } } else { // PT: TODO: we don't need to use this callback here (TA34704) IntersectBoxVsMeshCallback callback(meshScale, meshTransform, box, results, meshScale.hasNegativeDeterminant()); Box vertexOBB; // query box in vertex space computeVertexSpaceOBB(vertexOBB, box, meshTransform, meshScale); BV4_OverlapBoxCB(vertexOBB, tree, gBoxVsMeshCallback, &callback); return callback.mAnyHits; } } bool physx::Gu::intersectCapsuleVsMesh_BV4(const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { PX_ASSERT(triMesh.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4Tree& tree = static_cast<const BV4TriangleMesh&>(triMesh).getBV4Tree(); if(meshScale.isIdentity()) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, &meshTransform.p.x, &meshTransform.q.x); if(results) { const PxU32 nbResults = BV4_OverlapCapsuleAll(capsule, tree, TM, results->mResults, results->mMaxResults, results->mOverflow); results->mNbResults = nbResults; return nbResults!=0; } else { return BV4_OverlapCapsuleAny(capsule, tree, TM)!=0; } } else { // PT: TODO: we don't need to use this callback here (TA34704) IntersectCapsuleVsMeshCallback callback(meshScale, meshTransform, capsule, results, meshScale.hasNegativeDeterminant()); // make vertex space OBB Box vertexOBB; Box worldOBB_; worldOBB_.create(capsule); // AP: potential optimization (meshTransform.inverse is already in callback.mCapsule) computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale); BV4_OverlapBoxCB(vertexOBB, tree, gCapsuleVsMeshCallback, &callback); return callback.mAnyHits; } } // PT: TODO: get rid of this (TA34704) static bool gVolumeCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* vertexIndices) { MeshHitCallback<PxGeomRaycastHit>* callback = reinterpret_cast<MeshHitCallback<PxGeomRaycastHit>*>(userData); PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& hit = reinterpret_cast<PxGeomRaycastHit&>(buffer); hit.faceIndex = triangleIndex; PxReal dummy; return !callback->processHit(hit, p0, p1, p2, dummy, vertexIndices); } static bool gTetVolumeCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& p3, PxU32 tetIndex, const PxU32* vertexIndices) { TetMeshHitCallback<PxGeomRaycastHit>* callback = reinterpret_cast<TetMeshHitCallback<PxGeomRaycastHit>*>(userData); PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& hit = reinterpret_cast<PxGeomRaycastHit&>(buffer); hit.faceIndex = tetIndex; PxReal dummy; return !callback->processHit(hit, p0, p1, p2, p3, dummy, vertexIndices); } void physx::Gu::intersectOBB_BV4(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned) { PX_UNUSED(checkObbIsAligned); PX_UNUSED(bothTriangleSidesCollide); BV4_OverlapBoxCB(obb, static_cast<const BV4TriangleMesh*>(mesh)->getBV4Tree(), gVolumeCallback, &callback); } void physx::Gu::intersectOBB_BV4(const TetrahedronMesh* mesh, const Box& obb, TetMeshHitCallback<PxGeomRaycastHit>& callback) { BV4_OverlapBoxCB(obb, static_cast<const BVTetrahedronMesh*>(mesh)->getBV4Tree(), gTetVolumeCallback, &callback); } #include "GuVecCapsule.h" #include "GuSweepMTD.h" static bool gCapsuleMeshSweepCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, /*const PxU32* vertexIndices,*/ float& dist) { SweepCapsuleMeshHitCallback* callback = reinterpret_cast<SweepCapsuleMeshHitCallback*>(userData); PxGeomRaycastHit meshHit; meshHit.faceIndex = triangleIndex; return !callback->SweepCapsuleMeshHitCallback::processHit(meshHit, p0, p1, p2, dist, NULL/*vertexIndices*/); } // PT: TODO: refactor/share bits of this (TA34704) bool physx::Gu::sweepCapsule_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Capsule& lss, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4TriangleMesh* meshData = static_cast<const BV4TriangleMesh*>(mesh); const Capsule inflatedCapsule(lss.p0, lss.p1, lss.radius + inflation); const bool isIdentity = triMeshGeom.scale.isIdentity(); bool isDoubleSided = (triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED); const PxU32 meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; if(isIdentity) { const BV4Tree& tree = meshData->getBV4Tree(); const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY; BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, &pose.p.x, &pose.q.x); const PxU32 flags = setupFlags(anyHit, isDoubleSided, meshBothSides!=0); SweepHit hitData; if(lss.p0==lss.p1) { if(!sphereSweepVsMesh(hitData, tree, inflatedCapsule.p0, inflatedCapsule.radius, unitDir, distance, TM, flags)) return false; } else { if(!capsuleSweepVsMesh(hitData, tree, inflatedCapsule, unitDir, distance, TM, flags)) return false; } sweepHit.distance = hitData.mDistance; sweepHit.position = hitData.mPos; sweepHit.normal = hitData.mNormal; sweepHit.faceIndex = hitData.mTriangleID; if(hitData.mDistance==0.0f) { sweepHit.flags = PxHitFlag::eNORMAL; if(meshBothSides) isDoubleSided = true; // PT: TODO: consider using 'setInitialOverlapResults' here bool hasContacts = false; if(hitFlags & PxHitFlag::eMTD) { const Vec3V p0 = V3LoadU(inflatedCapsule.p0); const Vec3V p1 = V3LoadU(inflatedCapsule.p1); const FloatV radius = FLoad(lss.radius); CapsuleV capsuleV; capsuleV.initialize(p0, p1, radius); //we need to calculate the MTD hasContacts = computeCapsule_TriangleMeshMTD(triMeshGeom, pose, capsuleV, inflatedCapsule.radius, isDoubleSided, sweepHit); } setupSweepHitForMTD(sweepHit, hasContacts, unitDir); } else sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; return true; } // compute sweptAABB const PxVec3 localP0 = pose.transformInv(inflatedCapsule.p0); const PxVec3 localP1 = pose.transformInv(inflatedCapsule.p1); PxVec3 sweepOrigin = (localP0+localP1)*0.5f; PxVec3 sweepDir = pose.rotateInv(unitDir); PxVec3 sweepExtents = PxVec3(inflatedCapsule.radius) + (localP0-localP1).abs()*0.5f; PxReal distance1 = distance; PxReal distCoef = 1.0f; PxMat34 poseWithScale; if(!isIdentity) { poseWithScale = pose * triMeshGeom.scale; distance1 = computeSweepData(triMeshGeom, sweepOrigin, sweepExtents, sweepDir, distance); distCoef = distance1 / distance; } else poseWithScale = Matrix34FromTransform(pose); SweepCapsuleMeshHitCallback callback(sweepHit, poseWithScale, distance, isDoubleSided, inflatedCapsule, unitDir, hitFlags, triMeshGeom.scale.hasNegativeDeterminant(), distCoef); boxSweepVsMeshCBOld(meshData->getBV4Tree(), NULL, NULL, sweepOrigin, sweepExtents, sweepDir, distance1, gCapsuleMeshSweepCallback, &callback); if(meshBothSides) isDoubleSided = true; return callback.finalizeHit(sweepHit, inflatedCapsule, triMeshGeom, pose, isDoubleSided); } #include "GuSweepSharedTests.h" static bool gBoxMeshSweepCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, /*const PxU32* vertexIndices,*/ float& dist) { SweepBoxMeshHitCallback* callback = reinterpret_cast<SweepBoxMeshHitCallback*>(userData); PxGeomRaycastHit meshHit; meshHit.faceIndex = triangleIndex; return !callback->SweepBoxMeshHitCallback::processHit(meshHit, p0, p1, p2, dist, NULL/*vertexIndices*/); } // PT: TODO: refactor/share bits of this (TA34704) bool physx::Gu::sweepBox_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4TriangleMesh* meshData = static_cast<const BV4TriangleMesh*>(mesh); const bool isIdentity = triMeshGeom.scale.isIdentity(); const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; const bool isDoubleSided = triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED; if(isIdentity && inflation==0.0f) { const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY; // PT: TODO: this is wrong, we shouldn't actually sweep the inflated version // const PxVec3 inflated = (box.extents + PxVec3(inflation)) * 1.01f; // PT: TODO: avoid this copy // const Box tmp(box.center, inflated, box.rot); SweepHit hitData; // if(!boxSweepVsMesh(hitData, meshData->getBV4Tree(), &pose.p.x, &pose.q.x, tmp, unitDir, distance, anyHit, isDoubleSided, meshBothSides)) if(!boxSweepVsMesh(hitData, meshData->getBV4Tree(), &pose.p.x, &pose.q.x, box, unitDir, distance, anyHit, isDoubleSided, meshBothSides)) return false; sweepHit.distance = hitData.mDistance; sweepHit.position = hitData.mPos; sweepHit.normal = hitData.mNormal; sweepHit.faceIndex = hitData.mTriangleID; if(hitData.mDistance==0.0f) { sweepHit.flags = PxHitFlag::eNORMAL; const bool bothTriangleSidesCollide = isDoubleSided || meshBothSides; const PxTransform boxTransform = box.getTransform(); bool hasContacts = false; if(hitFlags & PxHitFlag::eMTD) hasContacts = computeBox_TriangleMeshMTD(triMeshGeom, pose, box, boxTransform, inflation, bothTriangleSidesCollide, sweepHit); setupSweepHitForMTD(sweepHit, hasContacts, unitDir); } else { sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; } return true; } // PT: TODO: revisit this codepath, we don't need to sweep an AABB all the time (TA34704) PxMat34 meshToWorldSkew; PxVec3 sweptAABBMeshSpaceExtents, meshSpaceOrigin, meshSpaceDir; // Input sweep params: geom, pose, box, unitDir, distance // We convert the origin from world space to mesh local space // and convert the box+pose to mesh space AABB if(isIdentity) { meshToWorldSkew = Matrix34FromTransform(pose); const PxMat33Padded worldToMeshRot(pose.q.getConjugate()); // extract rotation matrix from pose.q meshSpaceOrigin = worldToMeshRot.transform(box.center - pose.p); meshSpaceDir = worldToMeshRot.transform(unitDir) * distance; PxMat33 boxToMeshRot = worldToMeshRot * box.rot; sweptAABBMeshSpaceExtents = boxToMeshRot.column0.abs() * box.extents.x + boxToMeshRot.column1.abs() * box.extents.y + boxToMeshRot.column2.abs() * box.extents.z; } else { meshToWorldSkew = pose * triMeshGeom.scale; const PxMat33 meshToWorldSkew_Rot = PxMat33Padded(pose.q) * toMat33(triMeshGeom.scale); const PxVec3& meshToWorldSkew_Trans = pose.p; PxMat33 worldToVertexSkew_Rot; PxVec3 worldToVertexSkew_Trans; getInverse(worldToVertexSkew_Rot, worldToVertexSkew_Trans, meshToWorldSkew_Rot, meshToWorldSkew_Trans); //make vertex space OBB Box vertexSpaceBox1; const PxMat34 worldToVertexSkew(worldToVertexSkew_Rot, worldToVertexSkew_Trans); vertexSpaceBox1 = transform(worldToVertexSkew, box); // compute swept aabb sweptAABBMeshSpaceExtents = vertexSpaceBox1.computeAABBExtent(); meshSpaceOrigin = worldToVertexSkew.transform(box.center); meshSpaceDir = worldToVertexSkew.rotate(unitDir*distance); // also applies scale to direction/length } sweptAABBMeshSpaceExtents += PxVec3(inflation); // inflate the bounds with additive inflation sweptAABBMeshSpaceExtents *= 1.01f; // fatten the bounds to account for numerical discrepancies PxReal dirLen = PxMax(meshSpaceDir.magnitude(), 1e-5f); PxReal distCoeff = 1.0f; if (!isIdentity) distCoeff = dirLen / distance; // Move to AABB space PxMat34 worldToBox; computeWorldToBoxMatrix(worldToBox, box); const bool bothTriangleSidesCollide = isDoubleSided || meshBothSides; const PxMat34Padded meshToBox = worldToBox*meshToWorldSkew; const PxTransform boxTransform = box.getTransform(); // PT: TODO: this is not needed when there's no hit (TA34704) const PxVec3 localDir = worldToBox.rotate(unitDir); const PxVec3 localDirDist = localDir*distance; SweepBoxMeshHitCallback callback( // using eMULTIPLE with shrinkMaxT CallbackMode::eMULTIPLE, meshToBox, distance, bothTriangleSidesCollide, box, localDirDist, localDir, unitDir, hitFlags, inflation, triMeshGeom.scale.hasNegativeDeterminant(), distCoeff); const PxVec3 dir = meshSpaceDir/dirLen; boxSweepVsMeshCBOld(meshData->getBV4Tree(), NULL, NULL, meshSpaceOrigin, sweptAABBMeshSpaceExtents, dir, dirLen, gBoxMeshSweepCallback, &callback); return callback.finalizeHit(sweepHit, triMeshGeom, pose, boxTransform, localDir, meshBothSides, isDoubleSided); } static bool gConvexVsMeshSweepCallback(void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, /*const PxU32* vertexIndices,*/ float& dist) { SweepConvexMeshHitCallback* callback = reinterpret_cast<SweepConvexMeshHitCallback*>(userData); PX_ALIGN_PREFIX(16) char buffer[sizeof(PxGeomRaycastHit)] PX_ALIGN_SUFFIX(16); PxGeomRaycastHit& hit = reinterpret_cast<PxGeomRaycastHit&>(buffer); hit.faceIndex = triangleIndex; return !callback->SweepConvexMeshHitCallback::processHit(hit, p0, p1, p2, dist, NULL/*vertexIndices*/); } void physx::Gu::sweepConvex_MeshGeom_BV4(const TriangleMesh* mesh, const Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4TriangleMesh* meshData = static_cast<const BV4TriangleMesh*>(mesh); BV4_GenericSweepCB(hullBox, localDir, distance, meshData->getBV4Tree(), gConvexVsMeshSweepCallback, &callback, anyHit); } void BV4_PointDistance(const PxVec3& point, const BV4Tree& tree, float maxDist, PxU32& index, float& dist, PxVec3& cp/*, const PxMat44* PX_RESTRICT worldm_Aligned*/); void Gu::pointMeshDistance_BV4(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist , PxU32& index, float& dist, PxVec3& closestPt) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4TriangleMesh* meshData = static_cast<const BV4TriangleMesh*>(mesh); const BV4Tree& tree = static_cast<const BV4TriangleMesh*>(meshData)->getBV4Tree(); const bool idtScale = meshGeom.scale.isIdentity(); /* if(idtScale) { BV4_ALIGN16(PxMat44 World); const PxMat44* TM = setupWorldMatrix(World, &pose.p.x, &pose.q.x); PxU32 index; float dist; PxVec3 cp; BV4_PointDistance(point, tree, index, dist, cp, TM); } else*/ if(idtScale) { const PxVec3 orig = pose.transformInv(point); PxVec3 cp; BV4_PointDistance(orig, tree, maxDist, index, dist, cp); closestPt = pose.transform(cp); } else { // Scaling: transform the point to vertex space const PxMat34 world2vertexSkew = meshGeom.scale.getInverse() * pose.getInverse(); const PxVec3 orig = world2vertexSkew.transform(point); PxVec3 cp; BV4_PointDistance(orig, tree, maxDist, index, dist, cp); // PT: TODO: do we need to fix the distance when mesh scale is not idt? closestPt = pose.transform(meshGeom.scale.transform(cp)); } } bool BV4_OverlapMeshVsMesh( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, PxMeshMeshQueryFlags meshMeshFlags, float tolerance); bool BV4_OverlapMeshVsMesh( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, const PxTransform& meshPose0, const PxTransform& meshPose1, const PxMeshScale& meshScale0, const PxMeshScale& meshScale1, PxMeshMeshQueryFlags meshMeshFlags, float tolerance); bool physx::Gu::intersectMeshVsMesh_BV4(PxReportCallback<PxGeomIndexPair>& callback, const TriangleMesh& triMesh0, const PxTransform& meshPose0, const PxMeshScale& meshScale0, const TriangleMesh& triMesh1, const PxTransform& meshPose1, const PxMeshScale& meshScale1, PxMeshMeshQueryFlags meshMeshFlags, float tolerance) { PX_ASSERT(triMesh0.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); PX_ASSERT(triMesh1.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH34); const BV4Tree& tree0 = static_cast<const BV4TriangleMesh&>(triMesh0).getBV4Tree(); const BV4Tree& tree1 = static_cast<const BV4TriangleMesh&>(triMesh1).getBV4Tree(); const PxTransform t0to1 = meshPose1.transformInv(meshPose0); const PxTransform t1to0 = meshPose0.transformInv(meshPose1); BV4_ALIGN16(PxMat44 World0to1); const PxMat44* TM0to1 = setupWorldMatrix(World0to1, &t0to1.p.x, &t0to1.q.x); BV4_ALIGN16(PxMat44 World1to0); const PxMat44* TM1to0 = setupWorldMatrix(World1to0, &t1to0.p.x, &t1to0.q.x); if(!meshScale0.isIdentity() || !meshScale1.isIdentity()) return BV4_OverlapMeshVsMesh(callback, tree0, tree1, TM0to1, TM1to0, meshPose0, meshPose1, meshScale0, meshScale1, meshMeshFlags, tolerance)!=0; else return BV4_OverlapMeshVsMesh(callback, tree0, tree1, TM0to1, TM1to0, meshMeshFlags, tolerance)!=0; }
44,460
C++
39.677951
265
0.751282
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_CapsuleSweep_Internal.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_CAPSULE_SWEEP_INTERNAL_H #define GU_BV4_CAPSULE_SWEEP_INTERNAL_H // PT: for capsule-sweeps please refer to %SDKRoot%\InternalDocumentation\GU\Sweep strategies.ppt. // We use: // - method 3 if the capsule is axis-aligned (SWEEP_AABB_IMPL is defined) // - method 2 otherwise (SWEEP_AABB_IMPL is undefined) // PT: TODO: get rid of that one static PX_FORCE_INLINE bool sweepSphereVSTriangle( const PxVec3& center, const float radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& triUnitNormal, const PxVec3& unitDir, float& curT, bool& directHit) { float currentDistance; if(!sweepSphereVSTri(triVerts, triUnitNormal, center, radius, unitDir, currentDistance, directHit, true)) return false; // PT: using ">" or ">=" is enough to block the CCT or not in the DE5967 visual test. Change to ">=" if a repro is needed. if(currentDistance > curT + GU_EPSILON_SAME_DISTANCE * PxMax(1.0f, curT)) return false; curT = currentDistance; return true; } static PX_FORCE_INLINE bool sweepSphereVSQuad( const PxVec3& center, const float radius, const PxVec3* PX_RESTRICT quadVerts, const PxVec3& quadUnitNormal, const PxVec3& unitDir, float& curT) { float currentDistance; if(!sweepSphereVSQuad(quadVerts, quadUnitNormal, center, radius, unitDir, currentDistance)) return false; // PT: using ">" or ">=" is enough to block the CCT or not in the DE5967 visual test. Change to ">=" if a repro is needed. if(currentDistance > curT + GU_EPSILON_SAME_DISTANCE * PxMax(1.0f, curT)) return false; curT = currentDistance; return true; } /////////////////////////////////////////////////////////////////////////////// // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static bool /*__fastcall*/ testTri( const CapsuleSweepParams* PX_RESTRICT params, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& N, const PxVec3& unitDir, const float capsuleRadius, const float dpc0, float& curT, bool& status) { // PT: TODO: check the assembly here (TA34704) PxVec3 currentTri[3]; // PT: TODO: optimize this copy (TA34704) currentTri[0] = p0; currentTri[1] = p1; currentTri[2] = p2; // PT: beware, culling is only ok on the sphere I think if(rejectTriangle(params->mCapsuleCenter, unitDir, curT, capsuleRadius, currentTri, dpc0)) return false; float magnitude = N.magnitude(); if(magnitude==0.0f) return false; PxVec3 triNormal = N / magnitude; bool DirectHit; if(sweepSphereVSTriangle(params->mCapsuleCenter, capsuleRadius, currentTri, triNormal, unitDir, curT, DirectHit)) { status = true; } return DirectHit; } // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static void /*__fastcall*/ testQuad(const CapsuleSweepParams* PX_RESTRICT params, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& p3, const PxVec3& N, const PxVec3& unitDir, const float capsuleRadius, const float dpc0, float& curT, bool& status) { // PT: TODO: optimize this copy (TA34704) PxVec3 currentQuad[4]; currentQuad[0] = p0; currentQuad[1] = p1; currentQuad[2] = p2; currentQuad[3] = p3; // PT: beware, culling is only ok on the sphere I think if(rejectQuad(params->mCapsuleCenter, unitDir, curT, capsuleRadius, currentQuad, dpc0)) return; float magnitude = N.magnitude(); if(magnitude==0.0f) return; PxVec3 triNormal = N / magnitude; if(sweepSphereVSQuad(params->mCapsuleCenter, capsuleRadius, currentQuad, triNormal, unitDir, curT)) { status = true; } } static PX_FORCE_INLINE float Set2(const PxVec3& p0, const PxVec3& n, const PxVec3& p) { return (p-p0).dot(n); } static PX_FORCE_INLINE bool sweepCapsuleVsTriangle(const CapsuleSweepParams* PX_RESTRICT params, const PxTriangle& triangle, float& t, bool isDoubleSided, PxVec3& normal) { const PxVec3& unitDir = params->mLocalDir_Padded; // Create triangle normal PxVec3 denormalizedNormal = (triangle.verts[0] - triangle.verts[1]).cross(triangle.verts[0] - triangle.verts[2]); normal = denormalizedNormal; // Backface culling const bool culled = denormalizedNormal.dot(unitDir) > 0.0f; if(culled) { if(!isDoubleSided) return false; denormalizedNormal = -denormalizedNormal; } const float capsuleRadius = params->mLocalCapsule.radius; float curT = params->mStabbedFace.mDistance;// + GU_EPSILON_SAME_DISTANCE*20.0f; const float dpc0 = params->mCapsuleCenter.dot(unitDir); bool status = false; // Extrude mesh on the fly const PxVec3 p0 = triangle.verts[0] - params->mExtrusionDir; const PxVec3 p1 = triangle.verts[1+culled] - params->mExtrusionDir; const PxVec3 p2 = triangle.verts[2-culled] - params->mExtrusionDir; const PxVec3 p0b = triangle.verts[0] + params->mExtrusionDir; const PxVec3 p1b = triangle.verts[1+culled] + params->mExtrusionDir; const PxVec3 p2b = triangle.verts[2-culled] + params->mExtrusionDir; const float extrusionSign = denormalizedNormal.dot(params->mExtrusionDir); const PxVec3 p2b_p1b = p2b - p1b; const PxVec3 p0b_p1b = p0b - p1b; const PxVec3 p2b_p2 = 2.0f * params->mExtrusionDir; const PxVec3 p1_p1b = -p2b_p2; const PxVec3 N1 = p2b_p1b.cross(p0b_p1b); const float dp0 = Set2(p0b, N1, params->mCapsuleCenter); const PxVec3 N2 = (p2 - p1).cross(p0 - p1); const float dp1 = -Set2(p0, N2, params->mCapsuleCenter); bool directHit; if(extrusionSign >= 0.0f) directHit = testTri(params, p0b, p1b, p2b, N1, unitDir, capsuleRadius, dpc0, curT, status); else directHit = testTri(params, p0, p1, p2, N2, unitDir, capsuleRadius, dpc0, curT, status); const PxVec3 N3 = p2b_p1b.cross(p1_p1b); const float dp2 = -Set2(p1, N3, params->mCapsuleCenter); if(!directHit) { const float dp = N3.dot(unitDir); if(dp*extrusionSign>=0.0f) testQuad(params, p1, p1b, p2, p2b, N3, unitDir, capsuleRadius, dpc0, curT, status); } const PxVec3 N5 = p2b_p2.cross(p0 - p2); const float dp3 = -Set2(p0, N5, params->mCapsuleCenter); if(!directHit) { const float dp = N5.dot(unitDir); if(dp*extrusionSign>=0.0f) testQuad(params, p2, p2b, p0, p0b, N5, unitDir, capsuleRadius, dpc0, curT, status); } const PxVec3 N7 = p1_p1b.cross(p0b_p1b); const float dp4 = -Set2(p0b, N7, params->mCapsuleCenter); if(!directHit) { const float dp = N7.dot(unitDir); if(dp*extrusionSign>=0.0f) testQuad(params, p0, p0b, p1, p1b, N7, unitDir, capsuleRadius, dpc0, curT, status); } if(1) { bool originInside = true; if(extrusionSign<0.0f) { if(dp0<0.0f || dp1<0.0f || dp2<0.0f || dp3<0.0f || dp4<0.0f) originInside = false; } else { if(dp0>0.0f || dp1>0.0f || dp2>0.0f || dp3>0.0f || dp4>0.0f) originInside = false; } if(originInside) { t = 0.0f; return true; } } if(!status) return false; // We didn't touch any triangle t = curT; return true; } // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static bool /*__fastcall*/ triCapsuleSweep(CapsuleSweepParams* PX_RESTRICT params, PxU32 primIndex, bool nodeSorting=true) { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; const PxTriangle Tri(p0, p1, p2); // PT: TODO: check calls to empty ctor/dtor here (TA34704) const bool isDoubleSided = params->mBackfaceCulling==0; float dist; PxVec3 denormalizedNormal; if(sweepCapsuleVsTriangle(params, Tri, dist, isDoubleSided, denormalizedNormal)) { denormalizedNormal.normalize(); const PxReal alignmentValue = computeAlignmentValue(denormalizedNormal, params->mLocalDir_Padded); if(keepTriangle(dist, alignmentValue, params->mBestDistance, params->mBestAlignmentValue, params->mMaxDist)) { params->mStabbedFace.mDistance = dist; params->mStabbedFace.mTriangleID = primIndex; params->mP0 = p0; params->mP1 = p1; params->mP2 = p2; params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound params->mBestAlignmentValue = alignmentValue; params->mBestTriNormal = denormalizedNormal; if(nodeSorting) { #ifdef SWEEP_AABB_IMPL #ifndef GU_BV4_USE_SLABS //setupRayData(params, dist, params->mOrigin_Padded, params->mLocalDir_PaddedAligned); setupRayData(params, params->mBestDistance, params->mOrigin_Padded, params->mLocalDir_PaddedAligned); #endif #else //params->ShrinkOBB(dist); params->ShrinkOBB(params->mBestDistance); #endif } return true; } /// else if(keepTriangleBasic(dist, params->mBestDistance, params->mMaxDist)) { params->mStabbedFace.mDistance = dist; params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound } /// } return false; } #include "GuDistanceSegmentTriangle.h" namespace { class LeafFunction_CapsuleSweepClosest { public: static PX_FORCE_INLINE void doLeafTest(CapsuleSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { triCapsuleSweep(params, primIndex); primIndex++; }while(nbToGo--); } }; class LeafFunction_CapsuleSweepAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(CapsuleSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triCapsuleSweep(params, primIndex)) return 1; primIndex++; }while(nbToGo--); return 0; } }; class ImpactFunctionCapsule { public: static PX_FORCE_INLINE void computeImpact(PxVec3& impactPos, PxVec3& impactNormal, const Capsule& capsule, const PxVec3& dir, const PxReal t, const PxTrianglePadded& triangle) { const PxVec3 delta = dir * t; const PxVec3p P0 = capsule.p0 + delta; const PxVec3p P1 = capsule.p1 + delta; Vec3V pointOnSeg, pointOnTri; distanceSegmentTriangleSquared( // PT: we use PxVec3p so it is safe to V4LoadU P0 and P1 V3LoadU_SafeReadW(P0), V3LoadU_SafeReadW(P1), // PT: we use PxTrianglePadded so it is safe to V4LoadU the triangle vertices V3LoadU_SafeReadW(triangle.verts[0]), V3LoadU_SafeReadW(triangle.verts[1]), V3LoadU_SafeReadW(triangle.verts[2]), pointOnSeg, pointOnTri); PxVec3 localImpactPos, tmp; V3StoreU(pointOnTri, localImpactPos); V3StoreU(pointOnSeg, tmp); // PT: TODO: refactor with computeSphereTriImpactData (TA34704) PxVec3 localImpactNormal = tmp - localImpactPos; const float M = localImpactNormal.magnitude(); if(M<1e-3f) { localImpactNormal = (triangle.verts[0] - triangle.verts[1]).cross(triangle.verts[0] - triangle.verts[2]); localImpactNormal.normalize(); } else localImpactNormal /= M; impactPos = localImpactPos; impactNormal = localImpactNormal; } }; } static void computeBoxAroundCapsule(const Capsule& capsule, Box& box, PxVec3& extrusionDir) { // Box center = center of the two capsule's endpoints box.center = capsule.computeCenter(); extrusionDir = (capsule.p0 - capsule.p1)*0.5f; const PxF32 d = extrusionDir.magnitude(); // Box extents box.extents.x = capsule.radius + d; box.extents.y = capsule.radius; box.extents.z = capsule.radius; // Box orientation if(d==0.0f) { box.rot = PxMat33(PxIdentity); } else { PxVec3 dir, right, up; PxComputeBasisVectors(capsule.p0, capsule.p1, dir, right, up); box.setAxes(dir, right, up); } } template<class ParamsT> static PX_FORCE_INLINE void setupCapsuleParams(ParamsT* PX_RESTRICT params, const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree* PX_RESTRICT tree, const SourceMesh* PX_RESTRICT mesh, PxU32 flags) { params->mStabbedFace.mTriangleID = PX_INVALID_U32; params->mBestAlignmentValue = 2.0f; params->mBestDistance = maxDist + GU_EPSILON_SAME_DISTANCE; params->mMaxDist = maxDist; setupParamsFlags(params, flags); setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); params->mLocalCapsule = capsule; Box localBox; computeBoxAroundCapsule(capsule, localBox, params->mExtrusionDir); params->mCapsuleCenter = localBox.center; const PxVec3& localDir = dir; #ifdef SWEEP_AABB_IMPL const PxVec3& localP0 = params->mLocalCapsule.p0; const PxVec3& localP1 = params->mLocalCapsule.p1; const PxVec3 sweepOrigin = (localP0+localP1)*0.5f; const PxVec3 sweepExtents = PxVec3(params->mLocalCapsule.radius) + (localP0-localP1).abs()*0.5f; #ifndef GU_BV4_USE_SLABS params->mLocalDir_PaddedAligned = localDir; #endif params->mOrigin_Padded = sweepOrigin; const Box aabb(sweepOrigin, sweepExtents, PxMat33(PxIdentity)); prepareSweepData(aabb, localDir, maxDist, params); // PT: TODO: optimize this call for idt rotation (TA34704) #ifndef GU_BV4_USE_SLABS setupRayData(params, maxDist, sweepOrigin, localDir); #endif #else prepareSweepData(localBox, localDir, maxDist, params); #endif } #endif // GU_BV4_CAPSULE_SWEEP_INTERNAL_H
14,502
C
31.738149
215
0.722452
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedron.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TETRAHEDRON_H #define GU_TETRAHEDRON_H #include "foundation/PxVec3.h" #include "foundation/PxUtilities.h" #include "GuTriangle.h" namespace physx { namespace Gu { /** \brief Structure used to store indices for a triangles points. T is either PxU32 or PxU16 */ template <class T> struct TetrahedronT// : public PxUserAllocated { PX_INLINE TetrahedronT() {} PX_INLINE TetrahedronT(T a, T b, T c, T d) { v[0] = a; v[1] = b; v[2] = c; v[3] = d; } template <class TX> PX_INLINE TetrahedronT(const TetrahedronT<TX>& other) { v[0] = other[0]; v[1] = other[1]; v[2] = other[2]; } PX_INLINE T& operator[](T i) { return v[i]; } template<class TX>//any type of TriangleT<>, possibly with different T PX_INLINE TetrahedronT<T>& operator=(const TetrahedronT<TX>& i) { v[0] = i[0]; v[1] = i[1]; v[2] = i[2]; v[3] = i[3]; return *this; } PX_INLINE const T& operator[](T i) const { return v[i]; } PX_INLINE PxI32 indexOf(T i) const { if (v[0] == i) return 0; if (v[1] == i) return 1; if (v[2] == i) return 2; if (v[3] == i) return 3; return -1; } PX_INLINE bool contains(T id) const { return v[0] == id || v[1] == id || v[2] == id || v[3] == id; } PX_INLINE void replace(T oldId, T newId) { if (v[0] == oldId) v[0] = newId; if (v[1] == oldId) v[1] = newId; if (v[2] == oldId) v[2] = newId; if (v[3] == oldId) v[3] = newId; } PX_INLINE void sort() { if (v[0] > v[1]) PxSwap(v[0], v[1]); if (v[2] > v[3]) PxSwap(v[2], v[3]); if (v[0] > v[2]) PxSwap(v[0], v[2]); if (v[1] > v[3]) PxSwap(v[1], v[3]); if (v[1] > v[2]) PxSwap(v[1], v[2]); } PX_INLINE bool containsFace(const Gu::IndexedTriangleT<T>& triangle) const { return contains(triangle[0]) && contains(triangle[1]) && contains(triangle[2]); } PX_INLINE static bool identical(Gu::TetrahedronT<T> x, Gu::TetrahedronT<T> y) { x.sort(); y.sort(); return x.v[0] == y.v[0] && x.v[1] == y.v[1] && x.v[2] == y.v[2] && x.v[3] == y.v[3]; } T v[4]; //vertex indices }; } } #endif
3,801
C
34.53271
136
0.647198
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV32.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV32_H #define GU_BV32_H #include "foundation/PxBounds3.h" #include "foundation/PxVec4.h" #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxArray.h" #include "GuBV4.h" namespace physx { namespace Gu { struct BV32Data : public physx::PxUserAllocated { PxVec3 mMin; PxVec3 mMax; PxU32 mNbLeafNodes; PxU32 mDepth; size_t mData; PX_FORCE_INLINE BV32Data() : mNbLeafNodes(0), mDepth(0), mData(PX_INVALID_U32) { setEmpty(); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isLeaf() const { return mData & 1; } //if the node is leaf, PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbReferencedPrimitives() const { PX_ASSERT(isLeaf()); return PxU32((mData >>1)&63); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getPrimitiveStartIndex() const { PX_ASSERT(isLeaf()); return PxU32(mData >> 7); } //PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getPrimitive() const { return mData >> 1; } //if the node isn't leaf, we will get the childOffset PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getChildOffset() const { PX_ASSERT(!isLeaf()); return PxU32(mData >> GU_BV4_CHILD_OFFSET_SHIFT_COUNT); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbChildren() const { PX_ASSERT(!isLeaf()); return ((mData) & ((1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT) - 1))>>1; } PX_CUDA_CALLABLE PX_FORCE_INLINE void getMinMax(PxVec3& min, PxVec3& max) const { //min = mCenter - mExtents; //max = mCenter + mExtents; min = mMin; max = mMax; } PX_FORCE_INLINE void setEmpty() { //mCenter = PxVec3(0.0f, 0.0f, 0.0f); //mExtents = PxVec3(-1.0f, -1.0f, -1.0f); mMin = PxVec3(PX_MAX_F32); mMax = PxVec3(-PX_MAX_F32); } }; PX_ALIGN_PREFIX(16) struct BV32DataPacked { /*PxVec4 mCenter[32]; PxVec4 mExtents[32];*/ PxVec4 mMin[32]; PxVec4 mMax[32]; PxU32 mData[32]; PxU32 mNbNodes; PxU32 mDepth; PxU32 padding[2]; PX_CUDA_CALLABLE PX_FORCE_INLINE BV32DataPacked() : mNbNodes(0), mDepth(0) { } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isLeaf(const PxU32 index) const { return mData[index] & 1; } //if the node is leaf PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbReferencedPrimitives(const PxU32 index) const { PX_ASSERT(isLeaf(index)); return (mData[index] >> 1) & 63; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getPrimitiveStartIndex(const PxU32 index) const { PX_ASSERT(isLeaf(index)); return (mData[index] >> 7); } //if the node isn't leaf, we will get the childOffset PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getChildOffset(const PxU32 index) const { PX_ASSERT(!isLeaf(index)); return mData[index] >> GU_BV4_CHILD_OFFSET_SHIFT_COUNT; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbChildren(const PxU32 index) const { PX_ASSERT(!isLeaf(index)); return ((mData[index])& ((1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT) - 1)) >> 1; } } PX_ALIGN_SUFFIX(16); //This struct store the start and end index of the packed node at the same depth level in the tree struct BV32DataDepthInfo { public: PxU32 offset; PxU32 count; }; class BV32Tree : public physx::PxUserAllocated { public: // PX_SERIALIZATION BV32Tree(const PxEMPTY); void exportExtraData(PxSerializationContext&); void importExtraData(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION BV32Tree(); BV32Tree(SourceMesh* meshInterface, const PxBounds3& localBounds); ~BV32Tree(); bool refit(const float epsilon); bool load(PxInputStream& stream, bool mismatch); void createSOAformatNode(BV32DataPacked& packedData, const BV32Data& node, const PxU32 childOffset, PxU32& currentIndex, PxU32& nbPackedNodes); void reset(); void operator = (BV32Tree& v); bool init(SourceMeshBase* meshInterface, const PxBounds3& localBounds); void release(); SourceMeshBase* mMeshInterface; LocalBounds mLocalBounds; PxU32 mNbNodes; BV32Data* mNodes; BV32DataPacked* mPackedNodes; PxU32 mNbPackedNodes; PxU32* mRemapPackedNodeIndexWithDepth; BV32DataDepthInfo* mTreeDepthInfo; PxU32 mMaxTreeDepth; PxU32 mInitData; bool mUserAllocated; // PT: please keep these 4 bytes right after mCenterOrMinCoeff/mExtentsOrMaxCoeff for safe V4 loading bool mPadding[2]; }; } // namespace Gu } #endif // GU_BV32_H
6,175
C
36.430303
190
0.705101
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxSweep_Internal.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuSweepTriangleUtils.h" #include "GuSweepBoxTriangle_FeatureBased.h" #include "GuSweepBoxTriangle_SAT.h" #include "GuBV4_BoxOverlap_Internal.h" // PT: for box-sweeps please refer to %SDKRoot%\InternalDocumentation\GU\Sweep strategies.ppt. // We use: // - method 3 if the box is an AABB (SWEEP_AABB_IMPL is defined) // - method 2 if the box is an OBB (SWEEP_AABB_IMPL is undefined) #ifdef SWEEP_AABB_IMPL // PT: TODO: refactor structure (TA34704) namespace { struct RayParams { BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); #ifndef GU_BV4_USE_SLABS BV4_ALIGN16(PxVec3p mData2_PaddedAligned); BV4_ALIGN16(PxVec3p mFDir_PaddedAligned); BV4_ALIGN16(PxVec3p mData_PaddedAligned); BV4_ALIGN16(PxVec3p mLocalDir_PaddedAligned); #endif BV4_ALIGN16(PxVec3p mOrigin_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704) }; } #include "GuBV4_AABBAABBSweepTest.h" #else #include "GuBV4_BoxBoxOverlapTest.h" #endif #include "GuBV4_BoxSweep_Params.h" static PX_FORCE_INLINE Vec4V multiply3x3V(const Vec4V p, const PxMat33& mat_Padded) { const FloatV xxxV = V4GetX(p); const FloatV yyyV = V4GetY(p); const FloatV zzzV = V4GetZ(p); Vec4V ResV = V4Scale(V4LoadU_Safe(&mat_Padded.column0.x), xxxV); ResV = V4Add(ResV, V4Scale(V4LoadU_Safe(&mat_Padded.column1.x), yyyV)); ResV = V4Add(ResV, V4Scale(V4LoadU_Safe(&mat_Padded.column2.x), zzzV)); return ResV; } // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static bool /*__fastcall*/ triBoxSweep(BoxSweepParams* PX_RESTRICT params, PxU32 primIndex, bool nodeSorting=true) { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; // Don't bother doing the actual sweep test if the triangle is too far away if(1) { const float dp0 = p0.dot(params->mLocalDir_Padded); const float dp1 = p1.dot(params->mLocalDir_Padded); const float dp2 = p2.dot(params->mLocalDir_Padded); float TriMin = PxMin(dp0, dp1); TriMin = PxMin(TriMin, dp2); if(TriMin >= params->mOffset + params->mStabbedFace.mDistance) return false; } PxTrianglePadded triBoxSpace; const Vec4V transModelToBoxV = V4LoadU_Safe(&params->mTModelToBox_Padded.x); const Vec4V v0V = V4Add(multiply3x3V(V4LoadU_Safe(&p0.x), params->mRModelToBox_Padded), transModelToBoxV); V4StoreU_Safe(v0V, &triBoxSpace.verts[0].x); const Vec4V v1V = V4Add(multiply3x3V(V4LoadU_Safe(&p1.x), params->mRModelToBox_Padded), transModelToBoxV); V4StoreU_Safe(v1V, &triBoxSpace.verts[1].x); const Vec4V v2V = V4Add(multiply3x3V(V4LoadU_Safe(&p2.x), params->mRModelToBox_Padded), transModelToBoxV); V4StoreU_Safe(v2V, &triBoxSpace.verts[2].x); float Dist; if(triBoxSweepTestBoxSpace_inlined(triBoxSpace, params->mOriginalExtents_Padded, params->mOriginalDir_Padded*params->mStabbedFace.mDistance, params->mOneOverDir_Padded, 1.0f, Dist, params->mBackfaceCulling)) { // PT: TODO: these muls & divs may not be needed at all - we just pass the unit dir/inverse dir to the sweep code. Revisit. (TA34704) Dist *= params->mStabbedFace.mDistance; params->mOneOverDir_Padded = params->mOneOverOriginalDir / Dist; params->mStabbedFace.mDistance = Dist; params->mStabbedFace.mTriangleID = primIndex; // PT: TODO: revisit this (TA34704) params->mP0 = triBoxSpace.verts[0]; params->mP1 = triBoxSpace.verts[1]; params->mP2 = triBoxSpace.verts[2]; // V4StoreU_Safe(v0V, &params->mP0.x); // V4StoreU_Safe(v1V, &params->mP1.x); // V4StoreU_Safe(v2V, &params->mP2.x); if(nodeSorting) { #ifdef SWEEP_AABB_IMPL #ifndef GU_BV4_USE_SLABS setupRayData(params, Dist, params->mOrigin_Padded, params->mLocalDir_PaddedAligned); #endif #else params->ShrinkOBB(Dist); #endif } return true; } return false; } namespace { class LeafFunction_BoxSweepClosest { public: static PX_FORCE_INLINE void doLeafTest(BoxSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { triBoxSweep(params, primIndex); primIndex++; }while(nbToGo--); } }; class LeafFunction_BoxSweepAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(BoxSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triBoxSweep(params, primIndex)) return 1; primIndex++; }while(nbToGo--); return 0; } }; } // PT: TODO: refactor with sphere/capsule versions (TA34704) static PX_FORCE_INLINE bool computeImpactData(const Box& box, const PxVec3& dir, SweepHit* PX_RESTRICT hit, const BoxSweepParams* PX_RESTRICT params, bool isDoubleSided, bool meshBothSides) { if(params->mStabbedFace.mTriangleID==PX_INVALID_U32) return false; // We didn't touch any triangle if(hit) { const float t = params->mStabbedFace.mDistance; hit->mTriangleID = params->mStabbedFace.mTriangleID; hit->mDistance = t; if(t==0.0f) { hit->mPos = PxVec3(0.0f); hit->mNormal = -dir; } else { // PT: TODO: revisit/optimize/use this (TA34704) const PxTriangle triInBoxSpace(params->mP0, params->mP1, params->mP2); PxHitFlags outFlags = PxHitFlag::Enum(0); computeBoxLocalImpact(hit->mPos, hit->mNormal, outFlags, box, params->mOriginalDir_Padded, triInBoxSpace, PxHitFlag::ePOSITION|PxHitFlag::eNORMAL, isDoubleSided, meshBothSides, t); } } return true; } template<class ParamsT> static PX_FORCE_INLINE void setupBoxSweepParams(ParamsT* PX_RESTRICT params, const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree* PX_RESTRICT tree, const SourceMesh* PX_RESTRICT mesh, PxU32 flags) { params->mStabbedFace.mTriangleID = PX_INVALID_U32; setupParamsFlags(params, flags); setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); prepareSweepData(localBox, localDir, maxDist, params); #ifdef SWEEP_AABB_IMPL params->mOrigin_Padded = localBox.center; #ifndef GU_BV4_USE_SLABS params->mLocalDir_PaddedAligned = localDir; setupRayData(params, maxDist, localBox.center, localDir); #endif #endif } #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #ifdef SWEEP_AABB_IMPL #include "GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h" #include "GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_KajiyaNoOrder.h" #include "GuBV4_Slabs_KajiyaOrdered.h" #endif #else #include "GuBV4_ProcessStreamOrdered_OBBOBB.h" #include "GuBV4_ProcessStreamNoOrder_OBBOBB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_SwizzledNoOrder.h" #include "GuBV4_Slabs_SwizzledOrdered.h" #endif #endif #ifdef SWEEP_AABB_IMPL #define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER #define GU_BV4_PROCESS_STREAM_RAY_ORDERED #else #define GU_BV4_PROCESS_STREAM_NO_ORDER #define GU_BV4_PROCESS_STREAM_ORDERED #endif #include "GuBV4_Internal.h" #ifdef SWEEP_AABB_IMPL PxIntBool Sweep_AABB_BV4(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags) #else PxIntBool Sweep_OBB_BV4(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags) #endif { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); BoxSweepParams Params; setupBoxSweepParams(&Params, localBox, localDir, maxDist, &tree, mesh, flags); if(tree.mNodes) { #ifdef SWEEP_AABB_IMPL if(Params.mEarlyExit) processStreamRayNoOrder<1, LeafFunction_BoxSweepAny>(tree, &Params); else processStreamRayOrdered<1, LeafFunction_BoxSweepClosest>(tree, &Params); #else if(Params.mEarlyExit) processStreamNoOrder<LeafFunction_BoxSweepAny>(tree, &Params); else processStreamOrdered<LeafFunction_BoxSweepClosest>(tree, &Params); #endif } else doBruteForceTests<LeafFunction_BoxSweepAny, LeafFunction_BoxSweepClosest>(mesh->getNbTriangles(), &Params); return computeImpactData(localBox, localDir, hit, &Params, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); } // PT: box sweep callback version - currently not used namespace { struct BoxSweepParamsCB : BoxSweepParams { // PT: these new members are only here to call computeImpactData during traversal :( // PT: TODO: most of them may not be needed Box mBoxCB; // Box in original space (maybe not local/mesh space) PxVec3 mDirCB; // Dir in original space (maybe not local/mesh space) const PxMat44* mWorldm_Aligned; PxU32 mFlags; SweepUnlimitedCallback mCallback; void* mUserData; float mMaxDist; bool mNodeSorting; }; class LeafFunction_BoxSweepCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(BoxSweepParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triBoxSweep(params, primIndex, params->mNodeSorting)) { // PT: TODO: in this version we must compute the impact data immediately, // which is a terrible idea in general, but I'm not sure what else I can do. SweepHit hit; const bool b = computeImpactData(params->mBoxCB, params->mDirCB, &hit, params, (params->mFlags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (params->mFlags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); PX_ASSERT(b); // PT: then replicate part from BV4_BoxSweepSingle: if(b && params->mWorldm_Aligned) { // Move to world space // PT: TODO: optimize (TA34704) hit.mPos = params->mWorldm_Aligned->transform(hit.mPos); hit.mNormal = params->mWorldm_Aligned->rotate(hit.mNormal); } reportUnlimitedCallbackHit(params, hit); } primIndex++; }while(nbToGo--); return 0; } }; } // PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB(). // PT: 'worldm_Aligned' is only here to move back results to world space, but input is already in local space. #ifdef SWEEP_AABB_IMPL void Sweep_AABB_BV4_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting) #else void Sweep_OBB_BV4_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting) #endif { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); BoxSweepParamsCB Params; Params.mBoxCB = localBox; Params.mDirCB = localDir; Params.mWorldm_Aligned = worldm_Aligned; Params.mFlags = flags; Params.mCallback = callback; Params.mUserData = userData; Params.mMaxDist = maxDist; Params.mNodeSorting = nodeSorting; setupBoxSweepParams(&Params, localBox, localDir, maxDist, &tree, mesh, flags); PX_ASSERT(!Params.mEarlyExit); if(tree.mNodes) { if(nodeSorting) { #ifdef SWEEP_AABB_IMPL processStreamRayOrdered<1, LeafFunction_BoxSweepCB>(tree, &Params); #else processStreamOrdered<LeafFunction_BoxSweepCB>(tree, &Params); #endif } else { #ifdef SWEEP_AABB_IMPL processStreamRayNoOrder<1, LeafFunction_BoxSweepCB>(tree, &Params); #else processStreamNoOrder<LeafFunction_BoxSweepCB>(tree, &Params); #endif } } else doBruteForceTests<LeafFunction_BoxSweepCB, LeafFunction_BoxSweepCB>(mesh->getNbTriangles(), &Params); } // New callback-based box sweeps. Reuses code above, allow early exits. Some init code may be done in vain // since the leaf tests are not performed (we don't do box-sweeps-vs-tri since the box is only a BV around // the actual shape, say a convex) namespace { struct GenericSweepParamsCB : BoxSweepParams { MeshSweepCallback mCallback; void* mUserData; }; class LeafFunction_BoxSweepClosestCB { public: static PX_FORCE_INLINE void doLeafTest(GenericSweepParamsCB* PX_RESTRICT params, PxU32 prim_index) { PxU32 nbToGo = getNbPrimitives(prim_index); do { // PT: in the regular version we'd do a box-vs-triangle sweep test here // Instead we just grab the triangle and send it to the callback // // This can be used for regular "closest hit" sweeps, when the scale is not identity or // when the box is just around a more complex shape (e.g. convex). In this case we want // the calling code to compute a convex-triangle distance, and then we want to shrink // the ray/box while doing an ordered traversal. // // For "sweep all" or "sweep any" purposes we want to either report all hits or early exit // as soon as we find one. There is no need for shrinking or ordered traversals here. PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, prim_index, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; // Don't bother doing the actual sweep test if the triangle is too far away const float dp0 = p0.dot(params->mLocalDir_Padded); const float dp1 = p1.dot(params->mLocalDir_Padded); const float dp2 = p2.dot(params->mLocalDir_Padded); float TriMin = PxMin(dp0, dp1); TriMin = PxMin(TriMin, dp2); if(TriMin < params->mOffset + params->mStabbedFace.mDistance) { // const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; float Dist = params->mStabbedFace.mDistance; if((params->mCallback)(params->mUserData, p0, p1, p2, prim_index, /*vrefs,*/ Dist)) return; // PT: TODO: we return here but the ordered path doesn't really support early exits (TA34704) if(Dist<params->mStabbedFace.mDistance) { params->mStabbedFace.mDistance = Dist; params->mStabbedFace.mTriangleID = prim_index; #ifdef SWEEP_AABB_IMPL #ifndef GU_BV4_USE_SLABS setupRayData(params, Dist, params->mOrigin_Padded, params->mLocalDir_PaddedAligned); #endif #else params->ShrinkOBB(Dist); #endif } } prim_index++; }while(nbToGo--); } }; class LeafFunction_BoxSweepAnyCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(GenericSweepParamsCB* PX_RESTRICT params, PxU32 prim_index) { PxU32 nbToGo = getNbPrimitives(prim_index); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, prim_index, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; { // const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; float Dist = params->mStabbedFace.mDistance; if((params->mCallback)(params->mUserData, p0, p1, p2, prim_index, /*vrefs,*/ Dist)) return 1; } prim_index++; }while(nbToGo--); return 0; } }; } #ifdef SWEEP_AABB_IMPL void GenericSweep_AABB_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, MeshSweepCallback callback, void* userData, PxU32 flags) #else void GenericSweep_OBB_CB(const Box& localBox, const PxVec3& localDir, float maxDist, const BV4Tree& tree, MeshSweepCallback callback, void* userData, PxU32 flags) #endif { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); GenericSweepParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupBoxSweepParams(&Params, localBox, localDir, maxDist, &tree, mesh, flags); if(tree.mNodes) { #ifdef SWEEP_AABB_IMPL if(Params.mEarlyExit) processStreamRayNoOrder<1, LeafFunction_BoxSweepAnyCB>(tree, &Params); else processStreamRayOrdered<1, LeafFunction_BoxSweepClosestCB>(tree, &Params); #else if(Params.mEarlyExit) processStreamNoOrder<LeafFunction_BoxSweepAnyCB>(tree, &Params); else processStreamOrdered<LeafFunction_BoxSweepClosestCB>(tree, &Params); #endif } else doBruteForceTests<LeafFunction_BoxSweepAnyCB, LeafFunction_BoxSweepClosestCB>(mesh->getNbTriangles(), &Params); }
17,657
C
32.957692
226
0.737951
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Internal.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_INTERNAL_H #define GU_BV4_INTERNAL_H #include "foundation/PxFPU.h" // PT: the general structure is that there is a root "process stream" function which is the entry point for the query. // It then calls "process node" functions for each traversed node, except for the Slabs-based raycast versions that deal // with 4 nodes at a time within the "process stream" function itself. When a leaf is found, "doLeafTest" functors // passed to the "process stream" entry point are called. #ifdef GU_BV4_USE_SLABS // PT: Linux tries to compile templates even when they're not used so I had to wrap them all with defines to avoid build errors. Blame the only platform that does this. #ifdef GU_BV4_PROCESS_STREAM_NO_ORDER template<class LeafTestT, class ParamsT> PX_FORCE_INLINE PxIntBool processStreamNoOrder(const BV4Tree& tree, ParamsT* PX_RESTRICT params) { if(tree.mQuantized) return BV4_ProcessStreamSwizzledNoOrderQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params); else return BV4_ProcessStreamSwizzledNoOrderNQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params); } #endif #ifdef GU_BV4_PROCESS_STREAM_ORDERED template<class LeafTestT, class ParamsT> PX_FORCE_INLINE void processStreamOrdered(const BV4Tree& tree, ParamsT* PX_RESTRICT params) { if(tree.mQuantized) BV4_ProcessStreamSwizzledOrderedQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params); else BV4_ProcessStreamSwizzledOrderedNQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params); } #endif #ifdef GU_BV4_PROCESS_STREAM_RAY_NO_ORDER template<int inflateT, class LeafTestT, class ParamsT> PX_FORCE_INLINE PxIntBool processStreamRayNoOrder(const BV4Tree& tree, ParamsT* PX_RESTRICT params) { if(tree.mQuantized) return BV4_ProcessStreamKajiyaNoOrderQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params); else return BV4_ProcessStreamKajiyaNoOrderNQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params); } #endif #ifdef GU_BV4_PROCESS_STREAM_RAY_ORDERED template<int inflateT, class LeafTestT, class ParamsT> PX_FORCE_INLINE void processStreamRayOrdered(const BV4Tree& tree, ParamsT* PX_RESTRICT params) { if(tree.mQuantized) BV4_ProcessStreamKajiyaOrderedQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params); else BV4_ProcessStreamKajiyaOrderedNQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params); } #endif #else #define processStreamNoOrder BV4_ProcessStreamNoOrder #define processStreamOrdered BV4_ProcessStreamOrdered2 #define processStreamRayNoOrder(a, b) BV4_ProcessStreamNoOrder<b> #define processStreamRayOrdered(a, b) BV4_ProcessStreamOrdered2<b> #endif #ifndef GU_BV4_USE_SLABS #ifdef GU_BV4_PRECOMPUTED_NODE_SORT // PT: see http://www.codercorner.com/blog/?p=734 // PT: TODO: refactor with dup in bucket pruner (TA34704) PX_FORCE_INLINE PxU32 computeDirMask(const PxVec3& dir) { // XYZ // --- // --+ // -+- // -++ // +-- // +-+ // ++- // +++ const PxU32 X = PX_IR(dir.x)>>31; const PxU32 Y = PX_IR(dir.y)>>31; const PxU32 Z = PX_IR(dir.z)>>31; const PxU32 bitIndex = Z|(Y<<1)|(X<<2); return 1u<<bitIndex; } // 0 0 0 PP PN NP NN 0 1 2 3 // 0 0 1 PP PN NN NP 0 1 3 2 // 0 1 0 PN PP NP NN 1 0 2 3 // 0 1 1 PN PP NN NP 1 0 3 2 // 1 0 0 NP NN PP PN 2 3 0 1 // 1 0 1 NN NP PP PN 3 2 0 1 // 1 1 0 NP NN PN PP 2 3 1 0 // 1 1 1 NN NP PN PP 3 2 1 0 static const PxU8 order[] = { 0,1,2,3, 0,1,3,2, 1,0,2,3, 1,0,3,2, 2,3,0,1, 3,2,0,1, 2,3,1,0, 3,2,1,0, }; PX_FORCE_INLINE PxU32 decodePNS(const BVDataPacked* PX_RESTRICT node, const PxU32 dirMask) { const PxU32 bit0 = (node[0].decodePNSNoShift() & dirMask) ? 1u : 0; const PxU32 bit1 = (node[1].decodePNSNoShift() & dirMask) ? 1u : 0; const PxU32 bit2 = (node[2].decodePNSNoShift() & dirMask) ? 1u : 0; //### potentially reads past the end of the stream here! return bit2|(bit1<<1)|(bit0<<2); } #endif // GU_BV4_PRECOMPUTED_NODE_SORT #define PNS_BLOCK(i, a, b, c, d) \ case i: \ { \ if(code & (1<<a)) { stack[nb++] = node[a].getChildData(); } \ if(code & (1<<b)) { stack[nb++] = node[b].getChildData(); } \ if(code & (1<<c)) { stack[nb++] = node[c].getChildData(); } \ if(code & (1<<d)) { stack[nb++] = node[d].getChildData(); } \ }break; #define PNS_BLOCK1(i, a, b, c, d) \ case i: \ { \ stack[nb] = node[a].getChildData(); nb += (code & (1<<a))?1:0; \ stack[nb] = node[b].getChildData(); nb += (code & (1<<b))?1:0; \ stack[nb] = node[c].getChildData(); nb += (code & (1<<c))?1:0; \ stack[nb] = node[d].getChildData(); nb += (code & (1<<d))?1:0; \ }break; #define PNS_BLOCK2(a, b, c, d) { \ if(code & (1<<a)) { stack[nb++] = node[a].getChildData(); } \ if(code & (1<<b)) { stack[nb++] = node[b].getChildData(); } \ if(code & (1<<c)) { stack[nb++] = node[c].getChildData(); } \ if(code & (1<<d)) { stack[nb++] = node[d].getChildData(); } } \ template<class LeafTestT, class ParamsT> static PxIntBool BV4_ProcessStreamNoOrder(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU32 nodeType = getChildType(childData); if(nodeType>1 && BV4_ProcessNodeNoOrder<LeafTestT, 3>(stack, nb, node, params)) return 1; if(nodeType>0 && BV4_ProcessNodeNoOrder<LeafTestT, 2>(stack, nb, node, params)) return 1; if(BV4_ProcessNodeNoOrder<LeafTestT, 1>(stack, nb, node, params)) return 1; if(BV4_ProcessNodeNoOrder<LeafTestT, 0>(stack, nb, node, params)) return 1; }while(nb); return 0; } template<class LeafTestT, class ParamsT> static void BV4_ProcessStreamOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; const PxU32 dirMask = computeDirMask(params->mLocalDir)<<3; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU8* PX_RESTRICT ord = order + decodePNS(node, dirMask)*4; const PxU32 limit = 2 + getChildType(childData); BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[0], limit); BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[1], limit); BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[2], limit); BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[3], limit); }while(Nb); } // Alternative, experimental version using PNS template<class LeafTestT, class ParamsT> static void BV4_ProcessStreamOrdered2(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU32 nodeType = getChildType(childData); PxU32 code = 0; BV4_ProcessNodeOrdered2<LeafTestT, 0>(code, node, params); BV4_ProcessNodeOrdered2<LeafTestT, 1>(code, node, params); if(nodeType>0) BV4_ProcessNodeOrdered2<LeafTestT, 2>(code, node, params); if(nodeType>1) BV4_ProcessNodeOrdered2<LeafTestT, 3>(code, node, params); if(code) { // PT: TODO: check which implementation is best on each platform (TA34704) #define FOURTH_TEST // Version avoids computing the PNS index, and also avoids all non-constant shifts. Full of branches though. Fastest on Win32. #ifdef FOURTH_TEST { if(node[0].decodePNSNoShift() & dirMask) // Bit2 { if(node[1].decodePNSNoShift() & dirMask) // Bit1 { if(node[2].decodePNSNoShift() & dirMask) // Bit0 PNS_BLOCK2(3,2,1,0) // 7 else PNS_BLOCK2(2,3,1,0) // 6 } else { if(node[2].decodePNSNoShift() & dirMask) // Bit0 PNS_BLOCK2(3,2,0,1) // 5 else PNS_BLOCK2(2,3,0,1) // 4 } } else { if(node[1].decodePNSNoShift() & dirMask) // Bit1 { if(node[2].decodePNSNoShift() & dirMask) // Bit0 PNS_BLOCK2(1,0,3,2) // 3 else PNS_BLOCK2(1,0,2,3) // 2 } else { if(node[2].decodePNSNoShift() & dirMask) // Bit0 PNS_BLOCK2(0,1,3,2) // 1 else PNS_BLOCK2(0,1,2,3) // 0 } } } #endif } }while(nb); } #endif // GU_BV4_USE_SLABS #endif // GU_BV4_INTERNAL_H
11,113
C
36.170568
169
0.670206
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuRTree.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_RTREE_H #define GU_RTREE_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec4.h" #include "foundation/PxBounds3.h" #include "foundation/PxAssert.h" #include "common/PxSerialFramework.h" #include "geometry/PxTriangleMesh.h" #include "foundation/PxUserAllocated.h" // for PxSerializationContext #include "foundation/PxAlignedMalloc.h" #include "foundation/PxVecMath.h" #define RTREE_N 4 // changing this number will affect the mesh format PX_COMPILE_TIME_ASSERT(RTREE_N == 4 || RTREE_N == 8); // using the low 5 bits for storage of index(childPtr) for dynamic rtree namespace physx { #if PX_VC #pragma warning(push) #pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif namespace Gu { class Box; struct RTreePage; typedef PxF32 RTreeValue; ///////////////////////////////////////////////////////////////////////// // quantized untransposed RTree node - used for offline build and dynamic insertion struct RTreeNodeQ { RTreeValue minx, miny, minz, maxx, maxy, maxz; PxU32 ptr; // lowest bit is leaf flag PX_FORCE_INLINE void setLeaf(bool set) { if (set) ptr |= 1; else ptr &= ~1; } PX_FORCE_INLINE PxU32 isLeaf() const { return ptr & 1; } PX_FORCE_INLINE void setEmpty(); PX_FORCE_INLINE void grow(const RTreePage& page, int nodeIndex); PX_FORCE_INLINE void grow(const RTreeNodeQ& node); }; ///////////////////////////////////////////////////////////////////////// // RTreePage data structure, holds RTREE_N transposed nodes // RTreePage data structure, holds 8 transposed nodes PX_ALIGN_PREFIX(16) struct RTreePage { static const RTreeValue MN, MX; RTreeValue minx[RTREE_N]; // [min=MX, max=MN] is used as a sentinel range for empty bounds RTreeValue miny[RTREE_N]; RTreeValue minz[RTREE_N]; RTreeValue maxx[RTREE_N]; RTreeValue maxy[RTREE_N]; RTreeValue maxz[RTREE_N]; PxU32 ptrs[RTREE_N]; // for static rtree this is an offset relative to the first page divided by 16, for dynamics it's an absolute pointer divided by 16 PX_FORCE_INLINE PxU32 nodeCount() const; // returns the number of occupied nodes in this page PX_FORCE_INLINE void setEmpty(PxU32 startIndex = 0); PX_FORCE_INLINE bool isEmpty(PxU32 index) const { return minx[index] > maxx[index]; } PX_FORCE_INLINE void copyNode(PxU32 targetIndex, const RTreePage& sourcePage, PxU32 sourceIndex); PX_FORCE_INLINE void setNode(PxU32 targetIndex, const RTreeNodeQ& node); PX_FORCE_INLINE void clearNode(PxU32 nodeIndex); PX_FORCE_INLINE void getNode(PxU32 nodeIndex, RTreeNodeQ& result) const; PX_FORCE_INLINE void computeBounds(RTreeNodeQ& bounds); PX_FORCE_INLINE void adjustChildBounds(PxU32 index, const RTreeNodeQ& adjustedChildBounds); PX_FORCE_INLINE void growChildBounds(PxU32 index, const RTreeNodeQ& adjustedChildBounds); PX_FORCE_INLINE PxU32 getNodeHandle(PxU32 index) const; PX_FORCE_INLINE PxU32 isLeaf(PxU32 index) const { return ptrs[index] & 1; } } PX_ALIGN_SUFFIX(16); ///////////////////////////////////////////////////////////////////////// // RTree root data structure PX_ALIGN_PREFIX(16) struct RTree { // PX_SERIALIZATION RTree(const PxEMPTY); void exportExtraData(PxSerializationContext&); void importExtraData(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION PX_INLINE RTree(); // offline static rtree constructor used with cooking ~RTree() { release(); } PX_INLINE void release(); bool load(PxInputStream& stream, PxU32 meshVersion, bool mismatch); //////////////////////////////////////////////////////////////////////////// // QUERIES struct Callback { // result buffer should have room for at least RTREE_N items // should return true to continue traversal. If false is returned, traversal is aborted virtual bool processResults(PxU32 count, PxU32* buf) = 0; virtual void profile() {} virtual ~Callback() {} }; struct CallbackRaycast { // result buffer should have room for at least RTREE_N items // should return true to continue traversal. If false is returned, traversal is aborted // newMaxT serves as both input and output, as input it's the maxT so far // set it to a new value (which should be smaller) and it will become the new far clip t virtual bool processResults(PxU32 count, PxU32* buf, PxF32& newMaxT) = 0; virtual ~CallbackRaycast() {} }; // callback will be issued as soon as the buffer overflows maxResultsPerBlock-RTreePage:SIZE entries // use maxResults = RTreePage:SIZE and return false from callback for "first hit" early out void traverseAABB( const PxVec3& boxMin, const PxVec3& boxMax, const PxU32 maxResultsPerBlock, PxU32* resultsBlockBuf, Callback* processResultsBlockCallback) const; void traverseOBB( const Gu::Box& obb, const PxU32 maxResultsPerBlock, PxU32* resultsBlockBuf, Callback* processResultsBlockCallback) const; template <int inflate> void traverseRay( const PxVec3& rayOrigin, const PxVec3& rayDir, // dir doesn't have to be normalized and is B-A for raySegment const PxU32 maxResults, PxU32* resultsPtr, Gu::RTree::CallbackRaycast* callback, const PxVec3* inflateAABBs, // inflate tree's AABBs by this amount. This function turns into AABB sweep. PxF32 maxT = PX_MAX_F32 // maximum ray t parameter, p(t)=origin+t*dir; use 1.0f for ray segment ) const; struct CallbackRefit { // In this callback index is the number stored in the RTree, which is a LeafTriangles object for current PhysX mesh virtual void recomputeBounds(PxU32 index, aos::Vec3V& mn, aos::Vec3V& mx) = 0; virtual ~CallbackRefit() {} }; void refitAllStaticTree(CallbackRefit& cb, PxBounds3* resultMeshBounds); // faster version of refit for static RTree only //////////////////////////////////////////////////////////////////////////// // DEBUG HELPER FUNCTIONS PX_PHYSX_COMMON_API void validate(CallbackRefit* cb = NULL); // verify that all children are indeed included in parent bounds void openTextDump(); void closeTextDump(); void textDump(const char* prefix); void maxscriptExport(); PxU32 computeBottomLevelCount(PxU32 storedToMemMultiplier) const; //////////////////////////////////////////////////////////////////////////// // DATA // remember to update save() and load() when adding or removing data PxVec4 mBoundsMin, mBoundsMax, mInvDiagonal, mDiagonalScaler; // 16 PxU32 mPageSize; PxU32 mNumRootPages; PxU32 mNumLevels; PxU32 mTotalNodes; // 16 PxU32 mTotalPages; PxU32 mFlags; enum { USER_ALLOCATED = 0x1, IS_EDGE_SET = 0x2 }; RTreePage* mPages; protected: typedef PxU32 NodeHandle; void validateRecursive(PxU32 level, RTreeNodeQ parentBounds, RTreePage* page, CallbackRefit* cb = NULL); friend struct RTreePage; } PX_ALIGN_SUFFIX(16); #if PX_SUPPORT_EXTERN_TEMPLATE //explicit template instantiation declaration extern template void RTree::traverseRay<0>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const; extern template void RTree::traverseRay<1>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const; #endif #if PX_VC #pragma warning(pop) #endif ///////////////////////////////////////////////////////////////////////// PX_INLINE RTree::RTree() { mFlags = 0; mPages = NULL; mTotalNodes = 0; mNumLevels = 0; mPageSize = RTREE_N; } ///////////////////////////////////////////////////////////////////////// PX_INLINE void RTree::release() { if ((mFlags & USER_ALLOCATED) == 0 && mPages) { physx::PxAlignedAllocator<128>().deallocate(mPages); mPages = NULL; } } ///////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void RTreeNodeQ::setEmpty() { minx = miny = minz = RTreePage::MX; maxx = maxy = maxz = RTreePage::MN; } // bit 1 is always expected to be set to differentiate between leaf and non-leaf node PX_FORCE_INLINE PxU32 LeafGetNbTriangles(PxU32 Data) { return ((Data>>1) & 15)+1; } PX_FORCE_INLINE PxU32 LeafGetTriangleIndex(PxU32 Data) { return Data>>5; } PX_FORCE_INLINE PxU32 LeafSetData(PxU32 nb, PxU32 index) { PX_ASSERT(nb>0 && nb<=16); PX_ASSERT(index < (1<<27)); return (index<<5)|(((nb-1)&15)<<1) | 1; } struct LeafTriangles { PxU32 Data; // Gets number of triangles in the leaf, returns the number of triangles N, with 0 < N <= 16 PX_FORCE_INLINE PxU32 GetNbTriangles() const { return LeafGetNbTriangles(Data); } // Gets triangle index for this leaf. Indexed model's array of indices retrieved with RTreeMidphase::GetIndices() PX_FORCE_INLINE PxU32 GetTriangleIndex() const { return LeafGetTriangleIndex(Data); } PX_FORCE_INLINE void SetData(PxU32 nb, PxU32 index) { Data = LeafSetData(nb, index); } }; PX_COMPILE_TIME_ASSERT(sizeof(LeafTriangles)==4); // RTree has space for 4 bytes } // namespace Gu } #endif // #ifdef PX_COLLISION_RTREE
10,813
C
38.611721
154
0.686026
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxOverlap_Internal.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_BOX_OVERLAP_INTERNAL_H #define GU_BV4_BOX_OVERLAP_INTERNAL_H #include "GuBV4_Common.h" template<class ParamsT> PX_FORCE_INLINE void precomputeData(ParamsT* PX_RESTRICT dst, PxMat33* PX_RESTRICT absRot, const PxMat33* PX_RESTRICT boxToModelR) { // Precompute absolute box-to-model rotation matrix dst->mPreca0_PaddedAligned.x = boxToModelR->column0.x; dst->mPreca0_PaddedAligned.y = boxToModelR->column1.y; dst->mPreca0_PaddedAligned.z = boxToModelR->column2.z; dst->mPreca1_PaddedAligned.x = boxToModelR->column0.y; dst->mPreca1_PaddedAligned.y = boxToModelR->column1.z; dst->mPreca1_PaddedAligned.z = boxToModelR->column2.x; dst->mPreca2_PaddedAligned.x = boxToModelR->column0.z; dst->mPreca2_PaddedAligned.y = boxToModelR->column1.x; dst->mPreca2_PaddedAligned.z = boxToModelR->column2.y; // Epsilon value prevents floating-point inaccuracies (strategy borrowed from RAPID) const PxReal epsilon = 1e-6f; absRot->column0.x = dst->mPreca0b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.x); absRot->column0.y = dst->mPreca1b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.y); absRot->column0.z = dst->mPreca2b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.z); absRot->column1.x = dst->mPreca2b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.x); absRot->column1.y = dst->mPreca0b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.y); absRot->column1.z = dst->mPreca1b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.z); absRot->column2.x = dst->mPreca1b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.x); absRot->column2.y = dst->mPreca2b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.y); absRot->column2.z = dst->mPreca0b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.z); } template<class ParamsT> PX_FORCE_INLINE void setupBoxData(ParamsT* PX_RESTRICT dst, const PxVec3& extents, const PxMat33* PX_RESTRICT mAR) { dst->mBoxExtents_PaddedAligned = extents; const float Ex = extents.x; const float Ey = extents.y; const float Ez = extents.z; dst->mBB_PaddedAligned.x = Ex*mAR->column0.x + Ey*mAR->column1.x + Ez*mAR->column2.x; dst->mBB_PaddedAligned.y = Ex*mAR->column0.y + Ey*mAR->column1.y + Ez*mAR->column2.y; dst->mBB_PaddedAligned.z = Ex*mAR->column0.z + Ey*mAR->column1.z + Ez*mAR->column2.z; } struct OBBTestParams // Data needed to perform the OBB-OBB overlap test { BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mTBoxToModel_PaddedAligned); //!< Translation from obb space to model space BV4_ALIGN16(PxVec3p mBB_PaddedAligned); BV4_ALIGN16(PxVec3p mBoxExtents_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca0_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca1_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca2_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca0b_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca1b_PaddedAligned); BV4_ALIGN16(PxVec3p mPreca2b_PaddedAligned); PX_FORCE_INLINE void precomputeBoxData(const PxVec3& extents, const PxMat33* PX_RESTRICT box_to_model) { PxMat33 absRot; //!< Absolute rotation matrix precomputeData(this, &absRot, box_to_model); setupBoxData(this, extents, &absRot); } }; #endif // GU_BV4_BOX_OVERLAP_INTERNAL_H
5,017
C
47.718446
131
0.753638
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMesh.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TETRAHEDRONMESH_H #define GU_TETRAHEDRONMESH_H #include "foundation/PxIO.h" #include "geometry/PxTetrahedronMeshGeometry.h" #include "geometry/PxTetrahedronMesh.h" #include "geometry/PxTetrahedron.h" #include "geometry/PxSimpleTriangleMesh.h" #include "CmRefCountable.h" #include "common/PxRenderOutput.h" #include "GuMeshData.h" #include "GuCenterExtents.h" #include "GuMeshFactory.h" namespace physx { namespace Gu { class MeshFactory; #if PX_VC #pragma warning(push) #pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class SoftBodyAuxData : public PxSoftBodyAuxData, public PxUserAllocated { public: SoftBodyAuxData(SoftBodySimulationData& d, SoftBodyCollisionData& c, CollisionMeshMappingData& e); virtual ~SoftBodyAuxData(); virtual const char* getConcreteTypeName() const { return "PxSoftBodyAuxData"; } virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); } virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); } virtual void release() { Cm::RefCountable_decRefCount(*this); } virtual void onRefCountZero() { PX_DELETE_THIS; } virtual PxReal* getGridModelInvMass() { return mGridModelInvMass; } PX_FORCE_INLINE PxU32 getNbTetRemapSizeFast() const { return mTetsRemapSize; } PX_FORCE_INLINE PxReal* getGridModelInvMassFast() { return mGridModelInvMass; } PX_FORCE_INLINE PxU32 getNbGMPartitionFast() const { return mGMNbPartitions; } PX_FORCE_INLINE PxU32 getGMRemapOutputSizeFast() const { return mGMRemapOutputSize; } PX_FORCE_INLINE PxU32 getGMMaxTetsPerPartitionsFast() const { return mGMMaxMaxTetsPerPartitions; } PX_FORCE_INLINE PxU32* getCollisionAccumulatedTetrahedronRefs() const { return mCollisionAccumulatedTetrahedronsRef; } PX_FORCE_INLINE PxU32* getCollisionTetrahedronRefs() const { return mCollisionTetrahedronsReferences; } PX_FORCE_INLINE PxU32 getCollisionNbTetrahedronRefs() const { return mCollisionNbTetrahedronsReferences; } PX_FORCE_INLINE PxU32* getCollisionSurfaceVertToTetRemap() const { return mCollisionSurfaceVertToTetRemap; } PX_FORCE_INLINE PxMat33* getGridModelRestPosesFast() { return mGridModelTetraRestPoses; } PX_FORCE_INLINE PxMat33* getRestPosesFast() { return mTetraRestPoses; } float* mGridModelInvMass; PxMat33* mGridModelTetraRestPoses; PxU32* mGridModelOrderedTetrahedrons; PxU32 mGMNbPartitions; PxU32 mGMMaxMaxTetsPerPartitions; PxU32 mGMRemapOutputSize; PxU32* mGMRemapOutputCP; PxU32* mGMAccumulatedPartitionsCP; PxU32* mGMAccumulatedCopiesCP; PxU32* mCollisionAccumulatedTetrahedronsRef; PxU32* mCollisionTetrahedronsReferences; PxU32 mCollisionNbTetrahedronsReferences; PxU8* mCollisionSurfaceVertsHint; PxU32* mCollisionSurfaceVertToTetRemap; PxReal* mVertsBarycentricInGridModel; PxU32* mVertsRemapInGridModel; PxU32* mTetsRemapColToSim; PxU32 mTetsRemapSize; PxU32* mTetsAccumulatedRemapColToSim; PxU32* mGMPullIndices; PxMat33* mTetraRestPoses; PxU32 mNumTetsPerElement; }; class TetrahedronMesh : public PxTetrahedronMesh, public PxUserAllocated { public: TetrahedronMesh(PxU32 nbVertices, PxVec3* vertices, PxU32 nbTetrahedrons, void* tetrahedrons, PxU8 flags, PxBounds3 aabb, PxReal geomEpsilon); TetrahedronMesh(TetrahedronMeshData& mesh); TetrahedronMesh(MeshFactory* meshFactory, TetrahedronMeshData& mesh); virtual ~TetrahedronMesh(); virtual const char* getConcreteTypeName() const { return "PxTetrahedronMesh"; } virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); } virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); } virtual void release() { Cm::RefCountable_decRefCount(*this); } virtual void onRefCountZero(); virtual PxU32 getNbVertices() const { return mNbVertices; } virtual const PxVec3* getVertices() const { return mVertices; } virtual PxU32 getNbTetrahedrons() const { return mNbTetrahedrons; } virtual const void* getTetrahedrons() const { return mTetrahedrons; } virtual PxTetrahedronMeshFlags getTetrahedronMeshFlags() const { return PxTetrahedronMeshFlags(mFlags); } virtual const PxU32* getTetrahedraRemap() const { return NULL; } PX_FORCE_INLINE PxU32 getNbVerticesFast() const { return mNbVertices; } PX_FORCE_INLINE PxVec3* getVerticesFast() const { return mVertices; } PX_FORCE_INLINE PxU32 getNbTetrahedronsFast() const { return mNbTetrahedrons; } PX_FORCE_INLINE const void* getTetrahedronsFast() const { return mTetrahedrons; } PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxMeshFlag::e16_BIT_INDICES) ? true : false; } PX_FORCE_INLINE bool hasPerTriangleMaterials() const { return mMaterialIndices != NULL; } PX_FORCE_INLINE const PxU16* getMaterials() const { return mMaterialIndices; } PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mAABB; } PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const { // PT: see compile-time assert in cpp return static_cast<const CenterExtentsPadded&>(mAABB); } virtual PxBounds3 getLocalBounds() const { PX_ASSERT(mAABB.isValid()); return PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents); } PxU32 mNbVertices; PxVec3* mVertices; PxU32 mNbTetrahedrons; void* mTetrahedrons; PxU8 mFlags; //!< Flag whether indices are 16 or 32 bits wide PxU16* mMaterialIndices; //!< the size of the array is mNbTetrahedrons. // PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading CenterExtents mAABB; PxReal mGeomEpsilon; MeshFactory* mMeshFactory; // PT: changed to pointer for serialization }; PX_FORCE_INLINE const Gu::TetrahedronMesh* _getTetraMeshData(const PxTetrahedronMeshGeometry& meshGeom) { return static_cast<const Gu::TetrahedronMesh*>(meshGeom.tetrahedronMesh); } class BVTetrahedronMesh : public TetrahedronMesh { public: BVTetrahedronMesh(TetrahedronMeshData& mesh, SoftBodyCollisionData& d, MeshFactory* factory = NULL); virtual ~BVTetrahedronMesh() { PX_FREE(mGRB_tetraIndices); PX_FREE(mGRB_tetraSurfaceHint); PX_FREE(mGRB_faceRemap); PX_FREE(mGRB_faceRemapInverse); PX_DELETE(mGRB_BV32Tree); PX_FREE(mFaceRemap); } //virtual PxBounds3 refitBVH(); PX_FORCE_INLINE const Gu::BV4Tree& getBV4Tree() const { return mBV4Tree; } PX_FORCE_INLINE Gu::BV4Tree& getBV4Tree() { return mBV4Tree; } PX_FORCE_INLINE void* getGRBTetraFaceRemap() { return mGRB_faceRemap; } PX_FORCE_INLINE void* getGRBTetraFaceRemapInverse() { return mGRB_faceRemapInverse; } virtual const PxU32* getTetrahedraRemap() const { return mFaceRemap; } PX_FORCE_INLINE bool isTetMeshGPUCompatible() const { return mGRB_BV32Tree != NULL; } PxU32* mFaceRemap; //!< new faces to old faces mapping (after cleaning, etc). Usage: old = faceRemap[new] // GRB data ------------------------- void* mGRB_tetraIndices; //!< GRB: GPU-friendly tri indices [uint4] PxU8* mGRB_tetraSurfaceHint; PxU32* mGRB_faceRemap; PxU32* mGRB_faceRemapInverse; Gu::BV32Tree* mGRB_BV32Tree; //!< GRB: BV32 tree private: Gu::TetrahedronSourceMesh mMeshInterface4; Gu::BV4Tree mBV4Tree; Gu::TetrahedronSourceMesh mMeshInterface32; }; // Possible optimization: align the whole struct to cache line class SoftBodyMesh : public PxSoftBodyMesh, public PxUserAllocated { public: virtual const char* getConcreteTypeName() const { return "PxSoftBodyMesh"; } // PX_SERIALIZATION virtual void exportExtraData(PxSerializationContext& ctx); void importExtraData(PxDeserializationContext&); //PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream); virtual void release(); void resolveReferences(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} //~PX_SERIALIZATION virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); } virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); } virtual void onRefCountZero(); //virtual PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH34; } SoftBodyMesh(MeshFactory* factory, SoftBodyMeshData& data); virtual ~SoftBodyMesh(); void setMeshFactory(MeshFactory* factory) { mMeshFactory = factory; } virtual const PxTetrahedronMesh* getCollisionMesh() const { return mCollisionMesh; } virtual PxTetrahedronMesh* getCollisionMesh() { return mCollisionMesh; } PX_FORCE_INLINE const BVTetrahedronMesh* getCollisionMeshFast() const { return mCollisionMesh; } PX_FORCE_INLINE BVTetrahedronMesh* getCollisionMeshFast() { return mCollisionMesh; } virtual const PxTetrahedronMesh* getSimulationMesh() const { return mSimulationMesh; } virtual PxTetrahedronMesh* getSimulationMesh() { return mSimulationMesh; } PX_FORCE_INLINE const TetrahedronMesh* getSimulationMeshFast() const { return mSimulationMesh; } PX_FORCE_INLINE TetrahedronMesh* getSimulationMeshFast() { return mSimulationMesh; } virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const { return mSoftBodyAuxData; } virtual PxSoftBodyAuxData* getSoftBodyAuxData() { return mSoftBodyAuxData; } PX_FORCE_INLINE const SoftBodyAuxData* getSoftBodyAuxDataFast() const { return mSoftBodyAuxData; } PX_FORCE_INLINE SoftBodyAuxData* getSoftBodyAuxDataFast() { return mSoftBodyAuxData; } protected: TetrahedronMesh* mSimulationMesh; BVTetrahedronMesh* mCollisionMesh; SoftBodyAuxData* mSoftBodyAuxData; MeshFactory* mMeshFactory; // PT: changed to pointer for serialization }; #if PX_VC #pragma warning(pop) #endif } // namespace Gu } #endif
12,247
C
40.518644
153
0.716829
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Settings.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_SETTINGS_H #define GU_BV4_SETTINGS_H // PT: "BV4" ported from "Opcode 2.0". Available compile-time options are: #define GU_BV4_STACK_SIZE 256 // Default size of local stacks for non-recursive traversals. #define GU_BV4_PRECOMPUTED_NODE_SORT // Use node sorting or not. This should probably always be enabled. // #define GU_BV4_QUANTIZED_TREE // Use AABB quantization/compression or not. #define GU_BV4_USE_SLABS // Use swizzled data format or not. Swizzled = faster raycasts, but slower overlaps & larger trees. // #define GU_BV4_COMPILE_NON_QUANTIZED_TREE // #define GU_BV4_FILL_GAPS //#define PROFILE_MESH_COOKING #ifdef PROFILE_MESH_COOKING #include <intrin.h> #include <stdio.h> struct LocalProfileZone { LocalProfileZone(const char* name) { mName = name; mTime = __rdtsc(); } ~LocalProfileZone() { mTime = __rdtsc() - mTime; printf("%s: %d\n", mName, unsigned int(mTime/1024)); } const char* mName; unsigned long long mTime; }; #define GU_PROFILE_ZONE(name) LocalProfileZone zone(name); #else #define GU_PROFILE_ZONE(name) #endif #endif // GU_BV4_SETTINGS_H
2,833
C
41.298507
129
0.740205
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshBV4.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TRIANGLEMESH_BV4_H #define GU_TRIANGLEMESH_BV4_H #include "GuTriangleMesh.h" namespace physx { namespace Gu { class MeshFactory; #if PX_VC #pragma warning(push) #pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class BV4TriangleMesh : public TriangleMesh { public: virtual const char* getConcreteTypeName() const { return "PxBVH34TriangleMesh"; } // PX_SERIALIZATION BV4TriangleMesh(PxBaseFlags baseFlags) : TriangleMesh(baseFlags), mMeshInterface(PxEmpty), mBV4Tree(PxEmpty) {} PX_PHYSX_COMMON_API virtual void exportExtraData(PxSerializationContext& ctx); void importExtraData(PxDeserializationContext&); PX_PHYSX_COMMON_API static TriangleMesh* createObject(PxU8*& address, PxDeserializationContext& context); PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION BV4TriangleMesh(MeshFactory* factory, TriangleMeshData& data); virtual ~BV4TriangleMesh(){} virtual PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH34; } virtual PxVec3* getVerticesForModification(); virtual PxBounds3 refitBVH(); PX_PHYSX_COMMON_API BV4TriangleMesh(const PxTriangleMeshInternalData& data); virtual bool getInternalData(PxTriangleMeshInternalData&, bool) const; PX_FORCE_INLINE const Gu::BV4Tree& getBV4Tree() const { return mBV4Tree; } private: Gu::SourceMesh mMeshInterface; Gu::BV4Tree mBV4Tree; }; #if PX_VC #pragma warning(pop) #endif } // namespace Gu } #endif
3,362
C
40.012195
125
0.7442
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleCache.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TRIANGLE_CACHE_H #define GU_TRIANGLE_CACHE_H #include "foundation/PxHash.h" #include "foundation/PxUtilities.h" namespace physx { namespace Gu { struct CachedEdge { protected: PxU32 mId0, mId1; public: CachedEdge(PxU32 i0, PxU32 i1) { mId0 = PxMin(i0, i1); mId1 = PxMax(i0, i1); } CachedEdge() { } PxU32 getId0() const { return mId0; } PxU32 getId1() const { return mId1; } bool operator == (const CachedEdge& other) const { return mId0 == other.mId0 && mId1 == other.mId1; } PxU32 getHashCode() const { return PxComputeHash(mId0 << 16 | mId1); } }; struct CachedVertex { private: PxU32 mId; public: CachedVertex(PxU32 id) { mId = id; } CachedVertex() { } PxU32 getId() const { return mId; } PxU32 getHashCode() const { return mId; } bool operator == (const CachedVertex& other) const { return mId == other.mId; } }; template <typename Elem, PxU32 MaxCount> struct CacheMap { PX_COMPILE_TIME_ASSERT(MaxCount < 0xFF); Elem mCache[MaxCount]; PxU8 mNextInd[MaxCount]; PxU8 mIndex[MaxCount]; PxU32 mSize; CacheMap() : mSize(0) { for(PxU32 a = 0; a < MaxCount; ++a) { mIndex[a] = 0xFF; } } bool addData(const Elem& data) { if(mSize == MaxCount) return false; const PxU8 hash = PxU8(data.getHashCode() % MaxCount); PxU8 index = hash; PxU8 nextInd = mIndex[hash]; while(nextInd != 0xFF) { index = nextInd; if(mCache[index] == data) return false; nextInd = mNextInd[nextInd]; } if(mIndex[hash] == 0xFF) { mIndex[hash] = PxTo8(mSize); } else { mNextInd[index] = PxTo8(mSize); } mNextInd[mSize] = 0xFF; mCache[mSize++] = data; return true; } bool contains(const Elem& data) const { PxU32 hash = (data.getHashCode() % MaxCount); PxU8 index = mIndex[hash]; while(index != 0xFF) { if(mCache[index] == data) return true; index = mNextInd[index]; } return false; } const Elem* get(const Elem& data) const { PxU32 hash = (data.getHashCode() % MaxCount); PxU8 index = mIndex[hash]; while(index != 0xFF) { if(mCache[index] == data) return &mCache[index]; index = mNextInd[index]; } return NULL; } }; template <PxU32 MaxTriangles> struct TriangleCache { PxVec3 mVertices[3*MaxTriangles]; PxU32 mIndices[3*MaxTriangles]; PxU32 mTriangleIndex[MaxTriangles]; PxU8 mEdgeFlags[MaxTriangles]; PxU32 mNumTriangles; TriangleCache() : mNumTriangles(0) { } PX_FORCE_INLINE bool isEmpty() const { return mNumTriangles == 0; } PX_FORCE_INLINE bool isFull() const { return mNumTriangles == MaxTriangles; } PX_FORCE_INLINE void reset() { mNumTriangles = 0; } void addTriangle(const PxVec3* verts, const PxU32* indices, PxU32 triangleIndex, PxU8 edgeFlag) { PX_ASSERT(mNumTriangles < MaxTriangles); PxU32 triInd = mNumTriangles++; PxU32 triIndMul3 = triInd*3; mVertices[triIndMul3] = verts[0]; mVertices[triIndMul3+1] = verts[1]; mVertices[triIndMul3+2] = verts[2]; mIndices[triIndMul3] = indices[0]; mIndices[triIndMul3+1] = indices[1]; mIndices[triIndMul3+2] = indices[2]; mTriangleIndex[triInd] = triangleIndex; mEdgeFlags[triInd] = edgeFlag; } }; template <PxU32 MaxTetrahedrons> struct TetrahedronCache { PxVec3 mVertices[4 * MaxTetrahedrons]; PxU32 mTetVertIndices[4 * MaxTetrahedrons]; PxU32 mTetrahedronIndices[MaxTetrahedrons]; PxU32 mNumTetrahedrons; TetrahedronCache() : mNumTetrahedrons(0) { } PX_FORCE_INLINE bool isEmpty() const { return mNumTetrahedrons == 0; } PX_FORCE_INLINE bool isFull() const { return mNumTetrahedrons == MaxTetrahedrons; } PX_FORCE_INLINE void reset() { mNumTetrahedrons = 0; } void addTetrahedrons(const PxVec3* verts, const PxU32* indices, PxU32 tetIndex) { PX_ASSERT(mNumTetrahedrons < MaxTetrahedrons); PxU32 tetInd = mNumTetrahedrons++; PxU32 tetIndMul4 = tetInd * 4; mVertices[tetIndMul4] = verts[0]; mVertices[tetIndMul4 + 1] = verts[1]; mVertices[tetIndMul4 + 2] = verts[2]; mVertices[tetIndMul4 + 3] = verts[3]; mTetVertIndices[tetIndMul4] = indices[0]; mTetVertIndices[tetIndMul4 + 1] = indices[1]; mTetVertIndices[tetIndMul4 + 2] = indices[2]; mTetVertIndices[tetIndMul4 + 3] = indices[3]; mTetrahedronIndices[tetInd] = tetIndex; } }; } } #endif
6,284
C
25.1875
98
0.667887
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Build.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxVec4.h" #include "foundation/PxMemory.h" #include "GuAABBTreeBuildStats.h" #include "GuAABBTree.h" #include "GuSAH.h" #include "GuBounds.h" #include "GuBV4Build.h" #include "GuBV4.h" #include <stdio.h> using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #define GU_BV4_USE_NODE_POOLS static PX_FORCE_INLINE PxU32 largestAxis(const PxVec4& v) { const float* Vals = &v.x; PxU32 m = 0; if(Vals[1] > Vals[m]) m = 1; if(Vals[2] > Vals[m]) m = 2; return m; } BV4_AABBTree::BV4_AABBTree() : mIndices(NULL), mPool(NULL), mTotalNbNodes(0) { } BV4_AABBTree::~BV4_AABBTree() { release(); } void BV4_AABBTree::release() { PX_DELETE_ARRAY(mPool); PX_FREE(mIndices); } namespace { struct BuildParams { PX_FORCE_INLINE BuildParams(const PxBounds3* boxes, const PxVec3* centers, const AABBTreeNode* const node_base, const PxU32 limit, const SourceMesh* mesh) : mBoxes(boxes), mCenters(centers), mNodeBase(node_base), mLimit(limit), mMesh(mesh) {} const PxBounds3* mBoxes; const PxVec3* mCenters; const AABBTreeNode* const mNodeBase; const PxU32 mLimit; const SourceMesh* mMesh; PX_NOCOPY(BuildParams) }; } static PxU32 local_Split(const AABBTreeNode* PX_RESTRICT node, const PxBounds3* PX_RESTRICT /*Boxes*/, const PxVec3* PX_RESTRICT centers, PxU32 axis, const BuildParams& params) { const PxU32 nb = node->mNbPrimitives; PxU32* PX_RESTRICT prims = node->mNodePrimitives; // Get node split value float splitValue = 0.0f; if(params.mMesh) { VertexPointers VP; for(PxU32 i=0;i<nb;i++) { params.mMesh->getTriangle(VP, prims[i]); splitValue += (*VP.Vertex[0])[axis]; splitValue += (*VP.Vertex[1])[axis]; splitValue += (*VP.Vertex[2])[axis]; } splitValue /= float(nb*3); } else splitValue = node->mBV.getCenter(axis); return reshuffle(nb, prims, centers, splitValue, axis); } static bool local_Subdivide(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params) { const PxU32* PX_RESTRICT prims = node->mNodePrimitives; const PxU32 nb = node->mNbPrimitives; const PxBounds3* PX_RESTRICT boxes = params.mBoxes; const PxVec3* PX_RESTRICT centers = params.mCenters; // Compute bv & means at the same time Vec4V meansV; { Vec4V minV = V4LoadU(&boxes[prims[0]].minimum.x); Vec4V maxV = V4LoadU(&boxes[prims[0]].maximum.x); meansV = V4LoadU(&centers[prims[0]].x); for(PxU32 i=1;i<nb;i++) { const PxU32 index = prims[i]; minV = V4Min(minV, V4LoadU(&boxes[index].minimum.x)); maxV = V4Max(maxV, V4LoadU(&boxes[index].maximum.x)); meansV = V4Add(meansV, V4LoadU(&centers[index].x)); } const float coeffNb = 1.0f/float(nb); meansV = V4Scale(meansV, FLoad(coeffNb)); // BV4_ALIGN16(PxVec4 mergedMin); // BV4_ALIGN16(PxVec4 mergedMax); PX_ALIGN_PREFIX(16) PxVec4 mergedMin PX_ALIGN_SUFFIX(16); PX_ALIGN_PREFIX(16) PxVec4 mergedMax PX_ALIGN_SUFFIX(16); V4StoreA_Safe(minV, &mergedMin.x); V4StoreA_Safe(maxV, &mergedMax.x); node->mBV.minimum = PxVec3(mergedMin.x, mergedMin.y, mergedMin.z); node->mBV.maximum = PxVec3(mergedMax.x, mergedMax.y, mergedMax.z); } #ifndef GU_BV4_FILL_GAPS // // Stop subdividing if we reach a leaf node. This is always performed here, // // else we could end in trouble if user overrides this. // if(nb==1) // return false; if(nb<=params.mLimit) return false; #endif bool validSplit = true; PxU32 nbPos; { // Compute variances Vec4V varsV = V4Zero(); for(PxU32 i=0;i<nb;i++) { const PxU32 index = prims[i]; Vec4V centerV = V4LoadU(&centers[index].x); centerV = V4Sub(centerV, meansV); centerV = V4Mul(centerV, centerV); varsV = V4Add(varsV, centerV); } const float coeffNb1 = 1.0f/float(nb-1); varsV = V4Scale(varsV, FLoad(coeffNb1)); // BV4_ALIGN16(PxVec4 vars); PX_ALIGN_PREFIX(16) PxVec4 vars PX_ALIGN_SUFFIX(16); V4StoreA_Safe(varsV, &vars.x); // Choose axis with greatest variance const PxU32 axis = largestAxis(vars); // Split along the axis nbPos = local_Split(node, boxes, centers, axis, params); // Check split validity if(!nbPos || nbPos==nb) validSplit = false; } // Check the subdivision has been successful if(!validSplit) { // Here, all boxes lie in the same sub-space. Two strategies: // - if the tree *must* be complete, make an arbitrary 50-50 split // - else stop subdividing // if(nb>limit) { nbPos = node->mNbPrimitives>>1; if(1) { // Test 3 axes, take the best float results[3]; nbPos = local_Split(node, boxes, centers, 0, params); results[0] = float(nbPos)/float(node->mNbPrimitives); nbPos = local_Split(node, boxes, centers, 1, params); results[1] = float(nbPos)/float(node->mNbPrimitives); nbPos = local_Split(node, boxes, centers, 2, params); results[2] = float(nbPos)/float(node->mNbPrimitives); results[0]-=0.5f; results[0]*=results[0]; results[1]-=0.5f; results[1]*=results[1]; results[2]-=0.5f; results[2]*=results[2]; PxU32 Min=0; if(results[1]<results[Min]) Min = 1; if(results[2]<results[Min]) Min = 2; // Split along the axis nbPos = local_Split(node, boxes, centers, Min, params); // Check split validity if(!nbPos || nbPos==node->mNbPrimitives) nbPos = node->mNbPrimitives>>1; } } //else return } #ifdef GU_BV4_FILL_GAPS // We split the node a last time before returning when we're below the limit, for the "fill the gaps" strategy if(nb<=params.mLimit) { node->mNextSplit = nbPos; return false; } #endif // Now create children and assign their pointers. // We use a pre-allocated linear pool for complete trees [Opcode 1.3] const PxU32 count = stats.getCount(); node->mPos = size_t(params.mNodeBase + count); // Update stats stats.increaseCount(2); // Assign children AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos()); AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg()); pos->mNodePrimitives = node->mNodePrimitives; pos->mNbPrimitives = nbPos; neg->mNodePrimitives = node->mNodePrimitives + nbPos; neg->mNbPrimitives = node->mNbPrimitives - nbPos; return true; } static bool local_Subdivide_SAH(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params, SAH_Buffers& buffers) { const PxU32* prims = node->mNodePrimitives; const PxU32 nb = node->mNbPrimitives; const PxBounds3* PX_RESTRICT boxes = params.mBoxes; const PxVec3* PX_RESTRICT centers = params.mCenters; // Compute bv computeGlobalBox(node->mBV, nb, boxes, prims); #ifndef GU_BV4_FILL_GAPS // // Stop subdividing if we reach a leaf node. This is always performed here, // // else we could end in trouble if user overrides this. // if(nb==1) // return false; if(nb<=params.mLimit) return false; #endif PxU32 leftCount; if(!buffers.split(leftCount, nb, prims, boxes, centers)) { // Invalid split => fallback to previous strategy return local_Subdivide(node, stats, params); } #ifdef GU_BV4_FILL_GAPS // We split the node a last time before returning when we're below the limit, for the "fill the gaps" strategy if(nb<=params.mLimit) { node->mNextSplit = leftCount; return false; } #endif // Now create children and assign their pointers. // We use a pre-allocated linear pool for complete trees [Opcode 1.3] const PxU32 count = stats.getCount(); node->mPos = size_t(params.mNodeBase + count); // Update stats stats.increaseCount(2); // Assign children AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos()); AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg()); pos->mNodePrimitives = node->mNodePrimitives; pos->mNbPrimitives = leftCount; neg->mNodePrimitives = node->mNodePrimitives + leftCount; neg->mNbPrimitives = node->mNbPrimitives - leftCount; return true; } // PT: TODO: consider local_BuildHierarchy & local_BuildHierarchy_SAH static void local_BuildHierarchy(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params) { if(local_Subdivide(node, stats, params)) { AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos()); AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg()); local_BuildHierarchy(pos, stats, params); local_BuildHierarchy(neg, stats, params); } } static void local_BuildHierarchy_SAH(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params, SAH_Buffers& buffers) { if(local_Subdivide_SAH(node, stats, params, buffers)) { AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos()); AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg()); local_BuildHierarchy_SAH(pos, stats, params, buffers); local_BuildHierarchy_SAH(neg, stats, params, buffers); } } bool BV4_AABBTree::buildFromMesh(SourceMeshBase& mesh, PxU32 limit, BV4_BuildStrategy strategy) { const PxU32 nbBoxes = mesh.getNbPrimitives(); if(!nbBoxes) return false; PxBounds3* boxes = PX_ALLOCATE(PxBounds3, (nbBoxes + 1), "BV4"); // PT: +1 to safely V4Load/V4Store the last element PxVec3* centers = PX_ALLOCATE(PxVec3, (nbBoxes + 1), "BV4"); // PT: +1 to safely V4Load/V4Store the last element const FloatV halfV = FLoad(0.5f); for (PxU32 i = 0; i<nbBoxes; i++) { Vec4V minV, maxV; mesh.getPrimitiveBox(i, minV, maxV); V4StoreU_Safe(minV, &boxes[i].minimum.x); // PT: safe because 'maximum' follows 'minimum' V4StoreU_Safe(maxV, &boxes[i].maximum.x); // PT: safe because we allocated one more box const Vec4V centerV = V4Scale(V4Add(maxV, minV), halfV); V4StoreU_Safe(centerV, &centers[i].x); // PT: safe because we allocated one more PxVec3 } { // Release previous tree release(); // Init stats BuildStats Stats; Stats.setCount(1); // Initialize indices. This list will be modified during build. mIndices = PX_ALLOCATE(PxU32, nbBoxes, "BV4 indices"); // Identity permutation for (PxU32 i = 0; i<nbBoxes; i++) mIndices[i] = i; // Use a linear array for complete trees (since we can predict the final number of nodes) [Opcode 1.3] // Allocate a pool of nodes // PT: TODO: optimize memory here (TA34704) mPool = PX_NEW(AABBTreeNode)[nbBoxes * 2 - 1]; // Setup initial node. Here we have a complete permutation of the app's primitives. mPool->mNodePrimitives = mIndices; mPool->mNbPrimitives = nbBoxes; // Build the hierarchy if(strategy==BV4_SPLATTER_POINTS||strategy==BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER) { // PT: not sure what the equivalent would be for tet-meshes here SourceMesh* triMesh = NULL; if(strategy==BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER) { if(mesh.getMeshType()==SourceMeshBase::TRI_MESH) triMesh = static_cast<SourceMesh*>(&mesh); } local_BuildHierarchy(mPool, Stats, BuildParams(boxes, centers, mPool, limit, triMesh)); } else if(strategy==BV4_SAH) { SAH_Buffers sah(nbBoxes); local_BuildHierarchy_SAH(mPool, Stats, BuildParams(boxes, centers, mPool, limit, NULL), sah); } else return false; // Get back total number of nodes mTotalNbNodes = Stats.getCount(); } PX_FREE(centers); PX_FREE(boxes); if(0) printf("Tree depth: %d\n", walk(NULL, NULL)); return true; } PxU32 BV4_AABBTree::walk(WalkingCallback cb, void* userData) const { // Call it without callback to compute max depth PxU32 maxDepth = 0; PxU32 currentDepth = 0; struct Local { static void _walk(const AABBTreeNode* current_node, PxU32& max_depth, PxU32& current_depth, WalkingCallback callback, void* userData_) { // Checkings if(!current_node) return; // Entering a new node => increase depth current_depth++; // Keep track of max depth if(current_depth>max_depth) max_depth = current_depth; // Callback if(callback && !(callback)(current_node, current_depth, userData_)) return; // Recurse if(current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, userData_); current_depth--; } if(current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, userData_); current_depth--; } } }; Local::_walk(mPool, maxDepth, currentDepth, cb, userData); return maxDepth; } PxU32 BV4_AABBTree::walkDistance(WalkingCallback cb, WalkingDistanceCallback cb2, void* userData) const { // Call it without callback to compute max depth PxU32 maxDepth = 0; PxU32 currentDepth = 0; struct Local { static void _walk(const AABBTreeNode* current_node, PxU32& max_depth, PxU32& current_depth, WalkingCallback callback, WalkingDistanceCallback distanceCheck, void* userData_) { // Checkings if (!current_node) return; // Entering a new node => increase depth current_depth++; // Keep track of max depth if (current_depth > max_depth) max_depth = current_depth; // Callback if (callback && !(callback)(current_node, current_depth, userData_)) return; // Recurse bool posHint = distanceCheck && (distanceCheck)(current_node, userData_); if (posHint) { if (current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; } if (current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; } } else { if (current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; } if (current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; } } } }; Local::_walk(mPool, maxDepth, currentDepth, cb, cb2, userData); return maxDepth; } #include "GuBV4_Internal.h" #ifdef GU_BV4_PRECOMPUTED_NODE_SORT // PT: see http://www.codercorner.com/blog/?p=734 static PxU32 precomputeNodeSorting(const PxBounds3& box0, const PxBounds3& box1) { const PxVec3 C0 = box0.getCenter(); const PxVec3 C1 = box1.getCenter(); PxVec3 dirPPP(1.0f, 1.0f, 1.0f); dirPPP.normalize(); PxVec3 dirPPN(1.0f, 1.0f, -1.0f); dirPPN.normalize(); PxVec3 dirPNP(1.0f, -1.0f, 1.0f); dirPNP.normalize(); PxVec3 dirPNN(1.0f, -1.0f, -1.0f); dirPNN.normalize(); PxVec3 dirNPP(-1.0f, 1.0f, 1.0f); dirNPP.normalize(); PxVec3 dirNPN(-1.0f, 1.0f, -1.0f); dirNPN.normalize(); PxVec3 dirNNP(-1.0f, -1.0f, 1.0f); dirNNP.normalize(); PxVec3 dirNNN(-1.0f, -1.0f, -1.0f); dirNNN.normalize(); const PxVec3 deltaC = C0 - C1; const bool bPPP = deltaC.dot(dirPPP)<0.0f; const bool bPPN = deltaC.dot(dirPPN)<0.0f; const bool bPNP = deltaC.dot(dirPNP)<0.0f; const bool bPNN = deltaC.dot(dirPNN)<0.0f; const bool bNPP = deltaC.dot(dirNPP)<0.0f; const bool bNPN = deltaC.dot(dirNPN)<0.0f; const bool bNNP = deltaC.dot(dirNNP)<0.0f; const bool bNNN = deltaC.dot(dirNNN)<0.0f; PxU32 code = 0; if(!bPPP) code |= (1<<7); // Bit 0: PPP if(!bPPN) code |= (1<<6); // Bit 1: PPN if(!bPNP) code |= (1<<5); // Bit 2: PNP if(!bPNN) code |= (1<<4); // Bit 3: PNN if(!bNPP) code |= (1<<3); // Bit 4: NPP if(!bNPN) code |= (1<<2); // Bit 5: NPN if(!bNNP) code |= (1<<1); // Bit 6: NNP if(!bNNN) code |= (1<<0); // Bit 7: NNN return code; } #endif #ifdef GU_BV4_USE_SLABS #include "GuBV4_Common.h" #endif // PT: warning, not the same as CenterExtents::setEmpty() static void setEmpty(CenterExtents& box) { box.mCenter = PxVec3(0.0f, 0.0f, 0.0f); box.mExtents = PxVec3(-1.0f, -1.0f, -1.0f); } #define PX_INVALID_U64 0xffffffffffffffff // Data: // 1 bit for leaf/no leaf // 2 bits for child-node type // 8 bits for PNS // => 32 - 1 - 2 - 8 = 21 bits left for encoding triangle index or node *offset* // => limited to 2.097.152 triangles // => and 2Mb-large trees (this one may not work out well in practice) // ==> lines marked with //* have been changed to address this. Now we don't store offsets in bytes directly // but in BVData indices. There's more work at runtime calculating addresses, but now the format can support // 2 million single nodes. // // That being said we only need 3*8 = 24 bits in total, so that could be only 6 bits in each BVData. // For type0: we have 2 nodes, we need 8 bits => 6 bits/node = 12 bits available, ok // For type1: we have 3 nodes, we need 8*2 = 16 bits => 6 bits/node = 18 bits available, ok // For type2: we have 4 nodes, we need 8*3 = 24 bits => 6 bits/node = 24 bits available, ok //#pragma pack(1) struct BVData : public physx::PxUserAllocated { BVData(); CenterExtents mAABB; size_t mData64; #ifdef GU_BV4_PRECOMPUTED_NODE_SORT PxU32 mTempPNS; #endif }; //#pragma pack() BVData::BVData() : mData64(PX_INVALID_U64) { setEmpty(mAABB); #ifdef GU_BV4_PRECOMPUTED_NODE_SORT mTempPNS = 0; #endif } struct BV4Node : public physx::PxUserAllocated { PX_FORCE_INLINE BV4Node() {} PX_FORCE_INLINE ~BV4Node() {} BVData mBVData[4]; PX_FORCE_INLINE size_t isLeaf(PxU32 i) const { return mBVData[i].mData64 & 1; } PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return PxU32(mBVData[i].mData64 >> 1); } PX_FORCE_INLINE const BV4Node* getChild(PxU32 i) const { return reinterpret_cast<BV4Node*>(mBVData[i].mData64); } PxU32 getType() const { PxU32 Nb=0; for(PxU32 i=0;i<4;i++) { if(mBVData[i].mData64!=PX_INVALID_U64) Nb++; } return Nb; } PxU32 getSize() const { const PxU32 type = getType(); return sizeof(BVData)*type; } }; #define NB_NODES_PER_SLAB 256 struct BV4BuildParams { PX_FORCE_INLINE BV4BuildParams(const BV4_AABBTree& source, const SourceMesh* mesh, float epsilon) : mSource(source), mMesh(mesh), mEpsilon(epsilon) #ifdef GU_BV4_USE_NODE_POOLS ,mTop(NULL) #endif {} ~BV4BuildParams(); const BV4_AABBTree& mSource; const SourceMesh* mMesh; // Stats PxU32 mNbNodes; PxU32 mStats[4]; // float mEpsilon; #ifdef GU_BV4_USE_NODE_POOLS // struct Slab : public physx::PxUserAllocated { BV4Node mNodes[NB_NODES_PER_SLAB]; PxU32 mNbUsedNodes; Slab* mNext; }; Slab* mTop; BV4Node* allocateNode(); void releaseNodes(); #endif PX_NOCOPY(BV4BuildParams) }; BV4BuildParams::~BV4BuildParams() { #ifdef GU_BV4_USE_NODE_POOLS releaseNodes(); #endif } #ifdef GU_BV4_USE_NODE_POOLS BV4Node* BV4BuildParams::allocateNode() { if(!mTop || mTop->mNbUsedNodes==NB_NODES_PER_SLAB) { Slab* newSlab = PX_NEW(Slab); newSlab->mNbUsedNodes = 0; newSlab->mNext = mTop; mTop = newSlab; } return &mTop->mNodes[mTop->mNbUsedNodes++]; } void BV4BuildParams::releaseNodes() { Slab* current = mTop; while(current) { Slab* next = current->mNext; PX_DELETE(current); current = next; } mTop = NULL; } #endif static PX_FORCE_INLINE void setupBounds(BV4Node* node4, PxU32 i, const AABBTreeNode* node, float epsilon) { node4->mBVData[i].mAABB = node->getAABB(); if(epsilon!=0.0f) node4->mBVData[i].mAABB.mExtents += PxVec3(epsilon); } static void setPrimitive(const BV4_AABBTree& source, BV4Node* node4, PxU32 i, const AABBTreeNode* node, float epsilon) { const PxU32 nbPrims = node->getNbPrimitives(); PX_ASSERT(nbPrims<16); const PxU32* indexBase = source.getIndices(); const PxU32* prims = node->getPrimitives(); const PxU64 offset = PxU64(prims - indexBase); for(PxU32 j=0;j<nbPrims;j++) { PX_ASSERT(prims[j] == offset+j); } const PxU64 primitiveIndex = (offset<<4)|(nbPrims&15); setupBounds(node4, i, node, epsilon); node4->mBVData[i].mData64 = (primitiveIndex<<1)|1; } #ifdef GU_BV4_FILL_GAPS static bool splitPrimitives(const BV4BuildParams& params, BV4Node* node4, PxU32 i, const AABBTreeNode* node) { if(!params.mMesh) return false; const PxU32 nbPrims = node->getNbPrimitives(); PX_ASSERT(nbPrims<16); if(nbPrims<2) return false; const PxU32* indexBase = params.mSource.getIndices(); const PxU32* prims = node->getPrimitives(); PxU64 offset = PxU64(prims - indexBase); // In theory we should reshuffle the list but it would mean updating the remap table again. // A way to avoid that would be to virtually split & sort the triangles directly in the BV2 // source tree, before the initial remap table is created. //const PxU32 splitPrims = NbPrims/2; // ### actually should be the number in the last split in bv2 const PxU32 splitPrims = node->mNextSplit; PxU32 j=0; for(PxU32 ii=0;ii<2;ii++) { const PxU32 currentNb = ii==0 ? splitPrims : (nbPrims-splitPrims); PxBounds3 bounds = PxBounds3::empty(); for(PxU32 k=0;k<currentNb;k++) { PX_ASSERT(prims[j] == offset+k); PxU32 vref0, vref1, vref2; getVertexReferences(vref0, vref1, vref2, prims[j], params.mMesh->getTris32(), params.mMesh->getTris16()); // PT: TODO: SIMD const PxVec3* verts = params.mMesh->getVerts(); bounds.include(verts[vref0]); bounds.include(verts[vref1]); bounds.include(verts[vref2]); j++; } PX_ASSERT(bounds.isInside(node->mBV)); const PxU64 primitiveIndex = (offset<<4)|(currentNb&15); // SetupBounds(node4, i, node, context.mEpsilon); node4->mBVData[i+ii].mAABB = bounds; if(params.mEpsilon!=0.0f) node4->mBVData[i+ii].mAABB.mExtents += PxVec3(params.mEpsilon); node4->mBVData[i+ii].mData64 = (primitiveIndex<<1)|1; offset += currentNb; } return true; } #endif static BV4Node* setNode(const BV4_AABBTree& source, BV4Node* node4, PxU32 i, const AABBTreeNode* node, BV4BuildParams& params) { BV4Node* child = NULL; if(node->isLeaf()) { setPrimitive(source, node4, i, node, params.mEpsilon); } else { setupBounds(node4, i, node, params.mEpsilon); params.mNbNodes++; #ifdef GU_BV4_USE_NODE_POOLS child = params.allocateNode(); #else child = PX_NEW(BV4Node); #endif node4->mBVData[i].mData64 = size_t(child); } return child; } #ifdef GU_BV4_PRECOMPUTED_NODE_SORT static inline PxBounds3 getMinMaxBox(const CenterExtents& box) { if(box.mExtents.x>=0.0f && box.mExtents.y>=0.0f && box.mExtents.z>=0.0f) // if(!box.isEmpty()) // ### asserts! return PxBounds3::centerExtents(box.mCenter, box.mExtents); else return PxBounds3::empty(); } static void FigureOutPNS(BV4Node* node) { // ____A____ // P N // __|__ __|__ // PP PN NP NN const CenterExtents& box0 = node->mBVData[0].mAABB; const CenterExtents& box1 = node->mBVData[1].mAABB; const CenterExtents& box2 = node->mBVData[2].mAABB; const CenterExtents& box3 = node->mBVData[3].mAABB; // PT: TODO: SIMD, optimize const PxBounds3 boxPP = getMinMaxBox(box0); const PxBounds3 boxPN = getMinMaxBox(box1); const PxBounds3 boxNP = getMinMaxBox(box2); const PxBounds3 boxNN = getMinMaxBox(box3); PxBounds3 boxP = boxPP; boxP.include(boxPN); PxBounds3 boxN = boxNP; boxN.include(boxNN); node->mBVData[0].mTempPNS = precomputeNodeSorting(boxP, boxN); node->mBVData[1].mTempPNS = precomputeNodeSorting(boxPP, boxPN); node->mBVData[2].mTempPNS = precomputeNodeSorting(boxNP, boxNN); } #endif /*static bool hasTwoLeafChildren(const AABBTreeNode* current_node) { if(current_node->isLeaf()) return false; const AABBTreeNode* P = current_node->getPos(); const AABBTreeNode* N = current_node->getNeg(); return P->isLeaf() && N->isLeaf(); }*/ static void buildBV4(const BV4_AABBTree& source, BV4Node* tmp, const AABBTreeNode* current_node, BV4BuildParams& params) { PX_ASSERT(!current_node->isLeaf()); // In the regular tree we have current node A, and: // ____A____ // P N // __|__ __|__ // PP PN NP NN // // For PNS we have: // bit0 to sort P|N // bit1 to sort PP|PN // bit2 to sort NP|NN // // As much as possible we need to preserve the original order in BV4, if we want to reuse the same PNS bits. // // bit0|bit1|bit2 Order 8bits code // 0 0 0 PP PN NP NN 0 1 2 3 // 0 0 1 PP PN NN NP 0 1 3 2 // 0 1 0 PN PP NP NN 1 0 2 3 // 0 1 1 PN PP NN NP 1 0 3 2 // 1 0 0 NP NN PP PN 2 3 0 1 // 1 0 1 NN NP PP PN 3 2 0 1 // 1 1 0 NP NN PN PP 2 3 1 0 // 1 1 1 NN NP PN PP 3 2 1 0 // // So we can fetch/compute the sequence from the bits, combine it with limitations from the node type, and process the nodes in order. In theory. // 8*8bits => the whole thing fits in a single 64bit register, so we could potentially use a "register LUT" here. const AABBTreeNode* P = current_node->getPos(); const AABBTreeNode* N = current_node->getNeg(); const bool PLeaf = P->isLeaf(); const bool NLeaf = N->isLeaf(); if(PLeaf) { if(NLeaf) { // Case 1: P and N are both leaves: // ____A____ // P N // => store as (P,N) and keep bit0 #ifndef GU_BV4_FILL_GAPS params.mStats[0]++; // PN leaves => store 2 triangle pointers, lose 50% of node space setPrimitive(source, tmp, 0, P, params.mEpsilon); setPrimitive(source, tmp, 1, N, params.mEpsilon); #else { PxU32 nextIndex = 2; if(!splitPrimitives(params, tmp, 0, P)) { setPrimitive(source, tmp, 0, P, params.mEpsilon); nextIndex = 1; } if(!splitPrimitives(params, tmp, nextIndex, N)) setPrimitive(source, tmp, nextIndex, N, params.mEpsilon); const PxU32 statIndex = tmp->getType(); if(statIndex==4) params.mStats[3]++; else if(statIndex==3) params.mStats[1]++; else if(statIndex==2) params.mStats[0]++; else PX_ASSERT(0); } #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT0 tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV); #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT FigureOutPNS(tmp); #endif } else { // Case 2: P leaf, N no leaf // ____A____ // P N // __|__ // NP NN // => store as (P,NP,NN), keep bit0 and bit2 //#define NODE_FUSION #ifdef NODE_FUSION // P leaf => store 1 triangle pointers and 2 node pointers // => 3 slots used, 25% wasted const AABBTreeNode* NP = N->getPos(); const AABBTreeNode* NN = N->getNeg(); BV4Node* ChildNP; BV4Node* ChildNN; #ifdef GU_BV4_FILL_GAPS if(splitPrimitives(params, tmp, 0, P)) { // We used up the empty slot, continue as usual in slot 2 ChildNP = setNode(source, tmp, 2, NP, params); ChildNN = setNode(source, tmp, 3, NN, params); } else #endif { // We oouldn't split the prims, continue searching for a way to use the empty slot setPrimitive(source, tmp, 0, P, params.mEpsilon); PxU32 c=0; if(hasTwoLeafChildren(NP)) { // Drag the terminal leaves directly into this BV4 node, drop internal node NP setPrimitive(source, tmp, 1, NP->getPos(), params.mEpsilon); setPrimitive(source, tmp, 2, NP->getNeg(), params.mEpsilon); ChildNP = NULL; c=1; } else { ChildNP = setNode(source, tmp, 1, NP, params); } if(c==0 && hasTwoLeafChildren(NN)) { // Drag the terminal leaves directly into this BV4 node, drop internal node NN setPrimitive(source, tmp, 2, NN->getPos(), params.mEpsilon); setPrimitive(source, tmp, 3, NN->getNeg(), params.mEpsilon); ChildNN = NULL; } else { #ifdef GU_BV4_FILL_GAPS if(c==0 && NN->isLeaf()) { ChildNN = NULL; if(!splitPrimitives(params, tmp, 2, NN)) setPrimitive(source, tmp, 2, NN, params.mEpsilon); } else #endif { ChildNN = setNode(source, tmp, 2+c, NN, params); } } } const PxU32 statIndex = tmp->getType(); if(statIndex==4) params.mStats[3]++; else if(statIndex==3) params.mStats[1]++; else if(statIndex==2) params.mStats[0]++; else PX_ASSERT(0); #else params.mStats[1]++; // P leaf => store 1 triangle pointers and 2 node pointers // => 3 slots used, 25% wasted setPrimitive(source, tmp, 0, P, params.mEpsilon); const AABBTreeNode* NP = N->getPos(); const AABBTreeNode* NN = N->getNeg(); BV4Node* ChildNP = setNode(source, tmp, 1, NP, params); BV4Node* ChildNN = setNode(source, tmp, 2, NN, params); #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT0 tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV); tmp->mBVData[2].mTempPNS = precomputeNodeSorting(NP->mBV, NN->mBV); #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT FigureOutPNS(tmp); #endif if(ChildNP) buildBV4(source, ChildNP, NP, params); if(ChildNN) buildBV4(source, ChildNN, NN, params); } } else { if(NLeaf) { // Note: this case doesn't exist anymore because of the node reorganizing for shadow rays // Case 3: P no leaf, N leaf // ____A____ // P N // __|__ // PP PN // => store as (PP,PN,N), keep bit0 and bit1 params.mStats[2]++; // N leaf => store 1 triangle pointers and 2 node pointers // => 3 slots used, 25% wasted setPrimitive(source, tmp, 2, N, params.mEpsilon); // const AABBTreeNode* PP = P->getPos(); const AABBTreeNode* PN = P->getNeg(); BV4Node* ChildPP = setNode(source, tmp, 0, PP, params); BV4Node* ChildPN = setNode(source, tmp, 1, PN, params); #ifdef GU_BV4_PRECOMPUTED_NODE_SORT0 tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV); tmp->mBVData[1].mTempPNS = precomputeNodeSorting(PP->mBV, PN->mBV); #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT FigureOutPNS(tmp); #endif if(ChildPP) buildBV4(source, ChildPP, PP, params); if(ChildPN) buildBV4(source, ChildPN, PN, params); } else { // Case 4: P and N are no leaves: // => store as (PP,PN,NP,NN), keep bit0/bit1/bit2 params.mStats[3]++; // No leaves => store 4 node pointers const AABBTreeNode* PP = P->getPos(); const AABBTreeNode* PN = P->getNeg(); const AABBTreeNode* NP = N->getPos(); const AABBTreeNode* NN = N->getNeg(); BV4Node* ChildPP = setNode(source, tmp, 0, PP, params); BV4Node* ChildPN = setNode(source, tmp, 1, PN, params); BV4Node* ChildNP = setNode(source, tmp, 2, NP, params); BV4Node* ChildNN = setNode(source, tmp, 3, NN, params); #ifdef GU_BV4_PRECOMPUTED_NODE_SORT0 tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV); tmp->mBVData[1].mTempPNS = precomputeNodeSorting(PP->mBV, PN->mBV); tmp->mBVData[2].mTempPNS = precomputeNodeSorting(NP->mBV, NN->mBV); #endif #ifdef GU_BV4_PRECOMPUTED_NODE_SORT FigureOutPNS(tmp); #endif if(ChildPP) buildBV4(source, ChildPP, PP, params); if(ChildPN) buildBV4(source, ChildPN, PN, params); if(ChildNP) buildBV4(source, ChildNP, NP, params); if(ChildNN) buildBV4(source, ChildNN, NN, params); } } } #ifdef GU_BV4_USE_SLABS static void computeMaxValues(const BV4Node* current, PxVec3& MinMax, PxVec3& MaxMax) #else static void computeMaxValues(const BV4Node* current, PxVec3& CMax, PxVec3& EMax) #endif { for(PxU32 i=0; i<4; i++) { if(current->mBVData[i].mData64 != PX_INVALID_U64) { const CenterExtents& Box = current->mBVData[i].mAABB; #ifdef GU_BV4_USE_SLABS const PxVec3 Min = Box.mCenter - Box.mExtents; const PxVec3 Max = Box.mCenter + Box.mExtents; if(fabsf(Min.x)>MinMax.x) MinMax.x = fabsf(Min.x); if(fabsf(Min.y)>MinMax.y) MinMax.y = fabsf(Min.y); if(fabsf(Min.z)>MinMax.z) MinMax.z = fabsf(Min.z); if(fabsf(Max.x)>MaxMax.x) MaxMax.x = fabsf(Max.x); if(fabsf(Max.y)>MaxMax.y) MaxMax.y = fabsf(Max.y); if(fabsf(Max.z)>MaxMax.z) MaxMax.z = fabsf(Max.z); #else if(fabsf(Box.mCenter.x)>CMax.x) CMax.x = fabsf(Box.mCenter.x); if(fabsf(Box.mCenter.y)>CMax.y) CMax.y = fabsf(Box.mCenter.y); if(fabsf(Box.mCenter.z)>CMax.z) CMax.z = fabsf(Box.mCenter.z); if(fabsf(Box.mExtents.x)>EMax.x) EMax.x = fabsf(Box.mExtents.x); if(fabsf(Box.mExtents.y)>EMax.y) EMax.y = fabsf(Box.mExtents.y); if(fabsf(Box.mExtents.z)>EMax.z) EMax.z = fabsf(Box.mExtents.z); #endif if(!current->isLeaf(i)) { const BV4Node* ChildNode = current->getChild(i); #ifdef GU_BV4_USE_SLABS computeMaxValues(ChildNode, MinMax, MaxMax); #else computeMaxValues(ChildNode, CMax, EMax); #endif } } } } template<class T> static PX_FORCE_INLINE bool copyData(T* PX_RESTRICT dst, const BV4Node* PX_RESTRICT src, PxU32 i) { if(src->isLeaf(i)) { if(src->mBVData[i].mData64 > 0xffffffff) return false; } dst->mData = PxU32(src->mBVData[i].mData64); //dst->mData = PxTo32(src->mBVData[i].mData); // dst->mData = PxU32(src->mBVData[i].mData); // dst->encodePNS(src->mBVData[i].mTempPNS); return true; } namespace { struct flattenQParams { PxVec3 mCQuantCoeff; PxVec3 mEQuantCoeff; PxVec3 mCenterCoeff; PxVec3 mExtentsCoeff; }; } template<class T> static PX_FORCE_INLINE bool processNode(T* PX_RESTRICT data, const BV4Node* PX_RESTRICT current, PxU64* PX_RESTRICT nextIDs, const BV4Node** PX_RESTRICT childNodes, PxU32 i, PxU64& current_id, PxU32& nbToGo) { const BV4Node* childNode = current->getChild(i); const PxU64 nextID = current_id; #ifdef GU_BV4_USE_SLABS current_id += 4; #else const PxU32 childSize = childNode->getType(); current_id += childSize; #endif const PxU32 childType = (childNode->getType() - 2) << 1; const PxU64 data64 = size_t(childType + (nextID << GU_BV4_CHILD_OFFSET_SHIFT_COUNT)); if(data64 <= 0xffffffff) data[i].mData = PxU32(data64); else return false; //PX_ASSERT(data[i].mData == size_t(childType+(nextID<<3))); nextIDs[nbToGo] = nextID; childNodes[nbToGo] = childNode; nbToGo++; #ifdef GU_BV4_PRECOMPUTED_NODE_SORT data[i].encodePNS(current->mBVData[i].mTempPNS); #endif return true; } static bool flattenQ(const flattenQParams& params, BVDataPackedQ* const dest, const PxU64 box_id, PxU64& current_id, const BV4Node* current, PxU32& max_depth, PxU32& current_depth) { // Entering a new node => increase depth current_depth++; // Keep track of max depth if(current_depth>max_depth) max_depth = current_depth; // dest[box_id] = *current; const PxU32 CurrentType = current->getType(); for(PxU32 i=0; i<CurrentType; i++) { const CenterExtents& Box = current->mBVData[i].mAABB; #ifdef GU_BV4_USE_SLABS const PxVec3 m = Box.mCenter - Box.mExtents; const PxVec3 M = Box.mCenter + Box.mExtents; dest[box_id + i].mAABB.mData[0].mCenter = PxI16(m.x * params.mCQuantCoeff.x); dest[box_id + i].mAABB.mData[1].mCenter = PxI16(m.y * params.mCQuantCoeff.y); dest[box_id + i].mAABB.mData[2].mCenter = PxI16(m.z * params.mCQuantCoeff.z); dest[box_id + i].mAABB.mData[0].mExtents = PxU16(PxI16(M.x * params.mEQuantCoeff.x)); dest[box_id + i].mAABB.mData[1].mExtents = PxU16(PxI16(M.y * params.mEQuantCoeff.y)); dest[box_id + i].mAABB.mData[2].mExtents = PxU16(PxI16(M.z * params.mEQuantCoeff.z)); if (1) { for (PxU32 j = 0; j<3; j++) { // Dequantize the min/max // const float qmin = float(dest[box_id+i].mAABB.mData[j].mCenter) * mCenterCoeff[j]; // const float qmax = float(PxI16(dest[box_id+i].mAABB.mData[j].mExtents)) * mExtentsCoeff[j]; // Compare real & dequantized values /* if(qmax<M[j] || qmin>m[j]) { int stop=1; }*/ bool CanLeave; do { CanLeave = true; const float qmin = float(dest[box_id + i].mAABB.mData[j].mCenter) * params.mCenterCoeff[j]; const float qmax = float(PxI16(dest[box_id + i].mAABB.mData[j].mExtents)) * params.mExtentsCoeff[j]; if (qmax<M[j]) { // if(dest[box_id+i].mAABB.mData[j].mExtents!=0xffff) if (dest[box_id + i].mAABB.mData[j].mExtents != 0x7fff) { dest[box_id + i].mAABB.mData[j].mExtents++; CanLeave = false; } } if (qmin>m[j]) { if (dest[box_id + i].mAABB.mData[j].mCenter) { dest[box_id + i].mAABB.mData[j].mCenter--; CanLeave = false; } } } while (!CanLeave); } } #else // GU_BV4_USE_SLABS dest[box_id + i].mAABB.mData[0].mCenter = PxI16(Box.mCenter.x * CQuantCoeff.x); dest[box_id + i].mAABB.mData[1].mCenter = PxI16(Box.mCenter.y * CQuantCoeff.y); dest[box_id + i].mAABB.mData[2].mCenter = PxI16(Box.mCenter.z * CQuantCoeff.z); dest[box_id + i].mAABB.mData[0].mExtents = PxU16(Box.mExtents.x * EQuantCoeff.x); dest[box_id + i].mAABB.mData[1].mExtents = PxU16(Box.mExtents.y * EQuantCoeff.y); dest[box_id + i].mAABB.mData[2].mExtents = PxU16(Box.mExtents.z * EQuantCoeff.z); // Fix quantized boxes if (1) { // Make sure the quantized box is still valid const PxVec3 Max = Box.mCenter + Box.mExtents; const PxVec3 Min = Box.mCenter - Box.mExtents; // For each axis for (PxU32 j = 0; j<3; j++) { // Dequantize the box center const float qc = float(dest[box_id + i].mAABB.mData[j].mCenter) * mCenterCoeff[j]; bool FixMe = true; do { // Dequantize the box extent const float qe = float(dest[box_id + i].mAABB.mData[j].mExtents) * mExtentsCoeff[j]; // Compare real & dequantized values if (qc + qe<Max[j] || qc - qe>Min[j]) dest[box_id + i].mAABB.mData[j].mExtents++; else FixMe = false; // Prevent wrapping if (!dest[box_id + i].mAABB.mData[j].mExtents) { dest[box_id + i].mAABB.mData[j].mExtents = 0xffff; FixMe = false; } } while (FixMe); } } #endif // GU_BV4_USE_SLABS if(!copyData(&dest[box_id + i], current, i)) return false; } PxU32 NbToGo = 0; PxU64 NextIDs[4] = { PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64 }; const BV4Node* ChildNodes[4] = { NULL, NULL, NULL, NULL }; BVDataPackedQ* data = dest + box_id; for(PxU32 i=0; i<4; i++) { if(current->mBVData[i].mData64 != PX_INVALID_U64 && !current->isLeaf(i)) { if(!processNode(data, current, NextIDs, ChildNodes, i, current_id, NbToGo)) return false; //#define DEPTH_FIRST #ifdef DEPTH_FIRST if(!flattenQ(params, dest, NextID, current_id, ChildNode, max_depth, current_depth, CQuantCoeff, EQuantCoeff, mCenterCoeff, mExtentsCoeff)) return false; current_depth--; #endif } #ifdef GU_BV4_USE_SLABS if (current->mBVData[i].mData64 == PX_INVALID_U64) { data[i].mAABB.mData[0].mExtents = 0; data[i].mAABB.mData[1].mExtents = 0; data[i].mAABB.mData[2].mExtents = 0; data[i].mAABB.mData[0].mCenter = 0; data[i].mAABB.mData[1].mCenter = 0; data[i].mAABB.mData[2].mCenter = 0; data[i].mData = PX_INVALID_U32; } #endif } #ifndef DEPTH_FIRST for(PxU32 i=0; i<NbToGo; i++) { if(!flattenQ(params, dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth)) return false; current_depth--; } #endif #ifndef GU_BV4_USE_NODE_POOLS PX_DELETE(current); #endif return true; } static bool flattenNQ(BVDataPackedNQ* const dest, const PxU64 box_id, PxU64& current_id, const BV4Node* current, PxU32& max_depth, PxU32& current_depth) { // Entering a new node => increase depth current_depth++; // Keep track of max depth if(current_depth>max_depth) max_depth = current_depth; // dest[box_id] = *current; const PxU32 CurrentType = current->getType(); for(PxU32 i=0; i<CurrentType; i++) { #ifdef GU_BV4_USE_SLABS // Compute min & max right here. Store temp as Center/Extents = Min/Max const CenterExtents& Box = current->mBVData[i].mAABB; dest[box_id + i].mAABB.mCenter = Box.mCenter - Box.mExtents; dest[box_id + i].mAABB.mExtents = Box.mCenter + Box.mExtents; #else // GU_BV4_USE_SLABS dest[box_id + i].mAABB = current->mBVData[i].mAABB; #endif // GU_BV4_USE_SLABS if(!copyData(&dest[box_id + i], current, i)) return false; } PxU32 NbToGo = 0; PxU64 NextIDs[4] = { PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64 }; const BV4Node* ChildNodes[4] = { NULL, NULL, NULL, NULL }; BVDataPackedNQ* data = dest + box_id; for(PxU32 i=0; i<4; i++) { if(current->mBVData[i].mData64 != PX_INVALID_U64 && !current->isLeaf(i)) { if(!processNode(data, current, NextIDs, ChildNodes, i, current_id, NbToGo)) return false; //#define DEPTH_FIRST #ifdef DEPTH_FIRST if(!flattenNQ(dest, NextID, current_id, ChildNode, max_depth, current_depth)) return false; current_depth--; #endif } #ifdef GU_BV4_USE_SLABS if (current->mBVData[i].mData64 == PX_INVALID_U64) { data[i].mAABB.mCenter = PxVec3(0.0f); data[i].mAABB.mExtents = PxVec3(0.0f); data[i].mData = PX_INVALID_U32; } #endif } #ifndef DEPTH_FIRST for(PxU32 i=0; i<NbToGo; i++) { if(!flattenNQ(dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth)) return false; current_depth--; } #endif #ifndef GU_BV4_USE_NODE_POOLS PX_DELETE(current); #endif return true; } static bool BuildBV4FromRoot(BV4Tree& tree, BV4Node* Root, BV4BuildParams& Params, bool quantized, float epsilon) { GU_PROFILE_ZONE("....BuildBV4FromRoot") BV4Tree* T = &tree; T->mQuantized = quantized; // Version with variable-sized nodes in single stream { const PxU32 NbSingleNodes = Params.mStats[0] * 2 + (Params.mStats[1] + Params.mStats[2]) * 3 + Params.mStats[3] * 4; PxU64 CurID = Root->getType(); PxU32 InitData = PX_INVALID_U32; #ifdef GU_BV4_USE_SLABS PX_UNUSED(NbSingleNodes); const PxU32 NbNeeded = (Params.mStats[0] + Params.mStats[1] + Params.mStats[2] + Params.mStats[3]) * 4; // PT: TODO: refactor with code in BV4Tree::load // BVDataPacked* Nodes = reinterpret_cast<BVDataPacked*>(PX_ALLOC(sizeof(BVDataPacked)*NbNeeded, "BV4 nodes")); // PT: PX_NEW breaks alignment here // BVDataPacked* Nodes = PX_NEW(BVDataPacked)[NbNeeded]; void* nodes; { const PxU32 nodeSize = T->mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ); const PxU32 dataSize = nodeSize*NbNeeded; nodes = PX_ALLOC(dataSize, "BV4 nodes"); // PT: PX_NEW breaks alignment here } if (CurID == 2) { InitData = 0; } else if (CurID == 3) { InitData = 2; } else if (CurID == 4) { InitData = 4; } CurID = 4; // PxU32 CurID = 4; // PxU32 InitData = 4; #else BVDataPacked* Nodes = PX_NEW(BVDataPacked)[NbSingleNodes]; if (CurID == 2) { InitData = 0; } else if (CurID == 3) { InitData = 2; } else if (CurID == 4) { InitData = 4; } #endif T->mInitData = InitData; PxU32 MaxDepth = 0; PxU32 CurrentDepth = 0; bool buildStatus; if(T->mQuantized) { flattenQParams params; #ifdef GU_BV4_USE_SLABS PxVec3 MinQuantCoeff, MaxQuantCoeff; // Get max values PxVec3 MinMax(-FLT_MAX); PxVec3 MaxMax(-FLT_MAX); computeMaxValues(Root, MinMax, MaxMax); const PxU32 nbm = 15; // Compute quantization coeffs const float MinCoeff = float((1 << nbm) - 1); const float MaxCoeff = float((1 << nbm) - 1); MinQuantCoeff.x = MinMax.x != 0.0f ? MinCoeff / MinMax.x : 0.0f; MinQuantCoeff.y = MinMax.y != 0.0f ? MinCoeff / MinMax.y : 0.0f; MinQuantCoeff.z = MinMax.z != 0.0f ? MinCoeff / MinMax.z : 0.0f; MaxQuantCoeff.x = MaxMax.x != 0.0f ? MaxCoeff / MaxMax.x : 0.0f; MaxQuantCoeff.y = MaxMax.y != 0.0f ? MaxCoeff / MaxMax.y : 0.0f; MaxQuantCoeff.z = MaxMax.z != 0.0f ? MaxCoeff / MaxMax.z : 0.0f; // Compute and save dequantization coeffs T->mCenterOrMinCoeff.x = MinMax.x / MinCoeff; T->mCenterOrMinCoeff.y = MinMax.y / MinCoeff; T->mCenterOrMinCoeff.z = MinMax.z / MinCoeff; T->mExtentsOrMaxCoeff.x = MaxMax.x / MaxCoeff; T->mExtentsOrMaxCoeff.y = MaxMax.y / MaxCoeff; T->mExtentsOrMaxCoeff.z = MaxMax.z / MaxCoeff; params.mCQuantCoeff = MinQuantCoeff; params.mEQuantCoeff = MaxQuantCoeff; #else // Get max values PxVec3 CMax(-FLT_MAX); PxVec3 EMax(-FLT_MAX); computeMaxValues(Root, CMax, EMax); const PxU32 nbc = 15; const PxU32 nbe = 16; // const PxU32 nbc=7; // const PxU32 nbe=8; const float UnitQuantError = 2.0f / 65535.0f; EMax.x += CMax.x*UnitQuantError; EMax.y += CMax.y*UnitQuantError; EMax.z += CMax.z*UnitQuantError; // Compute quantization coeffs const float CCoeff = float((1 << nbc) - 1); CQuantCoeff.x = CMax.x != 0.0f ? CCoeff / CMax.x : 0.0f; CQuantCoeff.y = CMax.y != 0.0f ? CCoeff / CMax.y : 0.0f; CQuantCoeff.z = CMax.z != 0.0f ? CCoeff / CMax.z : 0.0f; const float ECoeff = float((1 << nbe) - 32); EQuantCoeff.x = EMax.x != 0.0f ? ECoeff / EMax.x : 0.0f; EQuantCoeff.y = EMax.y != 0.0f ? ECoeff / EMax.y : 0.0f; EQuantCoeff.z = EMax.z != 0.0f ? ECoeff / EMax.z : 0.0f; // Compute and save dequantization coeffs T->mCenterOrMinCoeff.x = CMax.x / CCoeff; T->mCenterOrMinCoeff.y = CMax.y / CCoeff; T->mCenterOrMinCoeff.z = CMax.z / CCoeff; T->mExtentsOrMaxCoeff.x = EMax.x / ECoeff; T->mExtentsOrMaxCoeff.y = EMax.y / ECoeff; T->mExtentsOrMaxCoeff.z = EMax.z / ECoeff; params.mCQuantCoeff = CQuantCoeff; params.mEQuantCoeff = EQuantCoeff; #endif params.mCenterCoeff = T->mCenterOrMinCoeff; params.mExtentsCoeff = T->mExtentsOrMaxCoeff; buildStatus = flattenQ(params, reinterpret_cast<BVDataPackedQ*>(nodes), 0, CurID, Root, MaxDepth, CurrentDepth); } else { buildStatus = flattenNQ(reinterpret_cast<BVDataPackedNQ*>(nodes), 0, CurID, Root, MaxDepth, CurrentDepth); } #ifdef GU_BV4_USE_NODE_POOLS Params.releaseNodes(); #endif if(!buildStatus) { T->mNodes = nodes; return false; } #ifdef GU_BV4_USE_SLABS // PT: TODO: revisit this, don't duplicate everything if(T->mQuantized) { BVDataPackedQ* _nodes = reinterpret_cast<BVDataPackedQ*>(nodes); PX_COMPILE_TIME_ASSERT(sizeof(BVDataSwizzledQ) == sizeof(BVDataPackedQ) * 4); BVDataPackedQ* Copy = PX_ALLOCATE(BVDataPackedQ, NbNeeded, "BVDataPackedQ"); PxMemCopy(Copy, nodes, sizeof(BVDataPackedQ)*NbNeeded); for (PxU32 i = 0; i<NbNeeded / 4; i++) { const BVDataPackedQ* Src = Copy + i * 4; BVDataSwizzledQ* Dst = reinterpret_cast<BVDataSwizzledQ*>(_nodes + i * 4); for (PxU32 j = 0; j<4; j++) { // We previously stored m/M within c/e so we just need to swizzle now const QuantizedAABB& Box = Src[j].mAABB; Dst->mX[j].mMin = Box.mData[0].mCenter; Dst->mY[j].mMin = Box.mData[1].mCenter; Dst->mZ[j].mMin = Box.mData[2].mCenter; Dst->mX[j].mMax = PxI16(Box.mData[0].mExtents); Dst->mY[j].mMax = PxI16(Box.mData[1].mExtents); Dst->mZ[j].mMax = PxI16(Box.mData[2].mExtents); Dst->mData[j] = Src[j].mData; } } PX_FREE(Copy); } else { BVDataPackedNQ* _nodes = reinterpret_cast<BVDataPackedNQ*>(nodes); PX_COMPILE_TIME_ASSERT(sizeof(BVDataSwizzledNQ) == sizeof(BVDataPackedNQ) * 4); BVDataPackedNQ* Copy = PX_ALLOCATE(BVDataPackedNQ, NbNeeded, "BVDataPackedNQ"); PxMemCopy(Copy, nodes, sizeof(BVDataPackedNQ)*NbNeeded); for (PxU32 i = 0; i<NbNeeded / 4; i++) { const BVDataPackedNQ* Src = Copy + i * 4; BVDataSwizzledNQ* Dst = reinterpret_cast<BVDataSwizzledNQ*>(_nodes + i * 4); for (PxU32 j = 0; j<4; j++) { // We previously stored m/M within c/e so we just need to swizzle now const CenterExtents& Box = Src[j].mAABB; Dst->mMinX[j] = Box.mCenter.x; Dst->mMinY[j] = Box.mCenter.y; Dst->mMinZ[j] = Box.mCenter.z; Dst->mMaxX[j] = Box.mExtents.x; Dst->mMaxY[j] = Box.mExtents.y; Dst->mMaxZ[j] = Box.mExtents.z; Dst->mData[j] = Src[j].mData; } } PX_FREE(Copy); if(0) { const PxVec3 eps(epsilon); float maxError = 0.0f; PxU32 nb = NbNeeded/4; BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(nodes); while(nb--) { BVDataSwizzledNQ* current = data + nb; for(PxU32 j=0;j<4;j++) { if(current->getChildData(j)==PX_INVALID_U32) continue; const PxBounds3 localBox( PxVec3(current->mMinX[j], current->mMinY[j], current->mMinZ[j]), PxVec3(current->mMaxX[j], current->mMaxY[j], current->mMaxZ[j])); PxBounds3 refitBox; refitBox.setEmpty(); if(current->isLeaf(j)) { PxU32 primIndex = current->getPrimitive(j); PxU32 nbToGo = getNbPrimitives(primIndex); do { PX_ASSERT(primIndex<T->mMeshInterface->getNbPrimitives()); T->mMeshInterface->refit(primIndex, refitBox); primIndex++; }while(nbToGo--); } else { PxU32 childOffset = current->getChildOffset(j); PX_ASSERT(!(childOffset&3)); childOffset>>=2; PX_ASSERT(childOffset>nb); const PxU32 childType = current->getChildType(j); const BVDataSwizzledNQ* next = data + childOffset; { if(childType>1) { const PxBounds3 childBox( PxVec3(next->mMinX[3], next->mMinY[3], next->mMinZ[3]), PxVec3(next->mMaxX[3], next->mMaxY[3], next->mMaxZ[3])); refitBox.include(childBox); } if(childType>0) { const PxBounds3 childBox( PxVec3(next->mMinX[2], next->mMinY[2], next->mMinZ[2]), PxVec3(next->mMaxX[2], next->mMaxY[2], next->mMaxZ[2])); refitBox.include(childBox); } { const PxBounds3 childBox( PxVec3(next->mMinX[1], next->mMinY[1], next->mMinZ[1]), PxVec3(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1])); refitBox.include(childBox); } { const PxBounds3 childBox( PxVec3(next->mMinX[0], next->mMinY[0], next->mMinZ[0]), PxVec3(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0])); refitBox.include(childBox); } } } refitBox.minimum -= eps; refitBox.maximum += eps; { float error = (refitBox.minimum - localBox.minimum).magnitude(); if(error>maxError) maxError = error; } { float error = (refitBox.maximum - localBox.maximum).magnitude(); if(error>maxError) maxError = error; } } } printf("maxError: %f\n", double(maxError)); } } PX_ASSERT(CurID == NbNeeded); T->mNbNodes = NbNeeded; #else PX_ASSERT(CurID == NbSingleNodes); T->mNbNodes = NbSingleNodes; #endif T->mNodes = nodes; } return true; } static bool BuildBV4Internal(BV4Tree& tree, const BV4_AABBTree& source, SourceMeshBase* mesh, float epsilon, bool quantized) { GU_PROFILE_ZONE("..BuildBV4Internal") if(mesh->getNbPrimitives()<=4) return tree.init(mesh, source.getBV()); { GU_PROFILE_ZONE("....CheckMD") struct Local { static void _checkMD(const AABBTreeNode* current_node, PxU32& md, PxU32& cd) { cd++; md = PxMax(md, cd); if(current_node->getPos()) { _checkMD(current_node->getPos(), md, cd); cd--; } if(current_node->getNeg()) { _checkMD(current_node->getNeg(), md, cd); cd--; } } static void _check(AABBTreeNode* current_node) { if(current_node->isLeaf()) return; AABBTreeNode* P = const_cast<AABBTreeNode*>(current_node->getPos()); AABBTreeNode* N = const_cast<AABBTreeNode*>(current_node->getNeg()); { PxU32 MDP = 0; PxU32 CDP = 0; _checkMD(P, MDP, CDP); PxU32 MDN = 0; PxU32 CDN = 0; _checkMD(N, MDN, CDN); if(MDP>MDN) // if(MDP<MDN) { PxSwap(*P, *N); PxSwap(P, N); } } _check(P); _check(N); } }; Local::_check(const_cast<AABBTreeNode*>(source.getNodes())); } // PT: not sure what the equivalent would be for tet-meshes here SourceMesh* triMesh = NULL; if(mesh->getMeshType()==SourceMeshBase::TRI_MESH) triMesh = static_cast<SourceMesh*>(mesh); BV4BuildParams Params(source, triMesh, epsilon); Params.mNbNodes=1; // Root node Params.mStats[0]=0; Params.mStats[1]=0; Params.mStats[2]=0; Params.mStats[3]=0; #ifdef GU_BV4_USE_NODE_POOLS BV4Node* Root = Params.allocateNode(); #else BV4Node* Root = PX_NEW(BV4Node); #endif { GU_PROFILE_ZONE("....buildBV4") buildBV4(source, Root, source.getNodes(), Params); } if(!tree.init(mesh, source.getBV())) return false; return BuildBV4FromRoot(tree, Root, Params, quantized, epsilon); } ///// #define REORDER_STATS_SIZE 16 struct ReorderData { public: PxU32* mOrder; PxU32 mNbPrimsPerLeaf; PxU32 mIndex; PxU32 mNbPrims; PxU32 mStats[REORDER_STATS_SIZE]; const SourceMeshBase* mMesh; }; static bool gReorderCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData) { ReorderData* Data = reinterpret_cast<ReorderData*>(userData); if(current->isLeaf()) { const PxU32 n = current->getNbPrimitives(); PX_ASSERT(n<=Data->mNbPrimsPerLeaf); Data->mStats[n]++; PxU32* Prims = const_cast<PxU32*>(current->getPrimitives()); for(PxU32 i=0;i<n;i++) { PX_ASSERT(Prims[i]<Data->mNbPrims); Data->mOrder[Data->mIndex] = Prims[i]; PX_ASSERT(Data->mIndex<Data->mNbPrims); Prims[i] = Data->mIndex; Data->mIndex++; } } return true; } bool physx::Gu::BuildBV4Ex(BV4Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivePerLeaf, bool quantized, BV4_BuildStrategy strategy) { //either number of triangle or number of tetrahedron const PxU32 nbPrimitives = mesh.getNbPrimitives(); BV4_AABBTree Source; { GU_PROFILE_ZONE("..BuildBV4Ex_buildFromMesh") if(!Source.buildFromMesh(mesh, nbPrimitivePerLeaf, strategy)) return false; } { GU_PROFILE_ZONE("..BuildBV4Ex_remap") PxU32* orderArray = PX_ALLOCATE(PxU32, nbPrimitives, "BV4"); ReorderData RD; RD.mMesh = &mesh; RD.mOrder = orderArray; RD.mNbPrimsPerLeaf = nbPrimitivePerLeaf; RD.mIndex = 0; RD.mNbPrims = nbPrimitives; for(PxU32 i=0;i<REORDER_STATS_SIZE;i++) RD.mStats[i] = 0; Source.walk(gReorderCallback, &RD); PX_ASSERT(RD.mIndex== nbPrimitives); mesh.remapTopology(orderArray); PX_FREE(orderArray); // for(PxU32 i=0;i<16;i++) // printf("%d: %d\n", i, RD.mStats[i]); } if(mesh.getNbPrimitives() <= nbPrimitivePerLeaf) return tree.init(&mesh, Source.getBV()); return BuildBV4Internal(tree, Source, &mesh, epsilon, quantized); }
54,942
C++
28.539247
207
0.662753
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxMemory.h" #include "GuBV4.h" #include "GuBV4_Common.h" #include "CmSerialize.h" #include "foundation/PxVecMath.h" #include "common/PxSerialFramework.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace physx::aos; SourceMeshBase::SourceMeshBase(MeshType meshType) : mNbVerts(0), mVerts(NULL), mType(meshType), mRemap(NULL) { } SourceMeshBase::~SourceMeshBase() { PX_FREE(mRemap); } /////////////////////////////////////////////////////////////////////////////// TetrahedronSourceMesh::TetrahedronSourceMesh() : SourceMeshBase(MeshType::TET_MESH) { reset(); } TetrahedronSourceMesh::~TetrahedronSourceMesh() { } void TetrahedronSourceMesh::reset() { mNbVerts = 0; mVerts = NULL; mNbTetrahedrons = 0; mTetrahedrons32 = NULL; mTetrahedrons16 = NULL; mRemap = NULL; } void TetrahedronSourceMesh::operator=(TetrahedronSourceMesh& v) { mNbVerts = v.mNbVerts; mVerts = v.mVerts; mNbTetrahedrons = v.mNbTetrahedrons; mTetrahedrons32 = v.mTetrahedrons32; mTetrahedrons16 = v.mTetrahedrons16; v.reset(); } void TetrahedronSourceMesh::remapTopology(const PxU32* order) { if(!mNbTetrahedrons) return; if(mTetrahedrons32) { IndTetrahedron32* newTopo = PX_NEW(IndTetrahedron32)[mNbTetrahedrons]; for(PxU32 i = 0; i<mNbTetrahedrons; i++) newTopo[i] = mTetrahedrons32[order[i]]; PxMemCopy(mTetrahedrons32, newTopo, sizeof(IndTetrahedron32)*mNbTetrahedrons); PX_DELETE_ARRAY(newTopo); } else { PX_ASSERT(mTetrahedrons16); IndTetrahedron16* newTopo = PX_NEW(IndTetrahedron16)[mNbTetrahedrons]; for(PxU32 i = 0; i<mNbTetrahedrons; i++) newTopo[i] = mTetrahedrons16[order[i]]; PxMemCopy(mTetrahedrons16, newTopo, sizeof(IndTetrahedron16)*mNbTetrahedrons); PX_DELETE_ARRAY(newTopo); } { PxU32* newMap = PX_ALLOCATE(PxU32, mNbTetrahedrons, "newMap"); for(PxU32 i = 0; i<mNbTetrahedrons; i++) newMap[i] = mRemap ? mRemap[order[i]] : order[i]; PX_FREE(mRemap); mRemap = newMap; } } void TetrahedronSourceMesh::getPrimitiveBox(const PxU32 primitiveInd, Vec4V& minV, Vec4V& maxV) { TetrahedronPointers VP; getTetrahedron(VP, primitiveInd); const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x); const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x); const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x); const Vec4V v3V = V4LoadU(&VP.Vertex[3]->x); minV = V4Min(v0V, v1V); minV = V4Min(minV, v2V); minV = V4Min(minV, v3V); maxV = V4Max(v0V, v1V); maxV = V4Max(maxV, v2V); maxV = V4Max(maxV, v3V); } void TetrahedronSourceMesh::refit(const PxU32 primitiveInd, PxBounds3& refitBox) { TetrahedronPointers VP; getTetrahedron(VP, primitiveInd); refitBox.include(*VP.Vertex[0]); refitBox.include(*VP.Vertex[1]); refitBox.include(*VP.Vertex[2]); refitBox.include(*VP.Vertex[3]); } /////////////////////////////////////////////////////////////////////////////// SourceMesh::SourceMesh() : SourceMeshBase(MeshType::TRI_MESH) { reset(); } SourceMesh::~SourceMesh() { } void SourceMesh::reset() { mNbVerts = 0; mVerts = NULL; mNbTris = 0; mTriangles32 = NULL; mTriangles16 = NULL; mRemap = NULL; } void SourceMesh::operator=(SourceMesh& v) { mNbVerts = v.mNbVerts; mVerts = v.mVerts; mNbTris = v.mNbTris; mTriangles32 = v.mTriangles32; mTriangles16 = v.mTriangles16; mRemap = v.mRemap; v.reset(); } void SourceMesh::remapTopology(const PxU32* order) { if(!mNbTris) return; if(mTriangles32) { IndTri32* newTopo = PX_NEW(IndTri32)[mNbTris]; for(PxU32 i=0;i<mNbTris;i++) newTopo[i] = mTriangles32[order[i]]; PxMemCopy(mTriangles32, newTopo, sizeof(IndTri32)*mNbTris); PX_DELETE_ARRAY(newTopo); } else { PX_ASSERT(mTriangles16); IndTri16* newTopo = PX_NEW(IndTri16)[mNbTris]; for(PxU32 i=0;i<mNbTris;i++) newTopo[i] = mTriangles16[order[i]]; PxMemCopy(mTriangles16, newTopo, sizeof(IndTri16)*mNbTris); PX_DELETE_ARRAY(newTopo); } { PxU32* newMap = PX_ALLOCATE(PxU32, mNbTris, "newMap"); for(PxU32 i=0;i<mNbTris;i++) newMap[i] = mRemap ? mRemap[order[i]] : order[i]; PX_FREE(mRemap); mRemap = newMap; } } void SourceMesh::getPrimitiveBox(const PxU32 primitiveInd, Vec4V& minV, Vec4V& maxV) { VertexPointers VP; getTriangle(VP, primitiveInd); const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x); const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x); const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x); minV = V4Min(v0V, v1V); minV = V4Min(minV, v2V); maxV = V4Max(v0V, v1V); maxV = V4Max(maxV, v2V); } void SourceMesh::refit(const PxU32 primitiveInd, PxBounds3& refitBox) { VertexPointers VP; getTriangle(VP, primitiveInd); refitBox.include(*VP.Vertex[0]); refitBox.include(*VP.Vertex[1]); refitBox.include(*VP.Vertex[2]); } bool SourceMesh::isValid() const { if(!mNbTris || !mNbVerts) return false; if(!mVerts) return false; if(!mTriangles32 && !mTriangles16) return false; return true; } ///// BV4Tree::BV4Tree(SourceMesh* meshInterface, const PxBounds3& localBounds) { reset(); init(meshInterface, localBounds); } BV4Tree::BV4Tree() { reset(); } void BV4Tree::release() { if(!mUserAllocated) { #ifdef GU_BV4_USE_SLABS PX_FREE(mNodes); // PX_DELETE(mNodes); #else PX_DELETE_ARRAY(mNodes); #endif } mNodes = NULL; mNbNodes = 0; reset(); } BV4Tree::~BV4Tree() { release(); } void BV4Tree::reset() { mMeshInterface = NULL; //mTetrahedronMeshInterface = NULL; mNbNodes = 0; mNodes = NULL; mInitData = 0; mCenterOrMinCoeff = PxVec3(0.0f); mExtentsOrMaxCoeff = PxVec3(0.0f); mUserAllocated = false; mQuantized = false; mIsEdgeSet = false; } void BV4Tree::operator=(BV4Tree& v) { mMeshInterface = v.mMeshInterface; //mTetrahedronMeshInterface = v.mTetrahedronMeshInterface; mLocalBounds = v.mLocalBounds; mNbNodes = v.mNbNodes; mNodes = v.mNodes; mInitData = v.mInitData; mCenterOrMinCoeff = v.mCenterOrMinCoeff; mExtentsOrMaxCoeff = v.mExtentsOrMaxCoeff; mUserAllocated = v.mUserAllocated; mQuantized = v.mQuantized; mIsEdgeSet = false; v.reset(); } bool BV4Tree::init(SourceMeshBase* meshInterface, const PxBounds3& localBounds) { mMeshInterface = meshInterface; mLocalBounds.init(localBounds); return true; } //bool BV4Tree::init(TetrahedronSourceMesh* meshInterface, const PxBounds3& localBounds) //{ // mTetrahedronMeshInterface = meshInterface; // mLocalBounds.init(localBounds); // return true; //} // PX_SERIALIZATION BV4Tree::BV4Tree(const PxEMPTY) : mLocalBounds(PxEmpty) { mUserAllocated = true; mIsEdgeSet = false; } void BV4Tree::exportExtraData(PxSerializationContext& stream) { if(mNbNodes) { stream.alignData(16); const PxU32 nodeSize = mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ); stream.writeData(mNodes, mNbNodes*nodeSize); } } void BV4Tree::importExtraData(PxDeserializationContext& context) { if(mNbNodes) { context.alignExtraData(16); if(mQuantized) mNodes = context.readExtraData<BVDataPackedQ>(mNbNodes); else mNodes = context.readExtraData<BVDataPackedNQ>(mNbNodes); } } //~PX_SERIALIZATION bool BV4Tree::load(PxInputStream& stream, bool mismatch_) { PX_ASSERT(!mUserAllocated); release(); PxI8 a, b, c, d; readChunk(a, b, c, d, stream); if(a!='B' || b!='V' || c!='4' || d!=' ') return false; bool mismatch; PxU32 fileVersion; if(!readBigEndianVersionNumber(stream, mismatch_, fileVersion, mismatch)) return false; readFloatBuffer(&mLocalBounds.mCenter.x, 3, mismatch, stream); mLocalBounds.mExtentsMagnitude = readFloat(mismatch, stream); mInitData = readDword(mismatch, stream); readFloatBuffer(&mCenterOrMinCoeff.x, 3, mismatch, stream); readFloatBuffer(&mExtentsOrMaxCoeff.x, 3, mismatch, stream); // PT: version 3 if(fileVersion>=3) { const PxU32 Quantized = readDword(mismatch, stream); mQuantized = Quantized!=0; } else mQuantized = true; const PxU32 nbNodes = readDword(mismatch, stream); mNbNodes = nbNodes; if(nbNodes) { PxU32 dataSize = 0; #ifdef GU_BV4_USE_SLABS const PxU32 nodeSize = mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ); dataSize = nodeSize*nbNodes; void* nodes = PX_ALLOC(dataSize, "BV4 nodes"); // PT: PX_NEW breaks alignment here // BVDataPacked* nodes = reinterpret_cast<BVDataPacked*>(PX_ALLOC(sizeof(BVDataPacked)*nbNodes, "BV4 nodes")); // PT: PX_NEW breaks alignment here mNodes = nodes; #else BVDataPacked* nodes = PX_NEW(BVDataPacked)[nbNodes]; mNodes = nodes; #endif // PxMarkSerializedMemory(nodes, dataSize); stream.read(nodes, dataSize); PX_ASSERT(!mismatch); } else mNodes = NULL; mIsEdgeSet = false; return true; } #define VERSION2 #ifdef VERSION1 bool BV4Tree::refit(PxBounds3& globalBounds, float epsilon) { if(mQuantized) if(!mNodes) { PxBounds3 bounds; bounds.setEmpty(); if(mMeshInterface) { PxU32 nbVerts = mMeshInterface->getNbVertices(); const PxVec3* verts = mMeshInterface->getVerts(); while(nbVerts--) bounds.include(*verts++); mLocalBounds.init(bounds); } if(mTetrahedronMeshInterface) { PX_ASSERT(0); } return true; } class PxBounds3Padded : public PxBounds3 { public: PX_FORCE_INLINE PxBounds3Padded() {} PX_FORCE_INLINE ~PxBounds3Padded() {} PxU32 padding; }; PX_ASSERT(!(mNbNodes&3)); PxU32 nb = mNbNodes/4; BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(mNodes); while(nb--) { BVDataSwizzledNQ* PX_RESTRICT current = data + nb; for(PxU32 j=0;j<4;j++) { if(current->getChildData(j)==PX_INVALID_U32) continue; Vec4V minV = V4Load(FLT_MAX); Vec4V maxV = V4Load(-FLT_MAX); if(current->isLeaf(j)) { PxU32 primIndex = current->getPrimitive(j); PxU32 nbToGo = getNbPrimitives(primIndex); VertexPointers VP; do { PX_ASSERT(primIndex<mMeshInterface->getNbTriangles()); mMeshInterface->getTriangle(VP, primIndex); const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x); const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x); const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x); minV = V4Min(minV, v0V); minV = V4Min(minV, v1V); minV = V4Min(minV, v2V); maxV = V4Max(maxV, v0V); maxV = V4Max(maxV, v1V); maxV = V4Max(maxV, v2V); primIndex++; }while(nbToGo--); const Vec4V epsilonV = V4Load(epsilon); minV = V4Sub(minV, epsilonV); maxV = V4Add(maxV, epsilonV); } else { PxU32 childOffset = current->getChildOffset(j); PX_ASSERT(!(childOffset&3)); childOffset>>=2; PX_ASSERT(childOffset>nb); const PxU32 childType = current->getChildType(j); // PT: TODO: revisit SIMD here, not great const BVDataSwizzledNQ* PX_RESTRICT next = data + childOffset; { { const Vec4V childMinV = V4LoadXYZW(next->mMinX[0], next->mMinY[0], next->mMinZ[0], 0.0f); const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0], 0.0f); // minV = V4Min(minV, childMinV); // maxV = V4Max(maxV, childMaxV); minV = childMinV; maxV = childMaxV; } { const Vec4V childMinV = V4LoadXYZW(next->mMinX[1], next->mMinY[1], next->mMinZ[1], 0.0f); const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1], 0.0f); minV = V4Min(minV, childMinV); maxV = V4Max(maxV, childMaxV); } /* { const Vec4V childMinV0 = V4LoadXYZW(next->mMinX[0], next->mMinY[0], next->mMinZ[0], 0.0f); const Vec4V childMaxV0 = V4LoadXYZW(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0], 0.0f); const Vec4V childMinV1 = V4LoadXYZW(next->mMinX[1], next->mMinY[1], next->mMinZ[1], 0.0f); const Vec4V childMaxV1 = V4LoadXYZW(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1], 0.0f); minV = V4Min(childMinV0, childMinV1); maxV = V4Max(childMaxV0, childMaxV1); }*/ if(childType>0) { const Vec4V childMinV = V4LoadXYZW(next->mMinX[2], next->mMinY[2], next->mMinZ[2], 0.0f); const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[2], next->mMaxY[2], next->mMaxZ[2], 0.0f); minV = V4Min(minV, childMinV); maxV = V4Max(maxV, childMaxV); } if(childType>1) { const Vec4V childMinV = V4LoadXYZW(next->mMinX[3], next->mMinY[3], next->mMinZ[3], 0.0f); const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[3], next->mMaxY[3], next->mMaxZ[3], 0.0f); minV = V4Min(minV, childMinV); maxV = V4Max(maxV, childMaxV); } } } PxBounds3Padded refitBox; V4StoreU_Safe(minV, &refitBox.minimum.x); V4StoreU_Safe(maxV, &refitBox.maximum.x); current->mMinX[j] = refitBox.minimum.x; current->mMinY[j] = refitBox.minimum.y; current->mMinZ[j] = refitBox.minimum.z; current->mMaxX[j] = refitBox.maximum.x; current->mMaxY[j] = refitBox.maximum.y; current->mMaxZ[j] = refitBox.maximum.z; } } BVDataSwizzledNQ* root = reinterpret_cast<BVDataSwizzledNQ*>(mNodes); { globalBounds.setEmpty(); for(PxU32 j=0;j<4;j++) { if(root->getChildData(j)==PX_INVALID_U32) continue; PxBounds3 refitBox; refitBox.minimum.x = root->mMinX[j]; refitBox.minimum.y = root->mMinY[j]; refitBox.minimum.z = root->mMinZ[j]; refitBox.maximum.x = root->mMaxX[j]; refitBox.maximum.y = root->mMaxY[j]; refitBox.maximum.z = root->mMaxZ[j]; globalBounds.include(refitBox); } mLocalBounds.init(globalBounds); } return true; } #endif #ifdef VERSION2 bool BV4Tree::refit(PxBounds3& globalBounds, float epsilon) { if(mQuantized) return false; if(!mNodes) { globalBounds.setEmpty(); if(mMeshInterface) { PxU32 nbVerts = mMeshInterface->getNbVertices(); const PxVec3* verts = mMeshInterface->getVerts(); while(nbVerts--) globalBounds.include(*verts++); mLocalBounds.init(globalBounds); } return true; } class PxBounds3Padded : public PxBounds3 { public: PX_FORCE_INLINE PxBounds3Padded() {} PX_FORCE_INLINE ~PxBounds3Padded() {} PxU32 padding; }; PX_ASSERT(!(mNbNodes&3)); PxU32 nb = mNbNodes/4; BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(mNodes); while(nb--) { BVDataSwizzledNQ* PX_RESTRICT current = data + nb; for(PxU32 j=0;j<4;j++) { if(current->getChildData(j)==PX_INVALID_U32) continue; if(current->isLeaf(j)) { PxU32 primIndex = current->getPrimitive(j); Vec4V minV = V4Load(FLT_MAX); Vec4V maxV = V4Load(-FLT_MAX); PxU32 nbToGo = getNbPrimitives(primIndex); //VertexPointers VP; do { PX_ASSERT(primIndex< mMeshInterface->getNbPrimitives()); //meshInterface->getTriangle(VP, primIndex); Vec4V tMin, tMax; mMeshInterface->getPrimitiveBox(primIndex, tMin, tMax); minV = V4Min(minV, tMin); maxV = V4Max(maxV, tMax); /* const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x); const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x); const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x); minV = V4Min(minV, v0V); minV = V4Min(minV, v1V); minV = V4Min(minV, v2V); maxV = V4Max(maxV, v0V); maxV = V4Max(maxV, v1V); maxV = V4Max(maxV, v2V);*/ primIndex++; }while(nbToGo--); const Vec4V epsilonV = V4Load(epsilon); minV = V4Sub(minV, epsilonV); maxV = V4Add(maxV, epsilonV); PxBounds3Padded refitBox; V4StoreU_Safe(minV, &refitBox.minimum.x); V4StoreU_Safe(maxV, &refitBox.maximum.x); current->mMinX[j] = refitBox.minimum.x; current->mMinY[j] = refitBox.minimum.y; current->mMinZ[j] = refitBox.minimum.z; current->mMaxX[j] = refitBox.maximum.x; current->mMaxY[j] = refitBox.maximum.y; current->mMaxZ[j] = refitBox.maximum.z; } else { PxU32 childOffset = current->getChildOffset(j); PX_ASSERT(!(childOffset&3)); childOffset>>=2; PX_ASSERT(childOffset>nb); const PxU32 childType = current->getChildType(j); const BVDataSwizzledNQ* PX_RESTRICT next = data + childOffset; { current->mMinX[j] = PxMin(next->mMinX[0], next->mMinX[1]); current->mMinY[j] = PxMin(next->mMinY[0], next->mMinY[1]); current->mMinZ[j] = PxMin(next->mMinZ[0], next->mMinZ[1]); current->mMaxX[j] = PxMax(next->mMaxX[0], next->mMaxX[1]); current->mMaxY[j] = PxMax(next->mMaxY[0], next->mMaxY[1]); current->mMaxZ[j] = PxMax(next->mMaxZ[0], next->mMaxZ[1]); if(childType>0) { current->mMinX[j] = PxMin(current->mMinX[j], next->mMinX[2]); current->mMinY[j] = PxMin(current->mMinY[j], next->mMinY[2]); current->mMinZ[j] = PxMin(current->mMinZ[j], next->mMinZ[2]); current->mMaxX[j] = PxMax(current->mMaxX[j], next->mMaxX[2]); current->mMaxY[j] = PxMax(current->mMaxY[j], next->mMaxY[2]); current->mMaxZ[j] = PxMax(current->mMaxZ[j], next->mMaxZ[2]); } if(childType>1) { current->mMinX[j] = PxMin(current->mMinX[j], next->mMinX[3]); current->mMinY[j] = PxMin(current->mMinY[j], next->mMinY[3]); current->mMinZ[j] = PxMin(current->mMinZ[j], next->mMinZ[3]); current->mMaxX[j] = PxMax(current->mMaxX[j], next->mMaxX[3]); current->mMaxY[j] = PxMax(current->mMaxY[j], next->mMaxY[3]); current->mMaxZ[j] = PxMax(current->mMaxZ[j], next->mMaxZ[3]); } } } } } BVDataSwizzledNQ* root = reinterpret_cast<BVDataSwizzledNQ*>(mNodes); { globalBounds.setEmpty(); for(PxU32 j=0;j<4;j++) { if(root->getChildData(j)==PX_INVALID_U32) continue; PxBounds3 refitBox; refitBox.minimum.x = root->mMinX[j]; refitBox.minimum.y = root->mMinY[j]; refitBox.minimum.z = root->mMinZ[j]; refitBox.maximum.x = root->mMaxX[j]; refitBox.maximum.y = root->mMaxY[j]; refitBox.maximum.z = root->mMaxZ[j]; globalBounds.include(refitBox); } mLocalBounds.init(globalBounds); } return true; } #endif
19,356
C++
25.228997
147
0.672711
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TRIANGLE_H #define GU_TRIANGLE_H #include "foundation/PxVec3.h" #include "foundation/PxUtilities.h" #include "foundation/PxUserAllocated.h" namespace physx { namespace Gu { // PT: I'm taking back control of these files and re-introducing the "ICE" naming conventions: // - "Triangle" is for actual triangles (like the PxTriangle class) // - If it contains vertex indices, it's "IndexedTriangle". // - "v" is too ambiguous (it could be either an actual vertex or a vertex reference) so use "ref" instead. // Plus we sometimes reference edges, not vertices, so "v" is too restrictive. template <class T> struct IndexedTriangleT : public PxUserAllocated { PX_INLINE IndexedTriangleT () {} PX_INLINE IndexedTriangleT (T a, T b, T c) { mRef[0] = a; mRef[1] = b; mRef[2] = c; } template <class TX> PX_INLINE IndexedTriangleT (const IndexedTriangleT <TX>& other) { mRef[0] = other[0]; mRef[1] = other[1]; mRef[2] = other[2]; } PX_INLINE T& operator[](T i) { return mRef[i]; } PX_INLINE const T& operator[](T i) const { return mRef[i]; } template<class TX>//any type of IndexedTriangleT <>, possibly with different T PX_INLINE IndexedTriangleT <T>& operator=(const IndexedTriangleT <TX>& i) { mRef[0]=i[0]; mRef[1]=i[1]; mRef[2]=i[2]; return *this; } void flip() { PxSwap(mRef[1], mRef[2]); } PX_INLINE bool contains(T id) const { return mRef[0] == id || mRef[1] == id || mRef[2] == id; } PX_INLINE void center(const PxVec3* verts, PxVec3& center) const { const PxVec3& p0 = verts[mRef[0]]; const PxVec3& p1 = verts[mRef[1]]; const PxVec3& p2 = verts[mRef[2]]; center = (p0+p1+p2)*0.33333333333333333333f; } float area(const PxVec3* verts) const { const PxVec3& p0 = verts[mRef[0]]; const PxVec3& p1 = verts[mRef[1]]; const PxVec3& p2 = verts[mRef[2]]; return ((p0-p1).cross(p0-p2)).magnitude() * 0.5f; } PxU8 findEdge(T vref0, T vref1) const { if(mRef[0]==vref0 && mRef[1]==vref1) return 0; else if(mRef[0]==vref1 && mRef[1]==vref0) return 0; else if(mRef[0]==vref0 && mRef[2]==vref1) return 1; else if(mRef[0]==vref1 && mRef[2]==vref0) return 1; else if(mRef[1]==vref0 && mRef[2]==vref1) return 2; else if(mRef[1]==vref1 && mRef[2]==vref0) return 2; return 0xff; } // counter clock wise order PxU8 findEdgeCCW(T vref0, T vref1) const { if(mRef[0]==vref0 && mRef[1]==vref1) return 0; else if(mRef[0]==vref1 && mRef[1]==vref0) return 0; else if(mRef[0]==vref0 && mRef[2]==vref1) return 2; else if(mRef[0]==vref1 && mRef[2]==vref0) return 2; else if(mRef[1]==vref0 && mRef[2]==vref1) return 1; else if(mRef[1]==vref1 && mRef[2]==vref0) return 1; return 0xff; } bool replaceVertex(T oldref, T newref) { if(mRef[0]==oldref) { mRef[0] = newref; return true; } else if(mRef[1]==oldref) { mRef[1] = newref; return true; } else if(mRef[2]==oldref) { mRef[2] = newref; return true; } return false; } bool isDegenerate() const { if(mRef[0]==mRef[1]) return true; if(mRef[1]==mRef[2]) return true; if(mRef[2]==mRef[0]) return true; return false; } PX_INLINE void denormalizedNormal(const PxVec3* verts, PxVec3& normal) const { const PxVec3& p0 = verts[mRef[0]]; const PxVec3& p1 = verts[mRef[1]]; const PxVec3& p2 = verts[mRef[2]]; normal = ((p2 - p1).cross(p0 - p1)); } T mRef[3]; //vertex indices }; typedef IndexedTriangleT<PxU32> IndexedTriangle32; typedef IndexedTriangleT<PxU16> IndexedTriangle16; PX_COMPILE_TIME_ASSERT(sizeof(IndexedTriangle32)==12); PX_COMPILE_TIME_ASSERT(sizeof(IndexedTriangle16)==6); } } #endif
5,358
C
35.95862
135
0.681411
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuSweepConvexTri.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_SWEEP_CONVEX_TRI #define GU_SWEEP_CONVEX_TRI #include "geometry/PxConvexMeshGeometry.h" #include "GuVecTriangle.h" #include "GuVecConvexHull.h" #include "GuConvexMesh.h" #include "GuGJKRaycast.h" // return true if hit, false if no hit static PX_FORCE_INLINE bool sweepConvexVsTriangle( const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, ConvexHullV& convexHull, const aos::PxMatTransformV& meshToConvex, const aos::PxTransformV& convexTransfV, const aos::Vec3VArg convexSpaceDir, const PxVec3& unitDir, const PxVec3& meshSpaceUnitDir, const aos::FloatVArg fullDistance, PxReal shrunkDistance, PxGeomSweepHit& hit, bool isDoubleSided, const PxReal inflation, bool& initialOverlap, PxU32 faceIndex) { using namespace aos; if(!isDoubleSided) { // Create triangle normal const PxVec3 denormalizedNormal = (v1 - v0).cross(v2 - v1); // Backface culling // PT: WARNING, the test is reversed compared to usual because we pass -unitDir to this function const bool culled = denormalizedNormal.dot(meshSpaceUnitDir) <= 0.0f; if(culled) return false; } const Vec3V zeroV = V3Zero(); const FloatV zero = FZero(); const Vec3V p0 = V3LoadU(v0); // in mesh local space const Vec3V p1 = V3LoadU(v1); const Vec3V p2 = V3LoadU(v2); // transform triangle verts from mesh local to convex local space TriangleV triangleV(meshToConvex.transform(p0), meshToConvex.transform(p1), meshToConvex.transform(p2)); FloatV toi; Vec3V closestA,normal; const LocalConvex<TriangleV> convexA(triangleV); const LocalConvex<ConvexHullV> convexB(convexHull); const Vec3V initialSearchDir = V3Sub(triangleV.getCenter(), convexHull.getCenter()); // run GJK raycast // sweep triangle in convex local space vs convex, closestA will be the impact point in convex local space const bool gjkHit = gjkRaycastPenetration<LocalConvex<TriangleV>, LocalConvex<ConvexHullV> >( convexA, convexB, initialSearchDir, zero, zeroV, convexSpaceDir, toi, normal, closestA, inflation, false); if(!gjkHit) return false; if(FAllGrtrOrEq(zero, toi)) { initialOverlap = true; // PT: TODO: redundant with hit distance, consider removing return setInitialOverlapResults(hit, unitDir, faceIndex); } const FloatV minDist = FLoad(shrunkDistance); const FloatV dist = FMul(toi, fullDistance); // scale the toi to original full sweep distance if(FAllGrtr(minDist, dist)) // is current dist < minDist? { hit.faceIndex = faceIndex; hit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; const Vec3V destWorldPointA = convexTransfV.transform(closestA); const Vec3V destNormal = V3Normalize(convexTransfV.rotate(normal)); V3StoreU(destWorldPointA, hit.position); V3StoreU(destNormal, hit.normal); FStore(dist, &hit.distance); return true; // report a hit } return false; // report no hit } #endif
4,543
C
42.27619
108
0.761171
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMidphaseRTree.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "GuSweepMesh.h" #include "GuIntersectionRayTriangle.h" #include "GuIntersectionCapsuleTriangle.h" #include "GuIntersectionRayBox.h" #include "GuSphere.h" #include "GuBoxConversion.h" #include "GuConvexUtilsInternal.h" #include "GuVecTriangle.h" #include "GuIntersectionTriangleBox.h" #include "GuRTree.h" #include "GuTriangleMeshRTree.h" #include "GuInternal.h" #include "CmMatrix34.h" // This file contains code specific to the RTree midphase. using namespace physx; using namespace Cm; using namespace Gu; using namespace physx::aos; struct MeshRayCollider { template <int tInflate, int tRayTest> PX_PHYSX_COMMON_API static void collide( const PxVec3& orig, const PxVec3& dir, // dir is not normalized (full length), both in mesh space (unless meshWorld is non-zero) PxReal maxT, // maxT is from [0,1], if maxT is 0.0f, AABB traversal will be used bool bothTriangleSidesCollide, const RTreeTriangleMesh* mesh, MeshHitCallback<PxGeomRaycastHit>& callback, const PxVec3* inflate = NULL); PX_PHYSX_COMMON_API static void collideOBB( const Box& obb, bool bothTriangleSidesCollide, const RTreeTriangleMesh* mesh, MeshHitCallback<PxGeomRaycastHit>& callback, bool checkObbIsAligned = true); // perf hint, pass false if obb is rarely axis aligned }; class SimpleRayTriOverlap { public: PX_FORCE_INLINE SimpleRayTriOverlap(const PxVec3& origin, const PxVec3& dir, bool bothSides, PxReal geomEpsilon) : mOrigin(origin), mDir(dir), mBothSides(bothSides), mGeomEpsilon(geomEpsilon) { } PX_FORCE_INLINE PxIntBool overlap(const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxGeomRaycastHit& hit) const { if(!intersectRayTriangle(mOrigin, mDir, vert0, vert1, vert2, hit.distance, hit.u, hit.v, !mBothSides, mGeomEpsilon)) return false; if(hit.distance< 0.0f) // test if the ray intersection t is negative return false; return true; } PxVec3 mOrigin; PxVec3 mDir; bool mBothSides; PxReal mGeomEpsilon; }; using Gu::RTree; // This callback comes from RTree and decodes LeafTriangle indices stored in rtree into actual triangles // This callback is needed because RTree doesn't know that it stores triangles since it's a general purpose spatial index #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif template <int tInflate, bool tRayTest> struct RayRTreeCallback : RTree::CallbackRaycast, RTree::Callback { MeshHitCallback<PxGeomRaycastHit>& outerCallback; PxI32 has16BitIndices; const void* mTris; const PxVec3* mVerts; const PxVec3* mInflate; const SimpleRayTriOverlap rayCollider; PxReal maxT; PxGeomRaycastHit closestHit; // recorded closest hit over the whole traversal (only for callback mode eCLOSEST) PxVec3 cv0, cv1, cv2; // PT: make sure these aren't last in the class, to safely V4Load them PxU32 cis[3]; bool hadClosestHit; const bool closestMode; Vec3V inflateV, rayOriginV, rayDirV; RayRTreeCallback( PxReal geomEpsilon, MeshHitCallback<PxGeomRaycastHit>& callback, PxI32 has16BitIndices_, const void* tris, const PxVec3* verts, const PxVec3& origin, const PxVec3& dir, PxReal maxT_, bool bothSides, const PxVec3* inflate) : outerCallback(callback), has16BitIndices(has16BitIndices_), mTris(tris), mVerts(verts), mInflate(inflate), rayCollider(origin, dir, bothSides, geomEpsilon), maxT(maxT_), closestMode(callback.inClosestMode()) { PX_ASSERT(closestHit.distance == PX_MAX_REAL); hadClosestHit = false; if (tInflate) inflateV = V3LoadU(*mInflate); rayOriginV = V3LoadU(rayCollider.mOrigin); rayDirV = V3LoadU(rayCollider.mDir); } PX_FORCE_INLINE void getVertIndices(PxU32 triIndex, PxU32& i0, PxU32 &i1, PxU32 &i2) { if(has16BitIndices) { const PxU16* p = reinterpret_cast<const PxU16*>(mTris) + triIndex*3; i0 = p[0]; i1 = p[1]; i2 = p[2]; } else { const PxU32* p = reinterpret_cast<const PxU32*>(mTris) + triIndex*3; i0 = p[0]; i1 = p[1]; i2 = p[2]; } } virtual PX_FORCE_INLINE bool processResults(PxU32 NumTouched, PxU32* Touched, PxF32& newMaxT) { PX_ASSERT(NumTouched > 0); // Loop through touched leaves PxGeomRaycastHit tempHit; for(PxU32 leaf = 0; leaf<NumTouched; leaf++) { // Each leaf box has a set of triangles LeafTriangles currentLeaf; currentLeaf.Data = Touched[leaf]; PxU32 nbLeafTris = currentLeaf.GetNbTriangles(); PxU32 baseLeafTriIndex = currentLeaf.GetTriangleIndex(); for(PxU32 i = 0; i < nbLeafTris; i++) { PxU32 i0, i1, i2; const PxU32 triangleIndex = baseLeafTriIndex+i; getVertIndices(triangleIndex, i0, i1, i2); const PxVec3& v0 = mVerts[i0], &v1 = mVerts[i1], &v2 = mVerts[i2]; const PxU32 vinds[3] = { i0, i1, i2 }; if (tRayTest) { PxIntBool overlap; if (tInflate) { // AP: mesh skew is already included here (ray is pre-transformed) Vec3V v0v = V3LoadU(v0), v1v = V3LoadU(v1), v2v = V3LoadU(v2); Vec3V minB = V3Min(V3Min(v0v, v1v), v2v), maxB = V3Max(V3Max(v0v, v1v), v2v); // PT: we add an epsilon to max distance, to make sure we don't reject triangles that are just at the same // distance as best triangle so far. We need to keep all of these to make sure we return the one with the // best normal. const float relativeEpsilon = GU_EPSILON_SAME_DISTANCE * PxMax(1.0f, maxT); FloatV tNear, tFar; overlap = intersectRayAABB2( V3Sub(minB, inflateV), V3Add(maxB, inflateV), rayOriginV, rayDirV, FLoad(maxT+relativeEpsilon), tNear, tFar); if (overlap) { // can't clip to tFar here because hitting the AABB doesn't guarantee that we can clip // (since we can still miss the actual tri) tempHit.distance = maxT; tempHit.faceIndex = triangleIndex; tempHit.u = tempHit.v = 0.0f; } } else overlap = rayCollider.overlap(v0, v1, v2, tempHit) && tempHit.distance <= maxT; if(!overlap) continue; } tempHit.faceIndex = triangleIndex; tempHit.flags = PxHitFlag::ePOSITION; // Intersection point is valid if dist < segment's length // We know dist>0 so we can use integers if (closestMode) { if(tempHit.distance < closestHit.distance) { closestHit = tempHit; newMaxT = PxMin(tempHit.distance, newMaxT); cv0 = v0; cv1 = v1; cv2 = v2; cis[0] = vinds[0]; cis[1] = vinds[1]; cis[2] = vinds[2]; hadClosestHit = true; } } else { PxReal shrunkMaxT = newMaxT; PxAgain again = outerCallback.processHit(tempHit, v0, v1, v2, shrunkMaxT, vinds); if (!again) return false; if (shrunkMaxT < newMaxT) { newMaxT = shrunkMaxT; maxT = shrunkMaxT; } } if (outerCallback.inAnyMode()) // early out if in ANY mode return false; } } // for(PxU32 leaf = 0; leaf<NumTouched; leaf++) return true; } virtual bool processResults(PxU32 numTouched, PxU32* touched) { PxF32 dummy; return RayRTreeCallback::processResults(numTouched, touched, dummy); } virtual ~RayRTreeCallback() { if (hadClosestHit) { PX_ASSERT(outerCallback.inClosestMode()); outerCallback.processHit(closestHit, cv0, cv1, cv2, maxT, cis); } } private: RayRTreeCallback& operator=(const RayRTreeCallback&); }; #if PX_VC #pragma warning(pop) #endif void MeshRayCollider::collideOBB( const Box& obb, bool bothTriangleSidesCollide, const RTreeTriangleMesh* mi, MeshHitCallback<PxGeomRaycastHit>& callback, bool checkObbIsAligned) { const PxU32 maxResults = RTREE_N; // maxResults=rtree page size for more efficient early out PxU32 buf[maxResults]; RayRTreeCallback<false, false> rTreeCallback( mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(), PxVec3(0), PxVec3(0), 0.0f, bothTriangleSidesCollide, NULL); if (checkObbIsAligned && PxAbs(PxQuat(obb.rot).w) > 0.9999f) { PxVec3 aabbExtents = obb.computeAABBExtent(); mi->getRTree().traverseAABB(obb.center - aabbExtents, obb.center + aabbExtents, maxResults, buf, &rTreeCallback); } else mi->getRTree().traverseOBB(obb, maxResults, buf, &rTreeCallback); } template <int tInflate, int tRayTest> void MeshRayCollider::collide( const PxVec3& orig, const PxVec3& dir, PxReal maxT, bool bothSides, const RTreeTriangleMesh* mi, MeshHitCallback<PxGeomRaycastHit>& callback, const PxVec3* inflate) { const PxU32 maxResults = RTREE_N; // maxResults=rtree page size for more efficient early out PxU32 buf[maxResults]; if (maxT == 0.0f) // AABB traversal path { RayRTreeCallback<tInflate, false> rTreeCallback( mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(), orig, dir, maxT, bothSides, inflate); PxVec3 inflate1 = tInflate ? *inflate : PxVec3(0); // both maxT and inflate can be zero, so need to check tInflate mi->getRTree().traverseAABB(orig-inflate1, orig+inflate1, maxResults, buf, &rTreeCallback); } else // ray traversal path { RayRTreeCallback<tInflate, tRayTest> rTreeCallback( mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(), orig, dir, maxT, bothSides, inflate); mi->getRTree().traverseRay<tInflate>(orig, dir, maxResults, buf, &rTreeCallback, inflate, maxT); } } #define TINST(a,b) \ template void MeshRayCollider::collide<a,b>( \ const PxVec3& orig, const PxVec3& dir, PxReal maxT, bool bothSides, const RTreeTriangleMesh* mesh, \ MeshHitCallback<PxGeomRaycastHit>& callback, const PxVec3* inflate); TINST(0,0) TINST(1,0) TINST(0,1) TINST(1,1) #undef TINST #include "GuRaycastTests.h" #include "geometry/PxTriangleMeshGeometry.h" #include "GuTriangleMesh.h" #include "CmScaling.h" struct RayMeshColliderCallback : public MeshHitCallback<PxGeomRaycastHit> { PxU8* mDstBase; PxU32 mHitNum; const PxU32 mMaxHits; const PxU32 mStride; const PxMeshScale* mScale; const PxTransform* mPose; const PxMat34* mWorld2vertexSkew; PxU32 mHitFlags; const PxVec3& mRayDir; bool mIsDoubleSided; float mDistCoeff; RayMeshColliderCallback( CallbackMode::Enum mode_, PxGeomRaycastHit* hits, PxU32 maxHits, PxU32 stride, const PxMeshScale* scale, const PxTransform* pose, const PxMat34* world2vertexSkew, PxU32 hitFlags, const PxVec3& rayDir, bool isDoubleSided, float distCoeff) : MeshHitCallback<PxGeomRaycastHit> (mode_), mDstBase (reinterpret_cast<PxU8*>(hits)), mHitNum (0), mMaxHits (maxHits), mStride (stride), mScale (scale), mPose (pose), mWorld2vertexSkew (world2vertexSkew), mHitFlags (hitFlags), mRayDir (rayDir), mIsDoubleSided (isDoubleSided), mDistCoeff (distCoeff) { } // return false for early out virtual bool processHit( const PxGeomRaycastHit& lHit, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxReal&, const PxU32*) { if(mHitNum == mMaxHits) return false; const PxReal u = lHit.u, v = lHit.v; const PxVec3 localImpact = (1.0f - u - v)*lp0 + u*lp1 + v*lp2; //not worth concatenating to do 1 transform: PxMat34Legacy vertex2worldSkew = scaling.getVertex2WorldSkew(absPose); // PT: TODO: revisit this for N hits PxGeomRaycastHit& hit = *reinterpret_cast<PxGeomRaycastHit*>(mDstBase); hit = lHit; hit.position = mPose->transform(mScale->transform(localImpact)); hit.flags = PxHitFlag::ePOSITION|PxHitFlag::eUV|PxHitFlag::eFACE_INDEX; hit.normal = PxVec3(0.0f); hit.distance *= mDistCoeff; // Compute additional information if needed if(mHitFlags & PxHitFlag::eNORMAL) { // User requested impact normal const PxVec3 localNormal = (lp1 - lp0).cross(lp2 - lp0); if(mWorld2vertexSkew) { hit.normal = mWorld2vertexSkew->rotateTranspose(localNormal); if (mScale->hasNegativeDeterminant()) PxSwap<PxReal>(hit.u, hit.v); // have to swap the UVs though since they were computed in mesh local space } else hit.normal = mPose->rotate(localNormal); hit.normal.normalize(); // PT: figure out correct normal orientation (DE7458) // - if the mesh is single-sided the normal should be the regular triangle normal N, regardless of eMESH_BOTH_SIDES. // - if the mesh is double-sided the correct normal can be either N or -N. We take the one opposed to ray direction. if(mIsDoubleSided && hit.normal.dot(mRayDir) > 0.0f) hit.normal = -hit.normal; hit.flags |= PxHitFlag::eNORMAL; } mHitNum++; mDstBase += mStride; return true; } private: RayMeshColliderCallback& operator=(const RayMeshColliderCallback&); }; PxU32 physx::Gu::raycast_triangleMesh_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33); const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh); //scaling: transform the ray to vertex space PxVec3 orig, dir; PxMat34 world2vertexSkew; PxMat34* world2vertexSkewP = NULL; PxReal distCoeff = 1.0f; if(meshGeom.scale.isIdentity()) { orig = pose.transformInv(rayOrigin); dir = pose.rotateInv(rayDir); } else { world2vertexSkew = meshGeom.scale.getInverse() * pose.getInverse(); world2vertexSkewP = &world2vertexSkew; orig = world2vertexSkew.transform(rayOrigin); dir = world2vertexSkew.rotate(rayDir); { distCoeff = dir.normalize(); maxDist *= distCoeff; maxDist += 1e-3f; distCoeff = 1.0f / distCoeff; } } const bool isDoubleSided = meshGeom.meshFlags.isSet(PxMeshGeometryFlag::eDOUBLE_SIDED); const bool bothSides = isDoubleSided || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES); const bool multipleHits = hitFlags & PxHitFlag::eMESH_MULTIPLE; RayMeshColliderCallback callback( multipleHits ? CallbackMode::eMULTIPLE : (hitFlags & PxHitFlag::eMESH_ANY ? CallbackMode::eANY : CallbackMode::eCLOSEST), hits, maxHits, stride, &meshGeom.scale, &pose, world2vertexSkewP, hitFlags, rayDir, isDoubleSided, distCoeff); MeshRayCollider::collide<0, 1>(orig, dir, maxDist, bothSides, static_cast<const RTreeTriangleMesh*>(meshData), callback, NULL); return callback.mHitNum; } /** \brief returns indices for the largest axis and 2 other axii */ PX_FORCE_INLINE PxU32 largestAxis(const PxVec3& v, PxU32& other1, PxU32& other2) { if (v.x >= PxMax(v.y, v.z)) { other1 = 1; other2 = 2; return 0; } else if (v.y >= v.z) { other1 = 0; other2 = 2; return 1; } else { other1 = 0; other2 = 1; return 2; } } static PX_INLINE void computeSweptAABBAroundOBB( const Box& obb, PxVec3& sweepOrigin, PxVec3& sweepExtents, PxVec3& sweepDir, PxReal& sweepLen) { PxU32 other1, other2; // largest axis of the OBB is the sweep direction, sum of abs of two other is the swept AABB extents PxU32 lai = largestAxis(obb.extents, other1, other2); PxVec3 longestAxis = obb.rot[lai]*obb.extents[lai]; PxVec3 absOther1 = obb.rot[other1].abs()*obb.extents[other1]; PxVec3 absOther2 = obb.rot[other2].abs()*obb.extents[other2]; sweepOrigin = obb.center - longestAxis; sweepExtents = absOther1 + absOther2 + PxVec3(GU_MIN_AABB_EXTENT); // see comments for GU_MIN_AABB_EXTENT sweepLen = 2.0f; // length is already included in longestAxis sweepDir = longestAxis; } enum { eSPHERE, eCAPSULE, eBOX }; // values for tSCB #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #pragma warning( disable : 4512 ) // assignment operator could not be generated #endif namespace { struct IntersectShapeVsMeshCallback : MeshHitCallback<PxGeomRaycastHit> { PX_NOCOPY(IntersectShapeVsMeshCallback) public: IntersectShapeVsMeshCallback(const PxMat33& vertexToShapeSkew, LimitedResults* results, bool flipNormal) : MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE), mVertexToShapeSkew (vertexToShapeSkew), mResults (results), mAnyHits (false), mFlipNormal (flipNormal) { } virtual ~IntersectShapeVsMeshCallback(){} const PxMat33& mVertexToShapeSkew; // vertex to box without translation for boxes LimitedResults* mResults; bool mAnyHits; bool mFlipNormal; PX_FORCE_INLINE bool recordHit(const PxGeomRaycastHit& aHit, PxIntBool hit) { if(hit) { mAnyHits = true; if(mResults) mResults->add(aHit.faceIndex); else return false; // abort traversal if we are only interested in firstContact (mResults is NULL) } return true; // if we are here, either no triangles were hit or multiple results are expected => continue traversal } }; template<bool tScaleIsIdentity> struct IntersectSphereVsMeshCallback : IntersectShapeVsMeshCallback { IntersectSphereVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {} virtual ~IntersectSphereVsMeshCallback(){} PxF32 mMinDist2; PxVec3 mLocalCenter; // PT: sphere center in local/mesh space virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*) { const Vec3V v0 = V3LoadU(tScaleIsIdentity ? av0 : mVertexToShapeSkew * av0); const Vec3V v1 = V3LoadU(tScaleIsIdentity ? av1 : mVertexToShapeSkew * (mFlipNormal ? av2 : av1)); const Vec3V v2 = V3LoadU(tScaleIsIdentity ? av2 : mVertexToShapeSkew * (mFlipNormal ? av1 : av2)); FloatV dummy1, dummy2; Vec3V closestP; PxReal dist2; FStore(distancePointTriangleSquared(V3LoadU(mLocalCenter), v0, v1, v2, dummy1, dummy2, closestP), &dist2); return recordHit(aHit, dist2 <= mMinDist2); } }; template<bool tScaleIsIdentity> struct IntersectCapsuleVsMeshCallback : IntersectShapeVsMeshCallback { IntersectCapsuleVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {} virtual ~IntersectCapsuleVsMeshCallback(){} Capsule mLocalCapsule; // PT: capsule in mesh/local space CapsuleTriangleOverlapData mParams; virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*) { bool hit; if(tScaleIsIdentity) { const PxVec3 normal = (av0 - av1).cross(av0 - av2); hit = intersectCapsuleTriangle(normal, av0, av1, av2, mLocalCapsule, mParams); } else { const PxVec3 v0 = mVertexToShapeSkew * av0; const PxVec3 v1 = mVertexToShapeSkew * (mFlipNormal ? av2 : av1); const PxVec3 v2 = mVertexToShapeSkew * (mFlipNormal ? av1 : av2); const PxVec3 normal = (v0 - v1).cross(v0 - v2); hit = intersectCapsuleTriangle(normal, v0, v1, v2, mLocalCapsule, mParams); } return recordHit(aHit, hit); } }; template<bool tScaleIsIdentity> struct IntersectBoxVsMeshCallback : IntersectShapeVsMeshCallback { IntersectBoxVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {} virtual ~IntersectBoxVsMeshCallback(){} PxMat34 mVertexToBox; PxVec3p mBoxExtents, mBoxCenter; virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*) { PxVec3p v0, v1, v2; if(tScaleIsIdentity) { v0 = mVertexToShapeSkew * av0; // transform from skewed mesh vertex to box space, v1 = mVertexToShapeSkew * av1; // this includes inverse skew, inverse mesh shape transform and inverse box basis v2 = mVertexToShapeSkew * av2; } else { v0 = mVertexToBox.transform(av0); v1 = mVertexToBox.transform(mFlipNormal ? av2 : av1); v2 = mVertexToBox.transform(mFlipNormal ? av1 : av2); } // PT: this one is safe because we're using PxVec3p for all parameters const PxIntBool hit = intersectTriangleBox_Unsafe(mBoxCenter, mBoxExtents, v0, v1, v2); return recordHit(aHit, hit); } }; } #if PX_VC #pragma warning(pop) #endif template<int tSCB, bool idtMeshScale> static bool intersectAnyVsMeshT( const Sphere* worldSphere, const Capsule* worldCapsule, const Box* worldOBB, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { const bool flipNormal = meshScale.hasNegativeDeterminant(); PxMat33 shapeToVertexSkew, vertexToShapeSkew; if (!idtMeshScale && tSCB != eBOX) { vertexToShapeSkew = toMat33(meshScale); shapeToVertexSkew = vertexToShapeSkew.getInverse(); } if (tSCB == eSPHERE) { IntersectSphereVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal); // transform sphere center from world to mesh shape space const PxVec3 center = meshTransform.transformInv(worldSphere->center); // callback will transform verts callback.mLocalCenter = center; callback.mMinDist2 = worldSphere->radius*worldSphere->radius; PxVec3 sweepOrigin, sweepDir, sweepExtents; PxReal sweepLen; if (!idtMeshScale) { // AP: compute a swept AABB around an OBB around a skewed sphere // TODO: we could do better than an AABB around OBB actually because we can slice off the corners.. const Box worldOBB_(worldSphere->center, PxVec3(worldSphere->radius), PxMat33(PxIdentity)); Box vertexOBB; computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale); computeSweptAABBAroundOBB(vertexOBB, sweepOrigin, sweepExtents, sweepDir, sweepLen); } else { sweepOrigin = center; sweepDir = PxVec3(1.0f,0,0); sweepLen = 0.0f; sweepExtents = PxVec3(PxMax(worldSphere->radius, GU_MIN_AABB_EXTENT)); } MeshRayCollider::collide<1, 1>(sweepOrigin, sweepDir, sweepLen, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback, &sweepExtents); return callback.mAnyHits; } else if (tSCB == eCAPSULE) { IntersectCapsuleVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal); const PxF32 radius = worldCapsule->radius; // transform world capsule to mesh shape space callback.mLocalCapsule.p0 = meshTransform.transformInv(worldCapsule->p0); callback.mLocalCapsule.p1 = meshTransform.transformInv(worldCapsule->p1); callback.mLocalCapsule.radius = radius; callback.mParams.init(callback.mLocalCapsule); if (idtMeshScale) { // traverse a sweptAABB around the capsule const PxVec3 radius3(radius); MeshRayCollider::collide<1, 0>(callback.mLocalCapsule.p0, callback.mLocalCapsule.p1-callback.mLocalCapsule.p0, 1.0f, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback, &radius3); } else { // make vertex space OBB Box vertexOBB; Box worldOBB_; worldOBB_.create(*worldCapsule); // AP: potential optimization (meshTransform.inverse is already in callback.mCapsule) computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale); MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback); } return callback.mAnyHits; } else if (tSCB == eBOX) { Box vertexOBB; // query box in vertex space if (idtMeshScale) { // mesh scale is identity - just inverse transform the box without optimization vertexOBB = transformBoxOrthonormal(*worldOBB, meshTransform.getInverse()); // mesh vertices will be transformed from skewed vertex space directly to box AABB space // box inverse rotation is baked into the vertexToShapeSkew transform // if meshScale is not identity, vertexOBB already effectively includes meshScale transform PxVec3 boxCenter; getInverse(vertexToShapeSkew, boxCenter, vertexOBB.rot, vertexOBB.center); IntersectBoxVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal); callback.mBoxCenter = -boxCenter; callback.mBoxExtents = worldOBB->extents; // extents do not change MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback); return callback.mAnyHits; } else { computeVertexSpaceOBB(vertexOBB, *worldOBB, meshTransform, meshScale); // mesh scale needs to be included - inverse transform and optimize the box const PxMat33 vertexToWorldSkew_Rot = PxMat33Padded(meshTransform.q) * toMat33(meshScale); const PxVec3& vertexToWorldSkew_Trans = meshTransform.p; PxMat34 tmp; buildMatrixFromBox(tmp, *worldOBB); const PxMat34 inv = tmp.getInverseRT(); const PxMat34 _vertexToWorldSkew(vertexToWorldSkew_Rot, vertexToWorldSkew_Trans); IntersectBoxVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal); callback.mVertexToBox = inv * _vertexToWorldSkew; callback.mBoxCenter = PxVec3(0.0f); callback.mBoxExtents = worldOBB->extents; // extents do not change MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback); return callback.mAnyHits; } } else { PX_ASSERT(0); return false; } } template<int tSCB> static bool intersectAnyVsMesh( const Sphere* worldSphere, const Capsule* worldCapsule, const Box* worldOBB, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { PX_ASSERT(triMesh.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33); if (meshScale.isIdentity()) return intersectAnyVsMeshT<tSCB, true>(worldSphere, worldCapsule, worldOBB, triMesh, meshTransform, meshScale, results); else return intersectAnyVsMeshT<tSCB, false>(worldSphere, worldCapsule, worldOBB, triMesh, meshTransform, meshScale, results); } bool physx::Gu::intersectSphereVsMesh_RTREE(const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { return intersectAnyVsMesh<eSPHERE>(&sphere, NULL, NULL, triMesh, meshTransform, meshScale, results); } bool physx::Gu::intersectBoxVsMesh_RTREE(const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { return intersectAnyVsMesh<eBOX>(NULL, NULL, &box, triMesh, meshTransform, meshScale, results); } bool physx::Gu::intersectCapsuleVsMesh_RTREE(const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { return intersectAnyVsMesh<eCAPSULE>(NULL, &capsule, NULL, triMesh, meshTransform, meshScale, results); } void physx::Gu::intersectOBB_RTREE(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned) { MeshRayCollider::collideOBB(obb, bothTriangleSidesCollide, static_cast<const RTreeTriangleMesh*>(mesh), callback, checkObbIsAligned); } // PT: TODO: refactor/share bits of this bool physx::Gu::sweepCapsule_MeshGeom_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Capsule& lss, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33); const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh); const Capsule inflatedCapsule(lss.p0, lss.p1, lss.radius + inflation); const bool isIdentity = triMeshGeom.scale.isIdentity(); bool isDoubleSided = (triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED); const PxU32 meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; // compute sweptAABB const PxVec3 localP0 = pose.transformInv(inflatedCapsule.p0); const PxVec3 localP1 = pose.transformInv(inflatedCapsule.p1); PxVec3 sweepOrigin = (localP0+localP1)*0.5f; PxVec3 sweepDir = pose.rotateInv(unitDir); PxVec3 sweepExtents = PxVec3(inflatedCapsule.radius) + (localP0-localP1).abs()*0.5f; PxReal distance1 = distance; PxReal distCoeff = 1.0f; PxMat34 poseWithScale; if(!isIdentity) { poseWithScale = pose * triMeshGeom.scale; distance1 = computeSweepData(triMeshGeom, sweepOrigin, sweepExtents, sweepDir, distance); distCoeff = distance1 / distance; } else poseWithScale = Matrix34FromTransform(pose); SweepCapsuleMeshHitCallback callback(sweepHit, poseWithScale, distance, isDoubleSided, inflatedCapsule, unitDir, hitFlags, triMeshGeom.scale.hasNegativeDeterminant(), distCoeff); MeshRayCollider::collide<1, 1>(sweepOrigin, sweepDir, distance1, true, meshData, callback, &sweepExtents); if(meshBothSides) isDoubleSided = true; return callback.finalizeHit(sweepHit, inflatedCapsule, triMeshGeom, pose, isDoubleSided); } #include "GuSweepSharedTests.h" // PT: TODO: refactor/share bits of this bool physx::Gu::sweepBox_MeshGeom_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33); const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh); const bool isIdentity = triMeshGeom.scale.isIdentity(); const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES; const bool isDoubleSided = triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED; PxMat34 meshToWorldSkew; PxVec3 sweptAABBMeshSpaceExtents, meshSpaceOrigin, meshSpaceDir; // Input sweep params: geom, pose, box, unitDir, distance // We convert the origin from world space to mesh local space // and convert the box+pose to mesh space AABB if(isIdentity) { meshToWorldSkew = Matrix34FromTransform(pose); const PxMat33Padded worldToMeshRot(pose.q.getConjugate()); // extract rotation matrix from pose.q meshSpaceOrigin = worldToMeshRot.transform(box.center - pose.p); meshSpaceDir = worldToMeshRot.transform(unitDir) * distance; PxMat33 boxToMeshRot = worldToMeshRot * box.rot; sweptAABBMeshSpaceExtents = boxToMeshRot.column0.abs() * box.extents.x + boxToMeshRot.column1.abs() * box.extents.y + boxToMeshRot.column2.abs() * box.extents.z; } else { meshToWorldSkew = pose * triMeshGeom.scale; const PxMat33 meshToWorldSkew_Rot = PxMat33Padded(pose.q) * toMat33(triMeshGeom.scale); const PxVec3& meshToWorldSkew_Trans = pose.p; PxMat33 worldToVertexSkew_Rot; PxVec3 worldToVertexSkew_Trans; getInverse(worldToVertexSkew_Rot, worldToVertexSkew_Trans, meshToWorldSkew_Rot, meshToWorldSkew_Trans); //make vertex space OBB Box vertexSpaceBox1; const PxMat34 worldToVertexSkew(worldToVertexSkew_Rot, worldToVertexSkew_Trans); vertexSpaceBox1 = transform(worldToVertexSkew, box); // compute swept aabb sweptAABBMeshSpaceExtents = vertexSpaceBox1.computeAABBExtent(); meshSpaceOrigin = worldToVertexSkew.transform(box.center); meshSpaceDir = worldToVertexSkew.rotate(unitDir*distance); // also applies scale to direction/length } sweptAABBMeshSpaceExtents += PxVec3(inflation); // inflate the bounds with additive inflation sweptAABBMeshSpaceExtents *= 1.01f; // fatten the bounds to account for numerical discrepancies PxReal dirLen = PxMax(meshSpaceDir.magnitude(), 1e-5f); PxReal distCoeff = 1.0f; if (!isIdentity) distCoeff = dirLen / distance; // Move to AABB space PxMat34 worldToBox; computeWorldToBoxMatrix(worldToBox, box); const bool bothTriangleSidesCollide = isDoubleSided || meshBothSides; const PxMat34Padded meshToBox = worldToBox*meshToWorldSkew; const PxTransform boxTransform = box.getTransform(); const PxVec3 localDir = worldToBox.rotate(unitDir); const PxVec3 localDirDist = localDir*distance; SweepBoxMeshHitCallback callback( // using eMULTIPLE with shrinkMaxT CallbackMode::eMULTIPLE, meshToBox, distance, bothTriangleSidesCollide, box, localDirDist, localDir, unitDir, hitFlags, inflation, triMeshGeom.scale.hasNegativeDeterminant(), distCoeff); MeshRayCollider::collide<1, 1>(meshSpaceOrigin, meshSpaceDir/dirLen, dirLen, bothTriangleSidesCollide, meshData, callback, &sweptAABBMeshSpaceExtents); return callback.finalizeHit(sweepHit, triMeshGeom, pose, boxTransform, localDir, meshBothSides, isDoubleSided); } #include "GuInternal.h" void physx::Gu::sweepConvex_MeshGeom_RTREE(const TriangleMesh* mesh, const Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool) { PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33); const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh); // create temporal bounds Box querySweptBox; computeSweptBox(querySweptBox, hullBox.extents, hullBox.center, hullBox.rot, localDir, distance); MeshRayCollider::collideOBB(querySweptBox, true, meshData, callback); } void physx::Gu::pointMeshDistance_RTREE(const TriangleMesh*, const PxTriangleMeshGeometry&, const PxTransform&, const PxVec3&, float, PxU32&, float&, PxVec3&) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Point-mesh distance query not supported for BVH33. Please use a BVH34 mesh.\n"); }
35,196
C++
37.216069
199
0.739743
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMeshQuery.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxProfileZone.h" #include "geometry/PxMeshQuery.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxGeometryQuery.h" #include "GuInternal.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuBoxConversion.h" #include "GuIntersectionTriangleBox.h" #include "CmScaling.h" #include "GuSweepTests.h" #include "GuMidphaseInterface.h" #include "foundation/PxFPU.h" using namespace physx; using namespace Gu; namespace { class HfTrianglesEntityReport2 : public OverlapReport, public LimitedResults { public: HfTrianglesEntityReport2( PxU32* results, PxU32 maxResults, PxU32 startIndex, HeightFieldUtil& hfUtil, const PxVec3& boxCenter, const PxVec3& boxExtents, const PxQuat& boxRot, bool aabbOverlap) : LimitedResults (results, maxResults, startIndex), mHfUtil (hfUtil), mAABBOverlap (aabbOverlap) { buildFrom(mBox2Hf, boxCenter, boxExtents, boxRot); } virtual bool reportTouchedTris(PxU32 nbEntities, const PxU32* entities) { if(mAABBOverlap) { while(nbEntities--) if(!add(*entities++)) return false; } else { const PxTransform idt(PxIdentity); for(PxU32 i=0; i<nbEntities; i++) { PxTrianglePadded tri; mHfUtil.getTriangle(idt, tri, NULL, NULL, entities[i], false, false); // First parameter not needed if local space triangle is enough // PT: this one is safe because triangle class is padded if(intersectTriangleBox(mBox2Hf, tri.verts[0], tri.verts[1], tri.verts[2])) { if(!add(entities[i])) return false; } } } return true; } HeightFieldUtil& mHfUtil; BoxPadded mBox2Hf; bool mAABBOverlap; private: HfTrianglesEntityReport2& operator=(const HfTrianglesEntityReport2&); }; } // namespace void physx::PxMeshQuery::getTriangle(const PxTriangleMeshGeometry& triGeom, const PxTransform& globalPose, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices, PxU32* adjacencyIndices) { const TriangleMesh* tm = static_cast<const TriangleMesh*>(triGeom.triangleMesh); PX_CHECK_AND_RETURN(triangleIndex<tm->getNbTriangles(), "PxMeshQuery::getTriangle: triangle index is out of bounds"); if(adjacencyIndices && !tm->getAdjacencies()) PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Adjacency information not created. Set buildTriangleAdjacencies on Cooking params."); const PxMat34 vertex2worldSkew = globalPose * triGeom.scale; tm->computeWorldTriangle(triangle, triangleIndex, vertex2worldSkew, triGeom.scale.hasNegativeDeterminant(), vertexIndices, adjacencyIndices); } /////////////////////////////////////////////////////////////////////////////// void physx::PxMeshQuery::getTriangle(const PxHeightFieldGeometry& hfGeom, const PxTransform& globalPose, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices, PxU32* adjacencyIndices) { HeightFieldUtil hfUtil(hfGeom); hfUtil.getTriangle(globalPose, triangle, vertexIndices, adjacencyIndices, triangleIndex, true, true); } /////////////////////////////////////////////////////////////////////////////// PxU32 physx::PxMeshQuery::findOverlapTriangleMesh( const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, PxGeometryQueryFlags queryFlags) { PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD) LimitedResults limitedResults(results, maxResults, startIndex); const TriangleMesh* tm = static_cast<const TriangleMesh*>(meshGeom.triangleMesh); switch(geom.getType()) { case PxGeometryType::eBOX: { const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); Box box; buildFrom(box, geomPose.p, boxGeom.halfExtents, geomPose.q); Midphase::intersectBoxVsMesh(box, *tm, meshPose, meshGeom.scale, &limitedResults); break; } case PxGeometryType::eCAPSULE: { const PxCapsuleGeometry& capsGeom = static_cast<const PxCapsuleGeometry&>(geom); Capsule capsule; getCapsule(capsule, capsGeom, geomPose); Midphase::intersectCapsuleVsMesh(capsule, *tm, meshPose, meshGeom.scale, &limitedResults); break; } case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); Midphase::intersectSphereVsMesh(Sphere(geomPose.p, sphereGeom.radius), *tm, meshPose, meshGeom.scale, &limitedResults); break; } default: { PX_CHECK_MSG(false, "findOverlapTriangleMesh: Only box, capsule and sphere geometries are supported."); } } overflow = limitedResults.mOverflow; return limitedResults.mNbResults; } /////////////////////////////////////////////////////////////////////////////// bool physx::PxMeshQuery::findOverlapTriangleMesh( PxReportCallback<PxGeomIndexPair>& callback, const PxTriangleMeshGeometry& meshGeom0, const PxTransform& meshPose0, const PxTriangleMeshGeometry& meshGeom1, const PxTransform& meshPose1, PxGeometryQueryFlags queryFlags, PxMeshMeshQueryFlags meshMeshFlags, float tolerance) { PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD) const TriangleMesh* tm0 = static_cast<const TriangleMesh*>(meshGeom0.triangleMesh); const TriangleMesh* tm1 = static_cast<const TriangleMesh*>(meshGeom1.triangleMesh); // PT: only implemented for BV4 if(!tm0 || !tm1 || tm0->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34 || tm1->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34) return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMeshQuery::findOverlapTriangleMesh(): only available between two BVH34 triangles meshes."); // PT: ...so we don't need a table like for the other ops, just go straight to BV4 return intersectMeshVsMesh_BV4(callback, *tm0, meshPose0, meshGeom0.scale, *tm1, meshPose1, meshGeom1.scale, meshMeshFlags, tolerance); } /////////////////////////////////////////////////////////////////////////////// PxU32 physx::PxMeshQuery::findOverlapHeightField( const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose, PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, PxGeometryQueryFlags queryFlags) { PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD) const PxTransform localPose0 = hfPose.transformInv(geomPose); PxBoxGeometry boxGeom; switch(geom.getType()) { case PxGeometryType::eCAPSULE: { const PxCapsuleGeometry& cap = static_cast<const PxCapsuleGeometry&>(geom); boxGeom.halfExtents = PxVec3(cap.halfHeight+cap.radius, cap.radius, cap.radius); // PT: TODO: improve these bounds - see computeCapsuleBounds } break; case PxGeometryType::eSPHERE: { const PxSphereGeometry& sph = static_cast<const PxSphereGeometry&>(geom); boxGeom.halfExtents = PxVec3(sph.radius); // PT: TODO: could this codepath be improved using the following? //PxBounds3 localBounds; //const PxVec3 localSphereCenter = getLocalSphereData(localBounds, pose0, pose1, sphereGeom.radius); } break; case PxGeometryType::eBOX: boxGeom = static_cast<const PxBoxGeometry&>(geom); break; default: { overflow = false; PX_CHECK_AND_RETURN_VAL(false, "findOverlapHeightField: Only box, sphere and capsule queries are supported.", false); } } const bool isAABB = ((localPose0.q.x == 0.0f) && (localPose0.q.y == 0.0f) && (localPose0.q.z == 0.0f)); PxBounds3 bounds; if (isAABB) bounds = PxBounds3::centerExtents(localPose0.p, boxGeom.halfExtents); else bounds = PxBounds3::poseExtent(localPose0, boxGeom.halfExtents); // box.halfExtents is really extent HeightFieldUtil hfUtil(hfGeom); HfTrianglesEntityReport2 entityReport(results, maxResults, startIndex, hfUtil, localPose0.p, boxGeom.halfExtents, localPose0.q, isAABB); hfUtil.overlapAABBTriangles(bounds, entityReport); overflow = entityReport.mOverflow; return entityReport.mNbResults; } /////////////////////////////////////////////////////////////////////////////// bool physx::PxMeshQuery::sweep( const PxVec3& unitDir, const PxReal maxDistance, const PxGeometry& geom, const PxTransform& pose, PxU32 triangleCount, const PxTriangle* triangles, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxU32* cachedIndex, const PxReal inflation, bool doubleSided, PxGeometryQueryFlags queryFlags) { PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD) PX_CHECK_AND_RETURN_VAL(pose.isValid(), "PxMeshQuery::sweep(): pose is not valid.", false); PX_CHECK_AND_RETURN_VAL(unitDir.isFinite(), "PxMeshQuery::sweep(): unitDir is not valid.", false); PX_CHECK_AND_RETURN_VAL(PxIsFinite(maxDistance), "PxMeshQuery::sweep(): distance is not valid.", false); PX_CHECK_AND_RETURN_VAL(maxDistance > 0, "PxMeshQuery::sweep(): sweep distance must be greater than 0.", false); PX_PROFILE_ZONE("MeshQuery.sweep", 0); const PxReal distance = PxMin(maxDistance, PX_MAX_SWEEP_DISTANCE); switch(geom.getType()) { case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f); return sweepCapsuleTriangles( triangleCount, triangles, doubleSided, capsuleGeom, pose, unitDir, distance, sweepHit, cachedIndex, inflation, hitFlags); } case PxGeometryType::eCAPSULE: { const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); return sweepCapsuleTriangles( triangleCount, triangles, doubleSided, capsuleGeom, pose, unitDir, distance, sweepHit, cachedIndex, inflation, hitFlags); } case PxGeometryType::eBOX: { const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); if(hitFlags & PxHitFlag::ePRECISE_SWEEP) { return sweepBoxTriangles_Precise( triangleCount, triangles, doubleSided, boxGeom, pose, unitDir, distance, sweepHit, cachedIndex, inflation, hitFlags); } else { return sweepBoxTriangles( triangleCount, triangles, doubleSided, boxGeom, pose, unitDir, distance, sweepHit, cachedIndex, inflation, hitFlags); } } default: PX_CHECK_MSG(false, "PxMeshQuery::sweep(): geometry object parameter must be sphere, capsule or box geometry."); } return false; } ///////////////////////////////////////////////////////////////////////////////
12,194
C++
37.837579
203
0.720026
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMesh.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_TRIANGLEMESH_H #define GU_TRIANGLEMESH_H #include "foundation/PxIO.h" #include "geometry/PxTriangle.h" #include "geometry/PxTriangleMeshGeometry.h" #include "geometry/PxSimpleTriangleMesh.h" #include "geometry/PxTriangleMesh.h" #include "GuMeshData.h" #include "GuCenterExtents.h" #include "CmScaling.h" #include "CmRefCountable.h" #include "common/PxRenderOutput.h" namespace physx { class PxMeshScale; struct PxTriangleMeshInternalData; namespace Gu { PX_FORCE_INLINE void getVertexRefs(PxU32 triangleIndex, PxU32& vref0, PxU32& vref1, PxU32& vref2, const void* indices, bool has16BitIndices) { if(has16BitIndices) { const PxU16* inds = reinterpret_cast<const PxU16*>(indices) + triangleIndex*3; vref0 = inds[0]; vref1 = inds[1]; vref2 = inds[2]; } else { const PxU32* inds = reinterpret_cast<const PxU32*>(indices) + triangleIndex*3; vref0 = inds[0]; vref1 = inds[1]; vref2 = inds[2]; } } class MeshFactory; #if PX_VC #pragma warning(push) #pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class EdgeList; class TriangleMesh : public PxTriangleMesh, public PxUserAllocated { public: // PX_SERIALIZATION TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags), mSdfData(PxEmpty) {} void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream); virtual void release(); virtual void requiresObjects(PxProcessPxBaseCallback&){} //~PX_SERIALIZATION TriangleMesh(MeshFactory* factory, TriangleMeshData& data); TriangleMesh(const PxTriangleMeshInternalData& data); virtual ~TriangleMesh(); // PxBase virtual void onRefCountZero(); //~PxBase // PxRefCounted virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); } virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); } //~PxRefCounted // PxTriangleMesh virtual PxU32 getNbVertices() const { return mNbVertices;} virtual const PxVec3* getVertices() const { return mVertices; } virtual PxVec3* getVerticesForModification(); virtual PxBounds3 refitBVH(); virtual PxU32 getNbTriangles() const { return mNbTriangles; } virtual const void* getTriangles() const { return mTriangles; } virtual PxTriangleMeshFlags getTriangleMeshFlags() const { return PxTriangleMeshFlags(mFlags); } virtual const PxU32* getTrianglesRemap() const { return mFaceRemap; } virtual void setPreferSDFProjection(bool preferProjection) { if (preferProjection) mFlags &= PxU8(~PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ); else mFlags |= PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ; } virtual bool getPreferSDFProjection() const { return !(mFlags & PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ); } virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const { return hasPerTriangleMaterials() ? getMaterials()[triangleIndex] : PxMaterialTableIndex(0xffff); } virtual PxBounds3 getLocalBounds() const { PX_ASSERT(mAABB.isValid()); return PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents); } virtual const PxReal* getSDF() const { return mSdfData.mSdf; } virtual void getSDFDimensions(PxU32& numX, PxU32& numY, PxU32& numZ) const { if(mSdfData.mSdf) { numX = mSdfData.mDims.x; numY = mSdfData.mDims.y; numZ = mSdfData.mDims.z; } else numX = numY = numZ = 0; } virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const { mass = mMass; localInertia = mInertia; localCenterOfMass = mLocalCenterOfMass; } //~PxTriangleMesh virtual bool getInternalData(PxTriangleMeshInternalData&, bool) const { return false; } // PT: this one is just to prevent instancing Gu::TriangleMesh. // But you should use PxBase::getConcreteType() instead to avoid the virtual call. virtual PxMeshMidPhase::Enum getMidphaseID() const = 0; PX_FORCE_INLINE const PxU32* getFaceRemap() const { return mFaceRemap; } PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxMeshFlag::e16_BIT_INDICES) ? true : false; } PX_FORCE_INLINE bool hasPerTriangleMaterials() const { return mMaterialIndices != NULL; } PX_FORCE_INLINE PxU32 getNbVerticesFast() const { return mNbVertices; } PX_FORCE_INLINE PxU32 getNbTrianglesFast() const { return mNbTriangles; } PX_FORCE_INLINE const void* getTrianglesFast() const { return mTriangles; } PX_FORCE_INLINE const PxVec3* getVerticesFast() const { return mVertices; } PX_FORCE_INLINE const PxU32* getAdjacencies() const { return mAdjacencies; } PX_FORCE_INLINE PxReal getGeomEpsilon() const { return mGeomEpsilon; } PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mAABB; } PX_FORCE_INLINE const PxU16* getMaterials() const { return mMaterialIndices; } PX_FORCE_INLINE const PxU8* getExtraTrigData() const { return mExtraTrigData; } PX_FORCE_INLINE const PxU32* getAccumulatedTriangleRef() const { return mAccumulatedTrianglesRef; } PX_FORCE_INLINE const PxU32* getTriangleReferences() const { return mTrianglesReferences; } PX_FORCE_INLINE PxU32 getNbTriangleReferences() const { return mNbTrianglesReferences; } PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const { // PT: see compile-time assert in cpp return static_cast<const CenterExtentsPadded&>(mAABB); } PX_FORCE_INLINE void computeWorldTriangle( PxTriangle& worldTri, PxTriangleID triangleIndex, const PxMat34& worldMatrix, bool flipNormal = false, PxU32* PX_RESTRICT vertexIndices=NULL, PxU32* PX_RESTRICT adjacencyIndices=NULL) const; PX_FORCE_INLINE void getLocalTriangle(PxTriangle& localTri, PxTriangleID triangleIndex, bool flipNormal = false) const; void setMeshFactory(MeshFactory* factory) { mMeshFactory = factory; } // SDF methods PX_FORCE_INLINE const SDF& getSdfDataFast() const { return mSdfData; } //~SDF methods PX_FORCE_INLINE PxReal getMass() const { return mMass; } // PT: for debug viz PX_PHYSX_COMMON_API const Gu::EdgeList* requestEdgeList() const; protected: PxU32 mNbVertices; PxU32 mNbTriangles; PxVec3* mVertices; void* mTriangles; //!< 16 (<= 0xffff #vertices) or 32 bit trig indices (mNbTriangles * 3) // 16 bytes block // PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading CenterExtents mAABB; PxU8* mExtraTrigData; //one per trig PxReal mGeomEpsilon; //!< see comments in cooking code referencing this variable // 16 bytes block /* low 3 bits (mask: 7) are the edge flags: b001 = 1 = ignore edge 0 = edge v0-->v1 b010 = 2 = ignore edge 1 = edge v0-->v2 b100 = 4 = ignore edge 2 = edge v1-->v2 */ PxU8 mFlags; //!< Flag whether indices are 16 or 32 bits wide //!< Flag whether triangle adajacencies are build PxU16* mMaterialIndices; //!< the size of the array is numTriangles. PxU32* mFaceRemap; //!< new faces to old faces mapping (after cleaning, etc). Usage: old = faceRemap[new] PxU32* mAdjacencies; //!< Adjacency information for each face - 3 adjacent faces //!< Set to 0xFFFFffff if no adjacent face MeshFactory* mMeshFactory; // PT: changed to pointer for serialization mutable Gu::EdgeList* mEdgeList; // PT: for debug viz PxReal mMass; //this is mass assuming a unit density that can be scaled by instances! PxMat33 mInertia; //in local space of mesh! PxVec3 mLocalCenterOfMass; //local space com public: // GRB data ------------------------- void* mGRB_triIndices; //!< GRB: GPU-friendly tri indices // TODO avoroshilov: cooking - adjacency info - duplicated, remove it and use 'mAdjacencies' and 'mExtraTrigData' see GuTriangleMesh.cpp:325 void* mGRB_triAdjacencies; //!< GRB: adjacency data, with BOUNDARY and NONCONVEX flags (flags replace adj indices where applicable) PxU32* mGRB_faceRemap; //!< GRB : gpu to cpu triangle indice remap PxU32* mGRB_faceRemapInverse; Gu::BV32Tree* mGRB_BV32Tree; //!< GRB: BV32 tree // End of GRB data ------------------ // SDF data ------------------------- SDF mSdfData; // End of SDF data ------------------ void setAllEdgesActive(); //Vertex mapping data PxU32* mAccumulatedTrianglesRef;//runsum PxU32* mTrianglesReferences; PxU32 mNbTrianglesReferences; //End of vertex mapping data }; #if PX_VC #pragma warning(pop) #endif } // namespace Gu PX_FORCE_INLINE void Gu::TriangleMesh::computeWorldTriangle(PxTriangle& worldTri, PxTriangleID triangleIndex, const PxMat34& worldMatrix, bool flipNormal, PxU32* PX_RESTRICT vertexIndices, PxU32* PX_RESTRICT adjacencyIndices) const { PxU32 vref0, vref1, vref2; getVertexRefs(triangleIndex, vref0, vref1, vref2, mTriangles, has16BitIndices()); if(flipNormal) PxSwap<PxU32>(vref1, vref2); const PxVec3* PX_RESTRICT vertices = getVerticesFast(); worldTri.verts[0] = worldMatrix.transform(vertices[vref0]); worldTri.verts[1] = worldMatrix.transform(vertices[vref1]); worldTri.verts[2] = worldMatrix.transform(vertices[vref2]); if(vertexIndices) { vertexIndices[0] = vref0; vertexIndices[1] = vref1; vertexIndices[2] = vref2; } if(adjacencyIndices) { if(mAdjacencies) { // PT: TODO: is this correct? adjacencyIndices[0] = flipNormal ? mAdjacencies[triangleIndex*3 + 2] : mAdjacencies[triangleIndex*3 + 0]; adjacencyIndices[1] = mAdjacencies[triangleIndex*3 + 1]; adjacencyIndices[2] = flipNormal ? mAdjacencies[triangleIndex*3 + 0] : mAdjacencies[triangleIndex*3 + 2]; } else { adjacencyIndices[0] = 0xffffffff; adjacencyIndices[1] = 0xffffffff; adjacencyIndices[2] = 0xffffffff; } } } PX_FORCE_INLINE void Gu::TriangleMesh::getLocalTriangle(PxTriangle& localTri, PxTriangleID triangleIndex, bool flipNormal) const { PxU32 vref0, vref1, vref2; getVertexRefs(triangleIndex, vref0, vref1, vref2, mTriangles, has16BitIndices()); if(flipNormal) PxSwap<PxU32>(vref1, vref2); const PxVec3* PX_RESTRICT vertices = getVerticesFast(); localTri.verts[0] = vertices[vref0]; localTri.verts[1] = vertices[vref1]; localTri.verts[2] = vertices[vref2]; } PX_INLINE float computeSweepData(const PxTriangleMeshGeometry& triMeshGeom, /*const Cm::FastVertex2ShapeScaling& scaling,*/ PxVec3& sweepOrigin, PxVec3& sweepExtents, PxVec3& sweepDir, float distance) { PX_ASSERT(!Cm::isEmpty(sweepOrigin, sweepExtents)); const PxVec3 endPt = sweepOrigin + sweepDir*distance; PX_ASSERT(!Cm::isEmpty(endPt, sweepExtents)); const Cm::FastVertex2ShapeScaling meshScaling(triMeshGeom.scale.getInverse()); // shape to vertex transform const PxMat33& vertex2ShapeSkew = meshScaling.getVertex2ShapeSkew(); const PxVec3 originBoundsCenter = vertex2ShapeSkew * sweepOrigin; const PxVec3 originBoundsExtents = Cm::basisExtent(vertex2ShapeSkew.column0, vertex2ShapeSkew.column1, vertex2ShapeSkew.column2, sweepExtents); sweepOrigin = originBoundsCenter; sweepExtents = originBoundsExtents; sweepDir = (vertex2ShapeSkew * endPt) - originBoundsCenter; return sweepDir.normalizeSafe(); } PX_FORCE_INLINE const Gu::TriangleMesh* _getMeshData(const PxTriangleMeshGeometry& meshGeom) { return static_cast<const Gu::TriangleMesh*>(meshGeom.triangleMesh); } } #endif
14,286
C
40.054598
200
0.682066
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_H #define GU_BV4_H #include "foundation/PxBounds3.h" #include "GuBV4Settings.h" #include "GuCenterExtents.h" #include "GuTriangle.h" #include "foundation/PxVecMath.h" #include "common/PxPhysXCommonConfig.h" #define V4LoadU_Safe physx::aos::V4LoadU // PT: prefix needed on Linux. Sigh. #define V4LoadA_Safe V4LoadA #define V4StoreA_Safe V4StoreA #define V4StoreU_Safe V4StoreU namespace physx { class PxSerializationContext; class PxDeserializationContext; namespace Gu { struct VertexPointers { const PxVec3* Vertex[3]; }; struct TetrahedronPointers { const PxVec3* Vertex[4]; }; // PT: TODO: make this more generic, rename to IndQuad32, refactor with GRB's int4 class IndTetrahedron32 : public physx::PxUserAllocated { public: public: PX_FORCE_INLINE IndTetrahedron32() {} PX_FORCE_INLINE IndTetrahedron32(PxU32 r0, PxU32 r1, PxU32 r2, PxU32 r3) { mRef[0] = r0; mRef[1] = r1; mRef[2] = r2; mRef[3] = r3; } PX_FORCE_INLINE IndTetrahedron32(const IndTetrahedron32& tetrahedron) { mRef[0] = tetrahedron.mRef[0]; mRef[1] = tetrahedron.mRef[1]; mRef[2] = tetrahedron.mRef[2]; mRef[3] = tetrahedron.mRef[3]; } PX_FORCE_INLINE ~IndTetrahedron32() {} PxU32 mRef[4]; }; PX_COMPILE_TIME_ASSERT(sizeof(IndTetrahedron32) == 16); // PT: TODO: make this more generic, rename to IndQuad16 class IndTetrahedron16 : public physx::PxUserAllocated { public: public: PX_FORCE_INLINE IndTetrahedron16() {} PX_FORCE_INLINE IndTetrahedron16(PxU16 r0, PxU16 r1, PxU16 r2, PxU16 r3) { mRef[0] = r0; mRef[1] = r1; mRef[2] = r2; mRef[3] = r3; } PX_FORCE_INLINE IndTetrahedron16(const IndTetrahedron16& tetrahedron) { mRef[0] = tetrahedron.mRef[0]; mRef[1] = tetrahedron.mRef[1]; mRef[2] = tetrahedron.mRef[2]; mRef[3] = tetrahedron.mRef[3]; } PX_FORCE_INLINE ~IndTetrahedron16() {} PxU16 mRef[4]; }; PX_COMPILE_TIME_ASSERT(sizeof(IndTetrahedron16) == 8); typedef IndexedTriangle32 IndTri32; typedef IndexedTriangle16 IndTri16; PX_FORCE_INLINE void getVertexReferences(PxU32& vref0, PxU32& vref1, PxU32& vref2, PxU32 index, const IndTri32* T32, const IndTri16* T16) { if(T32) { const IndTri32* PX_RESTRICT tri = T32 + index; vref0 = tri->mRef[0]; vref1 = tri->mRef[1]; vref2 = tri->mRef[2]; } else { const IndTri16* PX_RESTRICT tri = T16 + index; vref0 = tri->mRef[0]; vref1 = tri->mRef[1]; vref2 = tri->mRef[2]; } } PX_FORCE_INLINE void getVertexReferences(PxU32& vref0, PxU32& vref1, PxU32& vref2, PxU32& vref3, PxU32 index, const IndTetrahedron32* T32, const IndTetrahedron16* T16) { if(T32) { const IndTetrahedron32* PX_RESTRICT tet = T32 + index; vref0 = tet->mRef[0]; vref1 = tet->mRef[1]; vref2 = tet->mRef[2]; vref3 = tet->mRef[3]; } else { const IndTetrahedron16* PX_RESTRICT tet = T16 + index; vref0 = tet->mRef[0]; vref1 = tet->mRef[1]; vref2 = tet->mRef[2]; vref3 = tet->mRef[3]; } } class SourceMeshBase : public physx::PxUserAllocated { public: enum MeshType { TRI_MESH, TET_MESH, FORCE_DWORD = 0x7fffffff }; SourceMeshBase(MeshType meshType); virtual ~SourceMeshBase(); SourceMeshBase(const PxEMPTY) {} static void getBinaryMetaData(PxOutputStream& stream); PxU32 mNbVerts; const PxVec3* mVerts; PX_FORCE_INLINE PxU32 getNbVertices() const { return mNbVerts; } PX_FORCE_INLINE const PxVec3* getVerts() const { return mVerts; } PX_FORCE_INLINE void setNbVertices(PxU32 nb) { mNbVerts = nb; } PX_FORCE_INLINE void initRemap() { mRemap = NULL; } PX_FORCE_INLINE const PxU32* getRemap() const { return mRemap; } PX_FORCE_INLINE void releaseRemap() { PX_FREE(mRemap); } PX_FORCE_INLINE MeshType getMeshType() const { return mType; } // PT: TODO: check whether adding these vcalls affected build & runtime performance virtual PxU32 getNbPrimitives() const = 0; virtual void remapTopology(const PxU32* order) = 0; virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV) = 0; virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox) = 0; protected: MeshType mType; PxU32* mRemap; }; class SourceMesh : public SourceMeshBase { public: SourceMesh(); virtual ~SourceMesh(); // PX_SERIALIZATION SourceMesh(const PxEMPTY) : SourceMeshBase(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION void reset(); void operator = (SourceMesh& v); PxU32 mNbTris; IndTri32* mTriangles32; IndTri16* mTriangles16; PX_FORCE_INLINE PxU32 getNbTriangles() const { return mNbTris; } PX_FORCE_INLINE const IndTri32* getTris32() const { return mTriangles32; } PX_FORCE_INLINE const IndTri16* getTris16() const { return mTriangles16; } PX_FORCE_INLINE void setNbTriangles(PxU32 nb) { mNbTris = nb; } // SourceMeshBase virtual PxU32 getNbPrimitives() const { return getNbTriangles(); } virtual void remapTopology(const PxU32* order); virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV); virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox); //~SourceMeshBase PX_FORCE_INLINE void setPointers(IndTri32* tris32, IndTri16* tris16, const PxVec3* verts) { mTriangles32 = tris32; mTriangles16 = tris16; mVerts = verts; } bool isValid() const; PX_FORCE_INLINE void getTriangle(VertexPointers& vp, PxU32 index) const { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, index, mTriangles32, mTriangles16); vp.Vertex[0] = mVerts + VRef0; vp.Vertex[1] = mVerts + VRef1; vp.Vertex[2] = mVerts + VRef2; } }; class TetrahedronSourceMesh : public SourceMeshBase { public: TetrahedronSourceMesh(); virtual ~TetrahedronSourceMesh(); // PX_SERIALIZATION TetrahedronSourceMesh(const PxEMPTY) : SourceMeshBase(TET_MESH) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION void reset(); void operator = (TetrahedronSourceMesh& v); PxU32 mNbTetrahedrons; IndTetrahedron32* mTetrahedrons32; IndTetrahedron16* mTetrahedrons16; PX_FORCE_INLINE PxU32 getNbTetrahedrons() const { return mNbTetrahedrons; } PX_FORCE_INLINE const IndTetrahedron32* getTetrahedrons32() const { return mTetrahedrons32; } PX_FORCE_INLINE const IndTetrahedron16* getTetrahedrons16() const { return mTetrahedrons16; } PX_FORCE_INLINE void setNbTetrahedrons(PxU32 nb) { mNbTetrahedrons = nb; } // SourceMeshBase virtual PxU32 getNbPrimitives() const { return getNbTetrahedrons(); } virtual void remapTopology(const PxU32* order); virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV); virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox); //~SourceMeshBase PX_FORCE_INLINE void setPointers(IndTetrahedron32* tets32, IndTetrahedron16* tets16, const PxVec3* verts) { mTetrahedrons32 = tets32; mTetrahedrons16 = tets16; mVerts = verts; } bool isValid() const; PX_FORCE_INLINE void getTetrahedron(TetrahedronPointers& vp, PxU32 index) const { PxU32 VRef0, VRef1, VRef2, VRef3; getVertexReferences(VRef0, VRef1, VRef2, VRef3, index, mTetrahedrons32, mTetrahedrons16); vp.Vertex[0] = mVerts + VRef0; vp.Vertex[1] = mVerts + VRef1; vp.Vertex[2] = mVerts + VRef2; vp.Vertex[3] = mVerts + VRef3; } }; struct LocalBounds { // PX_SERIALIZATION LocalBounds(const PxEMPTY) {} //~PX_SERIALIZATION LocalBounds() : mCenter(PxVec3(0.0f)), mExtentsMagnitude(0.0f) {} PxVec3 mCenter; float mExtentsMagnitude; PX_FORCE_INLINE void init(const PxBounds3& bounds) { mCenter = bounds.getCenter(); // PT: TODO: compute mag first, then multiplies by 0.5f (TA34704) mExtentsMagnitude = bounds.getExtents().magnitude(); } }; class QuantizedAABB { public: struct Data { PxU16 mExtents; //!< Quantized extents PxI16 mCenter; //!< Quantized center }; Data mData[3]; }; PX_COMPILE_TIME_ASSERT(sizeof(QuantizedAABB)==12); ///// #define GU_BV4_CHILD_OFFSET_SHIFT_COUNT 11 static PX_FORCE_INLINE PxU32 getChildOffset(PxU32 data) { return data>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; } static PX_FORCE_INLINE PxU32 getChildType(PxU32 data) { return (data>>1)&3; } template<class BoxType> struct BVDataPackedT { BoxType mAABB; PxU32 mData; PX_FORCE_INLINE PxU32 isLeaf() const { return mData&1; } PX_FORCE_INLINE PxU32 getPrimitive() const { return mData>>1; } PX_FORCE_INLINE PxU32 getChildOffset() const { return mData>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT;} PX_FORCE_INLINE PxU32 getChildType() const { return (mData>>1)&3; } PX_FORCE_INLINE PxU32 getChildData() const { return mData; } PX_FORCE_INLINE void encodePNS(PxU32 code) { PX_ASSERT(code<256); mData |= code<<3; } PX_FORCE_INLINE PxU32 decodePNSNoShift() const { return mData; } }; typedef BVDataPackedT<QuantizedAABB> BVDataPackedQ; typedef BVDataPackedT<CenterExtents> BVDataPackedNQ; // PT: TODO: align class to 16? (TA34704) class BV4Tree : public physx::PxUserAllocated { public: // PX_SERIALIZATION BV4Tree(const PxEMPTY); void exportExtraData(PxSerializationContext&); void importExtraData(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION BV4Tree(); BV4Tree(SourceMesh* meshInterface, const PxBounds3& localBounds); ~BV4Tree(); bool refit(PxBounds3& globalBounds, float epsilon); bool load(PxInputStream& stream, bool mismatch); void reset(); void operator = (BV4Tree& v); bool init(SourceMeshBase* meshInterface, const PxBounds3& localBounds); void release(); SourceMeshBase* mMeshInterface; LocalBounds mLocalBounds; PxU32 mNbNodes; void* mNodes; // PT: BVDataPacked / BVDataSwizzled PxU32 mInitData; // PT: the dequantization coeffs are only used for quantized trees PxVec3 mCenterOrMinCoeff; // PT: dequantization coeff, either for Center or Min (depending on AABB format) PxVec3 mExtentsOrMaxCoeff; // PT: dequantization coeff, either for Extents or Max (depending on AABB format) bool mUserAllocated; // PT: please keep these 4 bytes right after mCenterOrMinCoeff/mExtentsOrMaxCoeff for safe V4 loading bool mQuantized; // PT: true for quantized trees bool mIsEdgeSet; // PT: equivalent to RTree::IS_EDGE_SET bool mPadding; }; } // namespace Gu } #endif // GU_BV4_H
13,036
C
33.039164
168
0.67375
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuSweepMesh.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_SWEEP_MESH_H #define GU_SWEEP_MESH_H #include "GuMidphaseInterface.h" #include "GuVecConvexHull.h" namespace physx { namespace Gu { // PT: intermediate class containing shared bits of code & members struct SweepShapeMeshHitCallback : MeshHitCallback<PxGeomRaycastHit> { SweepShapeMeshHitCallback(CallbackMode::Enum mode, const PxHitFlags& hitFlags, bool flipNormal, float distCoef); const PxHitFlags mHitFlags; bool mStatus; // Default is false, set to true if a valid hit is found. Stays true once true. bool mInitialOverlap; // Default is false, set to true if an initial overlap hit is found. Reset for each hit. bool mFlipNormal; // If negative scale is used we need to flip normal PxReal mDistCoeff; // dist coeff from unscaled to scaled distance void operator=(const SweepShapeMeshHitCallback&) {} }; struct SweepCapsuleMeshHitCallback : SweepShapeMeshHitCallback { PxGeomSweepHit& mSweepHit; const PxMat34& mVertexToWorldSkew; const PxReal mTrueSweepDistance; // max sweep distance that can be used PxReal mBestAlignmentValue; // best alignment value for triangle normal PxReal mBestDist; // best distance, not the same as sweepHit.distance, can be shorter by epsilon const Capsule& mCapsule; const PxVec3& mUnitDir; const bool mMeshDoubleSided; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED const bool mIsSphere; SweepCapsuleMeshHitCallback(PxGeomSweepHit& sweepHit, const PxMat34& worldMatrix, PxReal distance, bool meshDoubleSided, const Capsule& capsule, const PxVec3& unitDir, const PxHitFlags& hitFlags, bool flipNormal, float distCoef); virtual PxAgain processHit(const PxGeomRaycastHit& aHit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal& shrunkMaxT, const PxU32*); // PT: TODO: unify these operators void operator=(const SweepCapsuleMeshHitCallback&) {} bool finalizeHit( PxGeomSweepHit& sweepHit, const Capsule& lss, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, bool isDoubleSided) const; }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif struct SweepBoxMeshHitCallback : SweepShapeMeshHitCallback { const PxMat34Padded& mMeshToBox; PxReal mDist, mDist0; physx::aos::FloatV mDistV; const Box& mBox; const PxVec3& mLocalDir; const PxVec3& mWorldUnitDir; PxReal mInflation; PxTriangle mHitTriangle; physx::aos::Vec3V mMinClosestA; physx::aos::Vec3V mMinNormal; physx::aos::Vec3V mLocalMotionV; PxU32 mMinTriangleIndex; PxVec3 mOneOverDir; const bool mBothTriangleSidesCollide; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED || PxHitFlag::eMESH_BOTH_SIDES SweepBoxMeshHitCallback(CallbackMode::Enum mode_, const PxMat34Padded& meshToBox, PxReal distance, bool bothTriangleSidesCollide, const Box& box, const PxVec3& localMotion, const PxVec3& localDir, const PxVec3& unitDir, const PxHitFlags& hitFlags, const PxReal inflation, bool flipNormal, float distCoef); virtual ~SweepBoxMeshHitCallback() {} virtual PxAgain processHit(const PxGeomRaycastHit& meshHit, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxReal& shrinkMaxT, const PxU32*); bool finalizeHit( PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const PxTransform& boxTransform, const PxVec3& localDir, bool meshBothSides, bool isDoubleSided) const; private: SweepBoxMeshHitCallback& operator=(const SweepBoxMeshHitCallback&); }; struct SweepConvexMeshHitCallback : SweepShapeMeshHitCallback { PxTriangle mHitTriangle; ConvexHullV mConvexHull; physx::aos::PxMatTransformV mMeshToConvex; physx::aos::PxTransformV mConvexPoseV; const Cm::FastVertex2ShapeScaling& mMeshScale; PxGeomSweepHit mSweepHit; // stores either the closest or any hit depending on value of mAnyHit physx::aos::FloatV mInitialDistance; physx::aos::Vec3V mConvexSpaceDir; // convexPose.rotateInv(-unit*distance) PxVec3 mUnitDir; PxVec3 mMeshSpaceUnitDir; PxReal mInflation; const bool mAnyHit; const bool mBothTriangleSidesCollide; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED || PxHitFlag::eMESH_BOTH_SIDES SweepConvexMeshHitCallback( const ConvexHullData& hull, const PxMeshScale& convexScale, const Cm::FastVertex2ShapeScaling& meshScale, const PxTransform& convexPose, const PxTransform& meshPose, const PxVec3& unitDir, const PxReal distance, PxHitFlags hitFlags, const bool bothTriangleSidesCollide, const PxReal inflation, const bool anyHit, float distCoef); virtual ~SweepConvexMeshHitCallback() {} virtual PxAgain processHit(const PxGeomRaycastHit& hit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal& shrunkMaxT, const PxU32*); bool finalizeHit(PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose, const PxVec3& unitDir, PxReal inflation, bool isMtd, bool meshBothSides, bool isDoubleSided, bool bothTriangleSidesCollide); private: SweepConvexMeshHitCallback& operator=(const SweepConvexMeshHitCallback&); }; #if PX_VC #pragma warning(pop) #endif } } #endif
7,172
C
44.398734
153
0.755159
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_SphereSweep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxSimpleTypes.h" #include "foundation/PxMat44.h" #include "GuBV4.h" #include "GuBox.h" #include "GuSphere.h" #include "GuSweepSphereTriangle.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuBV4_Common.h" // PT: for sphere-sweeps we use method 3 in %SDKRoot%\InternalDocumentation\GU\Sweep strategies.ppt namespace { // PT: TODO: refactor structure (TA34704) struct RayParams { BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); #ifndef GU_BV4_USE_SLABS BV4_ALIGN16(PxVec3p mData2_PaddedAligned); BV4_ALIGN16(PxVec3p mFDir_PaddedAligned); BV4_ALIGN16(PxVec3p mData_PaddedAligned); #endif BV4_ALIGN16(PxVec3p mLocalDir_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704) BV4_ALIGN16(PxVec3p mOrigin_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704) }; struct SphereSweepParams : RayParams { const IndTri32* PX_RESTRICT mTris32; const IndTri16* PX_RESTRICT mTris16; const PxVec3* PX_RESTRICT mVerts; PxVec3 mOriginalExtents_Padded; RaycastHitInternal mStabbedFace; PxU32 mBackfaceCulling; PxU32 mEarlyExit; PxVec3 mP0, mP1, mP2; PxVec3 mBestTriNormal; float mBestAlignmentValue; float mBestDistance; float mMaxDist; // PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; } PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; } }; } #include "GuBV4_AABBAABBSweepTest.h" // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static bool /*__fastcall*/ triSphereSweep(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex, bool nodeSorting=true) { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; PxVec3 normal = (p1 - p0).cross(p2 - p0); // Backface culling const bool culled = params->mBackfaceCulling && normal.dot(params->mLocalDir_Padded) > 0.0f; if(culled) return false; const PxTriangle T(p0, p1, p2); // PT: TODO: check potential bad ctor/dtor here (TA34704) <= or avoid creating the tri, not needed anymore normal.normalize(); // PT: TODO: we lost some perf when switching to PhysX version. Revisit/investigate. (TA34704) float dist; bool directHit; if(!sweepSphereVSTri(T.verts, normal, params->mOrigin_Padded, params->mOriginalExtents_Padded.x, params->mLocalDir_Padded, dist, directHit, true)) return false; const PxReal alignmentValue = computeAlignmentValue(normal, params->mLocalDir_Padded); if(keepTriangle(dist, alignmentValue, params->mBestDistance, params->mBestAlignmentValue, params->mMaxDist)) { params->mStabbedFace.mDistance = dist; params->mStabbedFace.mTriangleID = primIndex; params->mP0 = p0; params->mP1 = p1; params->mP2 = p2; params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound params->mBestAlignmentValue = alignmentValue; params->mBestTriNormal = normal; if(nodeSorting) { #ifndef GU_BV4_USE_SLABS setupRayData(params, params->mBestDistance, params->mOrigin_Padded, params->mLocalDir_Padded); //setupRayData(params, dist, params->mOrigin_Padded, params->mLocalDir_Padded); #endif } return true; } // else if(keepTriangleBasic(dist, params->mBestDistance, params->mMaxDist)) { params->mStabbedFace.mDistance = dist; params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound } // return false; } namespace { class LeafFunction_SphereSweepClosest { public: static PX_FORCE_INLINE void doLeafTest(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { triSphereSweep(params, primIndex); primIndex++; }while(nbToGo--); } }; class LeafFunction_SphereSweepAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triSphereSweep(params, primIndex)) return 1; primIndex++; }while(nbToGo--); return 0; } }; class ImpactFunctionSphere { public: static PX_FORCE_INLINE void computeImpact(PxVec3& impactPos, PxVec3& impactNormal, const Sphere& sphere, const PxVec3& dir, const PxReal t, const PxTrianglePadded& triangle) { computeSphereTriImpactData(impactPos, impactNormal, sphere.center, dir, t, triangle); } }; } template<class ParamsT> static PX_FORCE_INLINE void setupSphereParams(ParamsT* PX_RESTRICT params, const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh, PxU32 flags) { params->mOriginalExtents_Padded = PxVec3(sphere.radius); params->mStabbedFace.mTriangleID = PX_INVALID_U32; params->mStabbedFace.mDistance = maxDist; params->mBestDistance = PX_MAX_REAL; params->mBestAlignmentValue = 2.0f; params->mMaxDist = maxDist; setupParamsFlags(params, flags); setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); computeLocalRay(params->mLocalDir_Padded, params->mOrigin_Padded, dir, sphere.center, worldm_Aligned); #ifndef GU_BV4_USE_SLABS setupRayData(params, maxDist, params->mOrigin_Padded, params->mLocalDir_Padded); #endif } #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h" #include "GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_KajiyaNoOrder.h" #include "GuBV4_Slabs_KajiyaOrdered.h" #endif #define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER #define GU_BV4_PROCESS_STREAM_RAY_ORDERED #include "GuBV4_Internal.h" PxIntBool BV4_SphereSweepSingle(const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepHit* PX_RESTRICT hit, PxU32 flags) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); SphereSweepParams Params; setupSphereParams(&Params, sphere, dir, maxDist, &tree, worldm_Aligned, mesh, flags); if(tree.mNodes) { if(Params.mEarlyExit) processStreamRayNoOrder<1, LeafFunction_SphereSweepAny>(tree, &Params); else processStreamRayOrdered<1, LeafFunction_SphereSweepClosest>(tree, &Params); } else doBruteForceTests<LeafFunction_SphereSweepAny, LeafFunction_SphereSweepClosest>(mesh->getNbTriangles(), &Params); return computeImpactDataT<ImpactFunctionSphere>(sphere, dir, hit, &Params, worldm_Aligned, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); } // PT: sphere sweep callback version - currently not used namespace { struct SphereSweepParamsCB : SphereSweepParams { // PT: these new members are only here to call computeImpactDataT during traversal :( // PT: TODO: most of them may not be needed if we just move sphere to local space before traversal Sphere mSphere; // Sphere in original space (maybe not local/mesh space) PxVec3 mDir; // Dir in original space (maybe not local/mesh space) const PxMat44* mWorldm_Aligned; PxU32 mFlags; SweepUnlimitedCallback mCallback; void* mUserData; bool mNodeSorting; }; class LeafFunction_SphereSweepCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(SphereSweepParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triSphereSweep(params, primIndex, params->mNodeSorting)) { // PT: TODO: in this version we must compute the impact data immediately, // which is a terrible idea in general, but I'm not sure what else I can do. SweepHit hit; const bool b = computeImpactDataT<ImpactFunctionSphere>(params->mSphere, params->mDir, &hit, params, params->mWorldm_Aligned, (params->mFlags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (params->mFlags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); PX_ASSERT(b); PX_UNUSED(b); reportUnlimitedCallbackHit(params, hit); } primIndex++; }while(nbToGo--); return 0; } }; } // PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB(). void BV4_SphereSweepCB(const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); SphereSweepParamsCB Params; Params.mSphere = sphere; Params.mDir = dir; Params.mWorldm_Aligned = worldm_Aligned; Params.mFlags = flags; Params.mCallback = callback; Params.mUserData = userData; Params.mMaxDist = maxDist; Params.mNodeSorting = nodeSorting; setupSphereParams(&Params, sphere, dir, maxDist, &tree, worldm_Aligned, mesh, flags); PX_ASSERT(!Params.mEarlyExit); if(tree.mNodes) { if(nodeSorting) processStreamRayOrdered<1, LeafFunction_SphereSweepCB>(tree, &Params); else processStreamRayNoOrder<1, LeafFunction_SphereSweepCB>(tree, &Params); } else doBruteForceTests<LeafFunction_SphereSweepCB, LeafFunction_SphereSweepCB>(mesh->getNbTriangles(), &Params); } // Old box sweep callback version, using sphere code namespace { struct BoxSweepParamsCB : SphereSweepParams { MeshSweepCallback mCallback; void* mUserData; }; class ExLeafTestSweepCB { public: static PX_FORCE_INLINE void doLeafTest(BoxSweepParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); { // const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; float dist = params->mStabbedFace.mDistance; if((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], primIndex, /*vrefs,*/ dist)) return; if(dist<params->mStabbedFace.mDistance) { params->mStabbedFace.mDistance = dist; #ifndef GU_BV4_USE_SLABS setupRayData(params, dist, params->mOrigin_Padded, params->mLocalDir_Padded); #endif } } primIndex++; }while(nbToGo--); } }; } void BV4_GenericSweepCB_Old(const PxVec3& origin, const PxVec3& extents, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshSweepCallback callback, void* userData) { BoxSweepParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; Params.mOriginalExtents_Padded = extents; Params.mStabbedFace.mTriangleID = PX_INVALID_U32; Params.mStabbedFace.mDistance = maxDist; computeLocalRay(Params.mLocalDir_Padded, Params.mOrigin_Padded, dir, origin, worldm_Aligned); #ifndef GU_BV4_USE_SLABS setupRayData(&Params, maxDist, Params.mOrigin_Padded, Params.mLocalDir_Padded); #endif const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); setupMeshPointersAndQuantizedCoeffs(&Params, mesh, &tree); if(tree.mNodes) processStreamRayOrdered<1, ExLeafTestSweepCB>(tree, &Params); else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); ExLeafTestSweepCB::doLeafTest(&Params, nbTris); } }
13,115
C++
32.459184
255
0.749523
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_KajiyaOrdered.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_SLABS_KAJIYA_ORDERED_H #define GU_BV4_SLABS_KAJIYA_ORDERED_H #include "GuBVConstants.h" #ifdef REMOVED // Kajiya + PNS template<const int inflateT, class LeafTestT, class ParamsT> static void BV4_ProcessStreamKajiyaOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; #ifdef BV4_SLABS_SORT const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; #endif #ifdef BV4_SLABS_FIX BV4_ALIGN16(float distances4[4]); #endif /// Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ; if(inflateT) { Vec4V fattenAABBs4 = V4LoadU_Safe(&params->mOriginalExtents_Padded.x); fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap fattenAABBsX = V4SplatElement<0>(fattenAABBs4); fattenAABBsY = V4SplatElement<1>(fattenAABBs4); fattenAABBsZ = V4SplatElement<2>(fattenAABBs4); } /// SLABS_INIT #ifdef GU_BV4_QUANTIZED_TREE const Vec4V minCoeffV = V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x); const Vec4V maxCoeffV = V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x); const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV); const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV); const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV); const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV); const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV); const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV); #endif do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node); #ifdef GU_BV4_QUANTIZED_TREE Vec4V minx4a; Vec4V maxx4a; OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV) Vec4V miny4a; Vec4V maxy4a; OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV) Vec4V minz4a; Vec4V maxz4a; OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV) #else Vec4V minx4a = V4LoadA(tn->mMinX); Vec4V miny4a = V4LoadA(tn->mMinY); Vec4V minz4a = V4LoadA(tn->mMinZ); Vec4V maxx4a = V4LoadA(tn->mMaxX); Vec4V maxy4a = V4LoadA(tn->mMaxY); Vec4V maxz4a = V4LoadA(tn->mMaxZ); #endif if(inflateT) { maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ); minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ); } SLABS_TEST #ifdef BV4_SLABS_FIX if(inflateT) V4StoreA(maxOfNeasa, &distances4[0]); #endif SLABS_TEST2 #ifdef BV4_SLABS_SORT #ifdef BV4_SLABS_FIX // PT: for some unknown reason the Linux/OSX compilers fail to understand this version /* #define DO_LEAF_TEST(x) \ { \ if(!inflateT) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } \ else \ { \ if(distances4[x]<params->mStabbedFace.mDistance) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } \ } \ }*/ // PT: TODO: check that this version compiles to the same code as above. Redo benchmarks. #define DO_LEAF_TEST(x) \ { \ if(!inflateT || distances4[x]<params->mStabbedFace.mDistance + GU_EPSILON_SAME_DISTANCE) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } \ } #else #define DO_LEAF_TEST(x) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } #endif PxU32 code2 = 0; const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) SLABS_PNS #else #define DO_LEAF_TEST(x) \ {if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ stack[nb++] = tn->getChildData(x); \ }} const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) #endif }while(nb); } #undef DO_LEAF_TEST #endif #ifdef BV4_SLABS_SORT #ifdef BV4_SLABS_FIX // PT: for some unknown reason the Linux/OSX compilers fail to understand this version /* #define DO_LEAF_TEST(x) \ { \ if(!inflateT) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } \ else \ { \ if(distances4[x]<params->mStabbedFace.mDistance) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; \ } \ } \ } \ }*/ // PT: TODO: check that this version compiles to the same code as above. Redo benchmarks. #define DO_LEAF_TEST(x) \ { \ if(!inflateT || distances4[x]<params->mStabbedFace.mDistance + GU_EPSILON_SAME_DISTANCE) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; nbHits++; \ } \ } \ } #else #define DO_LEAF_TEST(x) \ { \ if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ code2 |= 1<<x; nbHits++; \ } \ } #endif #else #define DO_LEAF_TEST(x) \ {if(tn->isLeaf(x)) \ { \ LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \ maxT4 = V4Load(params->mStabbedFace.mDistance); \ } \ else \ { \ stack[nb++] = tn->getChildData(x); \ }} #endif // Kajiya + PNS template<const int inflateT, class LeafTestT, class ParamsT> static void BV4_ProcessStreamKajiyaOrderedQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; #ifdef BV4_SLABS_SORT const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; #endif #ifdef BV4_SLABS_FIX BV4_ALIGN16(float distances4[4]); #endif /// Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ; if(inflateT) { Vec4V fattenAABBs4 = V4LoadU_Safe(&params->mOriginalExtents_Padded.x); fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap fattenAABBsX = V4SplatElement<0>(fattenAABBs4); fattenAABBsY = V4SplatElement<1>(fattenAABBs4); fattenAABBsZ = V4SplatElement<2>(fattenAABBs4); } /// SLABS_INIT const Vec4V minCoeffV = V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x); const Vec4V maxCoeffV = V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x); const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV); const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV); const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV); const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV); const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV); const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV); do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node); Vec4V minx4a; Vec4V maxx4a; OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV) Vec4V miny4a; Vec4V maxy4a; OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV) Vec4V minz4a; Vec4V maxz4a; OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV) if(inflateT) { maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ); minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ); } SLABS_TEST #ifdef BV4_SLABS_FIX if(inflateT) V4StoreA(maxOfNeasa, &distances4[0]); #endif SLABS_TEST2 #ifdef BV4_SLABS_SORT PxU32 code2 = 0; PxU32 nbHits = 0; const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) //SLABS_PNS if(nbHits==1) { PNS_BLOCK3(0,1,2,3) } else { SLABS_PNS } #else const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) #endif }while(nb); } // Kajiya + PNS template<const int inflateT, class LeafTestT, class ParamsT> static void BV4_ProcessStreamKajiyaOrderedNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedNQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; #ifdef BV4_SLABS_SORT const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; #endif #ifdef BV4_SLABS_FIX BV4_ALIGN16(float distances4[4]); #endif /// Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ; if(inflateT) { Vec4V fattenAABBs4 = V4LoadU_Safe(&params->mOriginalExtents_Padded.x); fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap fattenAABBsX = V4SplatElement<0>(fattenAABBs4); fattenAABBsY = V4SplatElement<1>(fattenAABBs4); fattenAABBsZ = V4SplatElement<2>(fattenAABBs4); } /// SLABS_INIT do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node); Vec4V minx4a = V4LoadA(tn->mMinX); Vec4V miny4a = V4LoadA(tn->mMinY); Vec4V minz4a = V4LoadA(tn->mMinZ); Vec4V maxx4a = V4LoadA(tn->mMaxX); Vec4V maxy4a = V4LoadA(tn->mMaxY); Vec4V maxz4a = V4LoadA(tn->mMaxZ); if(inflateT) { maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ); minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ); } SLABS_TEST #ifdef BV4_SLABS_FIX if(inflateT) V4StoreA(maxOfNeasa, &distances4[0]); #endif SLABS_TEST2 #ifdef BV4_SLABS_SORT PxU32 code2 = 0; PxU32 nbHits = 0; const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) //SLABS_PNS if(nbHits==1) { PNS_BLOCK3(0,1,2,3) } else { SLABS_PNS } #else const PxU32 nodeType = getChildType(childData); if(!(code&8) && nodeType>1) DO_LEAF_TEST(3) if(!(code&4) && nodeType>0) DO_LEAF_TEST(2) if(!(code&2)) DO_LEAF_TEST(1) if(!(code&1)) DO_LEAF_TEST(0) #endif }while(nb); } #undef DO_LEAF_TEST #endif // GU_BV4_SLABS_KAJIYA_ORDERED_H
16,434
C
27.782837
142
0.592552
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_SwizzledOrdered.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_SLABS_SWIZZLED_ORDERED_H #define GU_BV4_SLABS_SWIZZLED_ORDERED_H // Generic + PNS /* template<class LeafTestT, class ParamsT> static void BV4_ProcessStreamSwizzledOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU32 nodeType = getChildType(childData); const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node); PxU32 code2 = 0; BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 0>(code2, tn, params); BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 1>(code2, tn, params); if(nodeType>0) BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 2>(code2, tn, params); if(nodeType>1) BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 3>(code2, tn, params); SLABS_PNS }while(nb); }*/ // Generic + PNS template<class LeafTestT, class ParamsT> static void BV4_ProcessStreamSwizzledOrderedQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU32 nodeType = getChildType(childData); const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node); PxU32 code2 = 0; BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 0>(code2, tn, params); BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 1>(code2, tn, params); if(nodeType>0) BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 2>(code2, tn, params); if(nodeType>1) BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 3>(code2, tn, params); SLABS_PNS }while(nb); } // Generic + PNS template<class LeafTestT, class ParamsT> static void BV4_ProcessStreamSwizzledOrderedNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedNQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; const PxU32* tmp = reinterpret_cast<const PxU32*>(&params->mLocalDir_Padded); const PxU32 X = tmp[0]>>31; const PxU32 Y = tmp[1]>>31; const PxU32 Z = tmp[2]>>31; // const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31; // const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31; // const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31; const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2)); const PxU32 dirMask = 1u<<bitIndex; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const PxU32 nodeType = getChildType(childData); const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node); PxU32 code2 = 0; BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 0>(code2, tn, params); BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 1>(code2, tn, params); if(nodeType>0) BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 2>(code2, tn, params); if(nodeType>1) BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 3>(code2, tn, params); SLABS_PNS }while(nb); } #endif // GU_BV4_SLABS_SWIZZLED_ORDERED_H
5,831
C
36.146497
132
0.716344
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxOverlap.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" using namespace physx; using namespace Gu; using namespace physx::aos; #include "GuInternal.h" #include "GuDistancePointSegment.h" #include "GuIntersectionCapsuleTriangle.h" #include "GuBV4_BoxOverlap_Internal.h" #include "GuBV4_BoxBoxOverlapTest.h" // Box overlap any struct OBBParams : OBBTestParams { const IndTri32* PX_RESTRICT mTris32; const IndTri16* PX_RESTRICT mTris16; const PxVec3* PX_RESTRICT mVerts; PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space }; struct OBBTetParams : OBBTestParams { const IndTetrahedron32* PX_RESTRICT mTets32; const IndTetrahedron16* PX_RESTRICT mTets16; const PxVec3* PX_RESTRICT mVerts; PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space }; // PT: TODO: this used to be inlined so we lost some perf by moving to PhysX's version. Revisit. (TA34704) PxIntBool intersectTriangleBoxBV4(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents); namespace { class LeafFunction_BoxOverlapAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); if(intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) return 1; primIndex++; }while(nbToGo--); return 0; } }; } template<class ParamsT> static PX_FORCE_INLINE void setupBoxParams(ParamsT* PX_RESTRICT params, const Box& localBox, const BV4Tree* PX_RESTRICT tree, const SourceMesh* PX_RESTRICT mesh) { invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox); params->mTBoxToModel_PaddedAligned = localBox.center; setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); params->precomputeBoxData(localBox.extents, &localBox.rot); } template<class ParamsT> static PX_FORCE_INLINE void setupBoxParams(ParamsT* PX_RESTRICT params, const Box& localBox, const BV4Tree* PX_RESTRICT tree, const TetrahedronSourceMesh* PX_RESTRICT mesh) { invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox); params->mTBoxToModel_PaddedAligned = localBox.center; setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); params->precomputeBoxData(localBox.extents, &localBox.rot); } /////////////////////////////////////////////////////////////////////////////// #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamNoOrder_OBBOBB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_SwizzledNoOrder.h" #endif #define GU_BV4_PROCESS_STREAM_NO_ORDER #include "GuBV4_Internal.h" PxIntBool BV4_OverlapBoxAny(const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned) { const SourceMesh* PX_RESTRICT mesh =static_cast<const SourceMesh*>(tree.mMeshInterface); Box localBox; computeLocalBox(localBox, box, worldm_Aligned); OBBParams Params; setupBoxParams(&Params, localBox, &tree, mesh); if(tree.mNodes) return processStreamNoOrder<LeafFunction_BoxOverlapAny>(tree, &Params); else { const PxU32 nbTris = mesh->getNbPrimitives(); PX_ASSERT(nbTris<16); return LeafFunction_BoxOverlapAny::doLeafTest(&Params, nbTris); } } // Box overlap all struct OBBParamsAll : OBBParams { PxU32 mNbHits; PxU32 mMaxNbHits; PxU32* mHits; }; namespace { class LeafFunction_BoxOverlapAll { public: static PX_FORCE_INLINE PxIntBool doLeafTest(OBBParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); if(intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { OBBParamsAll* ParamsAll = static_cast<OBBParamsAll*>(params); if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits) return 1; ParamsAll->mHits[ParamsAll->mNbHits] = primIndex; ParamsAll->mNbHits++; } primIndex++; }while(nbToGo--); return 0; } }; } PxU32 BV4_OverlapBoxAll(const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); Box localBox; computeLocalBox(localBox, box, worldm_Aligned); OBBParamsAll Params; Params.mNbHits = 0; Params.mMaxNbHits = size; Params.mHits = results; setupBoxParams(&Params, localBox, &tree, mesh); if(tree.mNodes) overflow = processStreamNoOrder<LeafFunction_BoxOverlapAll>(tree, &Params)!=0; else { const PxU32 nbTris = mesh->getNbPrimitives(); PX_ASSERT(nbTris<16); overflow = LeafFunction_BoxOverlapAll::doLeafTest(&Params, nbTris)!=0; } return Params.mNbHits; } // Box overlap - callback version struct OBBParamsCB : OBBParams { MeshOverlapCallback mCallback; void* mUserData; }; struct OBBTetParamsCB : OBBTetParams { TetMeshOverlapCallback mCallback; void* mUserData; }; namespace { class LeafFunction_BoxOverlapCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], primIndex, vrefs)) return 1; } primIndex++; }while(nbToGo--); return 0; } static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBTetParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2, VRef3; getVertexReferences(VRef0, VRef1, VRef2, VRef3, primIndex, params->mTets32, params->mTets16); if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3}; if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs)) return 1; } if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef3], params->mVerts[VRef1], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 }; if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs)) return 1; } if (intersectTriangleBoxBV4(params->mVerts[VRef1], params->mVerts[VRef3], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 }; if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs)) return 1; } if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef3], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned)) { const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 }; if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs)) return 1; } primIndex++; } while (nbToGo--); return 0; } }; } void BV4_OverlapBoxCB(const Box& localBox, const BV4Tree& tree, MeshOverlapCallback callback, void* userData) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); OBBParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupBoxParams(&Params, localBox, &tree, mesh); if(tree.mNodes) processStreamNoOrder<LeafFunction_BoxOverlapCB>(tree, &Params); else { const PxU32 nbTris = mesh->getNbPrimitives(); PX_ASSERT(nbTris<16); LeafFunction_BoxOverlapCB::doLeafTest(&Params, nbTris); } } void BV4_OverlapBoxCB(const Box& localBox, const BV4Tree& tree, TetMeshOverlapCallback callback, void* userData) { const TetrahedronSourceMesh* PX_RESTRICT mesh = static_cast<TetrahedronSourceMesh*>(tree.mMeshInterface); OBBTetParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupBoxParams(&Params, localBox, &tree, mesh); if (tree.mNodes) processStreamNoOrder<LeafFunction_BoxOverlapCB>(tree, &Params); else { const PxU32 nbTetrahedrons = mesh->getNbTetrahedrons(); PX_ASSERT(nbTetrahedrons<16); LeafFunction_BoxOverlapCB::doLeafTest(&Params, nbTetrahedrons); } } // Capsule overlap any struct CapsuleParamsAny : OBBParams { Capsule mLocalCapsule; // Capsule in mesh space CapsuleTriangleOverlapData mData; }; // PT: TODO: try to refactor this one with the PhysX version (TA34704) static bool CapsuleVsTriangle_SAT(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const CapsuleParamsAny* PX_RESTRICT params) { // PX_ASSERT(capsule.p0!=capsule.p1); { const PxReal d2 = distancePointSegmentSquaredInternal(params->mLocalCapsule.p0, params->mData.mCapsuleDir, p0); if(d2<=params->mLocalCapsule.radius*params->mLocalCapsule.radius) return 1; } const PxVec3 N = (p0 - p1).cross(p0 - p2); if(!testAxis(p0, p1, p2, params->mLocalCapsule, N)) return 0; const float BDotB = params->mData.mBDotB; const float oneOverBDotB = params->mData.mOneOverBDotB; const PxVec3& capP0 = params->mLocalCapsule.p0; const PxVec3& capDir = params->mData.mCapsuleDir; if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p0, p1 - p0, capP0, capDir, BDotB, oneOverBDotB))) return 0; if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p1, p2 - p1, capP0, capDir, BDotB, oneOverBDotB))) return 0; if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p2, p0 - p2, capP0, capDir, BDotB, oneOverBDotB))) return 0; return 1; } static PxIntBool PX_FORCE_INLINE capsuleTriangle(const CapsuleParamsAny* PX_RESTRICT params, PxU32 primIndex) { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); return CapsuleVsTriangle_SAT(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params); } namespace { class LeafFunction_CapsuleOverlapAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(capsuleTriangle(static_cast<const CapsuleParamsAny*>(params), primIndex)) return 1; primIndex++; }while(nbToGo--); return 0; } }; } template<class ParamsT> static PX_FORCE_INLINE void setupCapsuleParams(ParamsT* PX_RESTRICT params, const Capsule& capsule, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh) { computeLocalCapsule(params->mLocalCapsule, capsule, worldm_Aligned); params->mData.init(params->mLocalCapsule); Box localBox; computeBoxAroundCapsule(params->mLocalCapsule, localBox); setupBoxParams(params, localBox, tree, mesh); } PxIntBool BV4_OverlapCapsuleAny(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); CapsuleParamsAny Params; setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh); if(tree.mNodes) return processStreamNoOrder<LeafFunction_CapsuleOverlapAny>(tree, &Params); else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); return LeafFunction_CapsuleOverlapAny::doLeafTest(&Params, nbTris); } } // Capsule overlap all struct CapsuleParamsAll : CapsuleParamsAny { PxU32 mNbHits; PxU32 mMaxNbHits; PxU32* mHits; }; namespace { class LeafFunction_CapsuleOverlapAll { public: static PX_FORCE_INLINE PxIntBool doLeafTest(OBBParams* PX_RESTRICT params, PxU32 primIndex) { CapsuleParamsAll* ParamsAll = static_cast<CapsuleParamsAll*>(params); PxU32 nbToGo = getNbPrimitives(primIndex); do { if(capsuleTriangle(ParamsAll, primIndex)) { if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits) return 1; ParamsAll->mHits[ParamsAll->mNbHits] = primIndex; ParamsAll->mNbHits++; } primIndex++; }while(nbToGo--); return 0; } }; } PxU32 BV4_OverlapCapsuleAll(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); CapsuleParamsAll Params; Params.mNbHits = 0; Params.mMaxNbHits = size; Params.mHits = results; setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh); if(tree.mNodes) overflow = processStreamNoOrder<LeafFunction_CapsuleOverlapAll>(tree, &Params)!=0; else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); overflow = LeafFunction_CapsuleOverlapAll::doLeafTest(&Params, nbTris)!=0; } return Params.mNbHits; } // Capsule overlap - callback version struct CapsuleParamsCB : CapsuleParamsAny { MeshOverlapCallback mCallback; void* mUserData; }; namespace { class LeafFunction_CapsuleOverlapCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const CapsuleParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; if(CapsuleVsTriangle_SAT(p0, p1, p2, params)) { const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; if((params->mCallback)(params->mUserData, p0, p1, p2, primIndex, vrefs)) return 1; } primIndex++; }while(nbToGo--); return 0; } }; } // PT: this one is currently not used void BV4_OverlapCapsuleCB(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); CapsuleParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh); if(tree.mNodes) processStreamNoOrder<LeafFunction_CapsuleOverlapCB>(tree, &Params); else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); LeafFunction_CapsuleOverlapCB::doLeafTest(&Params, nbTris); } }
17,269
C++
30.688073
211
0.742487
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Common.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_COMMON_H #define GU_BV4_COMMON_H #include "foundation/PxMat44.h" #include "geometry/PxTriangle.h" #include "GuBox.h" #include "GuSphere.h" #include "GuCapsule.h" #include "GuBV4.h" #define BV4_ALIGN16(x) PX_ALIGN_PREFIX(16) x PX_ALIGN_SUFFIX(16) namespace physx { namespace Gu { enum QueryModifierFlag { QUERY_MODIFIER_ANY_HIT = (1<<0), QUERY_MODIFIER_DOUBLE_SIDED = (1<<1), QUERY_MODIFIER_MESH_BOTH_SIDES = (1<<2) }; template<class ParamsT> PX_FORCE_INLINE void setupParamsFlags(ParamsT* PX_RESTRICT params, PxU32 flags) { params->mBackfaceCulling = (flags & (QUERY_MODIFIER_DOUBLE_SIDED|QUERY_MODIFIER_MESH_BOTH_SIDES)) ? 0 : 1u; params->mEarlyExit = flags & QUERY_MODIFIER_ANY_HIT; } enum HitCode { HIT_NONE = 0, //!< No hit HIT_CONTINUE = 1, //!< Hit found, but keep looking for closer one HIT_EXIT = 2 //!< Hit found, you can early-exit (raycast any) }; class RaycastHitInternal : public physx::PxUserAllocated { public: PX_FORCE_INLINE RaycastHitInternal() {} PX_FORCE_INLINE ~RaycastHitInternal() {} float mDistance; PxU32 mTriangleID; }; class SweepHit : public physx::PxUserAllocated { public: PX_FORCE_INLINE SweepHit() {} PX_FORCE_INLINE ~SweepHit() {} PxU32 mTriangleID; //!< Index of touched face float mDistance; //!< Impact distance PxVec3 mPos; PxVec3 mNormal; }; typedef HitCode (*MeshRayCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, float dist, float u, float v); typedef bool (*MeshOverlapCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* vertexIndices); typedef bool (*TetMeshOverlapCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& p3, PxU32 tetIndex, const PxU32* vertexIndices); typedef bool (*MeshSweepCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, /*const PxU32* vertexIndices,*/ float& dist); typedef bool (*SweepUnlimitedCallback) (void* userData, const SweepHit& hit); template<class ParamsT> PX_FORCE_INLINE void reportUnlimitedCallbackHit(ParamsT* PX_RESTRICT params, const SweepHit& hit) { // PT: we can't reuse the MeshSweepCallback here since it's designed for doing the sweep test inside the callback // (in the user's code) rather than inside the traversal code. So we use the SweepUnlimitedCallback instead to // report the already fully computed hit to users. // PT: TODO: this may not be very efficient, since computing the full hit is expensive. If we use this codepath // to implement the Epic Tweak, the resulting code will not be optimal. (params->mCallback)(params->mUserData, hit); // PT: the existing traversal code already shrunk the ray. For real "sweep all" calls we must undo that by reseting the max dist. // (params->mStabbedFace.mDistance is used in computeImpactDataX code, so we need it before that point - we can't simply avoid // modifying this value before this point). if(!params->mNodeSorting) params->mStabbedFace.mDistance = params->mMaxDist; } PX_FORCE_INLINE void invertPRMatrix(PxMat44* PX_RESTRICT dest, const PxMat44* PX_RESTRICT src) { const float m30 = src->column3.x; const float m31 = src->column3.y; const float m32 = src->column3.z; const float m00 = src->column0.x; const float m01 = src->column0.y; const float m02 = src->column0.z; dest->column0.x = m00; dest->column1.x = m01; dest->column2.x = m02; dest->column3.x = -(m30*m00 + m31*m01 + m32*m02); const float m10 = src->column1.x; const float m11 = src->column1.y; const float m12 = src->column1.z; dest->column0.y = m10; dest->column1.y = m11; dest->column2.y = m12; dest->column3.y = -(m30*m10 + m31*m11 + m32*m12); const float m20 = src->column2.x; const float m21 = src->column2.y; const float m22 = src->column2.z; dest->column0.z = m20; dest->column1.z = m21; dest->column2.z = m22; dest->column3.z = -(m30*m20 + m31*m21 + m32*m22); dest->column0.w = 0.0f; dest->column1.w = 0.0f; dest->column2.w = 0.0f; dest->column3.w = 1.0f; } PX_FORCE_INLINE void invertBoxMatrix(PxMat33& m, PxVec3& t, const Gu::Box& box) { const float m30 = box.center.x; const float m31 = box.center.y; const float m32 = box.center.z; const float m00 = box.rot.column0.x; const float m01 = box.rot.column0.y; const float m02 = box.rot.column0.z; m.column0.x = m00; m.column1.x = m01; m.column2.x = m02; t.x = -(m30*m00 + m31*m01 + m32*m02); const float m10 = box.rot.column1.x; const float m11 = box.rot.column1.y; const float m12 = box.rot.column1.z; m.column0.y = m10; m.column1.y = m11; m.column2.y = m12; t.y = -(m30*m10 + m31*m11 + m32*m12); const float m20 = box.rot.column2.x; const float m21 = box.rot.column2.y; const float m22 = box.rot.column2.z; m.column0.z = m20; m.column1.z = m21; m.column2.z = m22; t.z = -(m30*m20 + m31*m21 + m32*m22); } #ifdef GU_BV4_USE_SLABS // PT: this class moved here to make things compile with pedantic compilers. // PT: now duplicated because not easy to do otherwise struct BVDataSwizzledQ : public physx::PxUserAllocated { struct Data { PxI16 mMin; //!< Quantized min PxI16 mMax; //!< Quantized max }; Data mX[4]; Data mY[4]; Data mZ[4]; PxU32 mData[4]; PX_FORCE_INLINE PxU32 isLeaf(PxU32 i) const { return mData[i]&1; } PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return mData[i]>>1; } PX_FORCE_INLINE PxU32 getChildOffset(PxU32 i) const { return mData[i]>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; } PX_FORCE_INLINE PxU32 getChildType(PxU32 i) const { return (mData[i]>>1)&3; } PX_FORCE_INLINE PxU32 getChildData(PxU32 i) const { return mData[i]; } PX_FORCE_INLINE PxU32 decodePNSNoShift(PxU32 i) const { return mData[i]; } }; struct BVDataSwizzledNQ : public physx::PxUserAllocated { float mMinX[4]; float mMinY[4]; float mMinZ[4]; float mMaxX[4]; float mMaxY[4]; float mMaxZ[4]; PxU32 mData[4]; PX_FORCE_INLINE PxU32 isLeaf(PxU32 i) const { return mData[i]&1; } PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return mData[i]>>1; } PX_FORCE_INLINE PxU32 getChildOffset(PxU32 i) const { return mData[i]>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; } PX_FORCE_INLINE PxU32 getChildType(PxU32 i) const { return (mData[i]>>1)&3; } PX_FORCE_INLINE PxU32 getChildData(PxU32 i) const { return mData[i]; } PX_FORCE_INLINE PxU32 decodePNSNoShift(PxU32 i) const { return mData[i]; } }; #else #define SSE_CONST4(name, val) static const __declspec(align(16)) PxU32 name[4] = { (val), (val), (val), (val) } #define SSE_CONST(name) *(const __m128i *)&name #define SSE_CONSTF(name) *(const __m128 *)&name #endif PX_FORCE_INLINE PxU32 getNbPrimitives(PxU32& primIndex) { PxU32 NbToGo = (primIndex & 15)-1; primIndex>>=4; return NbToGo; } template<class ParamsT> PX_FORCE_INLINE void setupMeshPointersAndQuantizedCoeffs(ParamsT* PX_RESTRICT params, const SourceMesh* PX_RESTRICT mesh, const BV4Tree* PX_RESTRICT tree) { using namespace physx::aos; params->mTris32 = mesh->getTris32(); params->mTris16 = mesh->getTris16(); params->mVerts = mesh->getVerts(); V4StoreA_Safe(V4LoadU_Safe(&tree->mCenterOrMinCoeff.x), &params->mCenterOrMinCoeff_PaddedAligned.x); V4StoreA_Safe(V4LoadU_Safe(&tree->mExtentsOrMaxCoeff.x), &params->mExtentsOrMaxCoeff_PaddedAligned.x); } template<class ParamsT> PX_FORCE_INLINE void setupMeshPointersAndQuantizedCoeffs(ParamsT* PX_RESTRICT params, const TetrahedronSourceMesh* PX_RESTRICT mesh, const BV4Tree* PX_RESTRICT tree) { params->mTets32 = mesh->getTetrahedrons32(); params->mTets16 = mesh->getTetrahedrons16(); params->mVerts = mesh->getVerts(); V4StoreA_Safe(V4LoadU_Safe(&tree->mCenterOrMinCoeff.x), &params->mCenterOrMinCoeff_PaddedAligned.x); V4StoreA_Safe(V4LoadU_Safe(&tree->mExtentsOrMaxCoeff.x), &params->mExtentsOrMaxCoeff_PaddedAligned.x); } PX_FORCE_INLINE void rotateBox(Gu::Box& dst, const PxMat44& m, const Gu::Box& src) { // The extents remain constant dst.extents = src.extents; // The center gets x-formed dst.center = m.transform(src.center); // Combine rotations // PT: TODO: revisit.. this is awkward... grab 3x3 part of 4x4 matrix (TA34704) const PxMat33 tmp( PxVec3(m.column0.x, m.column0.y, m.column0.z), PxVec3(m.column1.x, m.column1.y, m.column1.z), PxVec3(m.column2.x, m.column2.y, m.column2.z)); dst.rot = tmp * src.rot; } PX_FORCE_INLINE PxVec3 inverseRotate(const PxMat44* PX_RESTRICT src, const PxVec3& p) { const float m00 = src->column0.x; const float m01 = src->column0.y; const float m02 = src->column0.z; const float m10 = src->column1.x; const float m11 = src->column1.y; const float m12 = src->column1.z; const float m20 = src->column2.x; const float m21 = src->column2.y; const float m22 = src->column2.z; return PxVec3( m00*p.x + m01*p.y + m02*p.z, m10*p.x + m11*p.y + m12*p.z, m20*p.x + m21*p.y + m22*p.z); } PX_FORCE_INLINE PxVec3 inverseTransform(const PxMat44* PX_RESTRICT src, const PxVec3& p) { const float m30 = src->column3.x; const float m31 = src->column3.y; const float m32 = src->column3.z; const float m00 = src->column0.x; const float m01 = src->column0.y; const float m02 = src->column0.z; const float m10 = src->column1.x; const float m11 = src->column1.y; const float m12 = src->column1.z; const float m20 = src->column2.x; const float m21 = src->column2.y; const float m22 = src->column2.z; return PxVec3( m00*p.x + m01*p.y + m02*p.z -(m30*m00 + m31*m01 + m32*m02), m10*p.x + m11*p.y + m12*p.z -(m30*m10 + m31*m11 + m32*m12), m20*p.x + m21*p.y + m22*p.z -(m30*m20 + m31*m21 + m32*m22)); } PX_FORCE_INLINE void computeLocalRay(PxVec3& localDir, PxVec3& localOrigin, const PxVec3& dir, const PxVec3& origin, const PxMat44* PX_RESTRICT worldm_Aligned) { if(worldm_Aligned) { localDir = inverseRotate(worldm_Aligned, dir); localOrigin = inverseTransform(worldm_Aligned, origin); } else { localDir = dir; localOrigin = origin; } } PX_FORCE_INLINE void computeLocalSphere(float& radius2, PxVec3& local_center, const Sphere& sphere, const PxMat44* PX_RESTRICT worldm_Aligned) { radius2 = sphere.radius * sphere.radius; if(worldm_Aligned) { local_center = inverseTransform(worldm_Aligned, sphere.center); } else { local_center = sphere.center; } } PX_FORCE_INLINE void computeLocalCapsule(Capsule& localCapsule, const Capsule& capsule, const PxMat44* PX_RESTRICT worldm_Aligned) { localCapsule.radius = capsule.radius; if(worldm_Aligned) { localCapsule.p0 = inverseTransform(worldm_Aligned, capsule.p0); localCapsule.p1 = inverseTransform(worldm_Aligned, capsule.p1); } else { localCapsule.p0 = capsule.p0; localCapsule.p1 = capsule.p1; } } PX_FORCE_INLINE void computeLocalBox(Gu::Box& dst, const Gu::Box& src, const PxMat44* PX_RESTRICT worldm_Aligned) { if(worldm_Aligned) { PxMat44 invWorldM; invertPRMatrix(&invWorldM, worldm_Aligned); rotateBox(dst, invWorldM, src); } else { dst = src; // PT: TODO: check asm for operator= (TA34704) } } template<class ImpactFunctionT, class ShapeT, class ParamsT> static PX_FORCE_INLINE bool computeImpactDataT(const ShapeT& shape, const PxVec3& dir, SweepHit* PX_RESTRICT hit, const ParamsT* PX_RESTRICT params, const PxMat44* PX_RESTRICT worldm, bool isDoubleSided, bool meshBothSides) { if(params->mStabbedFace.mTriangleID==PX_INVALID_U32) return false; // We didn't touch any triangle if(hit) { const float t = params->getReportDistance(); hit->mTriangleID = params->mStabbedFace.mTriangleID; hit->mDistance = t; if(t==0.0f) { hit->mPos = PxVec3(0.0f); hit->mNormal = -dir; } else { // PT: TODO: we shouldn't compute impact in world space, and in fact moving this to local space is necessary if we want to reuse this for box-sweeps (TA34704) PxTrianglePadded WP; if(worldm) { WP.verts[0] = worldm->transform(params->mP0); WP.verts[1] = worldm->transform(params->mP1); WP.verts[2] = worldm->transform(params->mP2); } else { WP.verts[0] = params->mP0; WP.verts[1] = params->mP1; WP.verts[2] = params->mP2; } PxVec3 impactNormal; ImpactFunctionT::computeImpact(hit->mPos, impactNormal, shape, dir, t, WP); // PT: by design, returned normal is opposed to the sweep direction. if(shouldFlipNormal(impactNormal, meshBothSides, isDoubleSided, params->mBestTriNormal, dir)) impactNormal = -impactNormal; hit->mNormal = impactNormal; } } return true; } // PT: we don't create a structure for small meshes with just a few triangles. We use brute-force tests on these. template<class LeafFunction_AnyT, class LeafFunction_ClosestT, class ParamsT> void doBruteForceTests(PxU32 nbTris, ParamsT* PX_RESTRICT params) { PX_ASSERT(nbTris<16); if(params->mEarlyExit) LeafFunction_AnyT::doLeafTest(params, nbTris); else LeafFunction_ClosestT::doLeafTest(params, nbTris); } #ifndef GU_BV4_USE_SLABS template<class ParamsT> PX_FORCE_INLINE void setupRayData(ParamsT* PX_RESTRICT params, float max_dist, const PxVec3& origin, const PxVec3& dir) { const float Half = 0.5f*max_dist; const FloatV HalfV = FLoad(Half); const Vec4V DataV = V4Scale(V4LoadU(&dir.x), HalfV); const Vec4V Data2V = V4Add(V4LoadU(&origin.x), DataV); const Vec4V FDirV = V4Abs(DataV); V4StoreA_Safe(DataV, &params->mData_PaddedAligned.x); V4StoreA_Safe(Data2V, &params->mData2_PaddedAligned.x); V4StoreA_Safe(FDirV, &params->mFDir_PaddedAligned.x); } #endif } } #endif // GU_BV4_COMMON_H
15,649
C
33.170306
224
0.695891
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Build.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_BUILD_H #define GU_BV4_BUILD_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBounds3.h" #include "GuBV4Settings.h" namespace physx { namespace Gu { class BV4Tree; class SourceMeshBase; // PT: TODO: refactor with SQ version (TA34704) class AABBTreeNode : public physx::PxUserAllocated { public: PX_FORCE_INLINE AABBTreeNode() : mPos(0), mNodePrimitives(NULL), mNbPrimitives(0) #ifdef GU_BV4_FILL_GAPS , mNextSplit(0) #endif { } PX_FORCE_INLINE ~AABBTreeNode() { mPos = 0; mNodePrimitives = NULL; // This was just a shortcut to the global list => no release mNbPrimitives = 0; } // Data access PX_FORCE_INLINE const PxBounds3& getAABB() const { return mBV; } PX_FORCE_INLINE const AABBTreeNode* getPos() const { return reinterpret_cast<const AABBTreeNode*>(mPos); } PX_FORCE_INLINE const AABBTreeNode* getNeg() const { const AABBTreeNode* P = getPos(); return P ? P+1 : NULL; } PX_FORCE_INLINE bool isLeaf() const { return !getPos(); } PxBounds3 mBV; // Global bounding-volume enclosing all the node-related primitives size_t mPos; // "Positive" & "Negative" children // Data access PX_FORCE_INLINE const PxU32* getPrimitives() const { return mNodePrimitives; } PX_FORCE_INLINE PxU32 getNbPrimitives() const { return mNbPrimitives; } PxU32* mNodePrimitives; //!< Node-related primitives (shortcut to a position in mIndices below) PxU32 mNbPrimitives; //!< Number of primitives for this node #ifdef GU_BV4_FILL_GAPS PxU32 mNextSplit; #endif }; typedef bool (*WalkingCallback) (const AABBTreeNode* current, PxU32 depth, void* userData); typedef bool (*WalkingDistanceCallback) (const AABBTreeNode* current, void* userData); enum BV4_BuildStrategy { BV4_SPLATTER_POINTS, BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER, BV4_SAH }; // PT: TODO: refactor with SQ version (TA34704) class BV4_AABBTree : public physx::PxUserAllocated { public: BV4_AABBTree(); ~BV4_AABBTree(); bool buildFromMesh(SourceMeshBase& mesh, PxU32 limit, BV4_BuildStrategy strategy=BV4_SPLATTER_POINTS); void release(); PX_FORCE_INLINE const PxU32* getIndices() const { return mIndices; } //!< Catch the indices PX_FORCE_INLINE PxU32 getNbNodes() const { return mTotalNbNodes; } //!< Catch the number of nodes PX_FORCE_INLINE const PxU32* getPrimitives() const { return mPool->mNodePrimitives; } PX_FORCE_INLINE PxU32 getNbPrimitives() const { return mPool->mNbPrimitives; } PX_FORCE_INLINE const AABBTreeNode* getNodes() const { return mPool; } PX_FORCE_INLINE const PxBounds3& getBV() const { return mPool->mBV; } PxU32 walk(WalkingCallback callback, void* userData) const; PxU32 walkDistance(WalkingCallback callback, WalkingDistanceCallback distancCallback, void* userData) const; private: PxU32* mIndices; //!< Indices in the app list. Indices are reorganized during build (permutation). AABBTreeNode* mPool; //!< Linear pool of nodes for complete trees. Null otherwise. [Opcode 1.3] PxU32 mTotalNbNodes; //!< Number of nodes in the tree. }; bool BuildBV4Ex(BV4Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivePerLeaf, bool quantized, BV4_BuildStrategy strategy=BV4_SPLATTER_POINTS); } // namespace Gu } #endif // GU_BV4_BUILD_H
5,236
C
41.233871
159
0.711803
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_SLABS_H #define GU_BV4_SLABS_H #include "foundation/PxFPU.h" #include "GuBV4_Common.h" #ifdef GU_BV4_USE_SLABS // PT: contains code for tree-traversal using the swizzled format. // PT: ray traversal based on Kay & Kajiya's slab intersection code, but using SIMD to do 4 ray-vs-AABB tests at a time. // PT: other (ordered or unordered) traversals just process one node at a time, similar to the non-swizzled format. #define BV4_SLABS_FIX #define BV4_SLABS_SORT #define PNS_BLOCK3(a, b, c, d) { \ if(code2 & (1<<a)) { stack[nb++] = tn->getChildData(a); } \ if(code2 & (1<<b)) { stack[nb++] = tn->getChildData(b); } \ if(code2 & (1<<c)) { stack[nb++] = tn->getChildData(c); } \ if(code2 & (1<<d)) { stack[nb++] = tn->getChildData(d); } } \ #define OPC_SLABS_GET_MIN_MAX(i) \ const VecI32V minVi = I4LoadXYZW(node->mX[i].mMin, node->mY[i].mMin, node->mZ[i].mMin, 0); \ const Vec4V minCoeffV = V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x); \ Vec4V minV = V4Mul(Vec4V_From_VecI32V(minVi), minCoeffV); \ const VecI32V maxVi = I4LoadXYZW(node->mX[i].mMax, node->mY[i].mMax, node->mZ[i].mMax, 0); \ const Vec4V maxCoeffV = V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x); \ Vec4V maxV = V4Mul(Vec4V_From_VecI32V(maxVi), maxCoeffV); \ #define OPC_SLABS_GET_CEQ(i) \ OPC_SLABS_GET_MIN_MAX(i) \ const FloatV HalfV = FLoad(0.5f); \ const Vec4V centerV = V4Scale(V4Add(maxV, minV), HalfV); \ const Vec4V extentsV = V4Scale(V4Sub(maxV, minV), HalfV); #define OPC_SLABS_GET_CE2Q(i) \ OPC_SLABS_GET_MIN_MAX(i) \ const Vec4V centerV = V4Add(maxV, minV); \ const Vec4V extentsV = V4Sub(maxV, minV); #define OPC_SLABS_GET_CENQ(i) \ const FloatV HalfV = FLoad(0.5f); \ const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f); \ const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f); \ const Vec4V centerV = V4Scale(V4Add(maxV, minV), HalfV); \ const Vec4V extentsV = V4Scale(V4Sub(maxV, minV), HalfV); #define OPC_SLABS_GET_CE2NQ(i) \ const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f); \ const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f); \ const Vec4V centerV = V4Add(maxV, minV); \ const Vec4V extentsV = V4Sub(maxV, minV); #define OPC_DEQ4(part2xV, part1xV, mMember, minCoeff, maxCoeff) \ { \ part2xV = V4LoadA(reinterpret_cast<const float*>(tn->mMember)); \ part1xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_And(VecI32V_ReinterpretFrom_Vec4V(part2xV), I4Load(0x0000ffff))); \ part1xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_RightShift(VecI32V_LeftShift(VecI32V_ReinterpretFrom_Vec4V(part1xV),16), 16)); \ part1xV = V4Mul(Vec4V_From_VecI32V(VecI32V_ReinterpretFrom_Vec4V(part1xV)), minCoeff); \ part2xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_RightShift(VecI32V_ReinterpretFrom_Vec4V(part2xV), 16)); \ part2xV = V4Mul(Vec4V_From_VecI32V(VecI32V_ReinterpretFrom_Vec4V(part2xV)), maxCoeff); \ } #define SLABS_INIT\ Vec4V maxT4 = V4Load(params->mStabbedFace.mDistance);\ const Vec4V rayP = V4LoadU_Safe(&params->mOrigin_Padded.x);\ Vec4V rayD = V4LoadU_Safe(&params->mLocalDir_Padded.x);\ const VecU32V raySign = V4U32and(VecU32V_ReinterpretFrom_Vec4V(rayD), signMask);\ const Vec4V rayDAbs = V4Abs(rayD);\ Vec4V rayInvD = Vec4V_ReinterpretFrom_VecU32V(V4U32or(raySign, VecU32V_ReinterpretFrom_Vec4V(V4Max(rayDAbs, epsFloat4))));\ rayD = rayInvD;\ rayInvD = V4RecipFast(rayInvD);\ rayInvD = V4Mul(rayInvD, V4NegMulSub(rayD, rayInvD, twos));\ const Vec4V rayPinvD = V4NegMulSub(rayInvD, rayP, zeroes);\ const Vec4V rayInvDsplatX = V4SplatElement<0>(rayInvD);\ const Vec4V rayInvDsplatY = V4SplatElement<1>(rayInvD);\ const Vec4V rayInvDsplatZ = V4SplatElement<2>(rayInvD);\ const Vec4V rayPinvDsplatX = V4SplatElement<0>(rayPinvD);\ const Vec4V rayPinvDsplatY = V4SplatElement<1>(rayPinvD);\ const Vec4V rayPinvDsplatZ = V4SplatElement<2>(rayPinvD); #define SLABS_TEST\ const Vec4V tminxa0 = V4MulAdd(minx4a, rayInvDsplatX, rayPinvDsplatX);\ const Vec4V tminya0 = V4MulAdd(miny4a, rayInvDsplatY, rayPinvDsplatY);\ const Vec4V tminza0 = V4MulAdd(minz4a, rayInvDsplatZ, rayPinvDsplatZ);\ const Vec4V tmaxxa0 = V4MulAdd(maxx4a, rayInvDsplatX, rayPinvDsplatX);\ const Vec4V tmaxya0 = V4MulAdd(maxy4a, rayInvDsplatY, rayPinvDsplatY);\ const Vec4V tmaxza0 = V4MulAdd(maxz4a, rayInvDsplatZ, rayPinvDsplatZ);\ const Vec4V tminxa = V4Min(tminxa0, tmaxxa0);\ const Vec4V tmaxxa = V4Max(tminxa0, tmaxxa0);\ const Vec4V tminya = V4Min(tminya0, tmaxya0);\ const Vec4V tmaxya = V4Max(tminya0, tmaxya0);\ const Vec4V tminza = V4Min(tminza0, tmaxza0);\ const Vec4V tmaxza = V4Max(tminza0, tmaxza0);\ const Vec4V maxOfNeasa = V4Max(V4Max(tminxa, tminya), tminza);\ const Vec4V minOfFarsa = V4Min(V4Min(tmaxxa, tmaxya), tmaxza);\ #define SLABS_TEST2\ BoolV ignore4a = V4IsGrtr(epsFloat4, minOfFarsa); /* if tfar is negative, ignore since its a ray, not a line */\ ignore4a = BOr(ignore4a, V4IsGrtr(maxOfNeasa, maxT4)); /* if tnear is over maxT, ignore this result */\ BoolV resa4 = V4IsGrtr(maxOfNeasa, minOfFarsa); /* if 1 => fail */\ resa4 = BOr(resa4, ignore4a);\ const PxU32 code = BGetBitMask(resa4);\ if(code==15)\ continue; #define SLABS_PNS \ if(code2) \ { \ if(tn->decodePNSNoShift(0) & dirMask) \ { \ if(tn->decodePNSNoShift(1) & dirMask) \ { \ if(tn->decodePNSNoShift(2) & dirMask) \ PNS_BLOCK3(3,2,1,0) \ else \ PNS_BLOCK3(2,3,1,0) \ } \ else \ { \ if(tn->decodePNSNoShift(2) & dirMask) \ PNS_BLOCK3(3,2,0,1) \ else \ PNS_BLOCK3(2,3,0,1) \ } \ } \ else \ { \ if(tn->decodePNSNoShift(1) & dirMask) \ { \ if(tn->decodePNSNoShift(2) & dirMask) \ PNS_BLOCK3(1,0,3,2) \ else \ PNS_BLOCK3(1,0,2,3) \ } \ else \ { \ if(tn->decodePNSNoShift(2) & dirMask) \ PNS_BLOCK3(0,1,3,2) \ else \ PNS_BLOCK3(0,1,2,3) \ } \ } \ } #endif // GU_BV4_USE_SLABS #endif // GU_BV4_SLABS_H
8,239
C
45.553672
129
0.66343
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_MeshMeshOverlap.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" using namespace physx; using namespace Gu; using namespace physx::aos; #include "GuBV4_BoxOverlap_Internal.h" #include "GuBV4_BoxBoxOverlapTest.h" #define USE_GU_TRI_TRI_OVERLAP_FUNCTION #ifdef USE_GU_TRI_TRI_OVERLAP_FUNCTION #include "GuIntersectionTriangleTriangle.h" #endif #include "GuDistanceTriangleTriangle.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamNoOrder_OBBOBB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_SwizzledNoOrder.h" #endif //#include <stdio.h> #include "geometry/PxMeshQuery.h" //#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION //! if OPC_TRITRI_EPSILON_TEST is true then we do a check (if |dv|<EPSILON then dv=0.0;) else no check is done (which is less robust, but faster) #define LOCAL_EPSILON 0.000001f //! Use epsilon value in tri-tri overlap test #define OPC_TRITRI_EPSILON_TEST //! sort so that a<=b #define SORT(a,b) \ if(a>b) \ { \ const float _c=a; \ a=b; \ b=_c; \ } //! Edge to edge test based on Franlin Antonio's gem: "Faster Line Segment Intersection", in Graphics Gems III, pp. 199-202 #define EDGE_EDGE_TEST(V0, U0, U1) \ Bx = U0[i0] - U1[i0]; \ By = U0[i1] - U1[i1]; \ Cx = V0[i0] - U0[i0]; \ Cy = V0[i1] - U0[i1]; \ f = Ay*Bx - Ax*By; \ d = By*Cx - Bx*Cy; \ if((f>0.0f && d>=0.0f && d<=f) || (f<0.0f && d<=0.0f && d>=f)) \ { \ const float e=Ax*Cy - Ay*Cx; \ if(f>0.0f) \ { \ if(e>=0.0f && e<=f) return 1; \ } \ else \ { \ if(e<=0.0f && e>=f) return 1; \ } \ } //! TO BE DOCUMENTED #define EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2) \ { \ float Bx,By,Cx,Cy,d,f; \ const float Ax = V1[i0] - V0[i0]; \ const float Ay = V1[i1] - V0[i1]; \ /* test edge U0,U1 against V0,V1 */ \ EDGE_EDGE_TEST(V0, U0, U1); \ /* test edge U1,U2 against V0,V1 */ \ EDGE_EDGE_TEST(V0, U1, U2); \ /* test edge U2,U1 against V0,V1 */ \ EDGE_EDGE_TEST(V0, U2, U0); \ } //! TO BE DOCUMENTED #define POINT_IN_TRI(V0, U0, U1, U2) \ { \ /* is T1 completly inside T2? */ \ /* check if V0 is inside tri(U0,U1,U2) */ \ float a = U1[i1] - U0[i1]; \ float b = -(U1[i0] - U0[i0]); \ float c = -a*U0[i0] - b*U0[i1]; \ float d0 = a*V0[i0] + b*V0[i1] + c; \ \ a = U2[i1] - U1[i1]; \ b = -(U2[i0] - U1[i0]); \ c = -a*U1[i0] - b*U1[i1]; \ const float d1 = a*V0[i0] + b*V0[i1] + c; \ \ a = U0[i1] - U2[i1]; \ b = -(U0[i0] - U2[i0]); \ c = -a*U2[i0] - b*U2[i1]; \ const float d2 = a*V0[i0] + b*V0[i1] + c; \ if(d0*d1>0.0f) \ { \ if(d0*d2>0.0f) return 1; \ } \ } static PxU32 CoplanarTriTri(const PxVec3& n, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& u0, const PxVec3& u1, const PxVec3& u2) { int i0,i1; { float A[3]; /* first project onto an axis-aligned plane, that maximizes the area */ /* of the triangles, compute indices: i0,i1. */ A[0] = fabsf(n.x); A[1] = fabsf(n.y); A[2] = fabsf(n.z); if(A[0]>A[1]) { if(A[0]>A[2]) { i0=1; /* A[0] is greatest */ i1=2; } else { i0=0; /* A[2] is greatest */ i1=1; } } else /* A[0]<=A[1] */ { if(A[2]>A[1]) { i0=0; /* A[2] is greatest */ i1=1; } else { i0=0; /* A[1] is greatest */ i1=2; } } } /* test all edges of triangle 1 against the edges of triangle 2 */ EDGE_AGAINST_TRI_EDGES(v0, v1, u0, u1, u2); EDGE_AGAINST_TRI_EDGES(v1, v2, u0, u1, u2); EDGE_AGAINST_TRI_EDGES(v2, v0, u0, u1, u2); /* finally, test if tri1 is totally contained in tri2 or vice versa */ POINT_IN_TRI(v0, u0, u1, u2); POINT_IN_TRI(u0, v0, v1, v2); return 0; } //! TO BE DOCUMENTED #define NEWCOMPUTE_INTERVALS(VV0, VV1, VV2, D0, D1, D2, D0D1, D0D2, A, B, C, X0, X1) \ { \ if(D0D1>0.0f) \ { \ /* here we know that D0D2<=0.0 */ \ /* that is D0, D1 are on the same side, D2 on the other or on the plane */ \ A=VV2; B=(VV0 - VV2)*D2; C=(VV1 - VV2)*D2; X0=D2 - D0; X1=D2 - D1; \ } \ else if(D0D2>0.0f) \ { \ /* here we know that d0d1<=0.0 */ \ A=VV1; B=(VV0 - VV1)*D1; C=(VV2 - VV1)*D1; X0=D1 - D0; X1=D1 - D2; \ } \ else if(D1*D2>0.0f || D0!=0.0f) \ { \ /* here we know that d0d1<=0.0 or that D0!=0.0 */ \ A=VV0; B=(VV1 - VV0)*D0; C=(VV2 - VV0)*D0; X0=D0 - D1; X1=D0 - D2; \ } \ else if(D1!=0.0f) \ { \ A=VV1; B=(VV0 - VV1)*D1; C=(VV2 - VV1)*D1; X0=D1 - D0; X1=D1 - D2; \ } \ else if(D2!=0.0f) \ { \ A=VV2; B=(VV0 - VV2)*D2; C=(VV1 - VV2)*D2; X0=D2 - D0; X1=D2 - D1; \ } \ else \ { \ /* triangles are coplanar */ \ return ignoreCoplanar ? 0 : CoplanarTriTri(N1, V0, V1, V2, U0, U1, U2); \ } \ } //#endif namespace { PX_ALIGN_PREFIX(16) struct TriangleData { PxVec3p mV0, mV1, mV2; PxVec3p mXXX, mYYY, mZZZ; //#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION PxVec3 mNormal; float mD; //#endif PX_FORCE_INLINE void init(const PxVec3& V0, const PxVec3& V1, const PxVec3& V2) { // 45 lines of asm (x64) const Vec4V V0V = V4LoadU(&V0.x); const Vec4V V1V = V4LoadU(&V1.x); const Vec4V V2V = V4LoadU(&V2.x); //#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION const Vec4V E1V = V4Sub(V1V, V0V); const Vec4V E2V = V4Sub(V2V, V0V); const Vec4V NV = V4Cross(E1V, E2V); const FloatV dV = FNeg(V4Dot3(NV, V0V)); //#endif V4StoreA(V0V, &mV0.x); V4StoreA(V1V, &mV1.x); V4StoreA(V2V, &mV2.x); //#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION V4StoreA(NV, &mNormal.x); FStore(dV, &mD); //#endif // 62 lines of asm (x64) // const PxVec3 E1 = V1 - V0; // const PxVec3 E2 = V2 - V0; // const PxVec3 N = E1.cross(E2); // mV0 = V0; // mV1 = V1; // mV2 = V2; // mNormal = N; // mD = -N.dot(V0); const Vec4V tri_xs = V4LoadXYZW(V0.x, V1.x, V2.x, 0.0f); const Vec4V tri_ys = V4LoadXYZW(V0.y, V1.y, V2.y, 0.0f); const Vec4V tri_zs = V4LoadXYZW(V0.z, V1.z, V2.z, 0.0f); V4StoreA(tri_xs, &mXXX.x); V4StoreA(tri_ys, &mYYY.x); V4StoreA(tri_zs, &mZZZ.x); } }PX_ALIGN_SUFFIX(16); } //#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION static PxU32 TriTriOverlap(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar) { const PxVec3& V0 = data0.mV0; const PxVec3& V1 = data0.mV1; const PxVec3& V2 = data0.mV2; const PxVec3& U0 = data1.mV0; const PxVec3& U1 = data1.mV1; const PxVec3& U2 = data1.mV2; const PxVec3& N1 = data0.mNormal; float du0, du1, du2, du0du1, du0du2; { const float d1 = data0.mD; // Put U0,U1,U2 into plane equation 1 to compute signed distances to the plane du0 = N1.dot(U0) + d1; du1 = N1.dot(U1) + d1; du2 = N1.dot(U2) + d1; // Coplanarity robustness check #ifdef OPC_TRITRI_EPSILON_TEST if(fabsf(du0)<LOCAL_EPSILON) du0 = 0.0f; if(fabsf(du1)<LOCAL_EPSILON) du1 = 0.0f; if(fabsf(du2)<LOCAL_EPSILON) du2 = 0.0f; #endif du0du1 = du0 * du1; du0du2 = du0 * du2; if(du0du1>0.0f && du0du2>0.0f) // same sign on all of them + not equal 0 ? return 0; // no intersection occurs } const PxVec3& N2 = data1.mNormal; float dv0, dv1, dv2, dv0dv1, dv0dv2; { const float d2 = data1.mD; // put V0,V1,V2 into plane equation 2 dv0 = N2.dot(V0) + d2; dv1 = N2.dot(V1) + d2; dv2 = N2.dot(V2) + d2; #ifdef OPC_TRITRI_EPSILON_TEST if(fabsf(dv0)<LOCAL_EPSILON) dv0 = 0.0f; if(fabsf(dv1)<LOCAL_EPSILON) dv1 = 0.0f; if(fabsf(dv2)<LOCAL_EPSILON) dv2 = 0.0f; #endif dv0dv1 = dv0 * dv1; dv0dv2 = dv0 * dv2; if(dv0dv1>0.0f && dv0dv2>0.0f) // same sign on all of them + not equal 0 ? return 0; // no intersection occurs } // Compute direction of intersection line // Compute and index to the largest component of D short index = 0; { const PxVec3 D = N1.cross(N2); float max = fabsf(D[0]); const float bb = fabsf(D[1]); const float cc = fabsf(D[2]); if(bb>max) { max=bb; index=1; } if(cc>max) { max=cc; index=2; } } // This is the simplified projection onto L const float vp0 = V0[index]; const float vp1 = V1[index]; const float vp2 = V2[index]; const float up0 = U0[index]; const float up1 = U1[index]; const float up2 = U2[index]; // Compute interval for triangle 1 float a,b,c,x0,x1; NEWCOMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,a,b,c,x0,x1); // Compute interval for triangle 2 float d,e,f,y0,y1; NEWCOMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,d,e,f,y0,y1); const float xx=x0*x1; const float yy=y0*y1; const float xxyy=xx*yy; float isect1[2], isect2[2]; float tmp=a*xxyy; isect1[0]=tmp+b*x1*yy; isect1[1]=tmp+c*x0*yy; tmp=d*xxyy; isect2[0]=tmp+e*xx*y1; isect2[1]=tmp+f*xx*y0; SORT(isect1[0],isect1[1]); SORT(isect2[0],isect2[1]); if(isect1[1]<isect2[0] || isect2[1]<isect1[0]) return 0; return 1; } //#endif ////////// static PX_FORCE_INLINE void projectTriangle4( const TriangleData& data, const Vec4V& axesX, // axis0x axis1x axis2x axis3x const Vec4V& axesY, // axis0y axis1y axis2y axis3y const Vec4V& axesZ, // axis0z axis1z axis2z axis3z Vec4V& min4, Vec4V& max4 ) { Vec4V dp0_4 = V4Mul(V4Load(data.mV0.x), axesX); dp0_4 = V4MulAdd(V4Load(data.mV0.y), axesY, dp0_4); //dp0_4 = V4Add(dp0_4, V4Mul(V4Load(data.mV0.y), axesY)); dp0_4 = V4MulAdd(V4Load(data.mV0.z), axesZ, dp0_4); //dp0_4 = V4Add(dp0_4, V4Mul(V4Load(data.mV0.z), axesZ)); Vec4V dp1_4 = V4Mul(V4Load(data.mV1.x), axesX); dp1_4 = V4MulAdd(V4Load(data.mV1.y), axesY, dp1_4); //dp1_4 = V4Add(dp1_4, V4Mul(V4Load(data.mV1.y), axesY)); dp1_4 = V4MulAdd(V4Load(data.mV1.z), axesZ, dp1_4); //dp1_4 = V4Add(dp1_4, V4Mul(V4Load(data.mV1.z), axesZ)); Vec4V dp2_4 = V4Mul(V4Load(data.mV2.x), axesX); dp2_4 = V4MulAdd(V4Load(data.mV2.y), axesY, dp2_4); //dp2_4 = V4Add(dp2_4, V4Mul(V4Load(data.mV2.y), axesY)); dp2_4 = V4MulAdd(V4Load(data.mV2.z), axesZ, dp2_4); //dp2_4 = V4Add(dp2_4, V4Mul(V4Load(data.mV2.z), axesZ)); min4 = V4Min(V4Min(dp0_4, dp1_4), dp2_4); max4 = V4Max(V4Max(dp0_4, dp1_4), dp2_4); } static PX_FORCE_INLINE PxU32 V4AnyGrtrX(const Vec4V a, const Vec4V b, PxU32 mask) { const PxU32 moveMask = BGetBitMask(V4IsGrtr(a, b)); return moveMask & mask; } static PX_FORCE_INLINE bool testSepAxis( const TriangleData& data0, const TriangleData& data1, const Vec4V& axesX, // axis0x axis1x axis2x axis3x const Vec4V& axesY, // axis0y axis1y axis2y axis3y const Vec4V& axesZ, // axis0z axis1z axis2z axis3z PxU32 mask ) { Vec4V min0, max0; projectTriangle4(data0, axesX, axesY, axesZ, min0, max0); Vec4V min1, max1; projectTriangle4(data1, axesX, axesY, axesZ, min1, max1); if( V4AnyGrtrX(min1, max0, mask) || V4AnyGrtrX(min0, max1, mask)) return false; return true; } static PX_FORCE_INLINE bool testEdges4( const TriangleData& data0, const TriangleData& data1, const FloatV& edge0_x, const FloatV& edge0_y, const FloatV& edge0_z, const Vec4V& edge1_xs, const Vec4V& edge1_ys, const Vec4V& edge1_zs ) { const Vec4V axis_xs = V4Sub(V4Scale(edge1_zs, edge0_y), V4Scale(edge1_ys, edge0_z)); const Vec4V axis_ys = V4Sub(V4Scale(edge1_xs, edge0_z), V4Scale(edge1_zs, edge0_x)); const Vec4V axis_zs = V4Sub(V4Scale(edge1_ys, edge0_x), V4Scale(edge1_xs, edge0_y)); const Vec4V eps = V4Load(1e-6f); Vec4V maxV = V4Max(axis_ys, axis_xs); maxV = V4Max(axis_zs, maxV); Vec4V minV = V4Min(axis_ys, axis_xs); minV = V4Min(axis_zs, minV); maxV = V4Max(V4Neg(minV), maxV); BoolV cmpV = V4IsGrtr(maxV, eps); const PxU32 mask = BGetBitMask(cmpV) & 0x7; return testSepAxis(data0, data1, axis_xs, axis_ys, axis_zs, mask); } ////////// static PX_FORCE_INLINE void projectTriangle(const PxVec3& axis, const TriangleData& triangle, float& min, float& max) { const float dp0 = triangle.mV0.dot(axis); const float dp1 = triangle.mV1.dot(axis); min = PxMin(dp0, dp1); max = PxMax(dp0, dp1); const float dp2 = triangle.mV2.dot(axis); min = PxMin(min, dp2); max = PxMax(max, dp2); } static PX_FORCE_INLINE bool testSepAxis(const PxVec3& axis, const TriangleData& triangle0, const TriangleData& triangle1) { float min0, max0; projectTriangle(axis, triangle0, min0, max0); float min1, max1; projectTriangle(axis, triangle1, min1, max1); if(max0<min1 || max1<min0) return false; return true; } static PX_FORCE_INLINE bool isAlmostZero(const PxVec3& v) { if(PxAbs(v.x)>1e-6f || PxAbs(v.y)>1e-6f || PxAbs(v.z)>1e-6f) return false; return true; } static PX_FORCE_INLINE bool testEdges( const TriangleData& tri0, const TriangleData& tri1, const PxVec3& edge0, const PxVec3& edge1) { PxVec3 cp = edge0.cross(edge1); if(!isAlmostZero(cp)) { if(!testSepAxis(cp, tri0, tri1)) return false; } return true; } static bool TriTriSAT(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar) { { const PxReal data1_v0_dot_N0 = data1.mV0.dot(data0.mNormal); const PxReal data1_v1_dot_N0 = data1.mV1.dot(data0.mNormal); const PxReal data1_v2_dot_N0 = data1.mV2.dot(data0.mNormal); const PxReal p1ToA = data1_v0_dot_N0 + data0.mD; const PxReal p1ToB = data1_v1_dot_N0 + data0.mD; const PxReal p1ToC = data1_v2_dot_N0 + data0.mD; const PxReal tolerance = 1e-8f; if(PxAbs(p1ToA) < tolerance && PxAbs(p1ToB) < tolerance && PxAbs(p1ToC) < tolerance) { return ignoreCoplanar ? false : CoplanarTriTri(data0.mNormal, data0.mV0, data0.mV1, data0.mV2, data1.mV0, data1.mV1, data1.mV2)!=0; } if ((p1ToA > 0) == (p1ToB > 0) && (p1ToA > 0) == (p1ToC > 0)) { return false; //All points of triangle 2 on same side of triangle 1 -> no intersection } } { const PxReal data0_v0_dot_N1 = data0.mV0.dot(data1.mNormal); const PxReal data0_v1_dot_N1 = data0.mV1.dot(data1.mNormal); const PxReal data0_v2_dot_N1 = data0.mV2.dot(data1.mNormal); const PxReal p2ToA = data0_v0_dot_N1 + data1.mD; const PxReal p2ToB = data0_v1_dot_N1 + data1.mD; const PxReal p2ToC = data0_v2_dot_N1 + data1.mD; if ((p2ToA > 0) == (p2ToB > 0) && (p2ToA > 0) == (p2ToC > 0)) return false; //All points of triangle 1 on same side of triangle 2 -> no intersection } { const PxVec3 edge1_01 = data1.mV0 - data1.mV1; const PxVec3 edge1_12 = data1.mV1 - data1.mV2; const PxVec3 edge1_20 = data1.mV2 - data1.mV0; { const PxVec3 edge0_01 = data0.mV0 - data0.mV1; if(!testEdges(data0, data1, edge0_01, edge1_01)) return false; if(!testEdges(data0, data1, edge0_01, edge1_12)) return false; if(!testEdges(data0, data1, edge0_01, edge1_20)) return false; } { const PxVec3 edge0_12 = data0.mV1 - data0.mV2; if(!testEdges(data0, data1, edge0_12, edge1_01)) return false; if(!testEdges(data0, data1, edge0_12, edge1_12)) return false; if(!testEdges(data0, data1, edge0_12, edge1_20)) return false; } { const PxVec3 edge0_20 = data0.mV2 - data0.mV0; if(!testEdges(data0, data1, edge0_20, edge1_01)) return false; if(!testEdges(data0, data1, edge0_20, edge1_12)) return false; if(!testEdges(data0, data1, edge0_20, edge1_20)) return false; } } return true; } static bool TriTriSAT_SIMD(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar) { const Vec4V tri1_xs = V4LoadA(&data1.mXXX.x); const Vec4V tri1_ys = V4LoadA(&data1.mYYY.x); const Vec4V tri1_zs = V4LoadA(&data1.mZZZ.x); { const Vec4V tri0_normal_x = V4Load(data0.mNormal.x); const Vec4V tri0_normal_y = V4Load(data0.mNormal.y); const Vec4V tri0_normal_z = V4Load(data0.mNormal.z); Vec4V tri1_dot_N0 = V4Mul(tri1_xs, tri0_normal_x); // PT: TODO: V4MulAdd tri1_dot_N0 = V4Add(tri1_dot_N0, V4Mul(tri1_ys, tri0_normal_y)); tri1_dot_N0 = V4Add(tri1_dot_N0, V4Mul(tri1_zs, tri0_normal_z)); const Vec4V p1ToABC = V4Add(tri1_dot_N0, V4Load(data0.mD)); if(V4AllGrtrOrEq3(V4Load(1e-8f), V4Abs(p1ToABC))) { return ignoreCoplanar ? false : CoplanarTriTri(data0.mNormal, data0.mV0, data0.mV1, data0.mV2, data1.mV0, data1.mV1, data1.mV2)!=0; } PxU32 mm = BGetBitMask(V4IsGrtr(p1ToABC, V4Zero())); if((mm & 0x7) == 0x7) return false; mm = BGetBitMask(V4IsGrtrOrEq(V4Zero(), p1ToABC)); if((mm & 0x7) == 0x7) return false; } { const Vec4V tri0_xs = V4LoadA(&data0.mXXX.x); const Vec4V tri0_ys = V4LoadA(&data0.mYYY.x); const Vec4V tri0_zs = V4LoadA(&data0.mZZZ.x); const Vec4V tri1_normal_x = V4Load(data1.mNormal.x); const Vec4V tri1_normal_y = V4Load(data1.mNormal.y); const Vec4V tri1_normal_z = V4Load(data1.mNormal.z); Vec4V tri0_dot_N1 = V4Mul(tri0_xs, tri1_normal_x); // PT: TODO: V4MulAdd tri0_dot_N1 = V4Add(tri0_dot_N1, V4Mul(tri0_ys, tri1_normal_y)); tri0_dot_N1 = V4Add(tri0_dot_N1, V4Mul(tri0_zs, tri1_normal_z)); const Vec4V p2ToABC = V4Add(tri0_dot_N1, V4Load(data1.mD)); PxU32 mm = BGetBitMask(V4IsGrtr(p2ToABC, V4Zero())); if((mm & 0x7) == 0x7) return false; //All points of triangle 1 on same side of triangle 2 -> no intersection mm = BGetBitMask(V4IsGrtrOrEq(V4Zero(), p2ToABC)); if((mm & 0x7) == 0x7) return false; //All points of triangle 1 on same side of triangle 2 -> no intersection } { const Vec4V tri1_xs_shuffled = V4PermYZXW(tri1_xs); const Vec4V tri1_ys_shuffled = V4PermYZXW(tri1_ys); const Vec4V tri1_zs_shuffled = V4PermYZXW(tri1_zs); const Vec4V edge1_xs = V4Sub(tri1_xs, tri1_xs_shuffled); const Vec4V edge1_ys = V4Sub(tri1_ys, tri1_ys_shuffled); const Vec4V edge1_zs = V4Sub(tri1_zs, tri1_zs_shuffled); const Vec4V data0_V0 = V4LoadA(&data0.mV0.x); const Vec4V data0_V1 = V4LoadA(&data0.mV1.x); const Vec4V data0_V2 = V4LoadA(&data0.mV2.x); const Vec4V edge0_01 = V4Sub(data0_V0, data0_V1); if(!testEdges4(data0, data1, V4GetX(edge0_01), V4GetY(edge0_01), V4GetZ(edge0_01), edge1_xs, edge1_ys, edge1_zs)) return false; const Vec4V edge0_12 = V4Sub(data0_V1, data0_V2); if(!testEdges4(data0, data1, V4GetX(edge0_12), V4GetY(edge0_12), V4GetZ(edge0_12), edge1_xs, edge1_ys, edge1_zs)) return false; const Vec4V edge0_20 = V4Sub(data0_V2, data0_V0); if(!testEdges4(data0, data1, V4GetX(edge0_20), V4GetY(edge0_20), V4GetZ(edge0_20), edge1_xs, edge1_ys, edge1_zs)) return false; } return true; } // PT: beware, needs padding at the end of src static PX_FORCE_INLINE void transformV(PxVec3p* PX_RESTRICT dst, const PxVec3* PX_RESTRICT src, const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3) { const Vec4V vertexV = V4LoadU(&src->x); Vec4V ResV = V4Scale(c0, V4GetX(vertexV)); // PT: TODO: V4ScaleAdd ResV = V4Add(ResV, V4Scale(c1, V4GetY(vertexV))); ResV = V4Add(ResV, V4Scale(c2, V4GetZ(vertexV))); ResV = V4Add(ResV, c3); V4StoreU(ResV, &dst->x); } static bool accumulateResults(PxReportCallback<PxGeomIndexPair>& callback, PxGeomIndexPair*& dst, PxU32& capacity, PxU32& currentSize, PxU32 primIndex0, PxU32 primIndex1, bool mustFlip, bool& abort) { dst[currentSize].id0 = mustFlip ? primIndex1 : primIndex0; dst[currentSize].id1 = mustFlip ? primIndex0 : primIndex1; currentSize++; if(currentSize==capacity) { callback.mSize = 0; if(!callback.flushResults(currentSize, dst)) { abort = true; return false; } dst = callback.mBuffer; capacity = callback.mCapacity; currentSize = callback.mSize; } return true; } namespace { struct TriVsTriParams; typedef bool (*trisVsTrisFunction)( const TriVsTriParams& params, PxU32 nb0, PxU32 startPrim0, const TriangleData* data0, PxU32 nb1, PxU32 startPrim1, const TriangleData* data1, bool& abort); enum TriVsTriImpl { TRI_TRI_MOLLER_REGULAR, // https://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/code/ TRI_TRI_MOLLER_NEW, // Alternative implementation in Gu TRI_TRI_NEW_SAT, // "New" SAT-based implementation TRI_TRI_NEW_SAT_SIMD, // "New" SAT-based implementation using SIMD }; struct TriVsTriParams { PX_FORCE_INLINE TriVsTriParams(trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, float tolerance, bool mustFlip, bool ignoreCoplanar) : mLeafFunction (leafFunc), mCallback (callback), mTolerance (tolerance), mMustFlip (mustFlip), mIgnoreCoplanar (ignoreCoplanar) { } const trisVsTrisFunction mLeafFunction; PxReportCallback<PxGeomIndexPair>& mCallback; const float mTolerance; const bool mMustFlip; const bool mIgnoreCoplanar; PX_NOCOPY(TriVsTriParams) }; } template<const TriVsTriImpl impl> static bool doTriVsTri_Overlap( const TriVsTriParams& params, PxU32 nb0, PxU32 startPrim0, const TriangleData* data0, PxU32 nb1, PxU32 startPrim1, const TriangleData* data1, bool& abort) { PX_ASSERT(nb0<=16); PX_ASSERT(nb1<=16); PxReportCallback<PxGeomIndexPair>& callback = params.mCallback; PxGeomIndexPair* dst = callback.mBuffer; PxU32 capacity = callback.mCapacity; PxU32 currentSize = callback.mSize; PX_ASSERT(currentSize<capacity); const bool ignoreCoplanar = params.mIgnoreCoplanar; const bool mustFlip = params.mMustFlip; bool foundHit = false; abort = false; for(PxU32 i=0;i<nb0;i++) { for(PxU32 j=0;j<nb1;j++) { bool ret; if(impl==TRI_TRI_MOLLER_REGULAR) ret = TriTriOverlap(data0[i], data1[j], ignoreCoplanar); else if(impl==TRI_TRI_MOLLER_NEW) ret = trianglesIntersect(data0[i].mV0, data0[i].mV1, data0[i].mV2, data1[j].mV0, data1[j].mV1, data1[j].mV2, ignoreCoplanar); else if(impl==TRI_TRI_NEW_SAT) ret = TriTriSAT(data0[i], data1[j], ignoreCoplanar); else if(impl==TRI_TRI_NEW_SAT_SIMD) ret = TriTriSAT_SIMD(data0[i], data1[j], ignoreCoplanar); else ret = false; if(ret) { foundHit = true; if(!accumulateResults(callback, dst, capacity, currentSize, startPrim0 + i, startPrim1 + j, mustFlip, abort)) return true; } } } callback.mSize = currentSize; return foundHit; } static bool doTriVsTri_Distance(const TriVsTriParams& params, PxU32 nb0, PxU32 startPrim0, const TriangleData* data0, PxU32 nb1, PxU32 startPrim1, const TriangleData* data1, bool& abort) { PX_ASSERT(nb0<=16); PX_ASSERT(nb1<=16); PxReportCallback<PxGeomIndexPair>& callback = params.mCallback; PxGeomIndexPair* dst = callback.mBuffer; PxU32 capacity = callback.mCapacity; PxU32 currentSize = callback.mSize; PX_ASSERT(currentSize<capacity); const bool mustFlip = params.mMustFlip; bool foundHit = false; abort = false; const float toleranceSquared = params.mTolerance * params.mTolerance; for(PxU32 i=0;i<nb0;i++) { // PT: TODO: improve this const PxVec3p pp[3] = { data0[i].mV0, data0[i].mV1, data0[i].mV2 }; for(PxU32 j=0;j<nb1;j++) { PxVec3 cp, cq; // PT: TODO: improve this const PxVec3p qq[3] = { data1[j].mV0, data1[j].mV1, data1[j].mV2 }; const float d = distanceTriangleTriangleSquared(cp, cq, pp, qq); if(d<=toleranceSquared) { foundHit = true; // PT: TODO: this is not enough here if(!accumulateResults(callback, dst, capacity, currentSize, startPrim0 + i, startPrim1 + j, mustFlip, abort)) return true; } } } callback.mSize = currentSize; return foundHit; } static bool doLeafVsLeaf(const TriVsTriParams& params, const PxU32 prim0, const PxU32 prim1, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1, bool& abort) { // PT: TODO: revisit this approach, it was fine with the original overlap code but now with the 2 additional queries, not so much TriangleData data0[16]; TriangleData data1[16]; PxU32 nb0 = 0; PxU32 startPrim0; { PxU32 primIndex0 = prim0; PxU32 nbTris0 = getNbPrimitives(primIndex0); startPrim0 = primIndex0; const PxVec3* verts0 = mesh0->getVerts(); do { PX_ASSERT(primIndex0<mesh0->getNbTriangles()); PxU32 VRef00, VRef01, VRef02; getVertexReferences(VRef00, VRef01, VRef02, primIndex0++, mesh0->getTris32(), mesh0->getTris16()); PX_ASSERT(VRef00<mesh0->getNbVertices()); PX_ASSERT(VRef01<mesh0->getNbVertices()); PX_ASSERT(VRef02<mesh0->getNbVertices()); if(mat0to1) { //const PxVec3 p0 = mat0to1->transform(verts0[VRef00]); //const PxVec3 p1 = mat0to1->transform(verts0[VRef01]); //const PxVec3 p2 = mat0to1->transform(verts0[VRef02]); //data0[nb0++].init(p0, p1, p2); const Vec4V c0 = V4LoadU(&mat0to1->column0.x); const Vec4V c1 = V4LoadU(&mat0to1->column1.x); const Vec4V c2 = V4LoadU(&mat0to1->column2.x); const Vec4V c3 = V4LoadU(&mat0to1->column3.x); PxVec3p p0, p1, p2; transformV(&p0, &verts0[VRef00], c0, c1, c2, c3); transformV(&p1, &verts0[VRef01], c0, c1, c2, c3); transformV(&p2, &verts0[VRef02], c0, c1, c2, c3); data0[nb0++].init(p0, p1, p2); } else { data0[nb0++].init(verts0[VRef00], verts0[VRef01], verts0[VRef02]); } }while(nbTris0--); } PxU32 nb1 = 0; PxU32 startPrim1; { PxU32 primIndex1 = prim1; PxU32 nbTris1 = getNbPrimitives(primIndex1); startPrim1 = primIndex1; const PxVec3* verts1 = mesh1->getVerts(); do { PX_ASSERT(primIndex1<mesh1->getNbTriangles()); PxU32 VRef10, VRef11, VRef12; getVertexReferences(VRef10, VRef11, VRef12, primIndex1++, mesh1->getTris32(), mesh1->getTris16()); PX_ASSERT(VRef10<mesh1->getNbVertices()); PX_ASSERT(VRef11<mesh1->getNbVertices()); PX_ASSERT(VRef12<mesh1->getNbVertices()); data1[nb1++].init(verts1[VRef10], verts1[VRef11], verts1[VRef12]); }while(nbTris1--); } return (params.mLeafFunction)(params, nb0, startPrim0, data0, nb1, startPrim1, data1, abort); } namespace { struct MeshMeshParams : OBBTestParams { PX_FORCE_INLINE MeshMeshParams( trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1, const BV4Tree& tree, bool mustFlip, bool ignoreCoplanar, float tolerance) : mTriVsTriParams (leafFunc, callback, tolerance, mustFlip, ignoreCoplanar), mMesh0 (mesh0), mMesh1 (mesh1), mMat0to1 (mat0to1), mStatus (false) { V4StoreA_Safe(V4LoadU_Safe(&tree.mCenterOrMinCoeff.x), &mCenterOrMinCoeff_PaddedAligned.x); V4StoreA_Safe(V4LoadU_Safe(&tree.mExtentsOrMaxCoeff.x), &mExtentsOrMaxCoeff_PaddedAligned.x); PxMat33 mLocalBox_rot; if(mat0to1) mLocalBox_rot = PxMat33(PxVec3(mat0to1->column0.x, mat0to1->column0.y, mat0to1->column0.z), PxVec3(mat0to1->column1.x, mat0to1->column1.y, mat0to1->column1.z), PxVec3(mat0to1->column2.x, mat0to1->column2.y, mat0to1->column2.z)); else mLocalBox_rot = PxMat33(PxIdentity); precomputeData(this, &mAbsRot, &mLocalBox_rot); } void setupForTraversal(const PxVec3p& center, const PxVec3p& extents, float tolerance) { if(mMat0to1) { const Vec4V c0 = V4LoadU(&mMat0to1->column0.x); const Vec4V c1 = V4LoadU(&mMat0to1->column1.x); const Vec4V c2 = V4LoadU(&mMat0to1->column2.x); const Vec4V c3 = V4LoadU(&mMat0to1->column3.x); transformV(&mTBoxToModel_PaddedAligned, &center, c0, c1, c2, c3); } else mTBoxToModel_PaddedAligned = center; setupBoxData(this, extents + PxVec3(tolerance), &mAbsRot); } PxMat33 mAbsRot; //!< Absolute rotation matrix const TriVsTriParams mTriVsTriParams; const SourceMesh* const mMesh0; const SourceMesh* const mMesh1; const PxMat44* const mMat0to1; PxU32 mPrimIndex0; bool mStatus; PX_NOCOPY(MeshMeshParams) }; class LeafFunction_MeshMesh { public: static PX_FORCE_INLINE PxIntBool doLeafTest(MeshMeshParams* PX_RESTRICT params, PxU32 primIndex1) { bool abort; if(doLeafVsLeaf(params->mTriVsTriParams, params->mPrimIndex0, primIndex1, params->mMesh0, params->mMesh1, params->mMat0to1, abort)) params->mStatus = true; return PxIntBool(abort); } }; } static PX_FORCE_INLINE void getNodeBounds(Vec4V& centerV, Vec4V& extentsV, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, const PxVec3p* PX_RESTRICT centerOrMinCoeff_PaddedAligned, const PxVec3p* PX_RESTRICT extentsOrMaxCoeff_PaddedAligned) { // Dequantize box0 //OPC_SLABS_GET_MIN_MAX(tn0, i) const VecI32V minVi = I4LoadXYZW(node->mX[i].mMin, node->mY[i].mMin, node->mZ[i].mMin, 0); const Vec4V minCoeffV = V4LoadA_Safe(&centerOrMinCoeff_PaddedAligned->x); Vec4V minV = V4Mul(Vec4V_From_VecI32V(minVi), minCoeffV); const VecI32V maxVi = I4LoadXYZW(node->mX[i].mMax, node->mY[i].mMax, node->mZ[i].mMax, 0); const Vec4V maxCoeffV = V4LoadA_Safe(&extentsOrMaxCoeff_PaddedAligned->x); Vec4V maxV = V4Mul(Vec4V_From_VecI32V(maxVi), maxCoeffV); // OPC_SLABS_GET_CEQ(i) const FloatV HalfV = FLoad(0.5f); centerV = V4Scale(V4Add(maxV, minV), HalfV); extentsV = V4Scale(V4Sub(maxV, minV), HalfV); } static PX_FORCE_INLINE void getNodeBounds(Vec4V& centerV, Vec4V& extentsV, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, const PxVec3p* PX_RESTRICT /*centerOrMinCoeff_PaddedAligned*/, const PxVec3p* PX_RESTRICT /*extentsOrMaxCoeff_PaddedAligned*/) { const FloatV HalfV = FLoad(0.5f); const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f); const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f); centerV = V4Scale(V4Add(maxV, minV), HalfV); extentsV = V4Scale(V4Sub(maxV, minV), HalfV); } static PX_FORCE_INLINE PxIntBool doLeafVsNode(const BVDataPackedQ* const PX_RESTRICT root, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, MeshMeshParams* PX_RESTRICT params) { return BV4_ProcessStreamSwizzledNoOrderQ<LeafFunction_MeshMesh, MeshMeshParams>(root, node->getChildData(i), params); } static PX_FORCE_INLINE PxIntBool doLeafVsNode(const BVDataPackedNQ* const PX_RESTRICT root, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, MeshMeshParams* PX_RESTRICT params) { return BV4_ProcessStreamSwizzledNoOrderNQ<LeafFunction_MeshMesh, MeshMeshParams>(root, node->getChildData(i), params); } static void computeBoundsAroundVertices(Vec4V& centerV, Vec4V& extentsV, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts) { Vec4V minV = V4LoadU(&verts[0].x); Vec4V maxV = minV; for(PxU32 i=1; i<nbVerts; i++) { const Vec4V vV = V4LoadU(&verts[i].x); minV = V4Min(minV, vV); maxV = V4Max(maxV, vV); } const FloatV HalfV = FLoad(0.5f); centerV = V4Scale(V4Add(maxV, minV), HalfV); extentsV = V4Scale(V4Sub(maxV, minV), HalfV); } static PX_NOINLINE bool abortQuery(PxReportCallback<PxGeomIndexPair>& callback, bool& abort) { abort = true; callback.mSize = 0; return true; } static PX_FORCE_INLINE trisVsTrisFunction getLeafFunc(PxMeshMeshQueryFlags meshMeshFlags, float tolerance) { if(tolerance!=0.0f) return doTriVsTri_Distance; if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED1) return doTriVsTri_Overlap<TRI_TRI_MOLLER_NEW>; if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED2) return doTriVsTri_Overlap<TRI_TRI_NEW_SAT>; if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED3) return doTriVsTri_Overlap<TRI_TRI_NEW_SAT_SIMD>; return doTriVsTri_Overlap<TRI_TRI_MOLLER_REGULAR>; } static PX_NOINLINE bool doSmallMeshVsSmallMesh( PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1, bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance) { const PxU32 nbTris0 = mesh0->getNbTriangles(); PX_ASSERT(nbTris0<16); const PxU32 nbTris1 = mesh1->getNbTriangles(); PX_ASSERT(nbTris1<16); const TriVsTriParams params(leafFunc, callback, tolerance, false, ignoreCoplanar); bool abort; bool status = false; if(doLeafVsLeaf(params, nbTris0, nbTris1, mesh0, mesh1, mat0to1, abort)) status = true; if(abort) return abortQuery(callback, _abort); return status; } template<class PackedNodeT, class SwizzledNodeT> static PX_NOINLINE bool doSmallMeshVsTree( PxReportCallback<PxGeomIndexPair>& callback, MeshMeshParams& params, const PackedNodeT* PX_RESTRICT node, const SourceMesh* mesh0, const SourceMesh* mesh1, bool& _abort) { const PxU32 nbTris = mesh0->getNbTriangles(); PX_ASSERT(nbTris<16); { BV4_ALIGN16(PxVec3p boxCenter); BV4_ALIGN16(PxVec3p boxExtents); Vec4V centerV, extentsV; computeBoundsAroundVertices(centerV, extentsV, mesh0->getNbVertices(), mesh0->getVerts()); V4StoreA(centerV, &boxCenter.x); V4StoreA(extentsV, &boxExtents.x); params.setupForTraversal(boxCenter, boxExtents, params.mTriVsTriParams.mTolerance); params.mPrimIndex0 = nbTris; } const PackedNodeT* const root = node; const SwizzledNodeT* tn = reinterpret_cast<const SwizzledNodeT*>(node); bool status = false; for(PxU32 i=0;i<4;i++) { if(tn->mData[i]==0xffffffff) continue; Vec4V centerV1, extentsV1; getNodeBounds(centerV1, extentsV1, tn, i, &params.mCenterOrMinCoeff_PaddedAligned, &params.mExtentsOrMaxCoeff_PaddedAligned); if(BV4_BoxBoxOverlap(centerV1, extentsV1, &params)) { if(tn->isLeaf(i)) { bool abort; if(doLeafVsLeaf(params.mTriVsTriParams, nbTris, tn->getPrimitive(i), mesh0, mesh1, params.mMat0to1, abort)) status = true; if(abort) return abortQuery(callback, _abort); } else { if(doLeafVsNode(root, tn, i, &params)) return abortQuery(callback, _abort); } } } return status || params.mStatus; } template<class PackedNodeT0, class PackedNodeT1, class SwizzledNodeT0, class SwizzledNodeT1> static bool BV4_OverlapMeshVsMeshT( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance) { const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface); const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface); const PackedNodeT0* PX_RESTRICT node0 = reinterpret_cast<const PackedNodeT0*>(tree0.mNodes); const PackedNodeT1* PX_RESTRICT node1 = reinterpret_cast<const PackedNodeT1*>(tree1.mNodes); PX_ASSERT(node0 || node1); if(!node0 && node1) { MeshMeshParams ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, mat0to1, tree1, false, ignoreCoplanar, tolerance); return doSmallMeshVsTree<PackedNodeT1, SwizzledNodeT1>(callback, ParamsForTree1Traversal, node1, mesh0, mesh1, _abort); } else if(node0 && !node1) { MeshMeshParams ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, mat1to0, tree0, true, ignoreCoplanar, tolerance); return doSmallMeshVsTree<PackedNodeT0, SwizzledNodeT0>(callback, ParamsForTree0Traversal, node0, mesh1, mesh0, _abort); } else { PX_ASSERT(node0); PX_ASSERT(node1); MeshMeshParams ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, mat0to1, tree1, false, ignoreCoplanar, tolerance); MeshMeshParams ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, mat1to0, tree0, true, ignoreCoplanar, tolerance); BV4_ALIGN16(PxVec3p boxCenter0); BV4_ALIGN16(PxVec3p boxExtents0); BV4_ALIGN16(PxVec3p boxCenter1); BV4_ALIGN16(PxVec3p boxExtents1); struct indexPair { PxU32 index0; PxU32 index1; }; PxU32 nb=1; indexPair stack[GU_BV4_STACK_SIZE]; stack[0].index0 = tree0.mInitData; stack[0].index1 = tree1.mInitData; bool status = false; const PackedNodeT0* const root0 = node0; const PackedNodeT1* const root1 = node1; do { const indexPair& childData = stack[--nb]; node0 = root0 + getChildOffset(childData.index0); node1 = root1 + getChildOffset(childData.index1); const SwizzledNodeT0* tn0 = reinterpret_cast<const SwizzledNodeT0*>(node0); const SwizzledNodeT1* tn1 = reinterpret_cast<const SwizzledNodeT1*>(node1); for(PxU32 i=0;i<4;i++) { if(tn0->mData[i]==0xffffffff) continue; Vec4V centerV0, extentsV0; getNodeBounds(centerV0, extentsV0, tn0, i, &ParamsForTree0Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree0Traversal.mExtentsOrMaxCoeff_PaddedAligned); V4StoreA(centerV0, &boxCenter0.x); V4StoreA(extentsV0, &boxExtents0.x); ParamsForTree1Traversal.setupForTraversal(boxCenter0, boxExtents0, tolerance); for(PxU32 j=0;j<4;j++) { if(tn1->mData[j]==0xffffffff) continue; Vec4V centerV1, extentsV1; getNodeBounds(centerV1, extentsV1, tn1, j, &ParamsForTree1Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree1Traversal.mExtentsOrMaxCoeff_PaddedAligned); if(BV4_BoxBoxOverlap(centerV1, extentsV1, &ParamsForTree1Traversal)) { const PxU32 isLeaf0 = tn0->isLeaf(i); const PxU32 isLeaf1 = tn1->isLeaf(j); if(isLeaf0) { if(isLeaf1) { bool abort; if(doLeafVsLeaf(ParamsForTree1Traversal.mTriVsTriParams, tn0->getPrimitive(i), tn1->getPrimitive(j), mesh0, mesh1, mat0to1, abort)) status = true; if(abort) return abortQuery(callback, _abort); } else { ParamsForTree1Traversal.mPrimIndex0 = tn0->getPrimitive(i); if(doLeafVsNode(root1, tn1, j, &ParamsForTree1Traversal)) return abortQuery(callback, _abort); } } else { if(isLeaf1) { V4StoreA(centerV1, &boxCenter1.x); V4StoreA(extentsV1, &boxExtents1.x); ParamsForTree0Traversal.setupForTraversal(boxCenter1, boxExtents1, tolerance); ParamsForTree0Traversal.mPrimIndex0 = tn1->getPrimitive(j); if(doLeafVsNode(root0, tn0, i, &ParamsForTree0Traversal)) return abortQuery(callback, _abort); } else { stack[nb].index0 = tn0->getChildData(i); stack[nb].index1 = tn1->getChildData(j); nb++; } } } } } }while(nb); return status || ParamsForTree0Traversal.mStatus || ParamsForTree1Traversal.mStatus; } } // PT: each mesh can be: // 1) a small mesh without tree // 2) a regular mesh with a quantized tree // 3) a regular mesh with a non-quantized tree // // So for mesh-vs-mesh that's 3*3 = 9 possibilities. Some of them are redundant (e.g. 1 vs 2 and 2 vs 1) so it comes down to: // 1) small mesh vs small mesh // 2) small mesh vs quantized tree // 3) small mesh vs non-quantized tree // 4) non-quantized tree vs non-quantized tree // 5) quantized tree vs non-quantized tree // 6) quantized tree vs quantized tree // => 6 codepaths // // But for each of this codepath the query can be: // - all hits or any hits // - using PxRegularReportCallback / PxLocalStorageReportCallback / PxExternalStorageReportCallback / PxDynamicArrayReportCallback // So for each codepath that's 2*4 = 8 possible queries. // // Thus we'd need 6*8 = 48 different test cases. // // This gets worse if we take scaling into account. // // UPDATE: and now we also want distance/tolerance queries so multiply this by 2. This is getting too complicated. // We were at 48 test cases, *2 for scaling, *2 for distance queries = 192 cases to test? bool BV4_OverlapMeshVsMesh( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, PxMeshMeshQueryFlags meshMeshFlags, float tolerance) { PxGeomIndexPair stackBuffer[256]; bool mustResetBuffer; if(callback.mBuffer) { PX_ASSERT(callback.mCapacity); mustResetBuffer = false; } else { callback.mBuffer = stackBuffer; PX_ASSERT(callback.mCapacity<=256); if(callback.mCapacity==0 || callback.mCapacity>256) { callback.mCapacity = 256; } callback.mSize = 0; mustResetBuffer = true; } const bool ignoreCoplanar = meshMeshFlags & PxMeshMeshQueryFlag::eDISCARD_COPLANAR; const trisVsTrisFunction leafFunc = getLeafFunc(meshMeshFlags, tolerance); bool status; bool abort = false; if(!tree0.mNodes && !tree1.mNodes) { const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface); const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface); status = doSmallMeshVsSmallMesh(callback, mesh0, mesh1, mat0to1, abort, ignoreCoplanar, leafFunc, tolerance); } else { if(tree0.mQuantized) { if(tree1.mQuantized) status = BV4_OverlapMeshVsMeshT<BVDataPackedQ, BVDataPackedQ, BVDataSwizzledQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance); else status = BV4_OverlapMeshVsMeshT<BVDataPackedQ, BVDataPackedNQ, BVDataSwizzledQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance); } else { if(tree1.mQuantized) status = BV4_OverlapMeshVsMeshT<BVDataPackedNQ, BVDataPackedQ, BVDataSwizzledNQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance); else status = BV4_OverlapMeshVsMeshT<BVDataPackedNQ, BVDataPackedNQ, BVDataSwizzledNQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance); } } if(!abort) { const PxU32 currentSize = callback.mSize; if(currentSize) { callback.mSize = 0; callback.flushResults(currentSize, callback.mBuffer); } } if(mustResetBuffer) callback.mBuffer = NULL; return status; } // PT: experimental version supporting scaling. Passed matrices etc are all temporary. #include "geometry/PxMeshScale.h" #include "CmMatrix34.h" #include "CmScaling.h" #include "GuConvexUtilsInternal.h" #include "GuBoxConversion.h" using namespace Cm; // PT/ dups from NpDebugViz.cpp static PX_FORCE_INLINE Vec4V multiply3x3V_(const Vec4V p, const PxMat34& mat) { Vec4V ResV = V4Scale(V4LoadU(&mat.m.column0.x), V4GetX(p)); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column1.x), V4GetY(p))); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column2.x), V4GetZ(p))); return ResV; } // PT: beware, needs padding at the end of dst/src static PX_FORCE_INLINE void transformV_(PxVec3* dst, const PxVec3* src, const Vec4V p, const PxMat34& mat) { const Vec4V vertexV = V4LoadU(&src->x); const Vec4V transformedV = V4Add(multiply3x3V_(vertexV, mat), p); V4StoreU(transformedV, &dst->x); } // PT: Following ones fetched from GuBounds.cpp and adapted to Vec4V inputs. // TODO: refactor! this is just a test // PT: this one may have duplicates in GuBV4_BoxSweep_Internal.h & GuBV4_Raycast.cpp static PX_FORCE_INLINE Vec4V multiply3x3V_(const Vec4V p, const PxMat33Padded& mat_Padded) { Vec4V ResV = V4Scale(V4LoadU(&mat_Padded.column0.x), V4GetX(p)); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat_Padded.column1.x), V4GetY(p))); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat_Padded.column2.x), V4GetZ(p))); return ResV; } static PX_FORCE_INLINE void transformNoEmptyTestV(Vec4V& c, Vec4V& ext, const PxMat33Padded& rot, const PxVec3& pos, Vec4V boundsCenterV, Vec4V boundsExtentsV) { // PT: unfortunately we can't V4LoadU 'pos' directly (it can come directly from users!). So we have to live with this for now: const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&pos.x)); // PT: but eventually we'd like to use the "unsafe" version (e.g. by switching p&q in PxTransform), which would save 6 instructions on Win32 const Vec4V cV = V4Add(multiply3x3V_(boundsCenterV, rot), posV); c = cV; // extended basis vectors const Vec4V c0V = V4Scale(V4LoadU(&rot.column0.x), V4GetX(boundsExtentsV)); const Vec4V c1V = V4Scale(V4LoadU(&rot.column1.x), V4GetY(boundsExtentsV)); const Vec4V c2V = V4Scale(V4LoadU(&rot.column2.x), V4GetZ(boundsExtentsV)); // find combination of base vectors that produces max. distance for each component = sum of abs() Vec4V extentsV = V4Add(V4Abs(c0V), V4Abs(c1V)); extentsV = V4Add(extentsV, V4Abs(c2V)); ext = extentsV; } static PX_FORCE_INLINE void transformNoEmptyTest(const PxMat34& absPose, Vec4V& c, Vec4V& ext, Vec4V boundsCenterV, Vec4V boundsExtentsV) { transformNoEmptyTestV(c, ext, static_cast<const PxMat33Padded&>(absPose.m), absPose.p, boundsCenterV, boundsExtentsV); } static void computeMeshBounds(const PxMat34& absPose, Vec4V boundsCenterV, Vec4V boundsExtentsV, Vec4V& origin, Vec4V& extent) { transformNoEmptyTest(absPose, origin, extent, boundsCenterV, boundsExtentsV); } // PT: TODO: refactor with non-scaled version static bool doLeafVsLeaf_Scaled(const TriVsTriParams& params, const PxU32 prim0, const PxU32 prim1, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat34& absPose0, const PxMat34& absPose1, bool& abort) { TriangleData data0[16]; TriangleData data1[16]; PxU32 nb0 = 0; PxU32 startPrim0; { PxU32 primIndex0 = prim0; PxU32 nbTris0 = getNbPrimitives(primIndex0); startPrim0 = primIndex0; const PxVec3* verts0 = mesh0->getVerts(); do { PX_ASSERT(primIndex0<mesh0->getNbTriangles()); PxU32 VRef00, VRef01, VRef02; getVertexReferences(VRef00, VRef01, VRef02, primIndex0++, mesh0->getTris32(), mesh0->getTris16()); PX_ASSERT(VRef00<mesh0->getNbVertices()); PX_ASSERT(VRef01<mesh0->getNbVertices()); PX_ASSERT(VRef02<mesh0->getNbVertices()); PxVec3p p0, p1, p2; const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose0.p.x)); transformV_(&p0, &verts0[VRef00], posV, absPose0); transformV_(&p1, &verts0[VRef01], posV, absPose0); transformV_(&p2, &verts0[VRef02], posV, absPose0); data0[nb0++].init(p0, p1, p2); }while(nbTris0--); } PxU32 nb1 = 0; PxU32 startPrim1; { PxU32 primIndex1 = prim1; PxU32 nbTris1 = getNbPrimitives(primIndex1); startPrim1 = primIndex1; const PxVec3* verts1 = mesh1->getVerts(); do { PX_ASSERT(primIndex1<mesh1->getNbTriangles()); PxU32 VRef10, VRef11, VRef12; getVertexReferences(VRef10, VRef11, VRef12, primIndex1++, mesh1->getTris32(), mesh1->getTris16()); PX_ASSERT(VRef10<mesh1->getNbVertices()); PX_ASSERT(VRef11<mesh1->getNbVertices()); PX_ASSERT(VRef12<mesh1->getNbVertices()); PxVec3p p0, p1, p2; const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose1.p.x)); transformV_(&p0, &verts1[VRef10], posV, absPose1); transformV_(&p1, &verts1[VRef11], posV, absPose1); transformV_(&p2, &verts1[VRef12], posV, absPose1); data1[nb1++].init(p0, p1, p2); }while(nbTris1--); } return (params.mLeafFunction)(params, nb0, startPrim0, data0, nb1, startPrim1, data1, abort); } static PX_NOINLINE bool doSmallMeshVsSmallMesh_Scaled( PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat34& absPose0, const PxMat34& absPose1, bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance) { const PxU32 nbTris0 = mesh0->getNbTriangles(); PX_ASSERT(nbTris0<16); const PxU32 nbTris1 = mesh1->getNbTriangles(); PX_ASSERT(nbTris1<16); const TriVsTriParams params(leafFunc, callback, tolerance, false, ignoreCoplanar); bool abort; bool status = false; if(doLeafVsLeaf_Scaled(params, nbTris0, nbTris1, mesh0, mesh1, absPose0, absPose1, abort)) status = true; if(abort) return abortQuery(callback, _abort); return status; } namespace { // PT: this bit from NpDebugViz.cpp, visualizeTriangleMesh() static PxMat34 getAbsPose(const PxTransform& meshPose, const PxMeshScale& meshScale) { const PxMat33Padded m33(meshPose.q); return PxMat34(m33 * toMat33(meshScale), meshPose.p); } struct MeshMeshParams_Scaled : MeshMeshParams { PX_FORCE_INLINE MeshMeshParams_Scaled(trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxTransform& meshPose0, const PxTransform& meshPose1, const PxMeshScale& meshScale0, const PxMeshScale& meshScale1, const PxMat34& absPose0, const PxMat34& absPose1, const PxMat44* mat0to1, const BV4Tree& tree, bool mustFlip, bool ignoreCoplanar, float tolerance) : MeshMeshParams (leafFunc, callback, mesh0, mesh1, mat0to1, tree, mustFlip, ignoreCoplanar, tolerance), mMeshPose0 (meshPose0), mMeshPose1 (meshPose1), mMeshScale0 (meshScale0), mMeshScale1 (meshScale1), mAbsPose0 (absPose0), mAbsPose1 (absPose1) { } PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space const PxTransform& mMeshPose0; const PxTransform& mMeshPose1; const PxMeshScale& mMeshScale0; const PxMeshScale& mMeshScale1; const PxMat34& mAbsPose0; const PxMat34& mAbsPose1; PX_NOCOPY(MeshMeshParams_Scaled) }; template<class ParamsT> static PX_FORCE_INLINE void setupBoxParams2(ParamsT* PX_RESTRICT params, const Box& localBox) { invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox); params->mTBoxToModel_PaddedAligned = localBox.center; params->precomputeBoxData(localBox.extents, &localBox.rot); } class LeafFunction_MeshMesh_Scaled { public: static PX_FORCE_INLINE PxIntBool doLeafTest(MeshMeshParams_Scaled* PX_RESTRICT params, PxU32 primIndex1) { bool abort; if(doLeafVsLeaf_Scaled(params->mTriVsTriParams, params->mPrimIndex0, primIndex1, params->mMesh0, params->mMesh1, params->mAbsPose0, params->mAbsPose1, abort)) params->mStatus = true; return PxIntBool(abort); } }; PX_FORCE_INLINE PxIntBool BV4_AABBAABBOverlap(const Vec4VArg boxCenter0V, const Vec4VArg extents0V, const Vec4VArg boxCenter1V, const Vec4VArg extents1V) { const Vec4V absTV = V4Abs(V4Sub(boxCenter0V, boxCenter1V)); const BoolV res = V4IsGrtr(absTV, V4Add(extents0V, extents1V)); const PxU32 test = BGetBitMask(res); if(test&7) return 0; return 1; } } static PX_FORCE_INLINE PxIntBool doLeafVsNode_Scaled(const BVDataPackedQ* const PX_RESTRICT root, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, MeshMeshParams_Scaled* PX_RESTRICT params) { return BV4_ProcessStreamSwizzledNoOrderQ<LeafFunction_MeshMesh_Scaled, MeshMeshParams_Scaled>(root, node->getChildData(i), params); } static PX_FORCE_INLINE PxIntBool doLeafVsNode_Scaled(const BVDataPackedNQ* const PX_RESTRICT root, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, MeshMeshParams_Scaled* PX_RESTRICT params) { return BV4_ProcessStreamSwizzledNoOrderNQ<LeafFunction_MeshMesh_Scaled, MeshMeshParams_Scaled>(root, node->getChildData(i), params); } static void computeVertexSpaceOBB(Box& dst, const Box& src, const PxMat34& inverse) { dst = transform(inverse, src); } template<class PackedNodeT, class SwizzledNodeT> static PX_NOINLINE bool doSmallMeshVsTree_Scaled( PxReportCallback<PxGeomIndexPair>& callback, MeshMeshParams_Scaled& params, const PackedNodeT* PX_RESTRICT node, const SourceMesh* mesh0, const SourceMesh* mesh1, bool& _abort) { const PxU32 nbTris = mesh0->getNbTriangles(); PX_ASSERT(nbTris<16); Vec4V scaledCenterV, scaledExtentV; Box vertexOBB; // query box in vertex space // { BV4_ALIGN16(PxVec3p boxCenter); BV4_ALIGN16(PxVec3p boxExtents); Vec4V centerV, extentsV; computeBoundsAroundVertices(centerV, extentsV, mesh0->getNbVertices(), mesh0->getVerts()); computeMeshBounds(params.mAbsPose0, centerV, extentsV, scaledCenterV, scaledExtentV); centerV = scaledCenterV; extentsV = scaledExtentV; V4StoreA(centerV, &boxCenter.x); V4StoreA(extentsV, &boxExtents.x); Box box; buildFrom(box, boxCenter, boxExtents, PxQuat(PxIdentity)); computeVertexSpaceOBB(vertexOBB, box, params.mMeshPose1, params.mMeshScale1); params.setupForTraversal(boxCenter, boxExtents, 0.0f/*params.mTolerance*/); setupBoxParams2(&params, vertexOBB); params.mPrimIndex0 = nbTris; // } const PackedNodeT* const root = node; const SwizzledNodeT* tn = reinterpret_cast<const SwizzledNodeT*>(node); bool status = false; for(PxU32 i=0;i<4;i++) { if(tn->mData[i]==0xffffffff) continue; Vec4V centerV1, extentsV1; getNodeBounds(centerV1, extentsV1, tn, i, &params.mCenterOrMinCoeff_PaddedAligned, &params.mExtentsOrMaxCoeff_PaddedAligned); Vec4V scaledCenterV1, scaledExtentV1; computeMeshBounds(params.mAbsPose1, centerV1, extentsV1, scaledCenterV1, scaledExtentV1); centerV1 = scaledCenterV1; extentsV1 = scaledExtentV1; if(BV4_AABBAABBOverlap(scaledCenterV, scaledExtentV, scaledCenterV1, scaledExtentV1)) { if(tn->isLeaf(i)) { bool abort; if(doLeafVsLeaf_Scaled(params.mTriVsTriParams, nbTris, tn->getPrimitive(i), mesh0, mesh1, params.mAbsPose0, params.mAbsPose1, abort)) status = true; if(abort) return abortQuery(callback, _abort); } else { if(doLeafVsNode_Scaled(root, tn, i, &params)) return abortQuery(callback, _abort); } } } return status || params.mStatus; } template<class PackedNodeT0, class PackedNodeT1, class SwizzledNodeT0, class SwizzledNodeT1> static bool BV4_OverlapMeshVsMeshT_Scaled(PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, const PxTransform& meshPose0, const PxTransform& meshPose1, const PxMeshScale& meshScale0, const PxMeshScale& meshScale1, const PxMat34& absPose0, const PxMat34& absPose1, bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance) { const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface); const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface); const PackedNodeT0* PX_RESTRICT node0 = reinterpret_cast<const PackedNodeT0*>(tree0.mNodes); const PackedNodeT1* PX_RESTRICT node1 = reinterpret_cast<const PackedNodeT1*>(tree1.mNodes); PX_ASSERT(node0 || node1); if(!node0 && node1) { MeshMeshParams_Scaled ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, mat0to1, tree1, false, ignoreCoplanar, tolerance); return doSmallMeshVsTree_Scaled<PackedNodeT1, SwizzledNodeT1>(callback, ParamsForTree1Traversal, node1, mesh0, mesh1, _abort); } else if(node0 && !node1) { MeshMeshParams_Scaled ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, meshPose1, meshPose0, meshScale1, meshScale0, absPose1, absPose0, mat1to0, tree0, true, ignoreCoplanar, tolerance); return doSmallMeshVsTree_Scaled<PackedNodeT0, SwizzledNodeT0>(callback, ParamsForTree0Traversal, node0, mesh1, mesh0, _abort); } else { PX_ASSERT(node0); PX_ASSERT(node1); // ### some useless computations in there now MeshMeshParams_Scaled ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, mat0to1, tree1, false, ignoreCoplanar, tolerance); MeshMeshParams_Scaled ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, meshPose1, meshPose0, meshScale1, meshScale0, absPose1, absPose0, mat1to0, tree0, true, ignoreCoplanar, tolerance); const PxMat34 inverse0 = meshScale0.getInverse() * Matrix34FromTransform(meshPose0.getInverse()); const PxMat34 inverse1 = meshScale1.getInverse() * Matrix34FromTransform(meshPose1.getInverse()); BV4_ALIGN16(PxVec3p boxCenter0); BV4_ALIGN16(PxVec3p boxExtents0); BV4_ALIGN16(PxVec3p boxCenter1); BV4_ALIGN16(PxVec3p boxExtents1); struct indexPair { PxU32 index0; PxU32 index1; }; PxU32 nb=1; indexPair stack[GU_BV4_STACK_SIZE]; stack[0].index0 = tree0.mInitData; stack[0].index1 = tree1.mInitData; bool status = false; const PackedNodeT0* const root0 = node0; const PackedNodeT1* const root1 = node1; do { const indexPair& childData = stack[--nb]; node0 = root0 + getChildOffset(childData.index0); node1 = root1 + getChildOffset(childData.index1); const SwizzledNodeT0* tn0 = reinterpret_cast<const SwizzledNodeT0*>(node0); const SwizzledNodeT1* tn1 = reinterpret_cast<const SwizzledNodeT1*>(node1); for(PxU32 i=0;i<4;i++) { if(tn0->mData[i]==0xffffffff) continue; Vec4V centerV0, extentsV0; getNodeBounds(centerV0, extentsV0, tn0, i, &ParamsForTree0Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree0Traversal.mExtentsOrMaxCoeff_PaddedAligned); Vec4V scaledCenterV0, scaledExtentV0; computeMeshBounds(absPose0, centerV0, extentsV0, scaledCenterV0, scaledExtentV0); centerV0 = scaledCenterV0; extentsV0 = scaledExtentV0; V4StoreA(centerV0, &boxCenter0.x); V4StoreA(extentsV0, &boxExtents0.x); for(PxU32 j=0;j<4;j++) { if(tn1->mData[j]==0xffffffff) continue; Vec4V centerV1, extentsV1; getNodeBounds(centerV1, extentsV1, tn1, j, &ParamsForTree1Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree1Traversal.mExtentsOrMaxCoeff_PaddedAligned); Vec4V scaledCenterV1, scaledExtentV1; computeMeshBounds(absPose1, centerV1, extentsV1, scaledCenterV1, scaledExtentV1); centerV1 = scaledCenterV1; extentsV1 = scaledExtentV1; if(BV4_AABBAABBOverlap(scaledCenterV0, scaledExtentV0, scaledCenterV1, scaledExtentV1)) { const PxU32 isLeaf0 = tn0->isLeaf(i); const PxU32 isLeaf1 = tn1->isLeaf(j); if(isLeaf0) { if(isLeaf1) { bool abort; if(doLeafVsLeaf_Scaled(ParamsForTree1Traversal.mTriVsTriParams, tn0->getPrimitive(i), tn1->getPrimitive(j), mesh0, mesh1, absPose0, absPose1, abort)) status = true; if(abort) return abortQuery(callback, _abort); } else { Box box; buildFrom(box, boxCenter0, boxExtents0, PxQuat(PxIdentity)); Box vertexOBB; // query box in vertex space computeVertexSpaceOBB(vertexOBB, box, inverse1); setupBoxParams2(&ParamsForTree1Traversal, vertexOBB); ParamsForTree1Traversal.mPrimIndex0 = tn0->getPrimitive(i); if(doLeafVsNode_Scaled(root1, tn1, j, &ParamsForTree1Traversal)) return abortQuery(callback, _abort); } } else { if(isLeaf1) { V4StoreA(centerV1, &boxCenter1.x); V4StoreA(extentsV1, &boxExtents1.x); Box box; buildFrom(box, boxCenter1, boxExtents1, PxQuat(PxIdentity)); Box vertexOBB; // query box in vertex space computeVertexSpaceOBB(vertexOBB, box, inverse0); setupBoxParams2(&ParamsForTree0Traversal, vertexOBB); ParamsForTree0Traversal.mPrimIndex0 = tn1->getPrimitive(j); if(doLeafVsNode_Scaled(root0, tn0, i, &ParamsForTree0Traversal)) return abortQuery(callback, _abort); } else { stack[nb].index0 = tn0->getChildData(i); stack[nb].index1 = tn1->getChildData(j); nb++; } } } } } }while(nb); return status || ParamsForTree0Traversal.mStatus || ParamsForTree1Traversal.mStatus; } } bool BV4_OverlapMeshVsMesh( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, const PxTransform& meshPose0, const PxTransform& meshPose1, const PxMeshScale& meshScale0, const PxMeshScale& meshScale1, PxMeshMeshQueryFlags meshMeshFlags, float tolerance) { PxGeomIndexPair stackBuffer[256]; bool mustResetBuffer; if(callback.mBuffer) { PX_ASSERT(callback.mCapacity); mustResetBuffer = false; } else { callback.mBuffer = stackBuffer; PX_ASSERT(callback.mCapacity<=256); if(callback.mCapacity==0 || callback.mCapacity>256) { callback.mCapacity = 256; } callback.mSize = 0; mustResetBuffer = true; } // PT: TODO: we now compute this pose eagerly rather than lazily. Maybe revisit this later. const PxMat34 absPose0 = getAbsPose(meshPose0, meshScale0); const PxMat34 absPose1 = getAbsPose(meshPose1, meshScale1); const bool ignoreCoplanar = meshMeshFlags & PxMeshMeshQueryFlag::eDISCARD_COPLANAR; const trisVsTrisFunction leafFunc = getLeafFunc(meshMeshFlags, tolerance); bool status; bool abort = false; if(!tree0.mNodes && !tree1.mNodes) { const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface); const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface); status = doSmallMeshVsSmallMesh_Scaled(callback, mesh0, mesh1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance); } else { if(tree0.mQuantized) { if(tree1.mQuantized) status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedQ, BVDataPackedQ, BVDataSwizzledQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance); else status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedQ, BVDataPackedNQ, BVDataSwizzledQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance); } else { if(tree1.mQuantized) status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedNQ, BVDataPackedQ, BVDataSwizzledNQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance); else status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedNQ, BVDataPackedNQ, BVDataSwizzledNQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance); } } if(!abort) { const PxU32 currentSize = callback.mSize; if(currentSize) { callback.mSize = 0; callback.flushResults(currentSize, callback.mBuffer); } } if(mustResetBuffer) callback.mBuffer = NULL; return status; }
63,268
C++
32.004173
263
0.695628
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_SwizzledNoOrder.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_SLABS_SWIZZLED_NO_ORDER_H #define GU_BV4_SLABS_SWIZZLED_NO_ORDER_H // Generic, no sort /* template<class LeafTestT, class ParamsT> static PxIntBool BV4_ProcessStreamSwizzledNoOrder(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPacked* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node); const PxU32 nodeType = getChildType(childData); if(nodeType>1 && BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 3>(stack, nb, tn, params)) return 1; if(nodeType>0 && BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 2>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 1>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 0>(stack, nb, tn, params)) return 1; }while(nb); return 0; }*/ template<class LeafTestT, class ParamsT> static PxIntBool BV4_ProcessStreamSwizzledNoOrderQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node); const PxU32 nodeType = getChildType(childData); if(nodeType>1 && BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 3>(stack, nb, tn, params)) return 1; if(nodeType>0 && BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 2>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 1>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 0>(stack, nb, tn, params)) return 1; }while(nb); return 0; } template<class LeafTestT, class ParamsT> static PxIntBool BV4_ProcessStreamSwizzledNoOrderNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params) { const BVDataPackedNQ* root = node; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; node = root + getChildOffset(childData); const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node); const PxU32 nodeType = getChildType(childData); if(nodeType>1 && BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 3>(stack, nb, tn, params)) return 1; if(nodeType>0 && BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 2>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 1>(stack, nb, tn, params)) return 1; if(BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 0>(stack, nb, tn, params)) return 1; }while(nb); return 0; } #endif // GU_BV4_SLABS_SWIZZLED_NO_ORDER_H
4,669
C
34.923077
137
0.730992
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_CapsuleSweep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" #include "GuSweepSphereTriangle.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuInternal.h" #include "GuBV4_BoxOverlap_Internal.h" #include "GuBV4_BoxSweep_Params.h" namespace { struct CapsuleSweepParams : BoxSweepParams { Capsule mLocalCapsule; PxVec3 mCapsuleCenter; PxVec3 mExtrusionDir; float mBestAlignmentValue; float mBestDistance; float mMaxDist; // PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; } PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; } }; } #include "GuBV4_CapsuleSweep_Internal.h" #include "GuBV4_BoxBoxOverlapTest.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamOrdered_OBBOBB.h" #include "GuBV4_ProcessStreamNoOrder_OBBOBB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_SwizzledNoOrder.h" #include "GuBV4_Slabs_SwizzledOrdered.h" #endif #define GU_BV4_PROCESS_STREAM_NO_ORDER #define GU_BV4_PROCESS_STREAM_ORDERED #include "GuBV4_Internal.h" PxIntBool BV4_CapsuleSweepSingle(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); CapsuleSweepParams Params; setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags); if(tree.mNodes) { if(Params.mEarlyExit) processStreamNoOrder<LeafFunction_CapsuleSweepAny>(tree, &Params); else processStreamOrdered<LeafFunction_CapsuleSweepClosest>(tree, &Params); } else doBruteForceTests<LeafFunction_CapsuleSweepAny, LeafFunction_CapsuleSweepClosest>(mesh->getNbTriangles(), &Params); return computeImpactDataT<ImpactFunctionCapsule>(capsule, dir, hit, &Params, NULL, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); } // PT: capsule sweep callback version - currently not used namespace { struct CapsuleSweepParamsCB : CapsuleSweepParams { // PT: these new members are only here to call computeImpactDataT during traversal :( // PT: TODO: most of them may not be needed // PT: TODO: for example mCapsuleCB probably dup of mLocalCapsule Capsule mCapsuleCB; // Capsule in original space (maybe not local/mesh space) PxVec3 mDirCB; // Dir in original space (maybe not local/mesh space) const PxMat44* mWorldm_Aligned; PxU32 mFlags; SweepUnlimitedCallback mCallback; void* mUserData; bool mNodeSorting; }; class LeafFunction_CapsuleSweepCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(CapsuleSweepParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(triCapsuleSweep(params, primIndex, params->mNodeSorting)) { // PT: TODO: in this version we must compute the impact data immediately, // which is a terrible idea in general, but I'm not sure what else I can do. SweepHit hit; const bool b = computeImpactDataT<ImpactFunctionCapsule>(params->mCapsuleCB, params->mDirCB, &hit, params, params->mWorldm_Aligned, (params->mFlags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (params->mFlags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); PX_ASSERT(b); PX_UNUSED(b); reportUnlimitedCallbackHit(params, hit); } primIndex++; }while(nbToGo--); return 0; } }; } // PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB(). void BV4_CapsuleSweepCB(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); CapsuleSweepParamsCB Params; Params.mCapsuleCB = capsule; Params.mDirCB = dir; Params.mWorldm_Aligned = worldm_Aligned; Params.mFlags = flags; Params.mCallback = callback; Params.mUserData = userData; Params.mMaxDist = maxDist; Params.mNodeSorting = nodeSorting; setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags); PX_ASSERT(!Params.mEarlyExit); if(tree.mNodes) { if(nodeSorting) processStreamOrdered<LeafFunction_CapsuleSweepCB>(tree, &Params); else processStreamNoOrder<LeafFunction_CapsuleSweepCB>(tree, &Params); } else doBruteForceTests<LeafFunction_CapsuleSweepCB, LeafFunction_CapsuleSweepCB>(mesh->getNbTriangles(), &Params); }
6,216
C++
35.145349
241
0.757239
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_CapsuleSweepAA.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" #include "GuSweepSphereTriangle.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuBV4_Common.h" #include "GuInternal.h" #define SWEEP_AABB_IMPL // PT: TODO: refactor structure (TA34704) namespace { struct RayParams { BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); #ifndef GU_BV4_USE_SLABS BV4_ALIGN16(PxVec3p mData2_PaddedAligned); BV4_ALIGN16(PxVec3p mFDir_PaddedAligned); BV4_ALIGN16(PxVec3p mData_PaddedAligned); BV4_ALIGN16(PxVec3p mLocalDir_PaddedAligned); #endif BV4_ALIGN16(PxVec3p mOrigin_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704) }; } #include "GuBV4_BoxSweep_Params.h" namespace { struct CapsuleSweepParams : BoxSweepParams { Capsule mLocalCapsule; PxVec3 mCapsuleCenter; PxVec3 mExtrusionDir; float mBestAlignmentValue; float mBestDistance; float mMaxDist; // PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; } PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; } }; } #include "GuBV4_CapsuleSweep_Internal.h" #include "GuBV4_AABBAABBSweepTest.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" #endif #include "GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h" #include "GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_KajiyaNoOrder.h" #include "GuBV4_Slabs_KajiyaOrdered.h" #endif #define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER #define GU_BV4_PROCESS_STREAM_RAY_ORDERED #include "GuBV4_Internal.h" PxIntBool BV4_CapsuleSweepSingleAA(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); CapsuleSweepParams Params; setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags); if(tree.mNodes) { if(Params.mEarlyExit) processStreamRayNoOrder<1, LeafFunction_CapsuleSweepAny>(tree, &Params); else processStreamRayOrdered<1, LeafFunction_CapsuleSweepClosest>(tree, &Params); } else doBruteForceTests<LeafFunction_CapsuleSweepAny, LeafFunction_CapsuleSweepClosest>(mesh->getNbPrimitives(), &Params); return computeImpactDataT<ImpactFunctionCapsule>(capsule, dir, hit, &Params, NULL, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0); }
4,216
C++
36.651785
171
0.771347
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuMidphaseInterface.h" #include "GuMeshFactory.h" #include "GuConvexEdgeFlags.h" #include "GuEdgeList.h" #include "geometry/PxGeometryInternal.h" using namespace physx; using namespace Gu; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PxConcreteType::Enum gTable[] = { PxConcreteType::eTRIANGLE_MESH_BVH33, PxConcreteType::eTRIANGLE_MESH_BVH34 }; TriangleMesh::TriangleMesh(MeshFactory* factory, TriangleMeshData& d) : PxTriangleMesh (PxType(gTable[d.mType]), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mNbVertices (d.mNbVertices), mNbTriangles (d.mNbTriangles), mVertices (d.mVertices), mTriangles (d.mTriangles), mAABB (d.mAABB), mExtraTrigData (d.mExtraTrigData), mGeomEpsilon (d.mGeomEpsilon), mFlags (d.mFlags), mMaterialIndices (d.mMaterialIndices), mFaceRemap (d.mFaceRemap), mAdjacencies (d.mAdjacencies), mMeshFactory (factory), mEdgeList (NULL), mMass (d.mMass), mInertia (d.mInertia), mLocalCenterOfMass (d.mLocalCenterOfMass), mGRB_triIndices (d.mGRB_primIndices), mGRB_triAdjacencies (d.mGRB_primAdjacencies), mGRB_faceRemap (d.mGRB_faceRemap), mGRB_faceRemapInverse (d.mGRB_faceRemapInverse), mGRB_BV32Tree (d.mGRB_BV32Tree), mSdfData (d.mSdfData), mAccumulatedTrianglesRef (d.mAccumulatedTrianglesRef), mTrianglesReferences (d.mTrianglesReferences), mNbTrianglesReferences (d.mNbTrianglesReferences) { // this constructor takes ownership of memory from the data object d.mVertices = NULL; d.mTriangles = NULL; d.mExtraTrigData = NULL; d.mFaceRemap = NULL; d.mAdjacencies = NULL; d.mMaterialIndices = NULL; d.mGRB_primIndices = NULL; d.mGRB_primAdjacencies = NULL; d.mGRB_faceRemap = NULL; d.mGRB_faceRemapInverse = NULL; d.mGRB_BV32Tree = NULL; d.mSdfData.mSdf = NULL; d.mSdfData.mSubgridStartSlots = NULL; d.mSdfData.mSubgridSdf = NULL; d.mAccumulatedTrianglesRef = NULL; d.mTrianglesReferences = NULL; // PT: 'getPaddedBounds()' is only safe if we make sure the bounds member is followed by at least 32bits of data PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(TriangleMesh, mExtraTrigData)>=PX_OFFSET_OF(TriangleMesh, mAABB)+4); } // PT: temporary for Kit TriangleMesh::TriangleMesh(const PxTriangleMeshInternalData& data) : PxTriangleMesh (PxConcreteType::eTRIANGLE_MESH_BVH34, PxBaseFlags(0)), mNbVertices (data.mNbVertices), mNbTriangles (data.mNbTriangles), mVertices (data.mVertices), mTriangles (data.mTriangles), mExtraTrigData (NULL), mGeomEpsilon (data.mGeomEpsilon), mFlags (data.mFlags), mMaterialIndices (NULL), mFaceRemap (data.mFaceRemap), mAdjacencies (NULL), mMeshFactory (NULL), mEdgeList (NULL), mGRB_triIndices (NULL), mGRB_triAdjacencies (NULL), mGRB_faceRemap (NULL), mGRB_faceRemapInverse (NULL), mGRB_BV32Tree (NULL), mAccumulatedTrianglesRef(NULL), mTrianglesReferences (NULL), mNbTrianglesReferences (0) { mAABB.mCenter = data.mAABB_Center; mAABB.mExtents = data.mAABB_Extents; } //~ PT: temporary for Kit TriangleMesh::~TriangleMesh() { if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { PX_FREE(mExtraTrigData); PX_FREE(mFaceRemap); PX_FREE(mAdjacencies); PX_FREE(mMaterialIndices); PX_FREE(mTriangles); PX_FREE(mVertices); PX_FREE(mGRB_triIndices); PX_FREE(mGRB_triAdjacencies); PX_FREE(mGRB_faceRemap); PX_FREE(mGRB_faceRemapInverse); PX_DELETE(mGRB_BV32Tree); PX_FREE(mAccumulatedTrianglesRef); PX_FREE(mTrianglesReferences); } PX_DELETE(mEdgeList); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PT: used to be automatic but making it manual saves bytes in the internal mesh void TriangleMesh::exportExtraData(PxSerializationContext& stream) { //PX_DEFINE_DYNAMIC_ARRAY(TriangleMesh, mVertices, PxField::eVEC3, mNbVertices, Ps::PxFieldFlag::eSERIALIZE), if(mVertices) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mVertices, mNbVertices * sizeof(PxVec3)); } if(mTriangles) { const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32); stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mTriangles, mNbTriangles * 3 * triangleSize); } //PX_DEFINE_DYNAMIC_ARRAY(TriangleMesh, mExtraTrigData, PxField::eBYTE, mNbTriangles, Ps::PxFieldFlag::eSERIALIZE), if(mExtraTrigData) { // PT: it might not be needed to 16-byte align this array of PxU8.... stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mExtraTrigData, mNbTriangles * sizeof(PxU8)); } if(mMaterialIndices) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mMaterialIndices, mNbTriangles * sizeof(PxU16)); } if(mFaceRemap) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mFaceRemap, mNbTriangles * sizeof(PxU32)); } if(mAdjacencies) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mAdjacencies, mNbTriangles * sizeof(PxU32) * 3); } if(mGRB_triIndices) { const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32); stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mGRB_triIndices, mNbTriangles * 3 * triangleSize); } if(mGRB_triAdjacencies) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mGRB_triAdjacencies, mNbTriangles * sizeof(PxU32) * 4); } if(mGRB_faceRemap) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mGRB_faceRemap, mNbTriangles * sizeof(PxU32)); } if(mGRB_faceRemapInverse) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mGRB_faceRemapInverse, mNbTriangles * sizeof(PxU32)); } if(mGRB_BV32Tree) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mGRB_BV32Tree, sizeof(BV32Tree)); mGRB_BV32Tree->exportExtraData(stream); } mSdfData.exportExtraData(stream); } void TriangleMesh::importExtraData(PxDeserializationContext& context) { // PT: vertices are followed by indices, so it will be safe to V4Load vertices from a deserialized binary file if(mVertices) mVertices = context.readExtraData<PxVec3, PX_SERIAL_ALIGN>(mNbVertices); if(mTriangles) { if(mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) mTriangles = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(3*mNbTriangles); else mTriangles = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3*mNbTriangles); } if(mExtraTrigData) mExtraTrigData = context.readExtraData<PxU8, PX_SERIAL_ALIGN>(mNbTriangles); if(mMaterialIndices) mMaterialIndices = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(mNbTriangles); if(mFaceRemap) mFaceRemap = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles); if(mAdjacencies) mAdjacencies = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3*mNbTriangles); if(mGRB_triIndices) { if(mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) mGRB_triIndices = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(3 * mNbTriangles); else mGRB_triIndices = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3 * mNbTriangles); } if(mGRB_triAdjacencies) { mGRB_triAdjacencies = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(4 * mNbTriangles); } if(mGRB_faceRemap) { mGRB_faceRemap = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles); } if(mGRB_faceRemapInverse) { mGRB_faceRemapInverse = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles); } if(mGRB_BV32Tree) { mGRB_BV32Tree = context.readExtraData<BV32Tree, PX_SERIAL_ALIGN>(); PX_PLACEMENT_NEW(mGRB_BV32Tree, BV32Tree(PxEmpty)); mGRB_BV32Tree->importExtraData(context); } mSdfData.importExtraData(context); } void TriangleMesh::onRefCountZero() { ::onRefCountZero(this, mMeshFactory, false, "PxTriangleMesh::release: double deletion detected!"); } void TriangleMesh::release() { Cm::RefCountable_decRefCount(*this); } PxVec3* TriangleMesh::getVerticesForModification() { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxTriangleMesh::getVerticesForModification() is not supported for this type of meshes."); return NULL; } PxBounds3 TriangleMesh::refitBVH() { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxTriangleMesh::refitBVH() is not supported for this type of meshes."); return PxBounds3(mAABB.getMin(), mAABB.getMax()); } void TriangleMesh::setAllEdgesActive() { if(mExtraTrigData) { const PxU32 nbTris = mNbTriangles; for(PxU32 i=0; i<nbTris; i++) mExtraTrigData[i] |= ETD_CONVEX_EDGE_ALL; } } const EdgeList* TriangleMesh::requestEdgeList() const { if(!mEdgeList) { EDGELISTCREATE create; create.NbFaces = mNbTriangles; create.Verts = mVertices; if(has16BitIndices()) create.WFaces = reinterpret_cast<const PxU16*>(mTriangles); else create.DFaces = reinterpret_cast<const PxU32*>(mTriangles); mEdgeList = PX_NEW(EdgeList); mEdgeList->init(create); } return mEdgeList; }
10,815
C++
30.625731
199
0.716412
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMidphaseInterface.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_MIDPHASE_INTERFACE_H #define GU_MIDPHASE_INTERFACE_H #include "GuOverlapTests.h" #include "GuRaycastTests.h" #include "GuTriangleMesh.h" #include "GuTetrahedronMesh.h" #include "foundation/PxVecMath.h" #include "PxQueryReport.h" #include "geometry/PxMeshQuery.h" // PT: TODO: revisit this include // PT: this file contains the common interface for all midphase implementations. Specifically the Midphase namespace contains the // midphase-related entry points, dispatching calls to the proper implementations depending on the triangle mesh's type. The rest of it // is simply classes & structs shared by all implementations. namespace physx { class PxMeshScale; class PxTriangleMeshGeometry; namespace Cm { class FastVertex2ShapeScaling; } namespace Gu { struct ConvexHullData; struct CallbackMode { enum Enum { eANY, eCLOSEST, eMULTIPLE }; }; template<typename HitType> struct MeshHitCallback { CallbackMode::Enum mode; MeshHitCallback(CallbackMode::Enum aMode) : mode(aMode) {} PX_FORCE_INLINE bool inAnyMode() const { return mode == CallbackMode::eANY; } PX_FORCE_INLINE bool inClosestMode() const { return mode == CallbackMode::eCLOSEST; } PX_FORCE_INLINE bool inMultipleMode() const { return mode == CallbackMode::eMULTIPLE; } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const HitType& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal& shrunkMaxT, const PxU32* vIndices) = 0; virtual ~MeshHitCallback() {} }; template<typename HitType> struct TetMeshHitCallback { CallbackMode::Enum mode; TetMeshHitCallback(CallbackMode::Enum aMode) : mode(aMode) {} PX_FORCE_INLINE bool inAnyMode() const { return mode == CallbackMode::eANY; } PX_FORCE_INLINE bool inClosestMode() const { return mode == CallbackMode::eCLOSEST; } PX_FORCE_INLINE bool inMultipleMode() const { return mode == CallbackMode::eMULTIPLE; } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const HitType& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& v3, PxReal& shrunkMaxT, const PxU32* vIndices) = 0; virtual ~TetMeshHitCallback() {} }; struct SweepConvexMeshHitCallback; struct LimitedResults { PxU32* mResults; PxU32 mNbResults; PxU32 mMaxResults; PxU32 mStartIndex; PxU32 mNbSkipped; bool mOverflow; PX_FORCE_INLINE LimitedResults(PxU32* results, PxU32 maxResults, PxU32 startIndex) : mResults(results), mMaxResults(maxResults), mStartIndex(startIndex) { reset(); } PX_FORCE_INLINE void reset() { mNbResults = 0; mNbSkipped = 0; mOverflow = false; } PX_FORCE_INLINE bool add(PxU32 index) { if(mNbResults>=mMaxResults) { mOverflow = true; return false; } if(mNbSkipped>=mStartIndex) mResults[mNbResults++] = index; else mNbSkipped++; return true; } }; // RTree forward declarations PX_PHYSX_COMMON_API PxU32 raycast_triangleMesh_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride); PX_PHYSX_COMMON_API bool intersectSphereVsMesh_RTREE(const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API bool intersectBoxVsMesh_RTREE (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API bool intersectCapsuleVsMesh_RTREE(const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API void intersectOBB_RTREE(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned); PX_PHYSX_COMMON_API bool sweepCapsule_MeshGeom_RTREE( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); PX_PHYSX_COMMON_API bool sweepBox_MeshGeom_RTREE( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); PX_PHYSX_COMMON_API void sweepConvex_MeshGeom_RTREE(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit); PX_PHYSX_COMMON_API void pointMeshDistance_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt); // BV4 forward declarations PX_PHYSX_COMMON_API PxU32 raycast_triangleMesh_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride); PX_PHYSX_COMMON_API bool intersectSphereVsMesh_BV4 (const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API bool intersectBoxVsMesh_BV4 (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API bool intersectCapsuleVsMesh_BV4 (const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); PX_PHYSX_COMMON_API void intersectOBB_BV4(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned); PX_PHYSX_COMMON_API void intersectOBB_BV4(const TetrahedronMesh* mesh, const Box& obb, TetMeshHitCallback<PxGeomRaycastHit>& callback); PX_PHYSX_COMMON_API bool sweepCapsule_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); PX_PHYSX_COMMON_API bool sweepBox_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); PX_PHYSX_COMMON_API void sweepConvex_MeshGeom_BV4(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit); PX_PHYSX_COMMON_API void pointMeshDistance_BV4(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt); PX_PHYSX_COMMON_API bool intersectMeshVsMesh_BV4( PxReportCallback<PxGeomIndexPair>& callback, const TriangleMesh& triMesh0, const PxTransform& meshPose0, const PxMeshScale& meshScale0, const TriangleMesh& triMesh1, const PxTransform& meshPose1, const PxMeshScale& meshScale1, PxMeshMeshQueryFlags meshMeshFlags, float tolerance); typedef PxU32 (*MidphaseRaycastFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride); typedef bool (*MidphaseSphereOverlapFunction) (const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); typedef bool (*MidphaseBoxOverlapFunction) (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); typedef bool (*MidphaseCapsuleOverlapFunction) (const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results); typedef void (*MidphaseBoxCBOverlapFunction) (const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned); typedef bool (*MidphaseCapsuleSweepFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); typedef bool (*MidphaseBoxSweepFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose, const Gu::Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation); typedef void (*MidphaseConvexSweepFunction)( const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit); typedef void (*MidphasePointMeshFunction)(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt); static const MidphaseRaycastFunction gMidphaseRaycastTable[PxMeshMidPhase::eLAST] = { raycast_triangleMesh_RTREE, raycast_triangleMesh_BV4, }; static const MidphaseSphereOverlapFunction gMidphaseSphereOverlapTable[PxMeshMidPhase::eLAST] = { intersectSphereVsMesh_RTREE, intersectSphereVsMesh_BV4, }; static const MidphaseBoxOverlapFunction gMidphaseBoxOverlapTable[PxMeshMidPhase::eLAST] = { intersectBoxVsMesh_RTREE, intersectBoxVsMesh_BV4, }; static const MidphaseCapsuleOverlapFunction gMidphaseCapsuleOverlapTable[PxMeshMidPhase::eLAST] = { intersectCapsuleVsMesh_RTREE, intersectCapsuleVsMesh_BV4, }; static const MidphaseBoxCBOverlapFunction gMidphaseBoxCBOverlapTable[PxMeshMidPhase::eLAST] = { intersectOBB_RTREE, intersectOBB_BV4, }; static const MidphaseBoxSweepFunction gMidphaseBoxSweepTable[PxMeshMidPhase::eLAST] = { sweepBox_MeshGeom_RTREE, sweepBox_MeshGeom_BV4, }; static const MidphaseCapsuleSweepFunction gMidphaseCapsuleSweepTable[PxMeshMidPhase::eLAST] = { sweepCapsule_MeshGeom_RTREE, sweepCapsule_MeshGeom_BV4, }; static const MidphaseConvexSweepFunction gMidphaseConvexSweepTable[PxMeshMidPhase::eLAST] = { sweepConvex_MeshGeom_RTREE, sweepConvex_MeshGeom_BV4, }; static const MidphasePointMeshFunction gMidphasePointMeshTable[PxMeshMidPhase::eLAST] = { pointMeshDistance_RTREE, pointMeshDistance_BV4, }; namespace Midphase { // \param[in] mesh triangle mesh to raycast against // \param[in] meshGeom geometry object associated with the mesh // \param[in] meshTransform pose/transform of geometry object // \param[in] rayOrigin ray's origin // \param[in] rayDir ray's unit dir // \param[in] maxDist ray's length/max distance // \param[in] hitFlags query behavior flags // \param[in] maxHits max number of hits = size of 'hits' buffer // \param[out] hits result buffer where to write raycast hits // \return number of hits written to 'hits' result buffer // \note there's no mechanism to report overflow. Returned number of hits is just clamped to maxHits. PX_FORCE_INLINE PxU32 raycastTriangleMesh( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseRaycastTable[index](mesh, meshGeom, meshTransform, rayOrigin, rayDir, maxDist, hitFlags, maxHits, hits, stride); } // \param[in] sphere sphere // \param[in] mesh triangle mesh // \param[in] meshTransform pose/transform of triangle mesh // \param[in] meshScale mesh scale // \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough // \return true if at least one overlap has been found PX_FORCE_INLINE bool intersectSphereVsMesh(const Sphere& sphere, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseSphereOverlapTable[index](sphere, mesh, meshTransform, meshScale, results); } // \param[in] box box // \param[in] mesh triangle mesh // \param[in] meshTransform pose/transform of triangle mesh // \param[in] meshScale mesh scale // \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough // \return true if at least one overlap has been found PX_FORCE_INLINE bool intersectBoxVsMesh(const Box& box, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseBoxOverlapTable[index](box, mesh, meshTransform, meshScale, results); } // \param[in] capsule capsule // \param[in] mesh triangle mesh // \param[in] meshTransform pose/transform of triangle mesh // \param[in] meshScale mesh scale // \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough // \return true if at least one overlap has been found PX_FORCE_INLINE bool intersectCapsuleVsMesh(const Capsule& capsule, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results) { const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseCapsuleOverlapTable[index](capsule, mesh, meshTransform, meshScale, results); } // \param[in] mesh triangle mesh // \param[in] box box // \param[in] callback callback object, called each time a hit is found // \param[in] bothTriangleSidesCollide true for double-sided meshes // \param[in] checkObbIsAligned true to use a dedicated codepath for axis-aligned boxes PX_FORCE_INLINE void intersectOBB(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned = true) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); gMidphaseBoxCBOverlapTable[index](mesh, obb, callback, bothTriangleSidesCollide, checkObbIsAligned); } // \param[in] mesh tetrahedron mesh // \param[in] box box // \param[in] callback callback object, called each time a hit is found PX_FORCE_INLINE void intersectOBB(const TetrahedronMesh* mesh, const Box& obb, TetMeshHitCallback<PxGeomRaycastHit>& callback) { intersectOBB_BV4(mesh, obb, callback); } // \param[in] mesh triangle mesh // \param[in] meshGeom geometry object associated with the mesh // \param[in] meshTransform pose/transform of geometry object // \param[in] capsule swept capsule // \param[in] unitDir sweep's unit dir // \param[in] distance sweep's length/max distance // \param[out] sweepHit hit result // \param[in] hitFlags query behavior flags // \param[in] inflation optional inflation value for swept shape // \return true if a hit was found, false otherwise PX_FORCE_INLINE bool sweepCapsuleVsMesh(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform, const Gu::Capsule& capsule, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseCapsuleSweepTable[index](mesh, meshGeom, meshTransform, capsule, unitDir, distance, sweepHit, hitFlags, inflation); } // \param[in] mesh triangle mesh // \param[in] meshGeom geometry object associated with the mesh // \param[in] meshTransform pose/transform of geometry object // \param[in] box swept box // \param[in] unitDir sweep's unit dir // \param[in] distance sweep's length/max distance // \param[out] sweepHit hit result // \param[in] hitFlags query behavior flags // \param[in] inflation optional inflation value for swept shape // \return true if a hit was found, false otherwise PX_FORCE_INLINE bool sweepBoxVsMesh(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform, const Gu::Box& box, const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); return gMidphaseBoxSweepTable[index](mesh, meshGeom, meshTransform, box, unitDir, distance, sweepHit, hitFlags, inflation); } // \param[in] mesh triangle mesh // \param[in] hullBox hull's bounding box // \param[in] localDir sweep's unit dir, in local/mesh space // \param[in] distance sweep's length/max distance // \param[in] callback callback object, called each time a hit is found // \param[in] anyHit true for PxHitFlag::eMESH_ANY queries PX_FORCE_INLINE void sweepConvexVsMesh(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); gMidphaseConvexSweepTable[index](mesh, hullBox, localDir, distance, callback, anyHit); } PX_FORCE_INLINE void pointMeshDistance(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist , PxU32& closestIndex, float& dist, PxVec3& closestPt) { const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33); gMidphasePointMeshTable[index](mesh, meshGeom, pose, point, maxDist, closestIndex, dist, closestPt); } } } } #endif // GU_MIDPHASE_INTERFACE_H
20,406
C
52.56168
223
0.764971
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxBoxOverlapTest.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_BV4_BOX_BOX_OVERLAP_TEST_H #define GU_BV4_BOX_BOX_OVERLAP_TEST_H #ifndef GU_BV4_USE_SLABS PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const PxVec3& extents, const PxVec3& center, const OBBTestParams* PX_RESTRICT params) { const Vec4V extentsV = V4LoadU(&extents.x); const Vec4V TV = V4Sub(V4LoadA_Safe(&params->mTBoxToModel_PaddedAligned.x), V4LoadU(&center.x)); { const Vec4V absTV = V4Abs(TV); const BoolV resTV = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(&params->mBB_PaddedAligned.x))); const PxU32 test = BGetBitMask(resTV); if(test&7) return 0; } Vec4V tV; { const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV); const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV); tV = V4Mul(TV, V4LoadA_Safe(&params->mPreca0_PaddedAligned.x)); tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(&params->mPreca1_PaddedAligned.x))); tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(&params->mPreca2_PaddedAligned.x))); } Vec4V t2V; { const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV); const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV); t2V = V4Mul(extentsV, V4LoadA_Safe(&params->mPreca0b_PaddedAligned.x)); t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(&params->mPreca1b_PaddedAligned.x))); t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(&params->mPreca2b_PaddedAligned.x))); t2V = V4Add(t2V, V4LoadA_Safe(&params->mBoxExtents_PaddedAligned.x)); } { const Vec4V abstV = V4Abs(tV); const BoolV resB = V4IsGrtr(abstV, t2V); const PxU32 test = BGetBitMask(resB); if(test&7) return 0; } return 1; } #ifdef GU_BV4_QUANTIZED_TREE template<class T> PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const T* PX_RESTRICT node, const OBBTestParams* PX_RESTRICT params) { // A.B. enable new version only for intel non simd path #if PX_INTEL_FAMILY && !defined(PX_SIMD_DISABLED) // #define NEW_VERSION #endif #ifdef NEW_VERSION SSE_CONST4(maskV, 0x7fffffff); SSE_CONST4(maskQV, 0x0000ffff); #endif #ifdef NEW_VERSION Vec4V centerV = V4LoadA((float*)node->mAABB.mData); __m128 extentsV = _mm_castsi128_ps(_mm_and_si128(_mm_castps_si128(centerV), SSE_CONST(maskQV))); extentsV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(extentsV)), V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x)); centerV = _mm_castsi128_ps(_mm_srai_epi32(_mm_castps_si128(centerV), 16)); centerV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(centerV)), V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x)); #else const VecI32V centerVI = I4LoadA((PxI32*)node->mAABB.mData); const VecI32V extentsVI = VecI32V_And(centerVI, I4Load(0x0000ffff)); const Vec4V extentsV = V4Mul(Vec4V_From_VecI32V(extentsVI), V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x)); const VecI32V centerVShift = VecI32V_RightShift(centerVI, 16); const Vec4V centerV = V4Mul(Vec4V_From_VecI32V(centerVShift), V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x)); #endif const Vec4V TV = V4Sub(V4LoadA_Safe(&params->mTBoxToModel_PaddedAligned.x), centerV); { #ifdef NEW_VERSION const __m128 absTV = _mm_and_ps(TV, SSE_CONSTF(maskV)); #else const Vec4V absTV = V4Abs(TV); #endif const BoolV resTV = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(&params->mBB_PaddedAligned.x))); const PxU32 test = BGetBitMask(resTV); if(test&7) return 0; } Vec4V tV; { const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV); const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV); tV = V4Mul(TV, V4LoadA_Safe(&params->mPreca0_PaddedAligned.x)); tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(&params->mPreca1_PaddedAligned.x))); tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(&params->mPreca2_PaddedAligned.x))); } Vec4V t2V; { const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV); const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV); t2V = V4Mul(extentsV, V4LoadA_Safe(&params->mPreca0b_PaddedAligned.x)); t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(&params->mPreca1b_PaddedAligned.x))); t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(&params->mPreca2b_PaddedAligned.x))); t2V = V4Add(t2V, V4LoadA_Safe(&params->mBoxExtents_PaddedAligned.x)); } { #ifdef NEW_VERSION const __m128 abstV = _mm_and_ps(tV, SSE_CONSTF(maskV)); #else const Vec4V abstV = V4Abs(tV); #endif const BoolV resB = V4IsGrtr(abstV, t2V); const PxU32 test = BGetBitMask(resB); if(test&7) return 0; } return 1; } #endif // GU_BV4_QUANTIZED_TREE #endif // GU_BV4_USE_SLABS #ifdef GU_BV4_USE_SLABS PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const Vec4V boxCenter, const Vec4V extentsV, const OBBTestParams* PX_RESTRICT params) { const Vec4V TV = V4Sub(V4LoadA_Safe(&params->mTBoxToModel_PaddedAligned.x), boxCenter); { const Vec4V absTV = V4Abs(TV); const BoolV res = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(&params->mBB_PaddedAligned.x))); const PxU32 test = BGetBitMask(res); if(test&7) return 0; } Vec4V tV; { const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV); const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV); tV = V4Mul(TV, V4LoadA_Safe(&params->mPreca0_PaddedAligned.x)); tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(&params->mPreca1_PaddedAligned.x))); tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(&params->mPreca2_PaddedAligned.x))); } Vec4V t2V; { const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV); const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV); t2V = V4Mul(extentsV, V4LoadA_Safe(&params->mPreca0b_PaddedAligned.x)); t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(&params->mPreca1b_PaddedAligned.x))); t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(&params->mPreca2b_PaddedAligned.x))); t2V = V4Add(t2V, V4LoadA_Safe(&params->mBoxExtents_PaddedAligned.x)); } { const Vec4V abstV = V4Abs(tV); const BoolV resB = V4IsGrtr(abstV, t2V); const PxU32 test = BGetBitMask(resB); if(test&7) return 0; } return 1; } #endif // GU_BV4_USE_SLABS #endif // GU_BV4_BOX_BOX_OVERLAP_TEST_H
7,726
C
37.829146
130
0.705022
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_SphereOverlap.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuBV4.h" using namespace physx; using namespace Gu; #include "foundation/PxBasicTemplates.h" #include "foundation/PxVecMath.h" using namespace physx::aos; #include "GuBV4_Common.h" #include "GuSphere.h" #include "GuDistancePointTriangle.h" #if PX_VC #pragma warning ( disable : 4324 ) #endif // Sphere overlap any struct SphereParams { const IndTri32* PX_RESTRICT mTris32; const IndTri16* PX_RESTRICT mTris16; const PxVec3* PX_RESTRICT mVerts; BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned); BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned); BV4_ALIGN16(PxVec3 mCenter_PaddedAligned); float mRadius2; #ifdef GU_BV4_USE_SLABS BV4_ALIGN16(PxVec3 mCenter_PaddedAligned2); float mRadius22; #endif }; #ifndef GU_BV4_USE_SLABS // PT: TODO: refactor with bucket pruner code (TA34704) static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const PxVec3& center, const PxVec3& extents, const SphereParams* PX_RESTRICT params) { const Vec4V mCenter = V4LoadA_Safe(&params->mCenter_PaddedAligned.x); const FloatV mRadius2 = FLoad(params->mRadius2); const Vec4V boxCenter = V4LoadU(&center.x); const Vec4V boxExtents = V4LoadU(&extents.x); const Vec4V offset = V4Sub(mCenter, boxCenter); const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents); const Vec4V d = V4Sub(offset, closest); const PxU32 test = (PxU32)_mm_movemask_ps(FIsGrtrOrEq(mRadius2, V4Dot3(d, d))); return (test & 0x7) == 0x7; } #endif static PX_FORCE_INLINE PxIntBool SphereTriangle(const SphereParams* PX_RESTRICT params, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2) { { const float sqrDist = (p0 - params->mCenter_PaddedAligned).magnitudeSquared(); if(sqrDist <= params->mRadius2) return 1; } const PxVec3 edge10 = p1 - p0; const PxVec3 edge20 = p2 - p0; const PxVec3 cp = closestPtPointTriangle2(params->mCenter_PaddedAligned, p0, p1, p2, edge10, edge20); const float sqrDist = (cp - params->mCenter_PaddedAligned).magnitudeSquared(); return sqrDist <= params->mRadius2; } // PT: TODO: evaluate if SIMD distance function would be faster here (TA34704) // PT: TODO: __fastcall removed to make it compile everywhere. Revisit. static /*PX_FORCE_INLINE*/ PxIntBool /*__fastcall*/ SphereTriangle(const SphereParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); return SphereTriangle(params, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2]); } namespace { class LeafFunction_SphereOverlapAny { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const SphereParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(SphereTriangle(params, primIndex)) return 1; primIndex++; }while(nbToGo--); return 0; } }; } template<class ParamsT> static PX_FORCE_INLINE void setupSphereParams(ParamsT* PX_RESTRICT params, const Sphere& sphere, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh) { computeLocalSphere(params->mRadius2, params->mCenter_PaddedAligned, sphere, worldm_Aligned); #ifdef GU_BV4_USE_SLABS params->mCenter_PaddedAligned2 = params->mCenter_PaddedAligned*2.0f; params->mRadius22 = params->mRadius2*4.0f; #endif setupMeshPointersAndQuantizedCoeffs(params, mesh, tree); } #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs.h" static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const Vec4V boxCenter, const Vec4V boxExtents, const SphereParams* PX_RESTRICT params) { const Vec4V mCenter = V4LoadA_Safe(&params->mCenter_PaddedAligned2.x); const FloatV mRadius2 = FLoad(params->mRadius22); const Vec4V offset = V4Sub(mCenter, boxCenter); const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents); const Vec4V d = V4Sub(offset, closest); const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, V4Dot3(d, d))); return (test & 0x7) == 0x7; } #else #ifdef GU_BV4_QUANTIZED_TREE static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const BVDataPacked* PX_RESTRICT node, const SphereParams* PX_RESTRICT params) { const VecI32V testV = I4LoadA((const PxI32*)&node->mAABB.mData[0]); const VecI32V qextentsV = VecI32V_And(testV, I4LoadXYZW(0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff)); const VecI32V qcenterV = VecI32V_RightShift(testV, 16); const Vec4V boxCenter = V4Mul(Vec4V_From_VecI32V(qcenterV), V4LoadA_Safe(&params->mCenterOrMinCoeff_PaddedAligned.x)); const Vec4V boxExtents = V4Mul(Vec4V_From_VecI32V(qextentsV), V4LoadA_Safe(&params->mExtentsOrMaxCoeff_PaddedAligned.x)); const Vec4V mCenter = V4LoadA_Safe(&params->mCenter_PaddedAligned.x); const FloatV mRadius2 = FLoad(params->mRadius2); const Vec4V offset = V4Sub(mCenter, boxCenter); const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents); const Vec4V d = V4Sub(offset, closest); const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, V4Dot3(d, d))); return (test & 0x7) == 0x7; } #endif #endif #include "GuBV4_ProcessStreamNoOrder_SphereAABB.h" #ifdef GU_BV4_USE_SLABS #include "GuBV4_Slabs_SwizzledNoOrder.h" #endif #define GU_BV4_PROCESS_STREAM_NO_ORDER #include "GuBV4_Internal.h" PxIntBool BV4_OverlapSphereAny(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned) { const SourceMesh* PX_RESTRICT mesh =static_cast<const SourceMesh*>(tree.mMeshInterface); SphereParams Params; setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh); if(tree.mNodes) return processStreamNoOrder<LeafFunction_SphereOverlapAny>(tree, &Params); else { const PxU32 nbTris = mesh->getNbPrimitives(); PX_ASSERT(nbTris<16); return LeafFunction_SphereOverlapAny::doLeafTest(&Params, nbTris); } } // Sphere overlap all struct SphereParamsAll : SphereParams { PxU32 mNbHits; PxU32 mMaxNbHits; PxU32* mHits; }; namespace { class LeafFunction_SphereOverlapAll { public: static PX_FORCE_INLINE PxIntBool doLeafTest(SphereParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { if(SphereTriangle(params, primIndex)) { SphereParamsAll* ParamsAll = static_cast<SphereParamsAll*>(params); if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits) return 1; ParamsAll->mHits[ParamsAll->mNbHits] = primIndex; ParamsAll->mNbHits++; } primIndex++; }while(nbToGo--); return 0; } }; } PxU32 BV4_OverlapSphereAll(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow) { const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface); SphereParamsAll Params; Params.mNbHits = 0; Params.mMaxNbHits = size; Params.mHits = results; setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh); if(tree.mNodes) overflow = processStreamNoOrder<LeafFunction_SphereOverlapAll>(tree, &Params)!=0; else { const PxU32 nbTris = mesh->getNbPrimitives(); PX_ASSERT(nbTris<16); overflow = LeafFunction_SphereOverlapAll::doLeafTest(&Params, nbTris)!=0; } return Params.mNbHits; } // Sphere overlap - callback version struct SphereParamsCB : SphereParams { MeshOverlapCallback mCallback; void* mUserData; }; namespace { class LeafFunction_SphereOverlapCB { public: static PX_FORCE_INLINE PxIntBool doLeafTest(const SphereParamsCB* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; if(SphereTriangle(params, p0, p1, p2)) { const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 }; if((params->mCallback)(params->mUserData, p0, p1, p2, primIndex, vrefs)) return 1; } primIndex++; }while(nbToGo--); return 0; } }; } // PT: this one is currently not used void BV4_OverlapSphereCB(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); SphereParamsCB Params; Params.mCallback = callback; Params.mUserData = userData; setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh); if(tree.mNodes) processStreamNoOrder<LeafFunction_SphereOverlapCB>(tree, &Params); else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); LeafFunction_SphereOverlapCB::doLeafTest(&Params, nbTris); } } // Point distance query // Implemented here as a variation on the sphere-overlap codepath // TODO: // * visit closest nodes first // - revisit inlining // - lazy-compute final results // - SIMD // - return uvs // - maxDist input param struct PointDistanceParams : SphereParams { PxVec3 mClosestPt; PxU32 mIndex; }; namespace { class LeafFunction_PointDistance { public: static PX_FORCE_INLINE PxIntBool doLeafTest(SphereParams* PX_RESTRICT params, PxU32 primIndex) { PxU32 nbToGo = getNbPrimitives(primIndex); do { PxU32 VRef0, VRef1, VRef2; getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16); const PxVec3& p0 = params->mVerts[VRef0]; const PxVec3& p1 = params->mVerts[VRef1]; const PxVec3& p2 = params->mVerts[VRef2]; const PxVec3 edge10 = p1 - p0; const PxVec3 edge20 = p2 - p0; const PxVec3 cp = closestPtPointTriangle2(params->mCenter_PaddedAligned, p0, p1, p2, edge10, edge20); const float sqrDist = (cp - params->mCenter_PaddedAligned).magnitudeSquared(); if(sqrDist <= params->mRadius2) { PointDistanceParams* Params = static_cast<PointDistanceParams*>(params); Params->mClosestPt = cp; Params->mIndex = primIndex; Params->mRadius2 = sqrDist; #ifdef GU_BV4_USE_SLABS Params->mRadius22 = sqrDist*4.0f; #endif } primIndex++; }while(nbToGo--); return 0; } }; } namespace { static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap2(const Vec4V boxCenter, const Vec4V boxExtents, const SphereParams* PX_RESTRICT params, float* PX_RESTRICT _d) { const Vec4V mCenter = V4LoadA_Safe(&params->mCenter_PaddedAligned2.x); const FloatV mRadius2 = FLoad(params->mRadius22); const Vec4V offset = V4Sub(mCenter, boxCenter); const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents); const Vec4V d = V4Sub(offset, closest); const FloatV dot = V4Dot3(d, d); FStore(dot, _d); const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, dot)); return (test & 0x7) == 0x7; } template<class LeafTestT, int i, class ParamsT> PX_FORCE_INLINE void BV4_ProcessNodeNoOrder_SwizzledQ2(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params, float* PX_RESTRICT _d) { OPC_SLABS_GET_CE2Q(i) if(BV4_SphereAABBOverlap2(centerV, extentsV, params, _d)) { if(node->isLeaf(i)) LeafTestT::doLeafTest(params, node->getPrimitive(i)); else Stack[Nb++] = node->getChildData(i); } } template<class LeafTestT, int i, class ParamsT> PX_FORCE_INLINE void BV4_ProcessNodeNoOrder_SwizzledNQ2(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledNQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params, float* PX_RESTRICT _d) { OPC_SLABS_GET_CE2NQ(i) if(BV4_SphereAABBOverlap2(centerV, extentsV, params, _d)) { if(node->isLeaf(i)) { LeafTestT::doLeafTest(params, node->getPrimitive(i)); } else Stack[Nb++] = node->getChildData(i); } } static PX_FORCE_INLINE void sort(PxU32* next, float* di, PxU32 i, PxU32 j) { if(di[i]<di[j]) // PT: "wrong" side on purpose, it's a LIFO stack { PxSwap(next[i], next[j]); PxSwap(di[i], di[j]); } } static PX_FORCE_INLINE void sortCandidates(PxU32 nbMore, PxU32* next, float* di, PxU32* stack, PxU32& nb) { // PT: this is not elegant and it looks slow, but for distance queries the time spent here is well worth it. if(0) { while(nbMore) { float minDist = di[0]; PxU32 minIndex = 0; for(PxU32 i=1;i<nbMore;i++) { if(di[i]>minDist) // PT: "wrong" side on purpose, it's a LIFO stack { minDist = di[i]; minIndex = i; } } stack[nb++] = next[minIndex]; nbMore--; PxSwap(next[minIndex], next[nbMore]); PxSwap(di[minIndex], di[nbMore]); } } else { switch(nbMore) { case 1: { stack[nb++] = next[0]; break; } case 2: { sort(next, di, 0, 1); PX_ASSERT(di[0]>=di[1]); stack[nb++] = next[0]; stack[nb++] = next[1]; break; } case 3: { sort(next, di, 0, 1); sort(next, di, 1, 2); sort(next, di, 0, 1); PX_ASSERT(di[0]>=di[1]); PX_ASSERT(di[1]>=di[2]); stack[nb++] = next[0]; stack[nb++] = next[1]; stack[nb++] = next[2]; break; } case 4: { sort(next, di, 0, 1); sort(next, di, 2, 3); sort(next, di, 0, 2); sort(next, di, 1, 3); sort(next, di, 1, 2); PX_ASSERT(di[0]>=di[1]); PX_ASSERT(di[1]>=di[2]); PX_ASSERT(di[2]>=di[3]); stack[nb++] = next[0]; stack[nb++] = next[1]; stack[nb++] = next[2]; stack[nb++] = next[3]; break; } } } } } void BV4_PointDistance(const PxVec3& point, const BV4Tree& tree, float maxDist, PxU32& index, float& dist, PxVec3& cp/*, const PxMat44* PX_RESTRICT worldm_Aligned*/) { const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface); const float limit = sqrtf(sqrtf(PX_MAX_F32)); if(maxDist>limit) maxDist = limit; PointDistanceParams Params; setupSphereParams(&Params, Sphere(point, maxDist), &tree, NULL/*worldm_Aligned*/, mesh); if(tree.mNodes) { if(0) { // PT: unfortunately distance queries don't map nicely to the current BV4 framework // This works but it doesn't visit closest nodes first so it's suboptimal. We also // cannot use the ordered traversal since it's based on PNS, i.e. a fixed ray direction. processStreamNoOrder<LeafFunction_PointDistance>(tree, &Params); } PxU32 initData = tree.mInitData; PointDistanceParams* PX_RESTRICT params = &Params; if(tree.mQuantized) { const BVDataPackedQ* PX_RESTRICT nodes = reinterpret_cast<const BVDataPackedQ*>(tree.mNodes); const BVDataPackedQ* root = nodes; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; nodes = root + getChildOffset(childData); const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(nodes); const PxU32 nodeType = getChildType(childData); PxU32 nbMore=0; PxU32 next[4]; float di[4]; if(nodeType>1) BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 3>(next, nbMore, tn, params, &di[nbMore]); if(nodeType>0) BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 2>(next, nbMore, tn, params, &di[nbMore]); BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 1>(next, nbMore, tn, params, &di[nbMore]); BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 0>(next, nbMore, tn, params, &di[nbMore]); sortCandidates(nbMore, next, di, stack, nb); }while(nb); } else { const BVDataPackedNQ* PX_RESTRICT nodes = reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes); const BVDataPackedNQ* root = nodes; PxU32 nb=1; PxU32 stack[GU_BV4_STACK_SIZE]; stack[0] = initData; do { const PxU32 childData = stack[--nb]; nodes = root + getChildOffset(childData); const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(nodes); const PxU32 nodeType = getChildType(childData); PxU32 nbMore=0; PxU32 next[4]; float di[4]; if(nodeType>1) BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 3>(next, nbMore, tn, params, &di[nbMore]); if(nodeType>0) BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 2>(next, nbMore, tn, params, &di[nbMore]); BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 1>(next, nbMore, tn, params, &di[nbMore]); BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 0>(next, nbMore, tn, params, &di[nbMore]); sortCandidates(nbMore, next, di, stack, nb); }while(nb); } } else { const PxU32 nbTris = mesh->getNbTriangles(); PX_ASSERT(nbTris<16); LeafFunction_PointDistance::doLeafTest(&Params, nbTris); } index = Params.mIndex; dist = sqrtf(Params.mRadius2); cp = Params.mClosestPt; }
18,353
C++
28.699029
208
0.711764
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuRTreeQueries.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. /* General notes: rtree depth-first traversal looks like this: push top level page onto stack pop page from stack for each node in page if node overlaps with testrect push node's subpage we want to efficiently keep track of current stack level to know if the current page is a leaf or not (since we don't store a flag with the page due to no space, we can't determine it just by looking at current page) since we traverse depth first, the levels for nodes on the stack look like this: l0 l0 l1 l2 l2 l3 l3 l3 l4 we can encode this as an array of 4 bits per level count into a 32-bit integer to simplify the code->level computation we also keep track of current level by incrementing the level whenever any subpages from current test page are pushed onto the stack when we pop a page off the stack we use this encoding to determine if we should decrement the stack level */ #include "foundation/PxBounds3.h" #include "foundation/PxIntrinsics.h" #include "foundation/PxBitUtils.h" #include "GuRTree.h" #include "GuBox.h" #include "foundation/PxVecMath.h" #include "PxQueryReport.h" // for PxAgain #include "GuBVConstants.h" //#define VERIFY_RTREE #ifdef VERIFY_RTREE #include "GuIntersectionRayBox.h" #include "GuIntersectionBoxBox.h" #include "stdio.h" #endif using namespace physx; using namespace aos; namespace physx { namespace Gu { using namespace aos; #define v_absm(a) V4Andc(a, signMask) #define V4FromF32A(x) V4LoadA(x) #define PxF32FV(x) FStore(x) #define CAST_U8(a) reinterpret_cast<PxU8*>(a) ///////////////////////////////////////////////////////////////////////// void RTree::traverseAABB(const PxVec3& boxMin, const PxVec3& boxMax, const PxU32 maxResults, PxU32* resultsPtr, Callback* callback) const { PX_UNUSED(resultsPtr); PX_ASSERT(callback); PX_ASSERT(maxResults >= mPageSize); PX_UNUSED(maxResults); const PxU32 maxStack = 128; PxU32 stack1[maxStack]; PxU32* stack = stack1+1; PX_ASSERT(mPages); PX_ASSERT((uintptr_t(mPages) & 127) == 0); PX_ASSERT((uintptr_t(this) & 15) == 0); // conservatively quantize the input box Vec4V nqMin = Vec4V_From_PxVec3_WUndefined(boxMin); Vec4V nqMax = Vec4V_From_PxVec3_WUndefined(boxMax); Vec4V nqMinx4 = V4SplatElement<0>(nqMin); Vec4V nqMiny4 = V4SplatElement<1>(nqMin); Vec4V nqMinz4 = V4SplatElement<2>(nqMin); Vec4V nqMaxx4 = V4SplatElement<0>(nqMax); Vec4V nqMaxy4 = V4SplatElement<1>(nqMax); Vec4V nqMaxz4 = V4SplatElement<2>(nqMax); // on 64-bit platforms the dynamic rtree pointer is also relative to mPages PxU8* treeNodes8 = CAST_U8(mPages); PxU32* stackPtr = stack; // AP potential perf optimization - fetch the top level right away PX_ASSERT(RTREE_N == 4 || RTREE_N == 8); PX_ASSERT(PxIsPowerOfTwo(mPageSize)); for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --) *stackPtr++ = j*sizeof(RTreePage); PxU32 cacheTopValid = true; PxU32 cacheTop = 0; do { stackPtr--; PxU32 top; if (cacheTopValid) // branch is faster than lhs top = cacheTop; else top = stackPtr[0]; PX_ASSERT(!cacheTopValid || stackPtr[0] == cacheTop); RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top); const PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs; Vec4V minx4 = V4LoadA(tn->minx); Vec4V miny4 = V4LoadA(tn->miny); Vec4V minz4 = V4LoadA(tn->minz); Vec4V maxx4 = V4LoadA(tn->maxx); Vec4V maxy4 = V4LoadA(tn->maxy); Vec4V maxz4 = V4LoadA(tn->maxz); // AABB/AABB overlap test BoolV res0 = V4IsGrtr(nqMinx4, maxx4); BoolV res1 = V4IsGrtr(nqMiny4, maxy4); BoolV res2 = V4IsGrtr(nqMinz4, maxz4); BoolV res3 = V4IsGrtr(minx4, nqMaxx4); BoolV res4 = V4IsGrtr(miny4, nqMaxy4); BoolV res5 = V4IsGrtr(minz4, nqMaxz4); BoolV resx = BOr(BOr(BOr(res0, res1), BOr(res2, res3)), BOr(res4, res5)); PX_ALIGN_PREFIX(16) PxU32 resa[RTREE_N] PX_ALIGN_SUFFIX(16); VecU32V res4x = VecU32V_From_BoolV(resx); U4StoreA(res4x, resa); cacheTopValid = false; for (PxU32 i = 0; i < RTREE_N; i++) { PxU32 ptr = ptrs[i] & ~1; // clear the isLeaf bit if (resa[i]) continue; if (tn->isLeaf(i)) { if (!callback->processResults(1, &ptr)) return; } else { *(stackPtr++) = ptr; cacheTop = ptr; cacheTopValid = true; } } } while (stackPtr > stack); } ///////////////////////////////////////////////////////////////////////// template <int inflate> void RTree::traverseRay( const PxVec3& rayOrigin, const PxVec3& rayDir, const PxU32 maxResults, PxU32* resultsPtr, Gu::RTree::CallbackRaycast* callback, const PxVec3* fattenAABBs, PxF32 maxT) const { // implements Kay-Kajiya 4-way SIMD test PX_UNUSED(resultsPtr); PX_UNUSED(maxResults); const PxU32 maxStack = 128; PxU32 stack1[maxStack]; PxU32* stack = stack1+1; PX_ASSERT(mPages); PX_ASSERT((uintptr_t(mPages) & 127) == 0); PX_ASSERT((uintptr_t(this) & 15) == 0); PxU8* treeNodes8 = CAST_U8(mPages); Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ; PX_UNUSED(fattenAABBsX); PX_UNUSED(fattenAABBsY); PX_UNUSED(fattenAABBsZ); if (inflate) { Vec4V fattenAABBs4 = Vec4V_From_PxVec3_WUndefined(*fattenAABBs); fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap fattenAABBsX = V4SplatElement<0>(fattenAABBs4); fattenAABBsY = V4SplatElement<1>(fattenAABBs4); fattenAABBsZ = V4SplatElement<2>(fattenAABBs4); } Vec4V maxT4; maxT4 = V4Load(maxT); Vec4V rayP = Vec4V_From_PxVec3_WUndefined(rayOrigin); Vec4V rayD = Vec4V_From_PxVec3_WUndefined(rayDir); VecU32V raySign = V4U32and(VecU32V_ReinterpretFrom_Vec4V(rayD), signMask); Vec4V rayDAbs = V4Abs(rayD); // abs value of rayD Vec4V rayInvD = Vec4V_ReinterpretFrom_VecU32V(V4U32or(raySign, VecU32V_ReinterpretFrom_Vec4V(V4Max(rayDAbs, epsFloat4)))); // clamp near-zero components up to epsilon rayD = rayInvD; //rayInvD = V4Recip(rayInvD); // Newton-Raphson iteration for reciprocal (see wikipedia): // X[n+1] = X[n]*(2-original*X[n]), X[0] = V4RecipFast estimate //rayInvD = rayInvD*(twos-rayD*rayInvD); rayInvD = V4RecipFast(rayInvD); // initial estimate, not accurate enough rayInvD = V4Mul(rayInvD, V4NegMulSub(rayD, rayInvD, twos)); // P+tD=a; t=(a-P)/D // t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x) Vec4V rayPinvD = V4NegMulSub(rayInvD, rayP, zeroes); Vec4V rayInvDsplatX = V4SplatElement<0>(rayInvD); Vec4V rayInvDsplatY = V4SplatElement<1>(rayInvD); Vec4V rayInvDsplatZ = V4SplatElement<2>(rayInvD); Vec4V rayPinvDsplatX = V4SplatElement<0>(rayPinvD); Vec4V rayPinvDsplatY = V4SplatElement<1>(rayPinvD); Vec4V rayPinvDsplatZ = V4SplatElement<2>(rayPinvD); PX_ASSERT(RTREE_N == 4 || RTREE_N == 8); PX_ASSERT(mNumRootPages > 0); PxU32 stackPtr = 0; for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --) stack[stackPtr++] = j*sizeof(RTreePage); PX_ALIGN_PREFIX(16) PxU32 resa[4] PX_ALIGN_SUFFIX(16); while (stackPtr) { PxU32 top = stack[--stackPtr]; if (top&1) // isLeaf test { top--; PxF32 newMaxT = maxT; if (!callback->processResults(1, &top, newMaxT)) return; /* shrink the ray if newMaxT is reduced compared to the original maxT */ if (maxT != newMaxT) { PX_ASSERT(newMaxT < maxT); maxT = newMaxT; maxT4 = V4Load(newMaxT); } continue; } RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top); // 6i load Vec4V minx4a = V4LoadA(tn->minx), miny4a = V4LoadA(tn->miny), minz4a = V4LoadA(tn->minz); Vec4V maxx4a = V4LoadA(tn->maxx), maxy4a = V4LoadA(tn->maxy), maxz4a = V4LoadA(tn->maxz); // 1i disabled test // AP scaffold - optimization opportunity - can save 2 instructions here VecU32V ignore4a = V4IsGrtrV32u(minx4a, maxx4a); // 1 if degenerate box (empty slot in the page) if (inflate) { // 6i maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ); minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ); } // P+tD=a; t=(a-P)/D // t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x) // 6i Vec4V tminxa0 = V4MulAdd(minx4a, rayInvDsplatX, rayPinvDsplatX); Vec4V tminya0 = V4MulAdd(miny4a, rayInvDsplatY, rayPinvDsplatY); Vec4V tminza0 = V4MulAdd(minz4a, rayInvDsplatZ, rayPinvDsplatZ); Vec4V tmaxxa0 = V4MulAdd(maxx4a, rayInvDsplatX, rayPinvDsplatX); Vec4V tmaxya0 = V4MulAdd(maxy4a, rayInvDsplatY, rayPinvDsplatY); Vec4V tmaxza0 = V4MulAdd(maxz4a, rayInvDsplatZ, rayPinvDsplatZ); // test half-spaces // P+tD=dN // t = (d(N,D)-(P,D))/(D,D) , (D,D)=1 // compute 4x dot products (N,D) and (P,N) for each AABB in the page // 6i // now compute tnear and tfar for each pair of planes for each box Vec4V tminxa = V4Min(tminxa0, tmaxxa0); Vec4V tmaxxa = V4Max(tminxa0, tmaxxa0); Vec4V tminya = V4Min(tminya0, tmaxya0); Vec4V tmaxya = V4Max(tminya0, tmaxya0); Vec4V tminza = V4Min(tminza0, tmaxza0); Vec4V tmaxza = V4Max(tminza0, tmaxza0); // 8i Vec4V maxOfNeasa = V4Max(V4Max(tminxa, tminya), tminza); Vec4V minOfFarsa = V4Min(V4Min(tmaxxa, tmaxya), tmaxza); ignore4a = V4U32or(ignore4a, V4IsGrtrV32u(epsFloat4, minOfFarsa)); // if tfar is negative, ignore since its a ray, not a line // AP scaffold: update the build to eliminate 3 more instructions for ignore4a above //VecU32V ignore4a = V4IsGrtrV32u(epsFloat4, minOfFarsa); // if tfar is negative, ignore since its a ray, not a line ignore4a = V4U32or(ignore4a, V4IsGrtrV32u(maxOfNeasa, maxT4)); // if tnear is over maxT, ignore this result // 2i VecU32V resa4 = V4IsGrtrV32u(maxOfNeasa, minOfFarsa); // if 1 => fail resa4 = V4U32or(resa4, ignore4a); // 1i V4U32StoreAligned(resa4, reinterpret_cast<VecU32V*>(resa)); PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs; stack[stackPtr] = ptrs[0]; stackPtr += (1+resa[0]); // AP scaffold TODO: use VecU32add stack[stackPtr] = ptrs[1]; stackPtr += (1+resa[1]); stack[stackPtr] = ptrs[2]; stackPtr += (1+resa[2]); stack[stackPtr] = ptrs[3]; stackPtr += (1+resa[3]); } } //explicit template instantiation template void RTree::traverseRay<0>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const; template void RTree::traverseRay<1>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const; ///////////////////////////////////////////////////////////////////////// void RTree::traverseOBB( const Gu::Box& obb, const PxU32 maxResults, PxU32* resultsPtr, Gu::RTree::Callback* callback) const { PX_UNUSED(resultsPtr); PX_UNUSED(maxResults); const PxU32 maxStack = 128; PxU32 stack[maxStack]; PX_ASSERT(mPages); PX_ASSERT((uintptr_t(mPages) & 127) == 0); PX_ASSERT((uintptr_t(this) & 15) == 0); PxU8* treeNodes8 = CAST_U8(mPages); PxU32* stackPtr = stack; Vec4V ones, halves, eps; ones = V4Load(1.0f); halves = V4Load(0.5f); eps = V4Load(1e-6f); PX_UNUSED(ones); Vec4V obbO = Vec4V_From_PxVec3_WUndefined(obb.center); Vec4V obbE = Vec4V_From_PxVec3_WUndefined(obb.extents); // Gu::Box::rot matrix columns are the OBB axes Vec4V obbX = Vec4V_From_PxVec3_WUndefined(obb.rot.column0); Vec4V obbY = Vec4V_From_PxVec3_WUndefined(obb.rot.column1); Vec4V obbZ = Vec4V_From_PxVec3_WUndefined(obb.rot.column2); #if PX_WINDOWS // Visual Studio compiler hangs with #defines // On VMX platforms we use #defines in the other branch of this #ifdef to avoid register spills (LHS) Vec4V obbESplatX = V4SplatElement<0>(obbE); Vec4V obbESplatY = V4SplatElement<1>(obbE); Vec4V obbESplatZ = V4SplatElement<2>(obbE); Vec4V obbESplatNegX = V4Sub(zeroes, obbESplatX); Vec4V obbESplatNegY = V4Sub(zeroes, obbESplatY); Vec4V obbESplatNegZ = V4Sub(zeroes, obbESplatZ); Vec4V obbXE = V4MulAdd(obbX, obbESplatX, zeroes); // scale axii by E Vec4V obbYE = V4MulAdd(obbY, obbESplatY, zeroes); // scale axii by E Vec4V obbZE = V4MulAdd(obbZ, obbESplatZ, zeroes); // scale axii by E Vec4V obbOSplatX = V4SplatElement<0>(obbO); Vec4V obbOSplatY = V4SplatElement<1>(obbO); Vec4V obbOSplatZ = V4SplatElement<2>(obbO); Vec4V obbXSplatX = V4SplatElement<0>(obbX); Vec4V obbXSplatY = V4SplatElement<1>(obbX); Vec4V obbXSplatZ = V4SplatElement<2>(obbX); Vec4V obbYSplatX = V4SplatElement<0>(obbY); Vec4V obbYSplatY = V4SplatElement<1>(obbY); Vec4V obbYSplatZ = V4SplatElement<2>(obbY); Vec4V obbZSplatX = V4SplatElement<0>(obbZ); Vec4V obbZSplatY = V4SplatElement<1>(obbZ); Vec4V obbZSplatZ = V4SplatElement<2>(obbZ); Vec4V obbXESplatX = V4SplatElement<0>(obbXE); Vec4V obbXESplatY = V4SplatElement<1>(obbXE); Vec4V obbXESplatZ = V4SplatElement<2>(obbXE); Vec4V obbYESplatX = V4SplatElement<0>(obbYE); Vec4V obbYESplatY = V4SplatElement<1>(obbYE); Vec4V obbYESplatZ = V4SplatElement<2>(obbYE); Vec4V obbZESplatX = V4SplatElement<0>(obbZE); Vec4V obbZESplatY = V4SplatElement<1>(obbZE); Vec4V obbZESplatZ = V4SplatElement<2>(obbZE); #else #define obbESplatX V4SplatElement<0>(obbE) #define obbESplatY V4SplatElement<1>(obbE) #define obbESplatZ V4SplatElement<2>(obbE) #define obbESplatNegX V4Sub(zeroes, obbESplatX) #define obbESplatNegY V4Sub(zeroes, obbESplatY) #define obbESplatNegZ V4Sub(zeroes, obbESplatZ) #define obbXE V4MulAdd(obbX, obbESplatX, zeroes) #define obbYE V4MulAdd(obbY, obbESplatY, zeroes) #define obbZE V4MulAdd(obbZ, obbESplatZ, zeroes) #define obbOSplatX V4SplatElement<0>(obbO) #define obbOSplatY V4SplatElement<1>(obbO) #define obbOSplatZ V4SplatElement<2>(obbO) #define obbXSplatX V4SplatElement<0>(obbX) #define obbXSplatY V4SplatElement<1>(obbX) #define obbXSplatZ V4SplatElement<2>(obbX) #define obbYSplatX V4SplatElement<0>(obbY) #define obbYSplatY V4SplatElement<1>(obbY) #define obbYSplatZ V4SplatElement<2>(obbY) #define obbZSplatX V4SplatElement<0>(obbZ) #define obbZSplatY V4SplatElement<1>(obbZ) #define obbZSplatZ V4SplatElement<2>(obbZ) #define obbXESplatX V4SplatElement<0>(obbXE) #define obbXESplatY V4SplatElement<1>(obbXE) #define obbXESplatZ V4SplatElement<2>(obbXE) #define obbYESplatX V4SplatElement<0>(obbYE) #define obbYESplatY V4SplatElement<1>(obbYE) #define obbYESplatZ V4SplatElement<2>(obbYE) #define obbZESplatX V4SplatElement<0>(obbZE) #define obbZESplatY V4SplatElement<1>(obbZE) #define obbZESplatZ V4SplatElement<2>(obbZE) #endif PX_ASSERT(mPageSize == 4 || mPageSize == 8); PX_ASSERT(mNumRootPages > 0); for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --) *stackPtr++ = j*sizeof(RTreePage); PxU32 cacheTopValid = true; PxU32 cacheTop = 0; PX_ALIGN_PREFIX(16) PxU32 resa_[4] PX_ALIGN_SUFFIX(16); do { stackPtr--; PxU32 top; if (cacheTopValid) // branch is faster than lhs top = cacheTop; else top = stackPtr[0]; PX_ASSERT(!cacheTopValid || top == cacheTop); RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top); const PxU32 offs = 0; PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs; // 6i Vec4V minx4a = V4LoadA(tn->minx+offs); Vec4V miny4a = V4LoadA(tn->miny+offs); Vec4V minz4a = V4LoadA(tn->minz+offs); Vec4V maxx4a = V4LoadA(tn->maxx+offs); Vec4V maxy4a = V4LoadA(tn->maxy+offs); Vec4V maxz4a = V4LoadA(tn->maxz+offs); VecU32V noOverlapa; VecU32V resa4u; { // PRECOMPUTE FOR A BLOCK // 109 instr per 4 OBB/AABB // ABB iteration 1, start with OBB origin as other point -- 6 Vec4V p1ABBxa = V4Max(minx4a, V4Min(maxx4a, obbOSplatX)); Vec4V p1ABBya = V4Max(miny4a, V4Min(maxy4a, obbOSplatY)); Vec4V p1ABBza = V4Max(minz4a, V4Min(maxz4a, obbOSplatZ)); // OBB iteration 1, move to OBB space first -- 12 Vec4V p1ABBOxa = V4Sub(p1ABBxa, obbOSplatX); Vec4V p1ABBOya = V4Sub(p1ABBya, obbOSplatY); Vec4V p1ABBOza = V4Sub(p1ABBza, obbOSplatZ); Vec4V obbPrjXa = V4MulAdd(p1ABBOxa, obbXSplatX, V4MulAdd(p1ABBOya, obbXSplatY, V4MulAdd(p1ABBOza, obbXSplatZ, zeroes))); Vec4V obbPrjYa = V4MulAdd(p1ABBOxa, obbYSplatX, V4MulAdd(p1ABBOya, obbYSplatY, V4MulAdd(p1ABBOza, obbYSplatZ, zeroes))); Vec4V obbPrjZa = V4MulAdd(p1ABBOxa, obbZSplatX, V4MulAdd(p1ABBOya, obbZSplatY, V4MulAdd(p1ABBOza, obbZSplatZ, zeroes))); // clamp AABB point in OBB space to OBB extents. Since we scaled the axii, the extents are [-1,1] -- 6 Vec4V pOBBxa = V4Max(obbESplatNegX, V4Min(obbPrjXa, obbESplatX)); Vec4V pOBBya = V4Max(obbESplatNegY, V4Min(obbPrjYa, obbESplatY)); Vec4V pOBBza = V4Max(obbESplatNegZ, V4Min(obbPrjZa, obbESplatZ)); // go back to AABB space. we have x,y,z in obb space, need to multiply by axii -- 9 Vec4V p1OBBxa = V4MulAdd(pOBBxa, obbXSplatX, V4MulAdd(pOBBya, obbYSplatX, V4MulAdd(pOBBza, obbZSplatX, obbOSplatX))); Vec4V p1OBBya = V4MulAdd(pOBBxa, obbXSplatY, V4MulAdd(pOBBya, obbYSplatY, V4MulAdd(pOBBza, obbZSplatY, obbOSplatY))); Vec4V p1OBBza = V4MulAdd(pOBBxa, obbXSplatZ, V4MulAdd(pOBBya, obbYSplatZ, V4MulAdd(pOBBza, obbZSplatZ, obbOSplatZ))); // ABB iteration 2 -- 6 instructions Vec4V p2ABBxa = V4Max(minx4a, V4Min(maxx4a, p1OBBxa)); Vec4V p2ABBya = V4Max(miny4a, V4Min(maxy4a, p1OBBya)); Vec4V p2ABBza = V4Max(minz4a, V4Min(maxz4a, p1OBBza)); // above blocks add up to 12+12+15=39 instr // END PRECOMPUTE FOR A BLOCK // for AABBs precompute extents and center -- 9i Vec4V abbCxa = V4MulAdd(V4Add(maxx4a, minx4a), halves, zeroes); Vec4V abbCya = V4MulAdd(V4Add(maxy4a, miny4a), halves, zeroes); Vec4V abbCza = V4MulAdd(V4Add(maxz4a, minz4a), halves, zeroes); Vec4V abbExa = V4Sub(maxx4a, abbCxa); Vec4V abbEya = V4Sub(maxy4a, abbCya); Vec4V abbEza = V4Sub(maxz4a, abbCza); // now test separating axes D1 = p1OBB-p1ABB and D2 = p1OBB-p2ABB -- 37 instructions per axis // D1 first -- 3 instructions Vec4V d1xa = V4Sub(p1OBBxa, p1ABBxa), d1ya = V4Sub(p1OBBya, p1ABBya), d1za = V4Sub(p1OBBza, p1ABBza); // for AABB compute projections of extents and center -- 6 Vec4V abbExd1Prja = V4MulAdd(d1xa, abbExa, zeroes); Vec4V abbEyd1Prja = V4MulAdd(d1ya, abbEya, zeroes); Vec4V abbEzd1Prja = V4MulAdd(d1za, abbEza, zeroes); Vec4V abbCd1Prja = V4MulAdd(d1xa, abbCxa, V4MulAdd(d1ya, abbCya, V4MulAdd(d1za, abbCza, zeroes))); // for obb project each halfaxis and origin and add abs values of half-axis projections -- 12 instructions Vec4V obbXEd1Prja = V4MulAdd(d1xa, obbXESplatX, V4MulAdd(d1ya, obbXESplatY, V4MulAdd(d1za, obbXESplatZ, zeroes))); Vec4V obbYEd1Prja = V4MulAdd(d1xa, obbYESplatX, V4MulAdd(d1ya, obbYESplatY, V4MulAdd(d1za, obbYESplatZ, zeroes))); Vec4V obbZEd1Prja = V4MulAdd(d1xa, obbZESplatX, V4MulAdd(d1ya, obbZESplatY, V4MulAdd(d1za, obbZESplatZ, zeroes))); Vec4V obbOd1Prja = V4MulAdd(d1xa, obbOSplatX, V4MulAdd(d1ya, obbOSplatY, V4MulAdd(d1za, obbOSplatZ, zeroes))); // compare lengths between projected centers with sum of projected radii -- 16i Vec4V originDiffd1a = v_absm(V4Sub(abbCd1Prja, obbOd1Prja)); Vec4V absABBRd1a = V4Add(V4Add(v_absm(abbExd1Prja), v_absm(abbEyd1Prja)), v_absm(abbEzd1Prja)); Vec4V absOBBRd1a = V4Add(V4Add(v_absm(obbXEd1Prja), v_absm(obbYEd1Prja)), v_absm(obbZEd1Prja)); VecU32V noOverlapd1a = V4IsGrtrV32u(V4Sub(originDiffd1a, eps), V4Add(absABBRd1a, absOBBRd1a)); VecU32V epsNoOverlapd1a = V4IsGrtrV32u(originDiffd1a, eps); // D2 next (35 instr) // 3i Vec4V d2xa = V4Sub(p1OBBxa, p2ABBxa), d2ya = V4Sub(p1OBBya, p2ABBya), d2za = V4Sub(p1OBBza, p2ABBza); // for AABB compute projections of extents and center -- 6 Vec4V abbExd2Prja = V4MulAdd(d2xa, abbExa, zeroes); Vec4V abbEyd2Prja = V4MulAdd(d2ya, abbEya, zeroes); Vec4V abbEzd2Prja = V4MulAdd(d2za, abbEza, zeroes); Vec4V abbCd2Prja = V4MulAdd(d2xa, abbCxa, V4MulAdd(d2ya, abbCya, V4MulAdd(d2za, abbCza, zeroes))); // for obb project each halfaxis and origin and add abs values of half-axis projections -- 12i Vec4V obbXEd2Prja = V4MulAdd(d2xa, obbXESplatX, V4MulAdd(d2ya, obbXESplatY, V4MulAdd(d2za, obbXESplatZ, zeroes))); Vec4V obbYEd2Prja = V4MulAdd(d2xa, obbYESplatX, V4MulAdd(d2ya, obbYESplatY, V4MulAdd(d2za, obbYESplatZ, zeroes))); Vec4V obbZEd2Prja = V4MulAdd(d2xa, obbZESplatX, V4MulAdd(d2ya, obbZESplatY, V4MulAdd(d2za, obbZESplatZ, zeroes))); Vec4V obbOd2Prja = V4MulAdd(d2xa, obbOSplatX, V4MulAdd(d2ya, obbOSplatY, V4MulAdd(d2za, obbOSplatZ, zeroes))); // compare lengths between projected centers with sum of projected radii -- 16i Vec4V originDiffd2a = v_absm(V4Sub(abbCd2Prja, obbOd2Prja)); Vec4V absABBRd2a = V4Add(V4Add(v_absm(abbExd2Prja), v_absm(abbEyd2Prja)), v_absm(abbEzd2Prja)); Vec4V absOBBRd2a = V4Add(V4Add(v_absm(obbXEd2Prja), v_absm(obbYEd2Prja)), v_absm(obbZEd2Prja)); VecU32V noOverlapd2a = V4IsGrtrV32u(V4Sub(originDiffd2a, eps), V4Add(absABBRd2a, absOBBRd2a)); VecU32V epsNoOverlapd2a = V4IsGrtrV32u(originDiffd2a, eps); // 8i noOverlapa = V4U32or(V4U32and(noOverlapd1a, epsNoOverlapd1a), V4U32and(noOverlapd2a, epsNoOverlapd2a)); VecU32V ignore4a = V4IsGrtrV32u(minx4a, maxx4a); // 1 if degenerate box (empty slot) noOverlapa = V4U32or(noOverlapa, ignore4a); resa4u = V4U32Andc(U4Load(1), noOverlapa); // 1 & ~noOverlap V4U32StoreAligned(resa4u, reinterpret_cast<VecU32V*>(resa_)); ///// 8+16+12+6+3+16+12+6+3+9+6+9+6+12+6+6=136i from load to result } cacheTopValid = false; for (PxU32 i = 0; i < 4; i++) { PxU32 ptr = ptrs[i+offs] & ~1; // clear the isLeaf bit if (resa_[i]) { if (tn->isLeaf(i)) { if (!callback->processResults(1, &ptr)) return; } else { *(stackPtr++) = ptr; cacheTop = ptr; cacheTopValid = true; } } } } while (stackPtr > stack); } } // namespace Gu }
23,271
C++
39.685315
167
0.713678
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshBV4.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuTriangleMesh.h" #include "GuTriangleMeshBV4.h" #include "geometry/PxGeometryInternal.h" using namespace physx; using namespace Gu; namespace physx { // PT: temporary for Kit BV4TriangleMesh::BV4TriangleMesh(const PxTriangleMeshInternalData& data) : TriangleMesh(data) { mMeshInterface.setNbTriangles(getNbTrianglesFast()); if(has16BitIndices()) mMeshInterface.setPointers(NULL, const_cast<IndTri16*>(reinterpret_cast<const IndTri16*>(getTrianglesFast())), getVerticesFast()); else mMeshInterface.setPointers(const_cast<IndTri32*>(reinterpret_cast<const IndTri32*>(getTrianglesFast())), NULL, getVerticesFast()); mBV4Tree.mMeshInterface = &mMeshInterface; mBV4Tree.mLocalBounds.mCenter = data.mAABB_Center; mBV4Tree.mLocalBounds.mExtentsMagnitude = data.mAABB_Extents.magnitude(); mBV4Tree.mNbNodes = data.mNbNodes; mBV4Tree.mNodes = data.mNodes; mBV4Tree.mInitData = data.mInitData; mBV4Tree.mCenterOrMinCoeff = data.mCenterOrMinCoeff; mBV4Tree.mExtentsOrMaxCoeff = data.mExtentsOrMaxCoeff; mBV4Tree.mQuantized = data.mQuantized; mBV4Tree.mUserAllocated = true; } bool BV4TriangleMesh::getInternalData(PxTriangleMeshInternalData& data, bool takeOwnership) const { data.mNbVertices = mNbVertices; data.mNbTriangles = mNbTriangles; data.mVertices = mVertices; data.mTriangles = mTriangles; data.mFaceRemap = mFaceRemap; data.mAABB_Center = mAABB.mCenter; data.mAABB_Extents = mAABB.mExtents; data.mGeomEpsilon = mGeomEpsilon; data.mFlags = mFlags; data.mNbNodes = mBV4Tree.mNbNodes; data.mNodeSize = mBV4Tree.mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ); data.mNodes = mBV4Tree.mNodes; data.mInitData = mBV4Tree.mInitData; data.mCenterOrMinCoeff = mBV4Tree.mCenterOrMinCoeff; data.mExtentsOrMaxCoeff = mBV4Tree.mExtentsOrMaxCoeff; data.mQuantized = mBV4Tree.mQuantized; if(takeOwnership) { const_cast<BV4TriangleMesh*>(this)->setBaseFlag(PxBaseFlag::eOWNS_MEMORY, false); const_cast<BV4TriangleMesh*>(this)->mBV4Tree.mUserAllocated = true; } return true; } bool PxGetTriangleMeshInternalData(PxTriangleMeshInternalData& data, const PxTriangleMesh& mesh, bool takeOwnership) { return static_cast<const TriangleMesh&>(mesh).getInternalData(data, takeOwnership); } //~ PT: temporary for Kit BV4TriangleMesh::BV4TriangleMesh(MeshFactory* factory, TriangleMeshData& d) : TriangleMesh(factory, d) { PX_ASSERT(d.mType==PxMeshMidPhase::eBVH34); BV4TriangleData& bv4Data = static_cast<BV4TriangleData&>(d); mMeshInterface = bv4Data.mMeshInterface; mBV4Tree = bv4Data.mBV4Tree; mBV4Tree.mMeshInterface = &mMeshInterface; } TriangleMesh* BV4TriangleMesh::createObject(PxU8*& address, PxDeserializationContext& context) { BV4TriangleMesh* obj = PX_PLACEMENT_NEW(address, BV4TriangleMesh(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(BV4TriangleMesh); obj->importExtraData(context); return obj; } void BV4TriangleMesh::exportExtraData(PxSerializationContext& stream) { mBV4Tree.exportExtraData(stream); TriangleMesh::exportExtraData(stream); } void BV4TriangleMesh::importExtraData(PxDeserializationContext& context) { mBV4Tree.importExtraData(context); TriangleMesh::importExtraData(context); if(has16BitIndices()) mMeshInterface.setPointers(NULL, const_cast<IndTri16*>(reinterpret_cast<const IndTri16*>(getTrianglesFast())), getVerticesFast()); else mMeshInterface.setPointers(const_cast<IndTri32*>(reinterpret_cast<const IndTri32*>(getTrianglesFast())), NULL, getVerticesFast()); mBV4Tree.mMeshInterface = &mMeshInterface; } PxVec3 * BV4TriangleMesh::getVerticesForModification() { return const_cast<PxVec3*>(getVertices()); } PxBounds3 BV4TriangleMesh::refitBVH() { PxBounds3 newBounds; const float gBoxEpsilon = 2e-4f; if(mBV4Tree.refit(newBounds, gBoxEpsilon)) { mAABB.setMinMax(newBounds.minimum, newBounds.maximum); } else { newBounds = PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "BVH34 trees: refit operation only available on non-quantized trees.\n"); } // PT: copied from RTreeTriangleMesh::refitBVH() // reset edge flags and remember we did that using a mesh flag (optimization) if(!mBV4Tree.mIsEdgeSet) { mBV4Tree.mIsEdgeSet = true; setAllEdgesActive(); } return newBounds; } } // namespace physx
6,038
C++
35.161676
139
0.776913
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxSweep_Params.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // This is used by the box-sweep & capsule-sweep code #if PX_VC #pragma warning(disable: 4505) // unreferenced local function has been removed #endif #include "foundation/PxBasicTemplates.h" namespace { #ifdef SWEEP_AABB_IMPL struct BoxSweepParams : RayParams #else struct BoxSweepParams : OBBTestParams #endif { const IndTri32* PX_RESTRICT mTris32; const IndTri16* PX_RESTRICT mTris16; const PxVec3* PX_RESTRICT mVerts; #ifndef SWEEP_AABB_IMPL Box mLocalBox; #endif PxVec3 mLocalDir_Padded; RaycastHitInternal mStabbedFace; PxU32 mBackfaceCulling; PxU32 mEarlyExit; PxVec3 mP0, mP1, mP2; PxVec3 mBestTriNormal; float mOffset; PxVec3 mProj; PxVec3 mDP; #ifndef SWEEP_AABB_IMPL PxMat33 mAR; //!< Absolute rotation matrix #endif PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space PxVec3 mTModelToBox_Padded; //!< Translation from model space to obb space PxVec3 mOriginalExtents_Padded; PxVec3 mOriginalDir_Padded; PxVec3 mOneOverDir_Padded; PxVec3 mOneOverOriginalDir; #ifndef SWEEP_AABB_IMPL PX_FORCE_INLINE void ShrinkOBB(float d) { const PxVec3 BoxExtents = mDP + d * mProj; mTBoxToModel_PaddedAligned = mLocalBox.center + mLocalDir_Padded*d*0.5f; setupBoxData(this, BoxExtents, &mAR); } #endif }; } // PT: TODO: check asm again in PhysX version, compare to original (TA34704) static void prepareSweepData(const Box& box, const PxVec3& dir, float maxDist, BoxSweepParams* PX_RESTRICT params) { invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, box); params->mOriginalExtents_Padded = box.extents; const PxVec3 OriginalDir = params->mRModelToBox_Padded.transform(dir); params->mOriginalDir_Padded = OriginalDir; const PxVec3 OneOverOriginalDir(OriginalDir.x!=0.0f ? 1.0f/OriginalDir.x : 0.0f, OriginalDir.y!=0.0f ? 1.0f/OriginalDir.y : 0.0f, OriginalDir.z!=0.0f ? 1.0f/OriginalDir.z : 0.0f); params->mOneOverOriginalDir = OneOverOriginalDir; params->mOneOverDir_Padded = OneOverOriginalDir / maxDist; { const Box& LocalBox = box; const PxVec3& LocalDir = dir; params->mLocalDir_Padded = LocalDir; params->mStabbedFace.mDistance = maxDist; #ifndef SWEEP_AABB_IMPL params->mLocalBox = LocalBox; // PT: TODO: check asm for operator= #endif PxMat33 boxToModelR; // Original code: // OBB::CreateOBB(LocalBox, LocalDir, 0.5f) { PxVec3 R1, R2; { float dd[3]; dd[0] = fabsf(LocalBox.rot.column0.dot(LocalDir)); dd[1] = fabsf(LocalBox.rot.column1.dot(LocalDir)); dd[2] = fabsf(LocalBox.rot.column2.dot(LocalDir)); float dmax = dd[0]; PxU32 ax0=1; PxU32 ax1=2; if(dd[1]>dmax) { dmax=dd[1]; ax0=0; ax1=2; } if(dd[2]>dmax) { dmax=dd[2]; ax0=0; ax1=1; } if(dd[ax1]<dd[ax0]) PxSwap(ax0, ax1); R1 = LocalBox.rot[ax0]; R1 -= R1.dot(LocalDir)*LocalDir; // Project to plane whose normal is dir R1.normalize(); R2 = LocalDir.cross(R1); } // Original code: // mRot = params->mRBoxToModel boxToModelR.column0 = LocalDir; boxToModelR.column1 = R1; boxToModelR.column2 = R2; // Original code: // float Offset[3]; // 0.5f comes from the Offset[r]*0.5f, doesn't mean 'd' is 0.5f params->mProj.x = 0.5f; params->mProj.y = LocalDir.dot(R1)*0.5f; params->mProj.z = LocalDir.dot(R2)*0.5f; // Original code: //mExtents[r] = Offset[r]*0.5f + fabsf(box.mRot[0]|R)*box.mExtents.x + fabsf(box.mRot[1]|R)*box.mExtents.y + fabsf(box.mRot[2]|R)*box.mExtents.z; // => we store the first part of the computation, minus 'Offset[r]*0.5f' for(PxU32 r=0;r<3;r++) { const PxVec3& R = boxToModelR[r]; params->mDP[r] = fabsf(LocalBox.rot.column0.dot(R)*LocalBox.extents.x) + fabsf(LocalBox.rot.column1.dot(R)*LocalBox.extents.y) + fabsf(LocalBox.rot.column2.dot(R)*LocalBox.extents.z); } // In the original code, both mCenter & mExtents depend on 'd', and thus we will need to recompute these two members. // // For mExtents we have: // // float Offset[3]; // Offset[0] = d; // Offset[1] = d*(dir|R1); // Offset[2] = d*(dir|R2); // // mExtents[r] = Offset[r]*0.5f + fabsf(box.mRot[0]|R)*box.mExtents.x + fabsf(box.mRot[1]|R)*box.mExtents.y + fabsf(box.mRot[2]|R)*box.mExtents.z; // <=> mExtents[r] = Offset[r]*0.5f + Params.mDP[r]; We precompute the second part that doesn't depend on d, stored in mDP // <=> mExtents[r] = Params.mProj[r]*d + Params.mDP[r]; We extract d from the first part, store what is left in mProj // // Thus in ShrinkOBB the code needed to update the extents is just: // mBoxExtents = mDP + d * mProj; // // For mCenter we have: // // mCenter = box.mCenter + dir*d*0.5f; // // So we simply use this formula directly, with the new d. Result is stored in 'mTBoxToModel' /* PX_FORCE_INLINE void ShrinkOBB(float d) { mBoxExtents = mDP + d * mProj; mTBoxToModel = mLocalBox.mCenter + mLocalDir*d*0.5f; */ } // This one is for culling tris, unrelated to CreateOBB params->mOffset = params->mDP.x + LocalBox.center.dot(LocalDir); #ifndef SWEEP_AABB_IMPL precomputeData(params, &params->mAR, &boxToModelR); params->ShrinkOBB(maxDist); #endif } }
6,999
C
32.175355
150
0.690956
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMeshUtils.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "GuTetrahedronMeshUtils.h" #include "GuDistancePointTetrahedron.h" namespace physx { namespace Gu { void convertSoftbodyCollisionToSimMeshTets(const PxTetrahedronMesh& simMesh, const SoftBodyAuxData& simState, const BVTetrahedronMesh& collisionMesh, PxU32 inTetId, const PxVec4& inTetBarycentric, PxU32& outTetId, PxVec4& outTetBarycentric) { if (inTetId == 0xFFFFFFFF) { outTetId = 0xFFFFFFFF; outTetBarycentric = PxVec4(0.0f); return; } // Map from CPU tet ID (corresponds to the ID in the BV4 mesh) to the GPU tet ID (corresponds to the ID in // the BV32 mesh) inTetId = collisionMesh.mGRB_faceRemapInverse[inTetId]; const PxU32 endIdx = simState.mTetsAccumulatedRemapColToSim[inTetId]; const PxU32 startIdx = inTetId != 0 ? simState.mTetsAccumulatedRemapColToSim[inTetId - 1] : 0; const PxU32* const tetRemapColToSim = simState.mTetsRemapColToSim; typedef PxVec4T<unsigned int> uint4; const uint4* const collInds = reinterpret_cast<const uint4*>(collisionMesh.mGRB_tetraIndices /*collisionMesh->mTetrahedrons*/); const uint4* const simInds = reinterpret_cast<const uint4*>(simMesh.getTetrahedrons()); const PxVec3* const collVerts = collisionMesh.mVertices; const PxVec3* const simVerts = simMesh.getVertices(); const uint4 ind = collInds[inTetId]; const PxVec3 point = collVerts[ind.x] * inTetBarycentric.x + collVerts[ind.y] * inTetBarycentric.y + collVerts[ind.z] * inTetBarycentric.z + collVerts[ind.w] * inTetBarycentric.w; PxReal currDist = PX_MAX_F32; for(PxU32 i = startIdx; i < endIdx; ++i) { const PxU32 simTet = tetRemapColToSim[i]; const uint4 simInd = simInds[simTet]; const PxVec3 a = simVerts[simInd.x]; const PxVec3 b = simVerts[simInd.y]; const PxVec3 c = simVerts[simInd.z]; const PxVec3 d = simVerts[simInd.w]; const PxVec3 tmpClosest = closestPtPointTetrahedronWithInsideCheck(point, a, b, c, d); const PxVec3 v = point - tmpClosest; const PxReal tmpDist = v.dot(v); if(tmpDist < currDist) { PxVec4 tmpBarycentric; computeBarycentric(a, b, c, d, tmpClosest, tmpBarycentric); currDist = tmpDist; outTetId = simTet; outTetBarycentric = tmpBarycentric; if(tmpDist < 1e-6f) break; } } PX_ASSERT(outTetId != 0xFFFFFFFF); } PxVec4 addAxisToSimMeshBarycentric(const PxTetrahedronMesh& simMesh, const PxU32 simTetId, const PxVec4& simBary, const PxVec3& axis) { const PxVec3* simMeshVerts = simMesh.getVertices(); PxVec3 tetVerts[4]; if(simMesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES) { const PxU16* indices = reinterpret_cast<const PxU16*>(simMesh.getTetrahedrons()); tetVerts[0] = simMeshVerts[indices[simTetId*4 + 0]]; tetVerts[1] = simMeshVerts[indices[simTetId*4 + 1]]; tetVerts[2] = simMeshVerts[indices[simTetId*4 + 2]]; tetVerts[3] = simMeshVerts[indices[simTetId*4 + 3]]; } else { const PxU32* indices = reinterpret_cast<const PxU32*>(simMesh.getTetrahedrons()); tetVerts[0] = simMeshVerts[indices[simTetId*4 + 0]]; tetVerts[1] = simMeshVerts[indices[simTetId*4 + 1]]; tetVerts[2] = simMeshVerts[indices[simTetId*4 + 2]]; tetVerts[3] = simMeshVerts[indices[simTetId*4 + 3]]; } const PxVec3 simPoint = tetVerts[0]*simBary.x + tetVerts[1]*simBary.y + tetVerts[2]*simBary.z + tetVerts[3]*simBary.w; const PxVec3 offsetPoint = simPoint + axis; PxVec4 offsetBary; computeBarycentric(tetVerts[0], tetVerts[1], tetVerts[2], tetVerts[3], offsetPoint, offsetBary); return offsetBary; } } }
5,145
C++
38.282442
133
0.732945
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV32Build.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxVec4.h" #include "foundation/PxBasicTemplates.h" #include "foundation/PxAllocator.h" #include "foundation/PxMemory.h" #include "geometry/PxTriangle.h" #include "GuBV32Build.h" #include "GuBV32.h" #include "GuCenterExtents.h" #include "GuBV4Build.h" using namespace physx; using namespace Gu; #include "foundation/PxVecMath.h" using namespace physx::aos; struct BV32Node : public physx::PxUserAllocated { BV32Node() : mNbChildBVNodes(0) {} BV32Data mBVData[32]; PxU32 mNbChildBVNodes; PX_FORCE_INLINE size_t isLeaf(PxU32 i) const { return mBVData[i].mData & 1; } PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return PxU32(mBVData[i].mData >> 1); } PX_FORCE_INLINE const BV32Node* getChild(PxU32 i) const { return reinterpret_cast<BV32Node*>(mBVData[i].mData); } PxU32 getSize() const { return sizeof(BV32Data)*mNbChildBVNodes; } }; static void fillInNodes(const AABBTreeNode* current_node, const PxU32 startIndex, const PxU32 endIndex, const AABBTreeNode** NODES, PxU32& stat) { if (startIndex + 1 == endIndex) { //fill in nodes const AABBTreeNode* P = current_node->getPos(); const AABBTreeNode* N = current_node->getNeg(); NODES[startIndex] = P; NODES[endIndex] = N; stat += 2; } else { const AABBTreeNode* P = current_node->getPos(); const AABBTreeNode* N = current_node->getNeg(); const PxU32 midIndex = startIndex + ((endIndex - startIndex) / 2); if (!P->isLeaf()) fillInNodes(P, startIndex, midIndex, NODES, stat); else { NODES[startIndex] = P; stat++; } if (!N->isLeaf()) fillInNodes(N, midIndex + 1, endIndex, NODES, stat); else { NODES[midIndex + 1] = N; stat++; } } } static void setPrimitive(const BV4_AABBTree& source, BV32Node* node32, PxU32 i, const AABBTreeNode* node, float epsilon) { const PxU32 nbPrims = node->getNbPrimitives(); PX_ASSERT(nbPrims<=32); const PxU32* indexBase = source.getIndices(); const PxU32* prims = node->getPrimitives(); const PxU32 offset = PxU32(prims - indexBase); #if BV32_VALIDATE for (PxU32 j = 0; j<nbPrims; j++) { PX_ASSERT(prims[j] == offset + j); } #endif const PxU32 primitiveIndex = (offset << 6) | (nbPrims & 63); node32->mBVData[i].mMin = node->getAABB().minimum; node32->mBVData[i].mMax = node->getAABB().maximum; if (epsilon != 0.0f) { node32->mBVData[i].mMin -= PxVec3(epsilon); node32->mBVData[i].mMax += PxVec3(epsilon); } node32->mBVData[i].mData = (primitiveIndex << 1) | 1; } static BV32Node* setNode(const BV4_AABBTree& source, BV32Node* node32, PxU32 i, const AABBTreeNode* node, float epsilon) { BV32Node* child = NULL; if (node) { if (node->isLeaf()) { setPrimitive(source, node32, i, node, epsilon); } else { node32->mBVData[i].mMin = node->getAABB().minimum; node32->mBVData[i].mMax = node->getAABB().maximum; if (epsilon != 0.0f) { node32->mBVData[i].mMin -= PxVec3(epsilon); node32->mBVData[i].mMax += PxVec3(epsilon); } child = PX_NEW(BV32Node); node32->mBVData[i].mData = size_t(child); } } return child; } static void buildBV32(const BV4_AABBTree& source, BV32Node* tmp, const AABBTreeNode* current_node, float epsilon, PxU32& nbNodes) { PX_ASSERT(!current_node->isLeaf()); const AABBTreeNode* NODES[32]; PxMemSet(NODES, 0, sizeof(AABBTreeNode*) * 32); fillInNodes(current_node, 0, 31, NODES, tmp->mNbChildBVNodes); PxU32 left = 0; PxU32 right = 31; while (left < right) { //sweep from the front while (left<right) { //found a hole if (NODES[left] == NULL) break; left++; } //sweep from the back while (left < right) { //found a node if (NODES[right]) break; right--; } if (left != right) { //swap left and right const AABBTreeNode* node = NODES[right]; NODES[right] = NODES[left]; NODES[left] = node; } } nbNodes += tmp->mNbChildBVNodes; for (PxU32 i = 0; i < tmp->mNbChildBVNodes; ++i) { const AABBTreeNode* tempNode = NODES[i]; BV32Node* Child = setNode(source, tmp, i, tempNode, epsilon); if (Child) { buildBV32(source, Child, tempNode, epsilon, nbNodes); } } } // //static void validateTree(const AABBTree& Source, const AABBTreeNode* currentNode) //{ // if (currentNode->isLeaf()) // { // const PxU32* indexBase = Source.getIndices(); // const PxU32* prims = currentNode->getPrimitives(); // const PxU32 offset = PxU32(prims - indexBase); // const PxU32 nbPrims = currentNode->getNbPrimitives(); // for (PxU32 j = 0; j<nbPrims; j++) // { // PX_ASSERT(prims[j] == offset + j); // } // } // else // { // const AABBTreeNode* pos = currentNode->getPos(); // validateTree(Source, pos); // const AABBTreeNode* neg = currentNode->getNeg(); // validateTree(Source, neg); // } //} #if BV32_VALIDATE static void validateNodeBound(const BV32Node* currentNode, SourceMeshBase* mesh, float epsilon) { const PxU32 nbPrimitivesFromMesh = mesh->getNbPrimitives(); const PxReal eps = 1e-5f; const PxU32 nbNodes = currentNode->mNbChildBVNodes; for (PxU32 i = 0; i < nbNodes; ++i) { const BV32Node* node = currentNode->getChild(i); if (currentNode->isLeaf(i)) { BV32Data data = currentNode->mBVData[i]; PxU32 nbPrimitives = data.getNbReferencedPrimitives(); PxU32 startIndex = data.getPrimitiveStartIndex(); PX_ASSERT(startIndex< nbPrimitivesFromMesh); PxVec3 min(PX_MAX_F32, PX_MAX_F32, PX_MAX_F32); PxVec3 max(-PX_MAX_F32, -PX_MAX_F32, -PX_MAX_F32); const PxVec3* verts = mesh->getVerts(); if (mesh->getMeshType() == SourceMeshBase::MeshType::TRI_MESH) { const IndTri32* triIndices = static_cast<SourceMesh*>(mesh)->getTris32(); for (PxU32 j = 0; j < nbPrimitives; ++j) { IndTri32 index = triIndices[startIndex + j]; for (PxU32 k = 0; k < 3; ++k) { const PxVec3& v = verts[index.mRef[k]]; min.x = (min.x > v.x) ? v.x : min.x; min.y = (min.y > v.y) ? v.y : min.y; min.z = (min.z > v.z) ? v.z : min.z; max.x = (max.x < v.x) ? v.x : max.x; max.y = (max.y < v.y) ? v.y : max.y; max.z = (max.z < v.z) ? v.z : max.z; } } } else { const IndTetrahedron32* tetIndices = static_cast<TetrahedronSourceMesh*>(mesh)->getTetrahedrons32(); for (PxU32 j = 0; j < nbPrimitives; ++j) { IndTetrahedron32 index = tetIndices[startIndex + j]; for (PxU32 k = 0; k < 4; ++k) { const PxVec3& v = verts[index.mRef[k]]; min.x = (min.x > v.x) ? v.x : min.x; min.y = (min.y > v.y) ? v.y : min.y; min.z = (min.z > v.z) ? v.z : min.z; max.x = (max.x < v.x) ? v.x : max.x; max.y = (max.y < v.y) ? v.y : max.y; max.z = (max.z < v.z) ? v.z : max.z; } } } PxVec3 dMin, dMax; data.getMinMax(dMin, dMax); const PxVec3 difMin = min - dMin; const PxVec3 difMax = dMax - max; PX_ASSERT(PxAbs(difMin.x - epsilon) < eps && PxAbs(difMin.y - epsilon) < eps && PxAbs(difMin.z - epsilon) < eps); PX_ASSERT(PxAbs(difMax.x - epsilon) < eps && PxAbs(difMax.y - epsilon) < eps && PxAbs(difMax.z - epsilon) < eps); } else { validateNodeBound(node, mesh, epsilon); } } } #endif static bool BuildBV32Internal(BV32Tree& bv32Tree, const BV4_AABBTree& Source, SourceMeshBase* mesh, float epsilon) { GU_PROFILE_ZONE("..BuildBV32Internal") const PxU32 nbPrimitives = mesh->getNbPrimitives(); if (nbPrimitives <= 32) { bv32Tree.mNbPackedNodes = 1; bv32Tree.mPackedNodes = reinterpret_cast<BV32DataPacked*>(PX_ALLOC(sizeof(BV32DataPacked), "BV32DataPacked")); BV32DataPacked& packedData = bv32Tree.mPackedNodes[0]; packedData.mNbNodes = 1; packedData.mMin[0] = PxVec4(Source.getBV().minimum, 0.f); packedData.mMax[0] = PxVec4(Source.getBV().maximum, 0.f); packedData.mData[0] = (nbPrimitives << 1) | 1; bv32Tree.mMaxTreeDepth = 1; bv32Tree.mTreeDepthInfo = reinterpret_cast<BV32DataDepthInfo*>(PX_ALLOC(sizeof(BV32DataDepthInfo), "BV32DataDepthInfo")); bv32Tree.mRemapPackedNodeIndexWithDepth = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32), "PxU32")); bv32Tree.mTreeDepthInfo[0].offset = 0; bv32Tree.mTreeDepthInfo[0].count = 1; bv32Tree.mRemapPackedNodeIndexWithDepth[0] = 0; return bv32Tree.init(mesh, Source.getBV()); } { GU_PROFILE_ZONE("...._checkMD") struct Local { static void _checkMD(const AABBTreeNode* current_node, PxU32& md, PxU32& cd) { cd++; md = PxMax(md, cd); if (current_node->getPos()) { _checkMD(current_node->getPos(), md, cd); cd--; } if (current_node->getNeg()) { _checkMD(current_node->getNeg(), md, cd); cd--; } } static void _check(AABBTreeNode* current_node) { if (current_node->isLeaf()) return; AABBTreeNode* P = const_cast<AABBTreeNode*>(current_node->getPos()); AABBTreeNode* N = const_cast<AABBTreeNode*>(current_node->getNeg()); { PxU32 MDP = 0; PxU32 CDP = 0; _checkMD(P, MDP, CDP); PxU32 MDN = 0; PxU32 CDN = 0; _checkMD(N, MDN, CDN); if (MDP>MDN) // if(MDP<MDN) { PxSwap(*P, *N); PxSwap(P, N); } } _check(P); _check(N); } }; Local::_check(const_cast<AABBTreeNode*>(Source.getNodes())); } PxU32 nbNodes = 1; BV32Node* Root32 = PX_NEW(BV32Node); { GU_PROFILE_ZONE("....buildBV32") buildBV32(Source, Root32, Source.getNodes(), epsilon, nbNodes); } #if BV32_VALIDATE validateNodeBound(Root32, mesh, epsilon); #endif if (!bv32Tree.init(mesh, Source.getBV())) return false; BV32Tree* T = &bv32Tree; PxU32 MaxDepth = 0; // Version with variable-sized nodes in single stream { GU_PROFILE_ZONE("...._flatten") struct Local { static void _flatten(BV32Data* const dest, const PxU32 box_id, PxU32& current_id, const BV32Node* current, PxU32& max_depth, PxU32& current_depth, const PxU32 nb_nodes) { // Entering a new node => increase depth current_depth++; // Keep track of max depth if (current_depth>max_depth) max_depth = current_depth; for (PxU32 i = 0; i<current->mNbChildBVNodes; i++) { dest[box_id + i].mMin = current->mBVData[i].mMin; dest[box_id + i].mMax = current->mBVData[i].mMax; dest[box_id + i].mData = PxU32(current->mBVData[i].mData); dest[box_id + i].mDepth = current_depth; PX_ASSERT(box_id + i < nb_nodes); } PxU32 NbToGo = 0; PxU32 NextIDs[32]; PxMemSet(NextIDs, PX_INVALID_U32, sizeof(PxU32)*32); const BV32Node* ChildNodes[32]; PxMemSet(ChildNodes, 0, sizeof(BV32Node*)*32); BV32Data* data = dest + box_id; for (PxU32 i = 0; i<current->mNbChildBVNodes; i++) { PX_ASSERT(current->mBVData[i].mData != PX_INVALID_U32); if (!current->isLeaf(i)) { const BV32Node* ChildNode = current->getChild(i); const PxU32 NextID = current_id; const PxU32 ChildSize = ChildNode->mNbChildBVNodes; current_id += ChildSize; const PxU32 ChildType = ChildNode->mNbChildBVNodes << 1; data[i].mData = size_t(ChildType + (NextID << GU_BV4_CHILD_OFFSET_SHIFT_COUNT)); //PX_ASSERT(data[i].mData == size_t(ChildType+(NextID<<3))); PX_ASSERT(box_id + i < nb_nodes); NextIDs[NbToGo] = NextID; ChildNodes[NbToGo] = ChildNode; NbToGo++; } } for (PxU32 i = 0; i<NbToGo; i++) { _flatten(dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth, nb_nodes); current_depth--; } PX_DELETE(current); } }; PxU32 CurID = Root32->mNbChildBVNodes+1; BV32Data* Nodes = PX_NEW(BV32Data)[nbNodes]; Nodes[0].mMin = Source.getBV().minimum; Nodes[0].mMax = Source.getBV().maximum; const PxU32 ChildType = Root32->mNbChildBVNodes << 1; Nodes[0].mData = size_t(ChildType + (1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT)); const PxU32 nbChilden = Nodes[0].getNbChildren(); PX_UNUSED(nbChilden); T->mInitData = CurID; PxU32 CurrentDepth = 0; Local::_flatten(Nodes, 1, CurID, Root32, MaxDepth, CurrentDepth, nbNodes); PX_ASSERT(CurID == nbNodes); T->mNbNodes = nbNodes; T->mNodes = Nodes; } { GU_PROFILE_ZONE("....calculateLeafNode") BV32Data* nodes = bv32Tree.mNodes; for(PxU32 i=0; i<nbNodes; i++) { BV32Data& node = nodes[i]; if(!node.isLeaf()) { PxU32 nbChildren = node.getNbChildren(); PxU32 offset = node.getChildOffset(); //calculate how many children nodes are leaf nodes PxU32 nbLeafNodes = 0; while(nbChildren--) { BV32Data& child = nodes[offset++]; if(child.isLeaf()) nbLeafNodes++; } node.mNbLeafNodes = nbLeafNodes; } } } bv32Tree.mPackedNodes = PX_ALLOCATE(BV32DataPacked, nbNodes, "BV32DataPacked"); bv32Tree.mNbPackedNodes = nbNodes; bv32Tree.mMaxTreeDepth = MaxDepth; PxU32 nbPackedNodes = 1; PxU32 currentIndex = bv32Tree.mNodes[0].getNbChildren() - bv32Tree.mNodes[0].mNbLeafNodes + 1; BV32DataPacked& packedData = bv32Tree.mPackedNodes[0]; //BV32DataDepth& depthData = bv32Tree.mMaxDepthForPackedNodes[0]; { GU_PROFILE_ZONE("....createSOAformatNode") bv32Tree.createSOAformatNode(packedData, bv32Tree.mNodes[0], 1, currentIndex, nbPackedNodes); } PX_ASSERT(nbPackedNodes == currentIndex); PX_ASSERT(nbPackedNodes > 0); bv32Tree.mNbPackedNodes = nbPackedNodes; #if BV32_VALIDATE /*for (PxU32 i = 0; i < nbNodes; ++i) { BV32Data& iNode = bv32Tree.mNodes[i]; for (PxU32 j = i+1; j < nbNodes; ++j) { BV32Data& jNode = bv32Tree.mNodes[j]; PX_ASSERT(iNode.mDepth <= jNode.mDepth); } }*/ #endif { GU_PROFILE_ZONE("....depth stuff") //bv32Tree.mMaxDepthForPackedNodes = reinterpret_cast<BV32DataDepth*>(PX_ALLOC(sizeof(BV32DataDepth)*MaxDepth, "BV32DataDepth")); bv32Tree.mTreeDepthInfo = PX_ALLOCATE(BV32DataDepthInfo, MaxDepth, "BV32DataDepthInfo"); PxU32 totalCount = 0; for (PxU32 i = 0; i < MaxDepth; ++i) { PxU32 count = 0; for (PxU32 j = 0; j < nbPackedNodes; ++j) { BV32DataPacked& jPackedData = bv32Tree.mPackedNodes[j]; if (jPackedData.mDepth == i) { count++; } } bv32Tree.mTreeDepthInfo[i].offset = totalCount; bv32Tree.mTreeDepthInfo[i].count = count; totalCount += count; } PX_ASSERT(totalCount == nbPackedNodes); bv32Tree.mRemapPackedNodeIndexWithDepth = PX_ALLOCATE(PxU32, nbPackedNodes, "PxU32"); for (PxU32 i = 0; i < MaxDepth; ++i) { PxU32 count = 0; const PxU32 offset = bv32Tree.mTreeDepthInfo[i].offset; PxU32* treeDepth = &bv32Tree.mRemapPackedNodeIndexWithDepth[offset]; for (PxU32 j = 0; j < nbPackedNodes; ++j) { BV32DataPacked& jPackedData = bv32Tree.mPackedNodes[j]; if (jPackedData.mDepth == i) { treeDepth[count++] = j; } } } #if BV32_VALIDATE for (PxU32 i = MaxDepth; i > 0; i--) { const PxU32 iOffset = bv32Tree.mTreeDepthInfo[i - 1].offset; const PxU32 iCount = bv32Tree.mTreeDepthInfo[i - 1].count; PxU32* iRempapNodeIndex = &bv32Tree.mRemapPackedNodeIndexWithDepth[iOffset]; for (PxU32 j = 0; j < iCount; ++j) { const PxU32 nodeIndex = iRempapNodeIndex[j]; BV32DataPacked& currentNode = bv32Tree.mPackedNodes[nodeIndex]; PX_ASSERT(currentNode.mDepth == i - 1); } } #endif } return true; } ///// struct ReorderData32 { //const SourceMesh* mMesh; SourceMeshBase* mMesh; PxU32* mOrder; PxU32 mNbPrimitivesPerLeaf; PxU32 mIndex; PxU32 mNbPrimitives; PxU32 mStats[32]; }; static bool gReorderCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData) { ReorderData32* Data = reinterpret_cast<ReorderData32*>(userData); if (current->isLeaf()) { const PxU32 n = current->getNbPrimitives(); PX_ASSERT(n > 0); PX_ASSERT(n <= Data->mNbPrimitivesPerLeaf); Data->mStats[n-1]++; PxU32* Prims = const_cast<PxU32*>(current->getPrimitives()); for (PxU32 i = 0; i<n; i++) { PX_ASSERT(Prims[i]<Data->mNbPrimitives); Data->mOrder[Data->mIndex] = Prims[i]; PX_ASSERT(Data->mIndex<Data->mNbPrimitives); Prims[i] = Data->mIndex; Data->mIndex++; } } return true; } bool physx::Gu::BuildBV32Ex(BV32Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivesPerLeaf) { const PxU32 nbPrimitives = mesh.getNbPrimitives(); BV4_AABBTree Source; { GU_PROFILE_ZONE("..BuildBV32Ex_buildFromMesh") // if (!Source.buildFromMesh(mesh, nbPrimitivesPerLeaf, BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER)) if (!Source.buildFromMesh(mesh, nbPrimitivesPerLeaf, BV4_SAH)) return false; } { GU_PROFILE_ZONE("..BuildBV32Ex_remap") PxU32* order = PX_ALLOCATE(PxU32, nbPrimitives, "BV32"); ReorderData32 RD; RD.mMesh = &mesh; RD.mOrder = order; RD.mNbPrimitivesPerLeaf = nbPrimitivesPerLeaf; RD.mIndex = 0; RD.mNbPrimitives = nbPrimitives; for (PxU32 i = 0; i<32; i++) RD.mStats[i] = 0; Source.walk(gReorderCallback, &RD); PX_ASSERT(RD.mIndex == nbPrimitives); mesh.remapTopology(order); PX_FREE(order); // for(PxU32 i=0;i<16;i++) // printf("%d: %d\n", i, RD.mStats[i]); } /*if (mesh.getNbPrimitives() <= nbPrimitivesPerLeaf) return tree.init(&mesh, Source.getBV());*/ return BuildBV32Internal(tree, Source, &mesh, epsilon); }
18,784
C++
26.028777
171
0.659497
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshRTree.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "GuTriangleMesh.h" #include "GuTriangleMeshRTree.h" using namespace physx; namespace physx { Gu::RTreeTriangleMesh::RTreeTriangleMesh(MeshFactory* factory, TriangleMeshData& d) : TriangleMesh(factory, d) { PX_ASSERT(d.mType==PxMeshMidPhase::eBVH33); RTreeTriangleData& rtreeData = static_cast<RTreeTriangleData&>(d); mRTree = rtreeData.mRTree; rtreeData.mRTree.mPages = NULL; } Gu::TriangleMesh* Gu::RTreeTriangleMesh::createObject(PxU8*& address, PxDeserializationContext& context) { RTreeTriangleMesh* obj = PX_PLACEMENT_NEW(address, RTreeTriangleMesh(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(RTreeTriangleMesh); obj->importExtraData(context); return obj; } void Gu::RTreeTriangleMesh::exportExtraData(PxSerializationContext& stream) { mRTree.exportExtraData(stream); TriangleMesh::exportExtraData(stream); } void Gu::RTreeTriangleMesh::importExtraData(PxDeserializationContext& context) { mRTree.importExtraData(context); TriangleMesh::importExtraData(context); } PxVec3 * Gu::RTreeTriangleMesh::getVerticesForModification() { return const_cast<PxVec3*>(getVertices()); } template<typename IndexType> struct RefitCallback : Gu::RTree::CallbackRefit { const PxVec3* newPositions; const IndexType* indices; RefitCallback(const PxVec3* aNewPositions, const IndexType* aIndices) : newPositions(aNewPositions), indices(aIndices) {} PX_FORCE_INLINE ~RefitCallback() {} virtual void recomputeBounds(PxU32 index, aos::Vec3V& aMn, aos::Vec3V& aMx) { using namespace aos; // Each leaf box has a set of triangles Gu::LeafTriangles currentLeaf; currentLeaf.Data = index; PxU32 nbTris = currentLeaf.GetNbTriangles(); PxU32 baseTri = currentLeaf.GetTriangleIndex(); PX_ASSERT(nbTris > 0); const IndexType* vInds = indices + 3 * baseTri; Vec3V vPos = V3LoadU(newPositions[vInds[0]]); Vec3V mn = vPos, mx = vPos; //PxBounds3 result(newPositions[vInds[0]], newPositions[vInds[0]]); vPos = V3LoadU(newPositions[vInds[1]]); mn = V3Min(mn, vPos); mx = V3Max(mx, vPos); vPos = V3LoadU(newPositions[vInds[2]]); mn = V3Min(mn, vPos); mx = V3Max(mx, vPos); for (PxU32 i = 1; i < nbTris; i++) { const IndexType* vInds1 = indices + 3 * (baseTri + i); vPos = V3LoadU(newPositions[vInds1[0]]); mn = V3Min(mn, vPos); mx = V3Max(mx, vPos); vPos = V3LoadU(newPositions[vInds1[1]]); mn = V3Min(mn, vPos); mx = V3Max(mx, vPos); vPos = V3LoadU(newPositions[vInds1[2]]); mn = V3Min(mn, vPos); mx = V3Max(mx, vPos); } aMn = mn; aMx = mx; } }; PxBounds3 Gu::RTreeTriangleMesh::refitBVH() { PxBounds3 meshBounds; if (has16BitIndices()) { RefitCallback<PxU16> cb(mVertices, static_cast<const PxU16*>(mTriangles)); mRTree.refitAllStaticTree(cb, &meshBounds); } else { RefitCallback<PxU32> cb(mVertices, static_cast<const PxU32*>(mTriangles)); mRTree.refitAllStaticTree(cb, &meshBounds); } // reset edge flags and remember we did that using a mesh flag (optimization) if ((mRTree.mFlags & RTree::IS_EDGE_SET) == 0) { mRTree.mFlags |= RTree::IS_EDGE_SET; setAllEdgesActive(); } mAABB = meshBounds; return meshBounds; } } // namespace physx
4,837
C++
33.805755
122
0.738888
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayTriangle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_INTERSECTION_RAY_TRIANGLE_H #define GU_INTERSECTION_RAY_TRIANGLE_H #include "foundation/PxVec3.h" #include "common/PxPhysXCommonConfig.h" namespace physx { namespace Gu { // PT: this is used for backface culling. It existed in Moller's original code already. Basically this is only to avoid dividing by zero. // This should not depend on what units are used, and neither should it depend on the size of triangles. A large triangle with the same // orientation as a small triangle should be backface culled the same way. A triangle whose orientation does not change should not suddenly // become culled or visible when we scale it. // // An absolute epsilon is fine here. The computation will work fine for small triangles, and large triangles will simply make 'det' larger, // more and more inaccurate, but it won't suddenly make it negative. // // Using FLT_EPSILON^2 ensures that triangles whose edges are smaller than FLT_EPSILON long are rejected. This epsilon makes the code work // for very small triangles, while still preventing divisions by too small values. #define GU_CULLING_EPSILON_RAY_TRIANGLE FLT_EPSILON*FLT_EPSILON /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes a ray-triangle intersection test. * From Tomas Moeller's "Fast Minimum Storage Ray-Triangle Intersection" * Could be optimized and cut into 2 methods (culled or not). Should make a batch one too to avoid the call overhead, or make it inline. * * \param orig [in] ray origin * \param dir [in] ray direction * \param vert0 [in] triangle vertex * \param vert1 [in] triangle vertex * \param vert2 [in] triangle vertex * \param at [out] distance * \param au [out] impact barycentric coordinate * \param av [out] impact barycentric coordinate * \param cull [in] true to use backface culling * \param enlarge [in] enlarge triangle by specified epsilon in UV space to avoid false near-edge rejections * \return true on overlap * \note u, v and t will remain unchanged if false is returned. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE bool intersectRayTriangle( const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxReal& at, PxReal& au, PxReal& av, bool cull, float enlarge=0.0f) { // Find vectors for two edges sharing vert0 const PxVec3 edge1 = vert1 - vert0; const PxVec3 edge2 = vert2 - vert0; // Begin calculating determinant - also used to calculate U parameter const PxVec3 pvec = dir.cross(edge2); // error ~ |v2-v0| // If determinant is near zero, ray lies in plane of triangle const PxReal det = edge1.dot(pvec); // error ~ |v2-v0|*|v1-v0| if(cull) { if(det<GU_CULLING_EPSILON_RAY_TRIANGLE) return false; // Calculate distance from vert0 to ray origin const PxVec3 tvec = orig - vert0; // Calculate U parameter and test bounds const PxReal u = tvec.dot(pvec); const PxReal enlargeCoeff = enlarge*det; const PxReal uvlimit = -enlargeCoeff; const PxReal uvlimit2 = det + enlargeCoeff; if(u<uvlimit || u>uvlimit2) return false; // Prepare to test V parameter const PxVec3 qvec = tvec.cross(edge1); // Calculate V parameter and test bounds const PxReal v = dir.dot(qvec); if(v<uvlimit || (u+v)>uvlimit2) return false; // Calculate t, scale parameters, ray intersects triangle const PxReal t = edge2.dot(qvec); const PxReal inv_det = 1.0f / det; at = t*inv_det; au = u*inv_det; av = v*inv_det; } else { // the non-culling branch if(PxAbs(det)<GU_CULLING_EPSILON_RAY_TRIANGLE) return false; const PxReal inv_det = 1.0f / det; // Calculate distance from vert0 to ray origin const PxVec3 tvec = orig - vert0; // error ~ |orig-v0| // Calculate U parameter and test bounds const PxReal u = tvec.dot(pvec) * inv_det; if(u<-enlarge || u>1.0f+enlarge) return false; // prepare to test V parameter const PxVec3 qvec = tvec.cross(edge1); // Calculate V parameter and test bounds const PxReal v = dir.dot(qvec) * inv_det; if(v<-enlarge || (u+v)>1.0f+enlarge) return false; // Calculate t, ray intersects triangle const PxReal t = edge2.dot(qvec) * inv_det; at = t; au = u; av = v; } return true; } /* \note u, v and t will remain unchanged if false is returned. */ PX_FORCE_INLINE bool intersectRayTriangleCulling( const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxReal& t, PxReal& u, PxReal& v, float enlarge=0.0f) { return intersectRayTriangle(orig, dir, vert0, vert1, vert2, t, u, v, true, enlarge); } /* \note u, v and t will remain unchanged if false is returned. */ PX_FORCE_INLINE bool intersectRayTriangleNoCulling( const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxReal& t, PxReal& u, PxReal& v, float enlarge=0.0f) { return intersectRayTriangle(orig, dir, vert0, vert1, vert2, t, u, v, false, enlarge); } } // namespace Gu } #endif
7,202
C
39.466292
200
0.667037