feat(physics): wire physx sdk into build

This commit is contained in:
2026-04-15 12:22:15 +08:00
parent 5bf258df6d
commit 31f40e2cbb
2044 changed files with 752623 additions and 1 deletions

View File

@@ -0,0 +1,138 @@
// 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-2025 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 "GuIntersectionBoxBox.h"
using namespace physx;
bool Gu::intersectOBBOBB(const PxVec3& e0, const PxVec3& c0, const PxMat33& r0, const PxVec3& e1, const PxVec3& c1, const PxMat33& r1, bool full_test)
{
// Translation, in parent frame
const PxVec3 v = c1 - c0;
// Translation, in A's frame
const PxVec3 T(v.dot(r0[0]), v.dot(r0[1]), v.dot(r0[2]));
// B's basis with respect to A's local frame
PxReal R[3][3];
PxReal FR[3][3];
PxReal ra, rb, t;
// Calculate rotation matrix
for(PxU32 i=0;i<3;i++)
{
for(PxU32 k=0;k<3;k++)
{
R[i][k] = r0[i].dot(r1[k]);
FR[i][k] = 1e-6f + PxAbs(R[i][k]); // Precompute fabs matrix
}
}
// A's basis vectors
for(PxU32 i=0;i<3;i++)
{
ra = e0[i];
rb = e1[0]*FR[i][0] + e1[1]*FR[i][1] + e1[2]*FR[i][2];
t = PxAbs(T[i]);
if(t > ra + rb) return false;
}
// B's basis vectors
for(PxU32 k=0;k<3;k++)
{
ra = e0[0]*FR[0][k] + e0[1]*FR[1][k] + e0[2]*FR[2][k];
rb = e1[k];
t = PxAbs(T[0]*R[0][k] + T[1]*R[1][k] + T[2]*R[2][k]);
if( t > ra + rb ) return false;
}
if(full_test)
{
//9 cross products
//L = A0 x B0
ra = e0[1]*FR[2][0] + e0[2]*FR[1][0];
rb = e1[1]*FR[0][2] + e1[2]*FR[0][1];
t = PxAbs(T[2]*R[1][0] - T[1]*R[2][0]);
if(t > ra + rb) return false;
//L = A0 x B1
ra = e0[1]*FR[2][1] + e0[2]*FR[1][1];
rb = e1[0]*FR[0][2] + e1[2]*FR[0][0];
t = PxAbs(T[2]*R[1][1] - T[1]*R[2][1]);
if(t > ra + rb) return false;
//L = A0 x B2
ra = e0[1]*FR[2][2] + e0[2]*FR[1][2];
rb = e1[0]*FR[0][1] + e1[1]*FR[0][0];
t = PxAbs(T[2]*R[1][2] - T[1]*R[2][2]);
if(t > ra + rb) return false;
//L = A1 x B0
ra = e0[0]*FR[2][0] + e0[2]*FR[0][0];
rb = e1[1]*FR[1][2] + e1[2]*FR[1][1];
t = PxAbs(T[0]*R[2][0] - T[2]*R[0][0]);
if(t > ra + rb) return false;
//L = A1 x B1
ra = e0[0]*FR[2][1] + e0[2]*FR[0][1];
rb = e1[0]*FR[1][2] + e1[2]*FR[1][0];
t = PxAbs(T[0]*R[2][1] - T[2]*R[0][1]);
if(t > ra + rb) return false;
//L = A1 x B2
ra = e0[0]*FR[2][2] + e0[2]*FR[0][2];
rb = e1[0]*FR[1][1] + e1[1]*FR[1][0];
t = PxAbs(T[0]*R[2][2] - T[2]*R[0][2]);
if(t > ra + rb) return false;
//L = A2 x B0
ra = e0[0]*FR[1][0] + e0[1]*FR[0][0];
rb = e1[1]*FR[2][2] + e1[2]*FR[2][1];
t = PxAbs(T[1]*R[0][0] - T[0]*R[1][0]);
if(t > ra + rb) return false;
//L = A2 x B1
ra = e0[0]*FR[1][1] + e0[1]*FR[0][1];
rb = e1[0] *FR[2][2] + e1[2]*FR[2][0];
t = PxAbs(T[1]*R[0][1] - T[0]*R[1][1]);
if(t > ra + rb) return false;
//L = A2 x B2
ra = e0[0]*FR[1][2] + e0[1]*FR[0][2];
rb = e1[0]*FR[2][1] + e1[1]*FR[2][0];
t = PxAbs(T[1]*R[0][2] - T[0]*R[1][2]);
if(t > ra + rb) return false;
}
return true;
}

View File

@@ -0,0 +1,60 @@
// 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-2025 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 "GuIntersectionCapsuleTriangle.h"
#include "GuDistancePointSegment.h"
using namespace physx;
using namespace Gu;
bool Gu::intersectCapsuleTriangle(const PxVec3& N, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params)
{
PX_ASSERT(capsule.p0!=capsule.p1);
{
const PxReal d2 = distancePointSegmentSquaredInternal(capsule.p0, params.mCapsuleDir, p0);
if(d2<=capsule.radius*capsule.radius)
return true;
}
// const PxVec3 N = (p0 - p1).cross(p0 - p2);
if(!testAxis(p0, p1, p2, capsule, N))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p0, p1 - p0, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p1, p2 - p1, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p2, p0 - p2, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
return true;
}

View File

@@ -0,0 +1,135 @@
// 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-2025 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_CAPSULE_TRIANGLE_H
#define GU_INTERSECTION_CAPSULE_TRIANGLE_H
#include "GuCapsule.h"
#include "foundation/PxUtilities.h"
namespace physx
{
namespace Gu
{
// PT: precomputed data for capsule-triangle test. Useful when testing the same capsule vs several triangles.
struct CapsuleTriangleOverlapData
{
PxVec3 mCapsuleDir;
float mBDotB;
float mOneOverBDotB;
void init(const Capsule& capsule)
{
const PxVec3 dir = capsule.p1 - capsule.p0;
const float BDotB = dir.dot(dir);
mCapsuleDir = dir;
mBDotB = BDotB;
mOneOverBDotB = BDotB!=0.0f ? 1.0f/BDotB : 0.0f;
}
};
// PT: tests if projections of capsule & triangle overlap on given axis
PX_FORCE_INLINE PxU32 testAxis(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Capsule& capsule, const PxVec3& axis)
{
// Project capsule
float min0 = capsule.p0.dot(axis);
float max0 = capsule.p1.dot(axis);
if(min0>max0)
PxSwap(min0, max0);
const float MR = axis.magnitude()*capsule.radius;
min0 -= MR;
max0 += MR;
// Project triangle
float min1, max1;
{
min1 = max1 = p0.dot(axis);
float dp = p1.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
dp = p2.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
}
// Test projections
if(max0<min1 || max1<min0)
return 0;
return 1;
}
// PT: computes shortest vector going from capsule axis to triangle edge
PX_FORCE_INLINE PxVec3 computeEdgeAxis( const PxVec3& p, const PxVec3& a,
const PxVec3& q, const PxVec3& b,
float BDotB, float oneOverBDotB)
{
const PxVec3 T = q - p;
const float ADotA = a.dot(a);
const float ADotB = a.dot(b);
const float ADotT = a.dot(T);
const float BDotT = b.dot(T);
const float denom = ADotA*BDotB - ADotB*ADotB;
float t = denom!=0.0f ? (ADotT*BDotB - BDotT*ADotB) / denom : 0.0f;
t = PxClamp(t, 0.0f, 1.0f);
float u = (t*ADotB - BDotT) * oneOverBDotB;
if(u<0.0f)
{
u = 0.0f;
t = ADotT / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
else if(u>1.0f)
{
u = 1.0f;
t = (ADotB + ADotT) / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
return T + b*u - a*t;
}
/**
* Checks if a capsule intersects a triangle.
*
* \param normal [in] triangle normal (orientation does not matter)
* \param p0 [in] triangle's first point
* \param p1 [in] triangle's second point
* \param p2 [in] triangle's third point
* \param capsule [in] capsule
* \param params [in] precomputed capsule params
* \return true if capsule overlaps triangle
*/
bool intersectCapsuleTriangle(const PxVec3& normal, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params);
}
}
#endif

View File

@@ -0,0 +1,82 @@
// 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-2025 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 "GuIntersectionEdgeEdge.h"
#include "GuInternal.h"
using namespace physx;
bool Gu::intersectEdgeEdge(const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip)
{
const PxVec3 v1 = p2 - p1;
// Build plane P based on edge (p1, p2) and direction (dir)
PxPlane plane;
plane.n = v1.cross(dir);
plane.d = -(plane.n.dot(p1));
// 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);
// find largest 2D plane projection
PxU32 i,j;
closestAxis(plane.n, i, j);
// 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]))/(v1[i]*dir[j]-v1[j]*dir[i]);
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<1e-3f) return true; // collision found
return false; // no collision
}

View File

@@ -0,0 +1,51 @@
// 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-2025 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_EDGE_EDGE_H
#define GU_INTERSECTION_EDGE_EDGE_H
#include "foundation/PxVec3.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
// collide edge (p1,p2) moving in direction (dir) colliding
// width edge (p3,p4). Return true on a collision with
// collision distance (dist) and intersection point (ip)
// note: dist and ip are invalid if function returns false.
// note: ip is on (p1,p2), not (p1+dist*dir,p2+dist*dir)
PX_PHYSX_COMMON_API bool intersectEdgeEdge(const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip);
} // namespace Gu
}
#endif

View File

@@ -0,0 +1,37 @@
// 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-2025 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_H
#define GU_INTERSECTION_RAY_H
// PT: small distance between a ray origin and a potentially hit surface. Should be small enough to
// limit accuracy issues coming from large distance values, but not too close to the surface to make
// sure we don't start inside the shape.
#define GU_RAY_SURFACE_OFFSET 10.0f
#endif

View File

@@ -0,0 +1,447 @@
// 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-2025 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/PxMathIntrinsics.h"
#include "foundation/PxFPU.h"
#include "GuIntersectionRayBox.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: p.terdiman@codercorner.com
*
* \param aabb [in] the axis-aligned bounding box
* \param origin [in] ray origin
* \param dir [in] ray direction
* \param coord [out] impact coordinates
* \return true if ray intersects AABB
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define RAYAABB_EPSILON 0.00001f
bool Gu::rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
return true;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return false;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON)
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i])
#endif
return false;
}
}
return true; // ray hits box
}
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
* Return of intersected face code and parameter by Adam! Also modified behavior for ray starts inside AABB. 2004 :-p
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: p.terdiman@codercorner.com
*
* \param minimum [in] the smaller corner of the bounding box
* \param maximum [in] the larger corner of the bounding box
* \param origin [in] ray origin
* \param _dir [in] ray direction
* \param coord [out] impact coordinates
* \param t [out] t such that coord = origin + dir * t
* \return false if ray does not intersect AABB, or ray origin is inside AABB. Else:
1 + coordinate index of box axis that was hit
Note: sign bit that determines if the minimum (0) or maximum (1) of the axis was hit is equal to sign(coord[returnVal-1]).
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxU32 Gu::rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
t = 0;
return 1;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return 0;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON) return 0;
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i]) return 0;
#endif
}
}
t = MaxT[WhichPlane];
return 1 + WhichPlane; // ray hits box
}
// Collide ray defined by ray origin (ro) and ray direction (rd)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
// ptchernev:
// Should we use an enum, or should we keep the anonymous ints?
// Should we increment the return code by one (return 0 for non intersection)?
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float& tnear, float& tfar)
{
// Refactor
int ret=-1;
tnear = -PX_MAX_F32;
tfar = PX_MAX_F32;
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
for(unsigned int a=0;a<3;a++)
{
if(rd[a]>-LOCAL_EPSILON && rd[a]<LOCAL_EPSILON)
{
if(ro[a]<minimum[a] || ro[a]>maximum[a])
return -1;
}
else
{
const PxReal OneOverDir = 1.0f / rd[a];
PxReal t1 = (minimum[a]-ro[a]) * OneOverDir;
PxReal t2 = (maximum[a]-ro[a]) * OneOverDir;
unsigned int b = a;
if(t1>t2)
{
PxReal t=t1;
t1=t2;
t2=t;
b += 3;
}
if(t1>tnear)
{
tnear = t1;
ret = int(b);
}
if(t2<tfar)
tfar=t2;
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
}
}
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
// PT: specialized version where oneOverDir is available
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, const PxVec3& oneOverDir, float& tnear, float& tfar)
{
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
if(physx::intrinsics::abs(rd.x)<LOCAL_EPSILON)
// if(rd.x>-LOCAL_EPSILON && rd.x<LOCAL_EPSILON)
if(ro.x<minimum.x || ro.x>maximum.x)
return -1;
if(physx::intrinsics::abs(rd.y)<LOCAL_EPSILON)
// if(rd.y>-LOCAL_EPSILON && rd.y<LOCAL_EPSILON)
if(ro.y<minimum.y || ro.y>maximum.y)
return -1;
if(physx::intrinsics::abs(rd.z)<LOCAL_EPSILON)
// if(rd.z>-LOCAL_EPSILON && rd.z<LOCAL_EPSILON)
if(ro.z<minimum.z || ro.z>maximum.z)
return -1;
PxReal t1x = (minimum.x - ro.x) * oneOverDir.x;
PxReal t2x = (maximum.x - ro.x) * oneOverDir.x;
PxReal t1y = (minimum.y - ro.y) * oneOverDir.y;
PxReal t2y = (maximum.y - ro.y) * oneOverDir.y;
PxReal t1z = (minimum.z - ro.z) * oneOverDir.z;
PxReal t2z = (maximum.z - ro.z) * oneOverDir.z;
int bx;
int by;
int bz;
if(t1x>t2x)
{
PxReal t=t1x; t1x=t2x; t2x=t;
bx = 3;
}
else
{
bx = 0;
}
if(t1y>t2y)
{
PxReal t=t1y; t1y=t2y; t2y=t;
by = 4;
}
else
{
by = 1;
}
if(t1z>t2z)
{
PxReal t=t1z; t1z=t2z; t2z=t;
bz = 5;
}
else
{
bz = 2;
}
int ret;
// if(t1x>tnear) // PT: no need to test for the first value
{
tnear = t1x;
ret = bx;
}
// tfar = PxMin(tfar, t2x);
tfar = t2x; // PT: no need to test for the first value
if(t1y>tnear)
{
tnear = t1y;
ret = by;
}
tfar = PxMin(tfar, t2y);
if(t1z>tnear)
{
tnear = t1z;
ret = bz;
}
tfar = PxMin(tfar, t2z);
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
bool Gu::intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar)
{
PX_ASSERT(maximum.x-minimum.x >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.y-minimum.y >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.z-minimum.z >= GU_MIN_AABB_EXTENT*0.5f);
// not using vector math due to vector to integer pipeline penalties. TODO: verify that it's indeed faster
namespace i = physx::intrinsics;
// P+tD=a; t=(a-P)/D
// t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x)
const PxF32 dEpsilon = 1e-9f;
// using recipFast fails height field unit tests case where a ray cast from y=10000 to 0 gets clipped to 0.27 in y
PxF32 invDx = i::recip(i::selectMax(i::abs(rd.x), dEpsilon) * i::sign(rd.x));
#ifdef RAYAABB_EPSILON
PxF32 tx0 = (minimum.x - RAYAABB_EPSILON - ro.x) * invDx;
PxF32 tx1 = (maximum.x + RAYAABB_EPSILON - ro.x) * invDx;
#else
PxF32 tx0 = (minimum.x - ro.x) * invDx;
PxF32 tx1 = (maximum.x - ro.x) * invDx;
#endif
PxF32 txMin = i::selectMin(tx0, tx1);
PxF32 txMax = i::selectMax(tx0, tx1);
PxF32 invDy = i::recip(i::selectMax(i::abs(rd.y), dEpsilon) * i::sign(rd.y));
#ifdef RAYAABB_EPSILON
PxF32 ty0 = (minimum.y - RAYAABB_EPSILON - ro.y) * invDy;
PxF32 ty1 = (maximum.y + RAYAABB_EPSILON - ro.y) * invDy;
#else
PxF32 ty0 = (minimum.y - ro.y) * invDy;
PxF32 ty1 = (maximum.y - ro.y) * invDy;
#endif
PxF32 tyMin = i::selectMin(ty0, ty1);
PxF32 tyMax = i::selectMax(ty0, ty1);
PxF32 invDz = i::recip(i::selectMax(i::abs(rd.z), dEpsilon) * i::sign(rd.z));
#ifdef RAYAABB_EPSILON
PxF32 tz0 = (minimum.z - RAYAABB_EPSILON - ro.z) * invDz;
PxF32 tz1 = (maximum.z + RAYAABB_EPSILON - ro.z) * invDz;
#else
PxF32 tz0 = (minimum.z - ro.z) * invDz;
PxF32 tz1 = (maximum.z - ro.z) * invDz;
#endif
PxF32 tzMin = i::selectMin(tz0, tz1);
PxF32 tzMax = i::selectMax(tz0, tz1);
PxF32 maxOfNears = i::selectMax(i::selectMax(txMin, tyMin), tzMin);
PxF32 minOfFars = i::selectMin(i::selectMin(txMax, tyMax), tzMax);
tnear = i::selectMax(maxOfNears, 0.0f);
tfar = i::selectMin(minOfFars, maxDist);
return (tnear<tfar);
}
bool Gu::intersectRayAABB2(const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar)
{
using namespace aos;
const FloatV zero = FZero();
const Vec3V eps = V3Load(1e-9f);
const Vec3V absRD = V3Max(V3Abs(rd), eps);
const Vec3V signRD = V3Sign(rd);
const Vec3V rdV = V3Mul(absRD, signRD);
const Vec3V rdVRecip = V3Recip(rdV);
const Vec3V _min = V3Mul(V3Sub(minimum, ro), rdVRecip);
const Vec3V _max = V3Mul(V3Sub(maximum, ro), rdVRecip);
const Vec3V min = V3Min(_max, _min);
const Vec3V max = V3Max(_max, _min);
const FloatV maxOfNears = FMax(V3GetX(min), FMax(V3GetY(min), V3GetZ(min)));
const FloatV minOfFars = FMin(V3GetX(max), FMin(V3GetY(max), V3GetZ(max)));
tnear = FMax(maxOfNears, zero);
tfar = FMin(minOfFars, maxDist);
//tfar = FAdd(FMin(minOfFars, maxDist), V3GetX(eps)); // AP: + epsilon because a test vs empty box should return true
return FAllGrtr(tfar, tnear) != 0;
}

View File

@@ -0,0 +1,92 @@
// 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-2025 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_BOX_H
#define GU_INTERSECTION_RAY_BOX_H
#include "foundation/PxMathIntrinsics.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
bool rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord);
PxU32 rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t);
// Collide ray defined by ray origin (rayOrigin) and ray direction (rayDirection)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
//
// ptchernev:
// Even though the above is the original comment by Pierre I am quite confident
// that the tnear and tfar parameters are parameters along rayDirection of the
// intersection points:
//
// ip0 = rayOrigin + (rayDirection * tnear)
// ip1 = rayOrigin + (rayDirection * tfar)
//
// The return code is:
// -1 no intersection
// 0 the ray first hits the plane at aabbMin.x
// 1 the ray first hits the plane at aabbMin.y
// 2 the ray first hits the plane at aabbMin.z
// 3 the ray first hits the plane at aabbMax.x
// 4 the ray first hits the plane at aabbMax.y
// 5 the ray first hits the plane at aabbMax.z
//
// The return code will be -1 if the RAY does not intersect the AABB.
// The tnear and tfar values will give the parameters of the intersection
// points between the INFINITE LINE and the AABB.
int PX_PHYSX_COMMON_API intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection,
float& tnear, float& tfar);
// Faster version when one-over-dir is available
int intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection, const PxVec3& invDirection,
float& tnear, float& tfar);
// minimum extent length required for intersectRayAABB2 to return true for a zero-extent box
// this can happen when inflating the raycast by a 2-d square
#define GU_MIN_AABB_EXTENT 1e-3f
// a much faster version that doesn't return face codes
bool PX_PHYSX_COMMON_API intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar);
bool PX_PHYSX_COMMON_API intersectRayAABB2( const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar);
} // namespace Gu
}
#endif

View File

@@ -0,0 +1,121 @@
// 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-2025 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 "GuIntersectionRayCapsule.h"
#include "foundation/PxBasicTemplates.h"
using namespace physx;
static bool intersectRaySphere(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& sphereCenter, float radius2, float& tmin, float& tmax)
{
const PxVec3 CO = rayOrigin - sphereCenter;
const float a = rayDir.dot(rayDir);
const float b = 2.0f * CO.dot(rayDir);
const float c = CO.dot(CO) - radius2;
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return false;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
tmin = (-b - sqrtDet) * OneOver2A;
tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
return true;
}
PxU32 Gu::intersectRayCapsuleInternal(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& capsuleP0, const PxVec3& capsuleP1, float radius, PxReal s[2])
{
const float radius2 = radius * radius;
const PxVec3 AB = capsuleP1 - capsuleP0;
const PxVec3 AO = rayOrigin - capsuleP0;
const float AB_dot_d = AB.dot(rayDir);
const float AB_dot_AO = AB.dot(AO);
const float AB_dot_AB = AB.dot(AB);
const float OneOverABDotAB = AB_dot_AB!=0.0f ? 1.0f / AB_dot_AB : 0.0f;
const float m = AB_dot_d * OneOverABDotAB;
const float n = AB_dot_AO * OneOverABDotAB;
const PxVec3 Q = rayDir - (AB * m);
const PxVec3 R = AO - (AB * n);
const float a = Q.dot(Q);
const float b = 2.0f * Q.dot(R);
const float c = R.dot(R) - radius2;
if(a == 0.0f)
{
float atmin, atmax, btmin, btmax;
if( !intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, atmin, atmax)
|| !intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, btmin, btmax))
return 0;
s[0] = atmin < btmin ? atmin : btmin;
return 1;
}
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return 0;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
float tmin = (-b - sqrtDet) * OneOver2A;
float tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
const float t_k1 = tmin * m + n;
if(t_k1 < 0.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else if(t_k1 > 1.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else
s[0] = tmin;
return 1;
}

View File

@@ -0,0 +1,91 @@
// 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-2025 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_CAPSULE_H
#define GU_INTERSECTION_RAY_CAPSULE_H
#include "GuCapsule.h"
#include "GuDistancePointSegment.h"
#include "GuIntersectionRay.h"
namespace physx
{
namespace Gu
{
PxU32 intersectRayCapsuleInternal(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal s[2]);
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal& t)
{
// PT: move ray origin close to capsule, to solve accuracy issues.
// We compute the distance D between the ray origin and the capsule's segment.
// Then E = D - radius = distance between the ray origin and the capsule.
// We can move the origin freely along 'dir' up to E units before touching the capsule.
PxReal l = distancePointSegmentSquaredInternal(p0, p1 - p0, origin);
l = PxSqrt(l) - radius;
// PT: if this becomes negative or null, the ray starts inside the capsule and we can early exit
if(l<=0.0f)
{
t = 0.0f;
return true;
}
// PT: we remove an arbitrary GU_RAY_SURFACE_OFFSET units to E, to make sure we don't go close to the surface.
// If we're moving in the direction of the capsule, the origin is now about GU_RAY_SURFACE_OFFSET units from it.
// If we're moving away from the capsule, the ray won't hit the capsule anyway.
// If l is smaller than GU_RAY_SURFACE_OFFSET we're close enough, accuracy is good, there is nothing to do.
if(l>GU_RAY_SURFACE_OFFSET)
l -= GU_RAY_SURFACE_OFFSET;
else
l = 0.0f;
// PT: move origin closer to capsule and do the raycast
PxReal s[2];
const PxU32 nbHits = Gu::intersectRayCapsuleInternal(origin + l*dir, dir, p0, p1, radius, s);
if(!nbHits)
return false;
// PT: keep closest hit only
if(nbHits == 1)
t = s[0];
else
t = (s[0] < s[1]) ? s[0] : s[1];
// PT: fix distance (smaller than expected after moving ray close to capsule)
t += l;
return true;
}
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const Gu::Capsule& capsule, PxReal& t)
{
return Gu::intersectRayCapsule(origin, dir, capsule.p0, capsule.p1, capsule.radius, t);
}
}
}
#endif

View File

@@ -0,0 +1,57 @@
// 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-2025 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_PLANE_H
#define GU_INTERSECTION_RAY_PLANE_H
#include "foundation/PxPlane.h"
namespace physx
{
namespace Gu
{
// Returns true if line and plane are not parallel
PX_INLINE bool intersectRayPlane(const PxVec3& orig, const PxVec3& dir, const PxPlane& plane, float& distanceAlongLine, PxVec3* pointOnPlane = NULL)
{
const float dn = dir.dot(plane.n);
if(-1E-7f < dn && dn < 1E-7f)
return false; // parallel
distanceAlongLine = -plane.distance(orig)/dn;
if(pointOnPlane)
*pointOnPlane = orig + distanceAlongLine * dir;
return true;
}
} // namespace Gu
}
#endif

View File

@@ -0,0 +1,104 @@
// 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-2025 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 "GuIntersectionRaySphere.h"
#include "GuIntersectionRay.h"
using namespace physx;
// Based on GD Mag code, but now works correctly when origin is inside the sphere.
// This version has limited accuracy.
bool Gu::intersectRaySphereBasic(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
// get the offset vector
const PxVec3 offset = center - origin;
// get the distance along the ray to the center point of the sphere
const PxReal ray_dist = dir.dot(offset);
// get the squared distances
const PxReal off2 = offset.dot(offset);
const PxReal rad_2 = radius * radius;
if(off2 <= rad_2)
{
// we're in the sphere
if(hit_pos)
*hit_pos = origin;
dist = 0.0f;
return true;
}
if(ray_dist <= 0 || (ray_dist - length) > radius)
{
// moving away from object or too far away
return false;
}
// find hit distance squared
const PxReal d = rad_2 - (off2 - ray_dist * ray_dist);
if(d<0.0f)
{
// ray passes by sphere without hitting
return false;
}
// get the distance along the ray
dist = ray_dist - PxSqrt(d);
if(dist > length)
{
// hit point beyond length
return false;
}
// sort out the details
if(hit_pos)
*hit_pos = origin + dir * dist;
return true;
}
// PT: modified version calls the previous function, but moves the ray origin closer to the sphere. The test accuracy is
// greatly improved as a result. This is an idea proposed on the GD-Algorithms list by Eddie Edwards.
// See: http://www.codercorner.com/blog/?p=321
bool Gu::intersectRaySphere(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
const PxVec3 x = origin - center;
PxReal l = PxSqrt(x.dot(x)) - radius - GU_RAY_SURFACE_OFFSET;
// if(l<0.0f)
// l=0.0f;
l = physx::intrinsics::selectMax(l, 0.0f);
bool status = intersectRaySphereBasic(origin + l*dir, dir, length - l, center, radius, dist, hit_pos);
if(status)
{
// dist += l/length;
dist += l;
}
return status;
}

View File

@@ -0,0 +1,48 @@
// 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-2025 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_SPHERE_H
#define GU_INTERSECTION_RAY_SPHERE_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
// PT: basic version, limited accuracy, might fail for long rays vs small spheres
PX_PHYSX_COMMON_API bool intersectRaySphereBasic(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos = NULL);
// PT: version with improved accuracy
PX_PHYSX_COMMON_API bool intersectRaySphere(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos = NULL);
} // namespace Gu
}
#endif

View File

@@ -0,0 +1,177 @@
// 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-2025 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

View File

@@ -0,0 +1,87 @@
// 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-2025 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 "GuIntersectionSphereBox.h"
#include "GuSphere.h"
#include "GuBox.h"
using namespace physx;
bool Gu::intersectSphereBox(const Sphere& sphere, const Box& box)
{
const PxVec3 delta = sphere.center - box.center;
PxVec3 dRot = box.rot.transformTranspose(delta); //transform delta into OBB body coords. (use method call!)
//check if delta is outside AABB - and clip the vector to the AABB.
bool outside = false;
if(dRot.x < -box.extents.x)
{
outside = true;
dRot.x = -box.extents.x;
}
else if(dRot.x > box.extents.x)
{
outside = true;
dRot.x = box.extents.x;
}
if(dRot.y < -box.extents.y)
{
outside = true;
dRot.y = -box.extents.y;
}
else if(dRot.y > box.extents.y)
{
outside = true;
dRot.y = box.extents.y;
}
if(dRot.z < -box.extents.z)
{
outside = true;
dRot.z = -box.extents.z;
}
else if(dRot.z > box.extents.z)
{
outside = true;
dRot.z = box.extents.z;
}
if(outside) //if clipping was done, sphere center is outside of box.
{
const PxVec3 clippedDelta = box.rot.transform(dRot); //get clipped delta back in world coords.
const PxVec3 clippedVec = delta - clippedDelta; //what we clipped away.
const PxReal lenSquared = clippedVec.magnitudeSquared();
const PxReal radius = sphere.radius;
if(lenSquared > radius * radius) // PT: objects are defined as closed, so we return 'true' in case of equality
return false; //disjoint
}
return true;
}

View File

@@ -0,0 +1,53 @@
// 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-2025 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_SPHERE_BOX_H
#define GU_INTERSECTION_SPHERE_BOX_H
namespace physx
{
namespace Gu
{
class Sphere;
class Box;
/**
Checks if a sphere intersects a box. Based on: Jim Arvo, A Simple Method for Box-Sphere Intersection Testing, Graphics Gems, pp. 247-250.
\param sphere [in] sphere
\param box [in] box
\return true if sphere overlaps box (or exactly touches it)
*/
bool intersectSphereBox(const Gu::Sphere& sphere, const Gu::Box& box);
} // namespace Gu
}
#endif

View File

@@ -0,0 +1,62 @@
// 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-2025 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 "GuIntersectionTetrahedronBox.h"
#include "foundation/PxBasicTemplates.h"
#include "GuIntersectionTriangleBox.h"
#include "GuBox.h"
using namespace physx;
namespace physx
{
namespace Gu
{
bool intersectTetrahedronBox(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxBounds3& box)
{
if (box.contains(a) || box.contains(b) || box.contains(c) || box.contains(d))
return true;
PxBounds3 tetBox = PxBounds3::empty();
tetBox.include(a);
tetBox.include(b);
tetBox.include(c);
tetBox.include(d);
tetBox.fattenFast(1e-6f);
if (!box.intersects(tetBox))
return false;
Gu::BoxPadded boxP;
boxP.center = box.getCenter();
boxP.extents = box.getExtents();
boxP.rot = PxMat33(PxIdentity);
return intersectTriangleBox(boxP, a, b, c) || intersectTriangleBox(boxP, a, b, d) || intersectTriangleBox(boxP, a, c, d) || intersectTriangleBox(boxP, b, c, d);
}
}
}

View File

@@ -0,0 +1,193 @@
// 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-2025 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 "GuIntersectionTriangleBox.h"
#include "GuIntersectionTriangleBoxRef.h"
#include "GuBox.h"
#include "foundation/PxVecMath.h"
using namespace physx;
PxIntBool Gu::intersectTriangleBox_ReferenceCode(const PxVec3& boxcenter, const PxVec3& extents, const PxVec3& tp0, const PxVec3& tp1, const PxVec3& tp2)
{
return intersectTriangleBox_RefImpl(boxcenter, extents, tp0, tp1, tp2);
}
using namespace aos;
static PX_FORCE_INLINE int testClassIIIAxes(const Vec4V& e0V, const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
const Vec4V e0XZY_V = V4PermYZXW(e0V);
const Vec4V v0XZY_V = V4PermYZXW(v0V);
const Vec4V p0V = V4NegMulSub(v0XZY_V, e0V, V4Mul(v0V, e0XZY_V));
const Vec4V v1XZY_V = V4PermYZXW(v1V);
const Vec4V p1V = V4NegMulSub(v1XZY_V, e0V, V4Mul(v1V, e0XZY_V));
const Vec4V v2XZY_V = V4PermYZXW(v2V);
const Vec4V p2V = V4NegMulSub(v2XZY_V, e0V, V4Mul(v2V, e0XZY_V));
Vec4V minV = V4Min(p0V, p1V);
minV = V4Min(minV, p2V);
const Vec4V extentsV = V4LoadU(&extents.x);
const Vec4V fe0ZYX_V = V4Abs(e0V);
const Vec4V fe0XZY_V = V4PermYZXW(fe0ZYX_V);
const Vec4V extentsXZY_V = V4PermYZXW(extentsV);
Vec4V radV = V4MulAdd(extentsV, fe0XZY_V, V4Mul(extentsXZY_V, fe0ZYX_V));
if(V4AnyGrtr3(minV, radV))
return 0;
Vec4V maxV = V4Max(p0V, p1V);
maxV = V4Max(maxV, p2V);
radV = V4Sub(V4Zero(), radV);
if(V4AnyGrtr3(radV, maxV))
return 0;
return 1;
}
static const VecU32V signV = U4LoadXYZW(0x80000000, 0x80000000, 0x80000000, 0x80000000);
static PX_FORCE_INLINE PxIntBool intersectTriangleBoxInternal(const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
// Test box axes
{
Vec4V extentsV = V4LoadU(&extents.x);
{
const Vec4V cV = V4Abs(v0V);
if(V4AllGrtrOrEq3(extentsV, cV))
return 1;
}
Vec4V minV = V4Min(v0V, v1V);
minV = V4Min(minV, v2V);
if(V4AnyGrtr3(minV, extentsV))
return 0;
Vec4V maxV = V4Max(v0V, v1V);
maxV = V4Max(maxV, v2V);
extentsV = V4Sub(V4Zero(), extentsV);
if(V4AnyGrtr3(extentsV, maxV))
return 0;
}
// Test if the box intersects the plane of the triangle
const Vec4V e0V = V4Sub(v1V, v0V);
const Vec4V e1V = V4Sub(v2V, v1V);
{
const Vec4V normalV = V4Cross(e0V, e1V);
const Vec4V dV = Vec4V_From_FloatV(V4Dot3(normalV, v0V));
const Vec4V extentsV = V4LoadU(&extents.x);
VecU32V normalSignsV = V4U32and(VecU32V_ReinterpretFrom_Vec4V(normalV), signV);
const Vec4V maxV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
Vec4V tmpV = Vec4V_From_FloatV(V4Dot3(normalV, maxV));
if(V4AnyGrtr3(dV, tmpV))
return 0;
normalSignsV = V4U32xor(normalSignsV, signV);
const Vec4V minV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
tmpV = Vec4V_From_FloatV(V4Dot3(normalV, minV));
if(V4AnyGrtr3(tmpV, dV))
return 0;
}
// Edge-edge tests
{
if(!testClassIIIAxes(e0V, v0V, v1V, v2V, extents))
return 0;
if(!testClassIIIAxes(e1V, v0V, v1V, v2V, extents))
return 0;
const Vec4V e2V = V4Sub(v0V, v2V);
if(!testClassIIIAxes(e2V, v0V, v1V, v2V, extents))
return 0;
}
return 1;
}
// PT: a SIMD version of Tomas Moller's triangle-box SAT code
PxIntBool Gu::intersectTriangleBox_Unsafe(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
{
// Move everything so that the boxcenter is in (0,0,0)
const Vec4V BoxCenterV = V4LoadU(&center.x);
const Vec4V v0V = V4Sub(V4LoadU(&p0.x), BoxCenterV);
const Vec4V v1V = V4Sub(V4LoadU(&p1.x), BoxCenterV);
const Vec4V v2V = V4Sub(V4LoadU(&p2.x), BoxCenterV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}
PxIntBool Gu::intersectTriangleBox(const BoxPadded& box, const PxVec3& p0_, const PxVec3& p1_, const PxVec3& p2_)
{
// PT: TODO: SIMDify this part
// PxVec3p ensures we can safely V4LoadU the data
const PxVec3p p0 = box.rotateInv(p0_ - box.center);
const PxVec3p p1 = box.rotateInv(p1_ - box.center);
const PxVec3p p2 = box.rotateInv(p2_ - box.center);
const Vec4V v0V = V4LoadU(&p0.x);
const Vec4V v1V = V4LoadU(&p1.x);
const Vec4V v2V = V4LoadU(&p2.x);
return intersectTriangleBoxInternal(v0V, v1V, v2V, box.extents);
}
static PX_FORCE_INLINE Vec4V multiply3x3V(const Vec4V p, const PxMat33& mat)
{
const FloatV xxxV = V4GetX(p);
const FloatV yyyV = V4GetY(p);
const FloatV zzzV = V4GetZ(p);
Vec4V ResV = V4Scale(V4LoadU(&mat.column0.x), xxxV);
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column1.x), yyyV));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column2.x), zzzV));
return ResV;
}
// PT: warning: all params must be safe to V4LoadU
PxIntBool intersectTriangleBoxBV4( const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents)
{
const Vec4V transModelToBoxV = V4LoadU(&transModelToBox.x);
const Vec4V v0V = V4Add(multiply3x3V(V4LoadU(&p0.x), rotModelToBox), transModelToBoxV);
const Vec4V v1V = V4Add(multiply3x3V(V4LoadU(&p1.x), rotModelToBox), transModelToBoxV);
const Vec4V v2V = V4Add(multiply3x3V(V4LoadU(&p2.x), rotModelToBox), transModelToBoxV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}

View File

@@ -0,0 +1,241 @@
// 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-2025 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 "GuIntersectionTriangleTriangle.h"
#include "foundation/PxPlane.h"
using namespace physx;
using namespace Gu;
namespace
{
//Based on the paper A Fast Triangle-Triangle Intersection Test by T. Moeller
//http://web.stanford.edu/class/cs277/resources/papers/Moller1997b.pdf
struct Interval
{
PxReal min;
PxReal max;
PxVec3 minPoint;
PxVec3 maxPoint;
PX_FORCE_INLINE Interval() : min(FLT_MAX), max(-FLT_MAX), minPoint(PxVec3(NAN)), maxPoint(PxVec3(NAN)) { }
PX_FORCE_INLINE static bool overlapOrTouch(const Interval& a, const Interval& b)
{
return !(a.min > b.max || b.min > a.max);
}
PX_FORCE_INLINE static Interval intersection(const Interval& a, const Interval& b)
{
Interval result;
if (!overlapOrTouch(a, b))
return result;
if (a.min > b.min)
{
result.min = a.min;
result.minPoint = a.minPoint;
}
else
{
result.min = b.min;
result.minPoint = b.minPoint;
}
if (a.max < b.max)
{
result.max = a.max;
result.maxPoint = a.maxPoint;
}
else
{
result.max = b.max;
result.maxPoint = b.maxPoint;
}
return result;
}
PX_FORCE_INLINE void include(PxReal d, const PxVec3& p)
{
if (d < min) { min = d; minPoint = p; }
if (d > max) { max = d; maxPoint = p; }
}
};
PX_FORCE_INLINE static Interval computeInterval(PxReal distanceA, PxReal distanceB, PxReal distanceC, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& dir)
{
Interval i;
const bool bA = distanceA > 0;
const bool bB = distanceB > 0;
const bool bC = distanceC > 0;
distanceA = PxAbs(distanceA);
distanceB = PxAbs(distanceB);
distanceC = PxAbs(distanceC);
if (bA != bB)
{
const PxVec3 p = (distanceA / (distanceA + distanceB)) * b + (distanceB / (distanceA + distanceB)) * a;
i.include(dir.dot(p), p);
}
if (bA != bC)
{
const PxVec3 p = (distanceA / (distanceA + distanceC)) * c + (distanceC / (distanceA + distanceC)) * a;
i.include(dir.dot(p), p);
}
if (bB != bC)
{
const PxVec3 p = (distanceB / (distanceB + distanceC)) * c + (distanceC / (distanceB + distanceC)) * b;
i.include(dir.dot(p), p);
}
return i;
}
PX_FORCE_INLINE PxReal orient2d(const PxVec3& a, const PxVec3& b, const PxVec3& c, PxU32 x, PxU32 y)
{
return (a[y] - c[y]) * (b[x] - c[x]) - (a[x] - c[x]) * (b[y] - c[y]);
}
PX_FORCE_INLINE PxReal pointInTriangle(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& point, PxU32 x, PxU32 y)
{
const PxReal ab = orient2d(a, b, point, x, y);
const PxReal bc = orient2d(b, c, point, x, y);
const PxReal ca = orient2d(c, a, point, x, y);
if ((ab >= 0) == (bc >= 0) && (ab >= 0) == (ca >= 0))
return true;
return false;
}
PX_FORCE_INLINE PxReal linesIntersect(const PxVec3& startA, const PxVec3& endA, const PxVec3& startB, const PxVec3& endB, PxU32 x, PxU32 y)
{
const PxReal aaS = orient2d(startA, endA, startB, x, y);
const PxReal aaE = orient2d(startA, endA, endB, x, y);
if ((aaS >= 0) == (aaE >= 0))
return false;
const PxReal bbS = orient2d(startB, endB, startA, x, y);
const PxReal bbE = orient2d(startB, endB, endA, x, y);
if ((bbS >= 0) == (bbE >= 0))
return false;
return true;
}
PX_FORCE_INLINE void getProjectionIndices(PxVec3 normal, PxU32& x, PxU32& y)
{
normal.x = PxAbs(normal.x);
normal.y = PxAbs(normal.y);
normal.z = PxAbs(normal.z);
if (normal.x >= normal.y && normal.x >= normal.z)
{
//x is the dominant normal direction
x = 1;
y = 2;
}
else if (normal.y >= normal.x && normal.y >= normal.z)
{
//y is the dominant normal direction
x = 2;
y = 0;
}
else
{
//z is the dominant normal direction
x = 0;
y = 1;
}
}
PX_FORCE_INLINE bool trianglesIntersectCoplanar(const PxPlane& p1, const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2)
{
PxU32 x = 0;
PxU32 y = 0;
getProjectionIndices(p1.n, x, y);
const PxReal third = (1.0f / 3.0f);
//A bit of the computations done inside the following functions could be shared but it's kept simple since the
//difference is not very big and the coplanar case is not expected to be the most common case
if (linesIntersect(a1, b1, a2, b2, x, y) || linesIntersect(a1, b1, b2, c2, x, y) || linesIntersect(a1, b1, c2, a2, x, y) ||
linesIntersect(b1, c1, a2, b2, x, y) || linesIntersect(b1, c1, b2, c2, x, y) || linesIntersect(b1, c1, c2, a2, x, y) ||
linesIntersect(c1, a1, a2, b2, x, y) || linesIntersect(c1, a1, b2, c2, x, y) || linesIntersect(c1, a1, c2, a2, x, y) ||
pointInTriangle(a1, b1, c1, third * (a2 + b2 + c2), x, y) || pointInTriangle(a2, b2, c2, third * (a1 + b1 + c1), x, y))
return true;
return false;
}
}
bool Gu::intersectTriangleTriangle(const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2/*, Segment* intersection*/, bool ignoreCoplanar)
{
const PxReal tolerance = 1e-8f;
const PxPlane p1(a1, b1, c1);
const PxReal p1ToA = p1.distance(a2);
const PxReal p1ToB = p1.distance(b2);
const PxReal p1ToC = p1.distance(c2);
if(PxAbs(p1ToA) < tolerance && PxAbs(p1ToB) < tolerance &&PxAbs(p1ToC) < tolerance)
return ignoreCoplanar ? false : trianglesIntersectCoplanar(p1, a1, b1, c1, a2, b2, c2); //Coplanar triangles
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 PxPlane p2(a2, b2, c2);
const PxReal p2ToA = p2.distance(a1);
const PxReal p2ToB = p2.distance(b1);
const PxReal p2ToC = p2.distance(c1);
if ((p2ToA > 0) == (p2ToB > 0) && (p2ToA > 0) == (p2ToC > 0))
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
PxVec3 intersectionDirection = p1.n.cross(p2.n);
const PxReal l2 = intersectionDirection.magnitudeSquared();
intersectionDirection *= 1.0f / PxSqrt(l2);
const Interval i1 = computeInterval(p2ToA, p2ToB, p2ToC, a1, b1, c1, intersectionDirection);
const Interval i2 = computeInterval(p1ToA, p1ToB, p1ToC, a2, b2, c2, intersectionDirection);
if (Interval::overlapOrTouch(i1, i2))
{
/*if (intersection)
{
const Interval i = Interval::intersection(i1, i2);
intersection->p0 = i.minPoint;
intersection->p1 = i.maxPoint;
}*/
return true;
}
return false;
}