file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenUtil.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 "GuPCMContactGenUtil.h"
using namespace physx;
using namespace Gu;
using namespace aos;
bool Gu::contains(Vec3V* verts, PxU32 numVerts, const Vec3VArg p, const Vec3VArg min, const Vec3VArg max)
{
const BoolV tempCon = BOr(V3IsGrtr(min, p), V3IsGrtr(p, max));
const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon));
if (BAllEqTTTT(con))
return false;
const FloatV tx = V3GetX(p);
const FloatV ty = V3GetY(p);
const FloatV eps = FEps();
const FloatV zero = FZero();
PxU32 intersectionPoints = 0;
PxU32 i = 0, j = numVerts - 1;
for (; i < numVerts; j = i++)
{
const FloatV jy = V3GetY(verts[j]);
const FloatV iy = V3GetY(verts[i]);
const FloatV jx = V3GetX(verts[j]);
const FloatV ix = V3GetX(verts[i]);
//if p is one of the end point, we will return intersect
const BoolV con0 = BAnd(FIsEq(tx, jx), FIsEq(ty, jy));
const BoolV con1 = BAnd(FIsEq(tx, ix), FIsEq(ty, iy));
if (BAllEqTTTT(BOr(con0, con1)))
return true;
//(verts[i].y > test.y) != (points[j].y > test.y)
const PxU32 yflag0 = FAllGrtr(jy, ty);
const PxU32 yflag1 = FAllGrtr(iy, ty);
//ML: the only case the ray will intersect this segment is when the p's y is in between two segments y
if (yflag0 != yflag1)
{
//ML: choose ray, which start at p and every points in the ray will have the same y component
//t1 = (yp - yj)/(yi - yj)
//qx = xj + t1*(xi-xj)
//t = qx - xp > 0 for the ray and segment intersection happen
const FloatV jix = FSub(ix, jx);
const FloatV jiy = FSub(iy, jy);
//const FloatV jtx = FSub(tx, jy);
const FloatV jty = FSub(ty, jy);
const FloatV part1 = FMul(jty, jix);
//const FloatV part2 = FMul(jx, jiy);
//const FloatV part3 = FMul(V3Sub(tx, eps), jiy);
const FloatV part2 = FMul(FAdd(jx, eps), jiy);
const FloatV part3 = FMul(tx, jiy);
const BoolV comp = FIsGrtr(jiy, zero);
const FloatV tmp = FAdd(part1, part2);
const FloatV comp1 = FSel(comp, tmp, part3);
const FloatV comp2 = FSel(comp, part3, tmp);
if (FAllGrtrOrEq(comp1, comp2))
{
if (intersectionPoints == 1)
return false;
intersectionPoints++;
}
}
}
return intersectionPoints> 0;
}
PxI32 Gu::getPolygonIndex(const PolygonalData& polyData, const SupportLocal* map, const Vec3VArg normal, PxI32& polyIndex2)
{
//normal is in shape space, need to transform the vertex space
const Vec3V n = M33TrnspsMulV3(map->vertex2Shape, normal);
const Vec3V nnormal = V3Neg(n);
const Vec3V planeN_ = V3LoadU_SafeReadW(polyData.mPolygons[0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
FloatV minProj = V3Dot(n, planeN_);
const FloatV zero = FZero();
PxI32 closestFaceIndex = 0;
polyIndex2 = -1;
for (PxU32 i = 1; i < polyData.mNbPolygons; ++i)
{
const Vec3V planeN = V3LoadU_SafeReadW(polyData.mPolygons[i].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const FloatV proj = V3Dot(n, planeN);
if (FAllGrtr(minProj, proj))
{
minProj = proj;
closestFaceIndex = PxI32(i);
}
}
const PxU32 numEdges = polyData.mNbEdges;
const PxU8* const edgeToFace = polyData.mFacesByEdges;
//Loop through edges
PxU32 closestEdge = 0xffffffff;
FloatV maxDpSq = FMul(minProj, minProj);
FloatV maxDpSq2 = FLoad(-10.0f);
for (PxU32 i = 0; i < numEdges; ++i)//, inc = VecI32V_Add(inc, vOne))
{
const PxU32 index = i * 2;
const PxU8 f0 = edgeToFace[index];
const PxU8 f1 = edgeToFace[index + 1];
const Vec3V planeNormal0 = V3LoadU_SafeReadW(polyData.mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const Vec3V planeNormal1 = V3LoadU_SafeReadW(polyData.mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
// unnormalized edge normal
const Vec3V edgeNormal = V3Add(planeNormal0, planeNormal1);//polys[f0].mPlane.n + polys[f1].mPlane.n;
const FloatV enMagSq = V3Dot(edgeNormal, edgeNormal);//edgeNormal.magnitudeSquared();
//Test normal of current edge - squared test is valid if dp and maxDp both >= 0
const FloatV dp = V3Dot(edgeNormal, nnormal);//edgeNormal.dot(normal);
const FloatV sqDp = FMul(dp, dp);
if(f0==closestFaceIndex || f1==closestFaceIndex)
{
if(BAllEqTTTT(FIsGrtrOrEq(sqDp, maxDpSq2)))
{
maxDpSq2 = sqDp;
polyIndex2 = f0==closestFaceIndex ? PxI32(f1) : PxI32(f0);
}
}
const BoolV con0 = FIsGrtrOrEq(dp, zero);
const BoolV con1 = FIsGrtr(sqDp, FMul(maxDpSq, enMagSq));
const BoolV con = BAnd(con0, con1);
if (BAllEqTTTT(con))
{
maxDpSq = FDiv(sqDp, enMagSq);
closestEdge = i;
}
}
if (closestEdge != 0xffffffff)
{
const PxU8* FBE = edgeToFace;
const PxU32 index = closestEdge * 2;
const PxU32 f0 = FBE[index];
const PxU32 f1 = FBE[index + 1];
const Vec3V planeNormal0 = V3LoadU_SafeReadW(polyData.mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const Vec3V planeNormal1 = V3LoadU_SafeReadW(polyData.mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const FloatV dp0 = V3Dot(planeNormal0, nnormal);
const FloatV dp1 = V3Dot(planeNormal1, nnormal);
if (FAllGrtr(dp0, dp1))
{
closestFaceIndex = PxI32(f0);
polyIndex2 = PxI32(f1);
}
else
{
closestFaceIndex = PxI32(f1);
polyIndex2 = PxI32(f0);
}
}
return closestFaceIndex;
}
PxU32 Gu::getWitnessPolygonIndex(const PolygonalData& polyData, const SupportLocal* map, const Vec3VArg normal, const Vec3VArg closest, PxReal tolerance)
{
PxReal pd[256];
//first pass : calculate the smallest distance from the closest point to the polygon face
//transform the closest p to vertex space
const Vec3V p = M33MulV3(map->shape2Vertex, closest);
PxU32 closestFaceIndex = 0;
PxVec3 closestP;
V3StoreU(p, closestP);
const PxReal eps = -tolerance;
PxPlane plane = polyData.mPolygons[0].mPlane;
PxReal dist = plane.distance(closestP);
PxReal minDist = dist >= eps ? PxAbs(dist) : PX_MAX_F32;
pd[0] = minDist;
PxReal maxDist = dist;
PxU32 maxFaceIndex = 0;
for (PxU32 i = 1; i < polyData.mNbPolygons; ++i)
{
plane = polyData.mPolygons[i].mPlane;
dist = plane.distance(closestP);
pd[i] = dist >= eps ? PxAbs(dist) : PX_MAX_F32;
if (minDist > pd[i])
{
minDist = pd[i];
closestFaceIndex = i;
}
if (dist > maxDist)
{
maxDist = dist;
maxFaceIndex = i;
}
}
if (minDist == PX_MAX_F32)
return maxFaceIndex;
//second pass : select the face which has the normal most close to the gjk/epa normal
Vec4V plane4 = V4LoadU(&polyData.mPolygons[closestFaceIndex].mPlane.n.x);
Vec3V n = Vec3V_From_Vec4V(plane4);
n = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, n));
FloatV bestProj = V3Dot(n, normal);
const PxU32 firstPassIndex = closestFaceIndex;
for (PxU32 i = 0; i< polyData.mNbPolygons; ++i)
{
//if the difference between the minimum distance and the distance of p to plane i is within tolerance, we use the normal to chose the best plane
if ((tolerance >(pd[i] - minDist)) && (firstPassIndex != i))
{
plane4 = V4LoadU(&polyData.mPolygons[i].mPlane.n.x);
n = Vec3V_From_Vec4V(plane4);
//rotate the plane normal to shape space. We can roate normal into the vertex space. The reason for
//that is because it will lose some numerical precision if the object has large scale and this algorithm
//will choose different face
n = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, n));
FloatV proj = V3Dot(n, normal);
if (FAllGrtr(bestProj, proj))
{
closestFaceIndex = i;
bestProj = proj;
}
}
}
return closestFaceIndex;
}
/* PX_FORCE_INLINE bool boxContainsInXY(const FloatVArg x, const FloatVArg y, const Vec3VArg p, const Vec3V* verts, const Vec3VArg min, const Vec3VArg max)
{
using namespace aos;
const BoolV tempCon = BOr(V3IsGrtr(min, p), V3IsGrtr(p, max));
const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon));
if(BAllEqTTTT(con))
return false;
const FloatV zero = FZero();
FloatV PreviousX = V3GetX(verts[3]);
FloatV PreviousY = V3GetY(verts[3]);
// Loop through quad vertices
for(PxI32 i=0; i<4; i++)
{
const FloatV CurrentX = V3GetX(verts[i]);
const FloatV CurrentY = V3GetY(verts[i]);
// |CurrentX - PreviousX x - PreviousX|
// |CurrentY - PreviousY y - PreviousY|
// => similar to backface culling, check each one of the 4 triangles are consistent, in which case
// the point is within the parallelogram.
const FloatV v00 = FSub(CurrentX, PreviousX);
const FloatV v01 = FSub(y, PreviousY);
const FloatV v10 = FSub(CurrentY, PreviousY);
const FloatV v11 = FSub(x, PreviousX);
const FloatV temp0 = FMul(v00, v01);
const FloatV temp1 = FMul(v10, v11);
if(FAllGrtrOrEq(FSub(temp0, temp1), zero))
return false;
PreviousX = CurrentX;
PreviousY = CurrentY;
}
return true;
}
*/
| 10,488 | C++ | 32.298413 | 155 | 0.69508 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereHeightField.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/PxTriangleMesh.h"
#include "geomutils/PxContactBuffer.h"
#include "GuVecBox.h"
#include "GuVecConvexHull.h"
#include "GuVecConvexHullNoScale.h"
#include "GuVecTriangle.h"
#include "GuContactMethodImpl.h"
#include "GuHeightField.h"
#include "GuPCMContactConvexCommon.h"
#include "GuPCMContactMeshCallback.h"
using namespace physx;
using namespace Gu;
using namespace aos;
namespace
{
struct PCMSphereVsHeightfieldContactGenerationCallback : PCMHeightfieldContactGenerationCallback<PCMSphereVsHeightfieldContactGenerationCallback>
{
PCMSphereVsMeshContactGeneration mGeneration;
PCMSphereVsHeightfieldContactGenerationCallback(
const Vec3VArg sphereCenter,
const FloatVArg sphereRadius,
const FloatVArg contactDistance,
const FloatVArg replaceBreakingThreshold,
const PxTransformV& sphereTransform,
const PxTransformV& heightfieldTransform,
const PxTransform& heightfieldTransform1,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
HeightFieldUtil& hfUtil
) :
PCMHeightfieldContactGenerationCallback<PCMSphereVsHeightfieldContactGenerationCallback>(hfUtil, heightfieldTransform1),
mGeneration(sphereCenter, sphereRadius, contactDistance, replaceBreakingThreshold, sphereTransform,
heightfieldTransform, multiManifold, contactBuffer, deferredContacts)
{
}
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMSphereVsMeshContactGeneration>(cache);
}
};
}
bool Gu::pcmContactSphereHeightField(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
const PxHeightFieldGeometry& shapeHeight = checkedCast<PxHeightFieldGeometry>(shape1);
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const QuatV q0 = QuatVLoadA(&transform0.q.x);
const Vec3V p0 = V3LoadA(&transform0.p.x);
const QuatV q1 = QuatVLoadA(&transform1.q.x);
const Vec3V p1 = V3LoadA(&transform1.p.x);
const FloatV sphereRadius = FLoad(shapeSphere.radius);
const FloatV contactDist = FLoad(params.mContactDistance);
const PxTransformV sphereTransform(p0, q0);//sphere transform
const PxTransformV heightfieldTransform(p1, q1);//height feild
const PxTransformV curTransform = heightfieldTransform.transformInv(sphereTransform);
// We must be in local space to use the cache
if(multiManifold.invalidate(curTransform, sphereRadius, FLoad(0.02f)))
{
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
const FloatV replaceBreakingThreshold = FMul(sphereRadius, FLoad(0.001f));
HeightFieldUtil hfUtil(shapeHeight);
PxBounds3 localBounds;
const PxVec3 localSphereCenter = getLocalSphereData(localBounds, transform0, transform1, shapeSphere.radius + params.mContactDistance);
const Vec3V sphereCenter = V3LoadU(localSphereCenter);
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts;
PCMSphereVsHeightfieldContactGenerationCallback blockCallback(
sphereCenter,
sphereRadius,
contactDist,
replaceBreakingThreshold,
sphereTransform,
heightfieldTransform,
transform1,
multiManifold,
contactBuffer,
&delayedContacts,
hfUtil);
hfUtil.overlapAABBTriangles(localBounds, blockCallback);
blockCallback.mGeneration.generateLastContacts();
blockCallback.mGeneration.processContacts(GU_SPHERE_MANIFOLD_CACHE_SIZE, false);
}
else
{
const PxMatTransformV aToB(curTransform);
const FloatV projectBreakingThreshold = FMul(sphereRadius, FLoad(0.05f));
const FloatV refereshDistance = FAdd(sphereRadius, contactDist);
multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance);
}
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, sphereTransform, heightfieldTransform, sphereRadius);
}
| 5,651 | C++ | 38.25 | 145 | 0.801805 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexCommon.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_PCM_CONTACT_CONVEX_COMMON_H
#define GU_PCM_CONTACT_CONVEX_COMMON_H
#define PCM_MAX_CONTACTPATCH_SIZE 32
#include "geomutils/PxContactBuffer.h"
#include "GuVecCapsule.h"
#include "GuPCMTriangleContactGen.h"
#include "GuTriangleCache.h"
#include "foundation/PxInlineArray.h"
namespace physx
{
namespace Gu
{
#define MAX_CACHE_SIZE 128
//sizeof(PCMDeferredPolyData)/sizeof(PxU32) = 15, 960/15 = 64 triangles in the local array
#define LOCAL_PCM_CONTACTS_SIZE 960
class PCMMeshContactGeneration
{
PX_NOCOPY(PCMMeshContactGeneration)
public:
PCMContactPatch mContactPatch[PCM_MAX_CONTACTPATCH_SIZE];
PCMContactPatch* mContactPatchPtr[PCM_MAX_CONTACTPATCH_SIZE];
const aos::FloatV mContactDist;
const aos::FloatV mReplaceBreakingThreshold;
const aos::PxTransformV& mConvexTransform;
const aos::PxTransformV& mMeshTransform;
Gu::MultiplePersistentContactManifold& mMultiManifold;
PxContactBuffer& mContactBuffer;
aos::FloatV mAcceptanceEpsilon;
aos::FloatV mSqReplaceBreakingThreshold;
aos::PxMatTransformV mMeshToConvex;
Gu::MeshPersistentContact* mManifoldContacts;
PxU32 mNumContacts;
PxU32 mNumContactPatch;
PxU32 mNumCalls;
Gu::CacheMap<Gu::CachedEdge, MAX_CACHE_SIZE> mEdgeCache;
Gu::CacheMap<Gu::CachedVertex, MAX_CACHE_SIZE> mVertexCache;
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* mDeferredContacts;
PxRenderOutput* mRenderOutput;
PCMMeshContactGeneration(
const aos::FloatVArg contactDist,
const aos::FloatVArg replaceBreakingThreshold,
const aos::PxTransformV& convexTransform,
const aos::PxTransformV& meshTransform,
Gu::MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
PxRenderOutput* renderOutput
) :
mContactDist(contactDist),
mReplaceBreakingThreshold(replaceBreakingThreshold),
mConvexTransform(convexTransform),
mMeshTransform(meshTransform),
mMultiManifold(multiManifold),
mContactBuffer(contactBuffer),
mDeferredContacts(deferredContacts),
mRenderOutput(renderOutput)
{
using namespace aos;
mNumContactPatch = 0;
mNumContacts = 0;
mNumCalls = 0;
mMeshToConvex = mConvexTransform.transformInv(mMeshTransform);
//Assign the PCMContactPatch to the PCMContactPathPtr
for(PxU32 i=0; i<PCM_MAX_CONTACTPATCH_SIZE; ++i)
{
mContactPatchPtr[i] = &mContactPatch[i];
}
mManifoldContacts = PX_CP_TO_MPCP(contactBuffer.contacts);
mSqReplaceBreakingThreshold = FMul(replaceBreakingThreshold, replaceBreakingThreshold);
mAcceptanceEpsilon = FLoad(0.996f);//5 degree
//mAcceptanceEpsilon = FloatV_From_F32(0.9999);//5 degree
}
template <PxU32 TriangleCount, typename Derived>
bool processTriangleCache(Gu::TriangleCache<TriangleCount>& cache)
{
PxU32 count = cache.mNumTriangles;
PxVec3* verts = cache.mVertices;
PxU32* vertInds = cache.mIndices;
PxU32* triInds = cache.mTriangleIndex;
PxU8* edgeFlags = cache.mEdgeFlags;
while(count--)
{
(static_cast<Derived*>(this))->processTriangle(verts, *triInds, *edgeFlags, vertInds);
verts += 3;
vertInds += 3;
triInds++;
edgeFlags++;
}
return true;
}
void prioritizeContactPatches();
void addManifoldPointToPatch(const aos::Vec3VArg currentPatchNormal, const aos::FloatVArg maxPen, PxU32 previousNumContacts);
void processContacts(PxU8 maxContactPerManifold, const bool isNotLastPatch = true);
};
// This function is based on the current patch normal to either create a new patch or merge the manifold contacts in this patch with the manifold contacts in the last existing
// patch. This means there might be more than GU_SINGLE_MANIFOLD_CACHE_SIZE in a SinglePersistentContactManifold.
PX_FORCE_INLINE void PCMMeshContactGeneration::addManifoldPointToPatch(const aos::Vec3VArg currentPatchNormal, const aos::FloatVArg maxPen, PxU32 previousNumContacts)
{
using namespace aos;
bool foundPatch = false;
//we have existing patch
if(mNumContactPatch > 0)
{
//if the direction between the last existing patch normal and the current patch normal are within acceptance epsilon, which means we will be
//able to merge the last patch's contacts with the current patch's contacts. This is just to avoid to create an extra patch. We have some logic
//later to refine the patch again
if(FAllGrtr(V3Dot(mContactPatch[mNumContactPatch-1].mPatchNormal, currentPatchNormal), mAcceptanceEpsilon))
{
//get the last patch
PCMContactPatch& patch = mContactPatch[mNumContactPatch-1];
//remove duplicate contacts
for(PxU32 i = patch.mStartIndex; i<patch.mEndIndex; ++i)
{
for(PxU32 j = previousNumContacts; j<mNumContacts; ++j)
{
Vec3V dif = V3Sub(mManifoldContacts[j].mLocalPointB, mManifoldContacts[i].mLocalPointB);
FloatV d = V3Dot(dif, dif);
if(FAllGrtr(mSqReplaceBreakingThreshold, d))
{
if(FAllGrtr(V4GetW(mManifoldContacts[i].mLocalNormalPen), V4GetW(mManifoldContacts[j].mLocalNormalPen)))
{
//The new contact is deeper than the old contact so we keep the deeper contact
mManifoldContacts[i] = mManifoldContacts[j];
}
mManifoldContacts[j] = mManifoldContacts[mNumContacts-1];
mNumContacts--;
j--;
}
}
}
patch.mEndIndex = mNumContacts;
patch.mPatchMaxPen = FMin(patch.mPatchMaxPen, maxPen);
foundPatch = true;
}
}
//If there are no existing patch which match the currentPatchNormal, we will create a new patch
if(!foundPatch)
{
mContactPatch[mNumContactPatch].mStartIndex = previousNumContacts;
mContactPatch[mNumContactPatch].mEndIndex = mNumContacts;
mContactPatch[mNumContactPatch].mPatchMaxPen = maxPen;
mContactPatch[mNumContactPatch++].mPatchNormal = currentPatchNormal;
}
}
// This function sort the contact patch based on the max penetration so that deepest penetration contact patch will be in front of the less penetration contact
// patch
PX_FORCE_INLINE void PCMMeshContactGeneration::prioritizeContactPatches()
{
//we are using insertion sort to prioritize contact patchs
using namespace aos;
//sort the contact patch based on the max penetration
for(PxU32 i=1; i<mNumContactPatch; ++i)
{
const PxU32 indexi = i-1;
if(FAllGrtr(mContactPatchPtr[indexi]->mPatchMaxPen, mContactPatchPtr[i]->mPatchMaxPen))
{
//swap
PCMContactPatch* tmp = mContactPatchPtr[indexi];
mContactPatchPtr[indexi] = mContactPatchPtr[i];
mContactPatchPtr[i] = tmp;
for(PxI32 j=PxI32(i-2); j>=0; j--)
{
const PxU32 indexj = PxU32(j+1);
if(FAllGrtrOrEq(mContactPatchPtr[indexj]->mPatchMaxPen, mContactPatchPtr[j]->mPatchMaxPen))
break;
//swap
PCMContactPatch* temp = mContactPatchPtr[indexj];
mContactPatchPtr[indexj] = mContactPatchPtr[j];
mContactPatchPtr[j] = temp;
}
}
}
}
PX_FORCE_INLINE void PCMMeshContactGeneration::processContacts(PxU8 maxContactPerManifold, bool isNotLastPatch)
{
using namespace aos;
if(mNumContacts != 0)
{
//reorder the contact patches based on the max penetration
prioritizeContactPatches();
//connect the patches which's angle between patch normals are within 5 degree
mMultiManifold.refineContactPatchConnective(mContactPatchPtr, mNumContactPatch, mManifoldContacts, mAcceptanceEpsilon);
//get rid of duplicate manifold contacts in connected contact patches
mMultiManifold.reduceManifoldContactsInDifferentPatches(mContactPatchPtr, mNumContactPatch, mManifoldContacts, mNumContacts, mSqReplaceBreakingThreshold);
//add the manifold contact to the corresponding manifold
mMultiManifold.addManifoldContactPoints(mManifoldContacts, mNumContacts, mContactPatchPtr, mNumContactPatch, mSqReplaceBreakingThreshold, mAcceptanceEpsilon, maxContactPerManifold);
mNumContacts = 0;
mNumContactPatch = 0;
if(isNotLastPatch)
{
//remap the contact patch pointer to contact patch
for(PxU32 i=0; i<PCM_MAX_CONTACTPATCH_SIZE; ++i)
{
mContactPatchPtr[i] = &mContactPatch[i];
}
}
}
}
struct PCMDeferredPolyData
{
public:
PxVec3 mVerts[3]; //36
PxU32 mInds[3]; //48
PxU32 mTriangleIndex; //52
PxU32 mFeatureIndex; //56
PxU32 triFlags32; //60
};
#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 PCMConvexVsMeshContactGeneration : public PCMMeshContactGeneration
{
PCMConvexVsMeshContactGeneration &operator=(PCMConvexVsMeshContactGeneration &);
public:
aos::Vec3V mHullCenterMesh;
const Gu::PolygonalData& mPolyData;
const SupportLocal* mPolyMap;
const Cm::FastVertex2ShapeScaling& mConvexScaling;
bool mIdtConvexScale;
bool mSilhouetteEdgesAreActive;
PCMConvexVsMeshContactGeneration(
const aos::FloatVArg contactDistance,
const aos::FloatVArg replaceBreakingThreshold,
const aos::PxTransformV& convexTransform,
const aos::PxTransformV& meshTransform,
Gu::MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
const Gu::PolygonalData& polyData,
const SupportLocal* polyMap,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts,
const Cm::FastVertex2ShapeScaling& convexScaling,
bool idtConvexScale,
bool silhouetteEdgesAreActive,
PxRenderOutput* renderOutput
) : PCMMeshContactGeneration(contactDistance, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer,
delayedContacts, renderOutput),
mPolyData(polyData),
mPolyMap(polyMap),
mConvexScaling(convexScaling),
mIdtConvexScale(idtConvexScale),
mSilhouetteEdgesAreActive(silhouetteEdgesAreActive)
{
using namespace aos;
// Hull center in local space
const Vec3V hullCenterLocal = V3LoadU(mPolyData.mCenter);
// Hull center in mesh space
mHullCenterMesh = mMeshToConvex.transformInv(hullCenterLocal);
}
bool generateTriangleFullContactManifold(const Gu::TriangleV& localTriangle, PxU32 triangleIndex, const PxU32* triIndices, PxU8 triFlags, const Gu::PolygonalData& polyData, const Gu::SupportLocalImpl<Gu::TriangleV>* localTriMap, const Gu::SupportLocal* polyMap, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts,
const aos::FloatVArg contactDist, aos::Vec3V& patchNormal);
bool generatePolyDataContactManifold(const Gu::TriangleV& localTriangle, PxU32 featureIndex, PxU32 triangleIndex, PxU8 triFlags, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& patchNormal);
void generateLastContacts();
void addContactsToPatch(const aos::Vec3VArg patchNormal, PxU32 previousNumContacts);
bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds);
static bool generateTriangleFullContactManifold(const Gu::TriangleV& localTriangle, PxU32 triangleIndex, PxU8 triFlags, const Gu::PolygonalData& polyData, const Gu::SupportLocalImpl<Gu::TriangleV>* localTriMap, const Gu::SupportLocal* polyMap, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts,
const aos::FloatVArg contactDist, aos::Vec3V& patchNormal, PxRenderOutput* renderOutput = NULL);
static bool processTriangle(const Gu::PolygonalData& polyData, const SupportLocal* polyMap, const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const aos::FloatVArg inflation, bool isDoubleSided,
const aos::PxTransformV& convexTransform, const aos::PxMatTransformV& meshToConvex, Gu::MeshPersistentContact* manifoldContact, PxU32& numContacts);
};
#if PX_VC
#pragma warning(pop)
#endif
struct SortedTriangle
{
aos::FloatV mSquareDist;
PxU32 mIndex;
PX_FORCE_INLINE bool operator < (const SortedTriangle& data) const
{
return aos::FAllGrtrOrEq(mSquareDist, data.mSquareDist) ==0;
}
};
class PCMSphereVsMeshContactGeneration : public PCMMeshContactGeneration
{
public:
aos::Vec3V mSphereCenter;
aos::FloatV mSphereRadius;
aos::FloatV mSqInflatedSphereRadius;
PxInlineArray<SortedTriangle, 64> mSortedTriangle;
PCMSphereVsMeshContactGeneration(
const aos::Vec3VArg sphereCenter,
const aos::FloatVArg sphereRadius,
const aos::FloatVArg contactDist,
const aos::FloatVArg replaceBreakingThreshold,
const aos::PxTransformV& sphereTransform,
const aos::PxTransformV& meshTransform,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
PxRenderOutput* renderOutput = NULL
) : PCMMeshContactGeneration(contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold,
contactBuffer, deferredContacts, renderOutput),
mSphereCenter(sphereCenter),
mSphereRadius(sphereRadius)
{
using namespace aos;
const FloatV inflatedSphereRadius = FAdd(sphereRadius, contactDist);
mSqInflatedSphereRadius = FMul(inflatedSphereRadius, inflatedSphereRadius);
}
bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds);
void generateLastContacts();
void addToPatch(const aos::Vec3VArg contactP, const aos::Vec3VArg patchNormal, const aos::FloatV pen, PxU32 triangleIndex);
};
class PCMCapsuleVsMeshContactGeneration : public PCMMeshContactGeneration
{
PCMCapsuleVsMeshContactGeneration &operator=(PCMCapsuleVsMeshContactGeneration &);
public:
aos::FloatV mInflatedRadius;
aos::FloatV mSqInflatedRadius;
const CapsuleV& mCapsule;
PCMCapsuleVsMeshContactGeneration(
const CapsuleV& capsule,
const aos::FloatVArg contactDist,
const aos::FloatVArg replaceBreakingThreshold,
const aos::PxTransformV& sphereTransform,
const aos::PxTransformV& meshTransform,
Gu::MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
PxRenderOutput* renderOutput = NULL
) : PCMMeshContactGeneration(contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer,
deferredContacts, renderOutput),
mCapsule(capsule)
{
using namespace aos;
mInflatedRadius = FAdd(capsule.radius, contactDist);
mSqInflatedRadius = FMul(mInflatedRadius, mInflatedRadius);
}
void generateEEContacts(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg normal, PxU32 triangleIndex,
const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg sqInflatedRadius, PxU32 previousNumContacts, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
void generateEE(const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg sqInflatedRadius, const aos::Vec3VArg normal, PxU32 triangleIndex,
const aos::Vec3VArg a, const aos::Vec3VArg b, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
static void generateContacts(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg planeNormal, const aos::Vec3VArg normal,
PxU32 triangleIndex, const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
static void generateEEContactsMTD(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg normal, PxU32 triangleIndex,
const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
static void generateEEMTD(const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, const aos::Vec3VArg normal, PxU32 triangleIndex,
const aos::Vec3VArg a, const aos::Vec3VArg b, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds);
static bool processTriangle(const TriangleV& triangle, PxU32 triangleIndex, const CapsuleV& capsule, const aos::FloatVArg inflatedRadius, const PxU8 triFlag, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts);
};
}
}
#endif
| 17,770 | C | 40.715962 | 327 | 0.776083 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenUtil.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_PCM_CONTACT_GEN_UTIL_H
#define GU_PCM_CONTACT_GEN_UTIL_H
#include "foundation/PxVecMath.h"
#include "geomutils/PxContactBuffer.h"
#include "GuShapeConvex.h"
#include "GuVecCapsule.h"
#include "GuConvexSupportTable.h"
//The smallest epsilon we will permit (scaled by PxTolerancesScale.length)
#define PCM_WITNESS_POINT_LOWER_EPS 1e-2f
//The largest epsilon we will permit (scaled by PxTolerancesScale.length)
#define PCM_WITNESS_POINT_UPPER_EPS 5e-2f
namespace physx
{
namespace Gu
{
enum FeatureStatus
{
POLYDATA0,
POLYDATA1,
EDGE
};
bool contains(aos::Vec3V* verts, PxU32 numVerts, const aos::Vec3VArg p, const aos::Vec3VArg min, const aos::Vec3VArg max);
PX_FORCE_INLINE aos::FloatV signed2DTriArea(const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c)
{
using namespace aos;
const Vec3V ca = V3Sub(a, c);
const Vec3V cb = V3Sub(b, c);
const FloatV t0 = FMul(V3GetX(ca), V3GetY(cb));
const FloatV t1 = FMul(V3GetY(ca), V3GetX(cb));
return FSub(t0, t1);
}
PxI32 getPolygonIndex(const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal, PxI32& polyIndex2);
PX_FORCE_INLINE PxI32 getPolygonIndex(const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal)
{
using namespace aos;
PxI32 index2;
return getPolygonIndex(polyData, map, normal, index2);
}
PxU32 getWitnessPolygonIndex( const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal,
const aos::Vec3VArg closest, PxReal tolerance);
PX_FORCE_INLINE void outputPCMContact(PxContactBuffer& contactBuffer, PxU32& contactCount, const aos::Vec3VArg point, const aos::Vec3VArg normal,
const aos::FloatVArg penetration, PxU32 internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX)
{
using namespace aos;
// PT: TODO: the PCM capsule-capsule code was using this alternative version, is it better?
// const Vec4V normalSep = V4SetW(Vec4V_From_Vec3V(normal), separation);
// V4StoreA(normalSep, &point.normal.x);
// Also aren't we overwriting maxImpulse with the position now? Ok to do so?
PX_ASSERT(contactCount < PxContactBuffer::MAX_CONTACTS);
PxContactPoint& contact = contactBuffer.contacts[contactCount++];
V4StoreA(Vec4V_From_Vec3V(normal), &contact.normal.x);
V4StoreA(Vec4V_From_Vec3V(point), &contact.point.x);
FStore(penetration, &contact.separation);
PX_ASSERT(contact.point.isFinite());
PX_ASSERT(contact.normal.isFinite());
PX_ASSERT(PxIsFinite(contact.separation));
contact.internalFaceIndex1 = internalFaceIndex1;
}
PX_FORCE_INLINE bool outputSimplePCMContact(PxContactBuffer& contactBuffer, const aos::Vec3VArg point, const aos::Vec3VArg normal,
const aos::FloatVArg penetration, PxU32 internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX)
{
outputPCMContact(contactBuffer, contactBuffer.count, point, normal, penetration, internalFaceIndex1);
return true;
}
}//Gu
}//physx
#endif
| 4,663 | C | 40.642857 | 146 | 0.75638 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGen.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_PCM_CONTACT_GEN_H
#define GU_PCM_CONTACT_GEN_H
#include "GuConvexSupportTable.h"
#include "GuPersistentContactManifold.h"
#include "GuShapeConvex.h"
#include "GuSeparatingAxes.h"
#include "GuGJKType.h"
#include "GuGJKUtil.h"
namespace physx
{
namespace Gu
{
//full contact gen code for box/convexhull vs convexhull
bool generateFullContactManifold(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, const Gu::SupportLocal* map0, const Gu::SupportLocal* map1, Gu::PersistentContact* manifoldContacts,
PxU32& numContacts, const aos::FloatVArg contactDist, const aos::Vec3VArg normal, const aos::Vec3VArg closestA, const aos::Vec3VArg closestB,
PxReal toleranceA, PxReal toleranceB, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength);
//full contact gen code for capsule vs convexhulll
bool generateFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, const aos::PxMatTransformV& aToB, Gu::PersistentContact* manifoldContacts,
PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& normal, const aos::Vec3VArg closest, PxReal tolerance, bool doOverlapTest, PxReal toleranceScale);
//full contact gen code for capsule vs box
bool generateCapsuleBoxFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, const aos::PxMatTransformV& aToB, Gu::PersistentContact* manifoldContacts, PxU32& numContacts,
const aos::FloatVArg contactDist, aos::Vec3V& normal, const aos::Vec3VArg closest, PxReal boxMargin, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput);
//based on the gjk status to decide whether we should do full contact gen with GJK/EPA normal. Also, this method store
//GJK/EPA point to the manifold in case full contact gen doesn't generate any contact
bool addGJKEPAContacts(const Gu::GjkConvex* relativeConvex, const Gu::GjkConvex* localConvex, const aos::PxMatTransformV& aToB, Gu::GjkStatus status,
Gu::PersistentContact* manifoldContacts, const aos::FloatV replaceBreakingThreshold, const aos::FloatV toleranceLength, GjkOutput& output,
Gu::PersistentContactManifold& manifold);
//MTD code for box/convexhull vs box/convexhull
bool computeMTD(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, aos::FloatV& penDepth, aos::Vec3V& normal);
//MTD code for capsule vs box/convexhull
bool computeMTD(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, aos::FloatV& penDepth, aos::Vec3V& normal);
//full contact gen code for sphere vs convexhull
bool generateSphereFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, Gu::PersistentContact* manifoldContacts, PxU32& numContacts,
const aos::FloatVArg contactDist, aos::Vec3V& normal, bool doOverlapTest);
}
}
#endif
| 4,685 | C | 61.479999 | 231 | 0.784205 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuBigConvexData.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_BIG_CONVEX_DATA_H
#define GU_BIG_CONVEX_DATA_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
class BigConvexDataBuilder;
class PxcHillClimb;
class BigConvexData;
// Data
namespace Gu
{
struct Valency
{
PxU16 mCount;
PxU16 mOffset;
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::Valency) == 4);
struct BigConvexRawData
{
// Support vertex map
PxU16 mSubdiv; // "Gaussmap" subdivision
PxU16 mNbSamples; // Total #samples in gaussmap PT: this is not even needed at runtime!
PxU8* mSamples;
PX_FORCE_INLINE const PxU8* getSamples2() const
{
return mSamples + mNbSamples;
}
//~Support vertex map
// Valencies data
PxU32 mNbVerts; //!< Number of vertices
PxU32 mNbAdjVerts; //!< Total number of adjacent vertices ### PT: this is useless at runtime and should not be stored here
Gu::Valency* mValencies; //!< A list of mNbVerts valencies (= number of neighbors)
PxU8* mAdjacentVerts; //!< List of adjacent vertices
//~Valencies data
};
#if PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(Gu::BigConvexRawData) == 40);
#else
PX_COMPILE_TIME_ASSERT(sizeof(Gu::BigConvexRawData) == 24);
#endif
} // namespace Gu
}
#endif
| 2,862 | C | 33.083333 | 126 | 0.74703 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexSupportTable.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_CONVEX_SUPPORT_TABLE_H
#define GU_CONVEX_SUPPORT_TABLE_H
#include "common/PxPhysXCommonConfig.h"
#include "GuVecConvex.h"
#include "foundation/PxVecTransform.h"
namespace physx
{
namespace Gu
{
class TriangleV;
class CapsuleV;
class BoxV;
class ConvexHullV;
class ConvexHullNoScaleV;
#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 SupportLocal
{
public:
aos::Vec3V shapeSpaceCenterOfMass;
const aos::PxTransformV& transform;
const aos::Mat33V& vertex2Shape;
const aos::Mat33V& shape2Vertex;
const bool isIdentityScale;
SupportLocal(const aos::PxTransformV& _transform, const aos::Mat33V& _vertex2Shape, const aos::Mat33V& _shape2Vertex, const bool _isIdentityScale = true): transform(_transform),
vertex2Shape(_vertex2Shape), shape2Vertex(_shape2Vertex), isIdentityScale(_isIdentityScale)
{
}
PX_FORCE_INLINE void setShapeSpaceCenterofMass(const aos::Vec3VArg _shapeSpaceCenterOfMass)
{
shapeSpaceCenterOfMass = _shapeSpaceCenterOfMass;
}
virtual ~SupportLocal() {}
virtual aos::Vec3V doSupport(const aos::Vec3VArg dir) const = 0;
virtual void doSupport(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const = 0;
virtual void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts)const = 0;
protected:
SupportLocal& operator=(const SupportLocal&);
};
#if PX_VC
#pragma warning(pop)
#endif
template <typename Convex>
class SupportLocalImpl : public SupportLocal
{
public:
const Convex& conv;
SupportLocalImpl(const Convex& _conv, const aos::PxTransformV& _transform, const aos::Mat33V& _vertex2Shape, const aos::Mat33V& _shape2Vertex, const bool _isIdentityScale = true) :
SupportLocal(_transform, _vertex2Shape, _shape2Vertex, _isIdentityScale), conv(_conv)
{
}
aos::Vec3V doSupport(const aos::Vec3VArg dir) const
{
//return conv.supportVertsLocal(dir);
return conv.supportLocal(dir);
}
void doSupport(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const
{
return conv.supportLocal(dir, min, max);
}
void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts) const
{
conv.populateVerts(inds, numInds, originalVerts, verts);
}
protected:
SupportLocalImpl& operator=(const SupportLocalImpl&);
};
}
}
#endif
| 4,185 | C | 34.777777 | 183 | 0.745998 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexSupportTable.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 "GuVecBox.h"
namespace physx
{
const aos::BoolV boxVertexTable[8] = {
aos::BFFFF(),//---
aos::BTFFF(),//+--
aos::BFTFF(),//-+-
aos::BTTFF(),//++-
aos::BFFTF(),//--+
aos::BTFTF(),//+-+
aos::BFTTF(),//-++
aos::BTTTF(),//+++
};
}
| 2,026 | C++ | 45.068181 | 74 | 0.702369 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMesh.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/PxFoundation.h"
#include "GuConvexMesh.h"
#include "GuBigConvexData2.h"
#include "GuMeshFactory.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
bool ConvexMesh::getPolygonData(PxU32 i, PxHullPolygon& data) const
{
if(i>=mHullData.mNbPolygons)
return false;
const HullPolygonData& poly = mHullData.mPolygons[i];
data.mPlane[0] = poly.mPlane.n.x;
data.mPlane[1] = poly.mPlane.n.y;
data.mPlane[2] = poly.mPlane.n.z;
data.mPlane[3] = poly.mPlane.d;
data.mNbVerts = poly.mNbVerts;
data.mIndexBase = poly.mVRef8;
return true;
}
static void initConvexHullData(ConvexHullData& data)
{
data.mAABB.setEmpty();
data.mCenterOfMass = PxVec3(0);
data.mNbEdges = PxBitAndWord();
data.mNbHullVertices = 0;
data.mNbPolygons = 0;
data.mPolygons = NULL;
data.mBigConvexRawData = NULL;
data.mInternal.mRadius = 0.0f;
data.mInternal.mExtents[0] = data.mInternal.mExtents[1] = data.mInternal.mExtents[2] = 0.0f;
}
ConvexMesh::ConvexMesh(MeshFactory* factory) :
PxConvexMesh (PxConcreteType::eCONVEX_MESH, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mNb (0),
mSdfData (NULL),
mBigConvexData (NULL),
mMass (0),
mInertia (PxMat33(PxIdentity)),
mMeshFactory (factory)
{
initConvexHullData(mHullData);
}
ConvexMesh::ConvexMesh(MeshFactory* factory, ConvexHullInitData& data) :
PxConvexMesh (PxConcreteType::eCONVEX_MESH, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mNb (data.mNb),
mSdfData (data.mSdfData),
mBigConvexData (data.mBigConvexData),
mMass (data.mMass),
mInertia (data.mInertia),
mMeshFactory (factory)
{
mHullData = data.mHullData;
// this constructor takes ownership of memory from the data object
data.mSdfData = NULL;
data.mBigConvexData = NULL;
}
ConvexMesh::~ConvexMesh()
{
if(getBaseFlags()&PxBaseFlag::eOWNS_MEMORY)
{
PX_FREE(mHullData.mPolygons);
PX_DELETE(mBigConvexData);
PX_DELETE(mSdfData);
}
}
bool ConvexMesh::isGpuCompatible() const
{
return mHullData.mNbHullVertices <= 64 &&
mHullData.mNbPolygons <= 64 &&
mHullData.mPolygons[0].mNbVerts <= 32 &&
mHullData.mNbEdges.isBitSet() &&
mHullData.checkExtentRadiusRatio();
}
void ConvexMesh::exportExtraData(PxSerializationContext& context)
{
context.alignData(PX_SERIAL_ALIGN);
const PxU32 bufferSize = computeBufferSize(mHullData, getNb());
context.writeData(mHullData.mPolygons, bufferSize);
if (mSdfData)
{
context.alignData(PX_SERIAL_ALIGN);
context.writeData(mSdfData, sizeof(SDF));
mSdfData->exportExtraData(context);
}
if(mBigConvexData)
{
context.alignData(PX_SERIAL_ALIGN);
context.writeData(mBigConvexData, sizeof(BigConvexData));
mBigConvexData->exportExtraData(context);
}
}
void ConvexMesh::importExtraData(PxDeserializationContext& context)
{
const PxU32 bufferSize = computeBufferSize(mHullData, getNb());
mHullData.mPolygons = reinterpret_cast<HullPolygonData*>(context.readExtraData<PxU8, PX_SERIAL_ALIGN>(bufferSize));
if (mSdfData)
{
mSdfData = context.readExtraData<SDF, PX_SERIAL_ALIGN>();
PX_PLACEMENT_NEW(mSdfData, SDF(PxEmpty));
mSdfData->importExtraData(context);
}
if(mBigConvexData)
{
mBigConvexData = context.readExtraData<BigConvexData, PX_SERIAL_ALIGN>();
PX_PLACEMENT_NEW(mBigConvexData, BigConvexData(PxEmpty));
mBigConvexData->importExtraData(context);
mHullData.mBigConvexRawData = &mBigConvexData->mData;
}
}
ConvexMesh* ConvexMesh::createObject(PxU8*& address, PxDeserializationContext& context)
{
ConvexMesh* obj = PX_PLACEMENT_NEW(address, ConvexMesh(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(ConvexMesh);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
static bool convexHullLoad(ConvexHullData& data, PxInputStream& stream, PxBitAndDword& bufferSize)
{
PxU32 version;
bool Mismatch;
if(!ReadHeader('C', 'L', 'H', 'L', version, Mismatch, stream))
return false;
if(version<=8)
{
if(!ReadHeader('C', 'V', 'H', 'L', version, Mismatch, stream))
return false;
}
PxU32 Nb;
// Import figures
{
PxU32 tmp[4];
ReadDwordBuffer(tmp, 4, Mismatch, stream);
data.mNbHullVertices = PxTo8(tmp[0]);
data.mNbEdges = PxTo16(tmp[1]);
data.mNbPolygons = PxTo8(tmp[2]);
Nb = tmp[3];
}
//AM: In practice the old aligner approach wastes 20 bytes and there is no reason to 20 byte align this data.
//I changed the code to just 4 align for the time being.
//On consoles if anything we will need to make this stuff 16 byte align vectors to have any sense, which will have to be done by padding data structures.
PX_ASSERT(sizeof(HullPolygonData) % sizeof(PxReal) == 0); //otherwise please pad it.
PX_ASSERT(sizeof(PxVec3) % sizeof(PxReal) == 0);
PxU32 bytesNeeded = computeBufferSize(data, Nb);
PX_FREE(data.mPolygons); // Load() can be called for an existing convex mesh. In that case we need to free the memory first.
bufferSize = Nb;
void* mDataMemory = PX_ALLOC(bytesNeeded, "ConvexHullData data");
PxU8* address = reinterpret_cast<PxU8*>(mDataMemory);
PX_ASSERT(address);
data.mPolygons = reinterpret_cast<HullPolygonData*>(address); address += sizeof(HullPolygonData) * data.mNbPolygons;
PxVec3* mDataHullVertices = reinterpret_cast<PxVec3*>(address); address += sizeof(PxVec3) * data.mNbHullVertices;
PxU8* mDataFacesByEdges8 = address; address += sizeof(PxU8) * data.mNbEdges * 2;
PxU8* mDataFacesByVertices8 = address; address += sizeof(PxU8) * data.mNbHullVertices * 3;
PxU16* mEdges = reinterpret_cast<PxU16*>(address); address += data.mNbEdges.isBitSet() ? (sizeof(PxU16) * data.mNbEdges * 2) : 0;
PxU8* mDataVertexData8 = address; address += sizeof(PxU8) * Nb; // PT: leave that one last, so that we don't need to serialize "Nb"
PX_ASSERT(!(size_t(mDataHullVertices) % sizeof(PxReal)));
PX_ASSERT(!(size_t(data.mPolygons) % sizeof(PxReal)));
PX_ASSERT(size_t(address)<=size_t(mDataMemory)+bytesNeeded);
// Import vertices
readFloatBuffer(&mDataHullVertices->x, PxU32(3*data.mNbHullVertices), Mismatch, stream);
if(version<=6)
{
PxU16 useUnquantizedNormals = readWord(Mismatch, stream);
PX_UNUSED(useUnquantizedNormals);
}
// Import polygons
stream.read(data.mPolygons, data.mNbPolygons*sizeof(HullPolygonData));
if(Mismatch)
{
for(PxU32 i=0;i<data.mNbPolygons;i++)
flipData(data.mPolygons[i]);
}
stream.read(mDataVertexData8, Nb);
stream.read(mDataFacesByEdges8, PxU32(data.mNbEdges*2));
if(version <= 5)
{
//KS - we need to compute faces-by-vertices here
bool noPlaneShift = false;
for(PxU32 i=0; i< data.mNbHullVertices; ++i)
{
PxU32 count = 0;
PxU8 inds[3];
for(PxU32 j=0; j<data.mNbPolygons; ++j)
{
HullPolygonData& polygon = data.mPolygons[j];
for(PxU32 k=0; k< polygon.mNbVerts; ++k)
{
PxU8 index = mDataVertexData8[polygon.mVRef8 + k];
if(i == index)
{
//Found a polygon
inds[count++] = PxTo8(j);
break;
}
}
if(count == 3)
break;
}
//We have 3 indices
//PX_ASSERT(count == 3);
//Do something here
if(count == 3)
{
mDataFacesByVertices8[i*3+0] = inds[0];
mDataFacesByVertices8[i*3+1] = inds[1];
mDataFacesByVertices8[i*3+2] = inds[2];
}
else
{
noPlaneShift = true;
break;
}
}
if(noPlaneShift)
{
for(PxU32 a = 0; a < data.mNbHullVertices; ++a)
{
mDataFacesByVertices8[a*3] = 0xFF;
mDataFacesByVertices8[a*3+1] = 0xFF;
mDataFacesByVertices8[a*3+2] = 0xFF;
}
}
}
else
stream.read(mDataFacesByVertices8, PxU32(data.mNbHullVertices * 3));
if (data.mNbEdges.isBitSet())
{
if (version <= 7)
{
for (PxU32 a = 0; a < PxU32(data.mNbEdges * 2); ++a)
{
mEdges[a] = 0xFFFF;
}
}
else
{
readWordBuffer(mEdges, PxU32(data.mNbEdges * 2), Mismatch, stream);
}
}
return true;
}
bool ConvexMesh::load(PxInputStream& stream)
{
// Import header
PxU32 version;
bool mismatch;
if(!readHeader('C', 'V', 'X', 'M', version, mismatch, stream))
return false;
// Check if old (incompatible) mesh format is loaded
if (version < PX_CONVEX_VERSION)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Loading convex mesh failed: Deprecated mesh cooking format.");
// Import serialization flags
PxU32 serialFlags = readDword(mismatch, stream);
PX_UNUSED(serialFlags);
if(!convexHullLoad(mHullData, stream, mNb))
return false;
// Import local bounds
float tmp[8];
readFloatBuffer(tmp, 8, mismatch, stream);
// geomEpsilon = tmp[0];
mHullData.mAABB = PxBounds3(PxVec3(tmp[1], tmp[2], tmp[3]), PxVec3(tmp[4],tmp[5],tmp[6]));
// Import mass info
mMass = tmp[7];
if(mMass!=-1.0f)
{
readFloatBuffer(&mInertia(0,0), 9, mismatch, stream);
readFloatBuffer(&mHullData.mCenterOfMass.x, 3, mismatch, stream);
}
// Import gaussmaps
PxF32 gaussMapFlag = readFloat(mismatch, stream);
if(gaussMapFlag != -1.0f)
{
PX_ASSERT(gaussMapFlag == 1.0f); //otherwise file is corrupt
PX_DELETE(mBigConvexData);
PX_NEW_SERIALIZED(mBigConvexData, BigConvexData);
if(mBigConvexData)
{
mBigConvexData->Load(stream);
mHullData.mBigConvexRawData = &mBigConvexData->mData;
}
}
//Import Sdf data
PxF32 sdfFlag = readFloat(mismatch, stream);
if (sdfFlag != -1.0f)
{
PX_ASSERT(sdfFlag == 1.0f); //otherwise file is corrupt
PX_DELETE(mSdfData);
PX_NEW_SERIALIZED(mSdfData, SDF);
if (mSdfData)
{
// Import sdf values
mSdfData->mMeshLower.x = readFloat(mismatch, stream);
mSdfData->mMeshLower.y = readFloat(mismatch, stream);
mSdfData->mMeshLower.z = readFloat(mismatch, stream);
mSdfData->mSpacing = readFloat(mismatch, stream);
mSdfData->mDims.x = readDword(mismatch, stream);
mSdfData->mDims.y = readDword(mismatch, stream);
mSdfData->mDims.z = readDword(mismatch, stream);
mSdfData->mNumSdfs = readDword(mismatch, stream);
mSdfData->mNumSubgridSdfs = readDword(mismatch, stream);
mSdfData->mNumStartSlots = readDword(mismatch, stream);
mSdfData->mSubgridSize = readDword(mismatch, stream);
mSdfData->mSdfSubgrids3DTexBlockDim.x = readDword(mismatch, stream);
mSdfData->mSdfSubgrids3DTexBlockDim.y = readDword(mismatch, stream);
mSdfData->mSdfSubgrids3DTexBlockDim.z = readDword(mismatch, stream);
mSdfData->mSubgridsMinSdfValue = readFloat(mismatch, stream);
mSdfData->mSubgridsMaxSdfValue = readFloat(mismatch, stream);
mSdfData->mBytesPerSparsePixel = readDword(mismatch, stream);
//allocate sdf
mSdfData->allocateSdfs(mSdfData->mMeshLower, mSdfData->mSpacing, mSdfData->mDims.x, mSdfData->mDims.y, mSdfData->mDims.z,
mSdfData->mSubgridSize, mSdfData->mSdfSubgrids3DTexBlockDim.x, mSdfData->mSdfSubgrids3DTexBlockDim.y, mSdfData->mSdfSubgrids3DTexBlockDim.z,
mSdfData->mSubgridsMinSdfValue, mSdfData->mSubgridsMaxSdfValue, mSdfData->mBytesPerSparsePixel);
readFloatBuffer(mSdfData->mSdf, mSdfData->mNumSdfs, mismatch, stream);
readByteBuffer(mSdfData->mSubgridSdf, mSdfData->mNumSubgridSdfs, stream);
readIntBuffer(mSdfData->mSubgridStartSlots, mSdfData->mNumStartSlots, mismatch, stream);
mHullData.mSdfData = mSdfData;
}
}
/*
printf("\n\n");
printf("COM: %f %f %f\n", massInfo.centerOfMass.x, massInfo.centerOfMass.y, massInfo.centerOfMass.z);
printf("BND: %f %f %f\n", mHullData.aabb.getCenter().x, mHullData.aabb.getCenter().y, mHullData.aabb.getCenter().z);
printf("CNT: %f %f %f\n", mHullData.mCenterxx.x, mHullData.mCenterxx.y, mHullData.mCenterxx.z);
printf("COM-BND: %f BND-CNT: %f, CNT-COM: %f\n", (massInfo.centerOfMass - mHullData.aabb.getCenter()).magnitude(), (mHullData.aabb.getCenter() - mHullData.mCenterxx).magnitude(), (mHullData.mCenterxx - massInfo.centerOfMass).magnitude());
*/
// TEST_INTERNAL_OBJECTS
readFloatBuffer(&mHullData.mInternal.mRadius, 4, mismatch, stream);
PX_ASSERT(PxVec3(mHullData.mInternal.mExtents[0], mHullData.mInternal.mExtents[1], mHullData.mInternal.mExtents[2]).isFinite());
PX_ASSERT(mHullData.mInternal.mExtents[0] != 0.0f);
PX_ASSERT(mHullData.mInternal.mExtents[1] != 0.0f);
PX_ASSERT(mHullData.mInternal.mExtents[2] != 0.0f);
//~TEST_INTERNAL_OBJECTS
return true;
}
void ConvexMesh::release()
{
RefCountable_decRefCount(*this);
}
void ConvexMesh::onRefCountZero()
{
// when the mesh failed to load properly, it will not have been added to the convex array
::onRefCountZero(this, mMeshFactory, !getBufferSize(), "PxConvexMesh::release: double deletion detected!");
}
void ConvexMesh::acquireReference()
{
RefCountable_incRefCount(*this);
}
PxU32 ConvexMesh::getReferenceCount() const
{
return RefCountable_getRefCount(*this);
}
void ConvexMesh::getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const
{
mass = ConvexMesh::getMass();
localInertia = ConvexMesh::getInertia();
localCenterOfMass = ConvexMesh::getHull().mCenterOfMass;
}
PxBounds3 ConvexMesh::getLocalBounds() const
{
PX_ASSERT(mHullData.mAABB.isValid());
return PxBounds3::centerExtents(mHullData.mAABB.mCenter, mHullData.mAABB.mExtents);
}
const PxReal* ConvexMesh::getSDF() const
{
if(mSdfData)
return mSdfData->mSdf;
return NULL;
}
| 14,811 | C++ | 30.717345 | 239 | 0.722841 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuShapeConvex.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 "GuShapeConvex.h"
#include "GuBigConvexData.h"
#include "GuEdgeList.h"
#include "GuInternal.h"
#include "foundation/PxMat34.h"
#include "GuHillClimbing.h"
#include "foundation/PxFPU.h"
using namespace physx;
using namespace Gu;
static PX_FORCE_INLINE PxU32 selectClosestPolygon(PxReal& maxDp_, PxU32 numPolygons, const Gu::HullPolygonData* polys, const PxVec3& axis)
{
float maxDp = polys[0].mPlane.n.dot(axis);
PxU32 closest = 0;
// Loop through polygons
for(PxU32 i=1; i <numPolygons; i++)
{
// Catch current polygon and test its plane
const PxReal dp = polys[i].mPlane.n.dot(axis);
if(dp>maxDp)
{
maxDp = dp;
closest = i;
}
}
maxDp_ = maxDp;
return closest;
}
static PxU32 SelectClosestEdgeCB_Convex(const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localSpaceDirection)
{
//vertex1TOShape1Skew is a symmetric matrix.
//it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v
const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection;
const Gu::HullPolygonData* PX_RESTRICT polys = data.mPolygons;
PxReal maxDp;
// ##might not be needed
PxU32 closest = ::selectClosestPolygon(maxDp, data.mNbPolygons, polys, vertexSpaceDirection);
// Since the convex is closed, at least some poly must satisfy this
PX_ASSERT(maxDp>=0);
const PxU32 numEdges = data.mNbEdges;
const PxU8* const edgeToFace = data.mFacesByEdges;
//Loop through edges
PxU32 closestEdge = 0xffffffff;
PxReal maxDpSq = maxDp * maxDp;
for(PxU32 i=0; i < numEdges; i++)
{
const PxU8 f0 = edgeToFace[i*2];
const PxU8 f1 = edgeToFace[i*2+1];
// unnormalized edge normal
const PxVec3 edgeNormal = polys[f0].mPlane.n + polys[f1].mPlane.n;
const PxReal enMagSq = edgeNormal.magnitudeSquared();
//Test normal of current edge - squared test is valid if dp and maxDp both >= 0
const float dp = edgeNormal.dot(vertexSpaceDirection);
if(dp>=0.0f && dp*dp>maxDpSq*enMagSq)
{
maxDpSq = dp*dp/enMagSq;
closestEdge = i;
}
}
if(closestEdge!=0xffffffff)
{
const PxU8* FBE = edgeToFace;
const PxU32 f0 = FBE[closestEdge*2];
const PxU32 f1 = FBE[closestEdge*2+1];
const PxReal dp0 = polys[f0].mPlane.n.dot(vertexSpaceDirection);
const PxReal dp1 = polys[f1].mPlane.n.dot(vertexSpaceDirection);
if(dp0>dp1)
closest = f0;
else
closest = f1;
}
return closest;
}
// Hull projection callback for "small" hulls
static void HullProjectionCB_SmallConvex(const PolygonalData& data, const PxVec3& dir,
const PxMat34& world,
const Cm::FastVertex2ShapeScaling& scaling,
PxReal& min, PxReal& max)
{
const PxVec3 localSpaceDirection = world.rotateTranspose(dir);
//vertex1TOShape1Skew is a symmetric matrix.
//it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v
const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection;
// PT: prevents aliasing
PxReal minimum = PX_MAX_REAL;
PxReal maximum = -PX_MAX_REAL;
//brute-force, localspace
{
const PxVec3* PX_RESTRICT verts = data.mVerts;
PxU32 numVerts = data.mNbVerts;
while(numVerts--)
{
const PxReal dp = (*verts++).dot(vertexSpaceDirection);
minimum = physx::intrinsics::selectMin(minimum, dp);
maximum = physx::intrinsics::selectMax(maximum, dp);
}
}
const PxReal offset = world.p.dot(dir);
min = minimum + offset;
max = maximum + offset;
}
static PxU32 computeNearestOffset(const PxU32 subdiv, const PxVec3& dir)
{
// ComputeCubemapNearestOffset(const Point& dir, udword subdiv)
// PT: ok so why exactly was the code duplicated here?
// PxU32 CI = CubemapLookup(dir,u,v)
PxU32 index;
PxReal coeff;
// find largest axis
PxReal absNx = PxAbs(dir.x);
PxReal absNy = PxAbs(dir.y);
PxReal absNz = PxAbs(dir.z);
if( absNy > absNx &&
absNy > absNz)
{
//y biggest
index = 1;
coeff = 1.0f/absNy;
}
else if(absNz > absNx)
{
index = 2;
coeff = 1.0f/absNz;
}
else
{
index = 0;
coeff = 1.0f/absNx;
}
union
{
PxU32 aU32;
PxReal aFloat;
} conv;
conv.aFloat = dir[index];
PxU32 sign = conv.aU32>>31;
const PxU32 index2 = PxGetNextIndex3(index);
const PxU32 index3 = PxGetNextIndex3(index2);
PxReal u = dir[index2] * coeff;
PxReal v = dir[index3] * coeff;
PxU32 CI = (sign | (index+index));
//Remap to [0, subdiv[
coeff = 0.5f * PxReal(subdiv-1);
u += 1.0f; u *= coeff;
v += 1.0f; v *= coeff;
//Round to nearest
PxU32 ui = PxU32(u);
PxU32 vi = PxU32(v);
PxReal du = u - PxReal(ui);
PxReal dv = v - PxReal(vi);
if(du>0.5f) ui++;
if(dv>0.5f) vi++;
//Compute offset
return CI*(subdiv*subdiv) + ui*subdiv + vi;
}
// Hull projection callback for "big" hulls
static void HullProjectionCB_BigConvex(const PolygonalData& data, const PxVec3& dir, const PxMat34& world, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum)
{
const PxVec3* PX_RESTRICT verts = data.mVerts;
const PxVec3 localSpaceDirection = world.rotateTranspose(dir);
//vertex1TOShape1Skew is a symmetric matrix.
//it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v
const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection; //NB: triangles are always shape 1! eek!
// This version is better for objects with a lot of vertices
const Gu::BigConvexRawData* bigData = data.mBigData;
PxU32 minID = 0, maxID = 0;
{
const PxU32 offset = computeNearestOffset(bigData->mSubdiv, -vertexSpaceDirection);
minID = bigData->mSamples[offset];
maxID = bigData->getSamples2()[offset];
}
// Do hillclimbing!
localSearch(minID, -vertexSpaceDirection, verts, bigData);
localSearch(maxID, vertexSpaceDirection, verts, bigData);
const PxReal offset = world.p.dot(dir);
minimum = offset + verts[minID].dot(vertexSpaceDirection);
maximum = offset + verts[maxID].dot(vertexSpaceDirection);
PX_ASSERT(maximum >= minimum);
}
void Gu::getPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling)
{
dst->mCenter = scaling * src->mCenterOfMass;
dst->mNbVerts = src->mNbHullVertices;
dst->mNbPolygons = src->mNbPolygons;
dst->mNbEdges = src->mNbEdges;
dst->mPolygons = src->mPolygons;
dst->mVerts = src->getHullVertices();
dst->mPolygonVertexRefs = src->getVertexData8();
dst->mFacesByEdges = src->getFacesByEdges8();
// TEST_INTERNAL_OBJECTS
dst->mInternal = src->mInternal;
//~TEST_INTERNAL_OBJECTS
dst->mBigData = src->mBigConvexRawData;
// This threshold test doesnt cost much and many customers cook on PC and use this on 360.
// 360 has a much higher threshold than PC(and it makes a big difference)
// PT: the cool thing is that this test is now done once by contact generation call, not once by hull projection
if(!src->mBigConvexRawData)
dst->mProjectHull = HullProjectionCB_SmallConvex;
else
dst->mProjectHull = HullProjectionCB_BigConvex;
dst->mSelectClosestEdgeCB = SelectClosestEdgeCB_Convex;
}
// Box emulating convex mesh
// Face0: 0-1-2-3
// Face1: 1-5-6-2
// Face2: 5-4-7-6
// Face3: 4-0-3-7
// Face4; 3-2-6-7
// Face5: 4-5-1-0
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
static const PxU8 gPxcBoxPolygonData[] = {
0, 1, 2, 3,
1, 5, 6, 2,
5, 4, 7, 6,
4, 0, 3, 7,
3, 2, 6, 7,
4, 5, 1, 0,
};
#define INVSQRT2 0.707106781188f //!< 1 / sqrt(2)
static PxVec3 gPxcBoxEdgeNormals[] =
{
PxVec3(0, -INVSQRT2, -INVSQRT2), // 0-1
PxVec3(INVSQRT2, 0, -INVSQRT2), // 1-2
PxVec3(0, INVSQRT2, -INVSQRT2), // 2-3
PxVec3(-INVSQRT2, 0, -INVSQRT2), // 3-0
PxVec3(0, INVSQRT2, INVSQRT2), // 7-6
PxVec3(INVSQRT2, 0, INVSQRT2), // 6-5
PxVec3(0, -INVSQRT2, INVSQRT2), // 5-4
PxVec3(-INVSQRT2, 0, INVSQRT2), // 4-7
PxVec3(INVSQRT2, -INVSQRT2, 0), // 1-5
PxVec3(INVSQRT2, INVSQRT2, 0), // 6-2
PxVec3(-INVSQRT2, INVSQRT2, 0), // 3-7
PxVec3(-INVSQRT2, -INVSQRT2, 0) // 4-0
};
#undef INVSQRT2
// ### needs serious checkings
// Flags(16), Count(16), Offset(32);
static Gu::EdgeDescData gPxcBoxEdgeDesc[] = {
{Gu::PX_EDGE_ACTIVE, 2, 0},
{Gu::PX_EDGE_ACTIVE, 2, 2},
{Gu::PX_EDGE_ACTIVE, 2, 4},
{Gu::PX_EDGE_ACTIVE, 2, 6},
{Gu::PX_EDGE_ACTIVE, 2, 8},
{Gu::PX_EDGE_ACTIVE, 2, 10},
{Gu::PX_EDGE_ACTIVE, 2, 12},
{Gu::PX_EDGE_ACTIVE, 2, 14},
{Gu::PX_EDGE_ACTIVE, 2, 16},
{Gu::PX_EDGE_ACTIVE, 2, 18},
{Gu::PX_EDGE_ACTIVE, 2, 20},
{Gu::PX_EDGE_ACTIVE, 2, 22},
};
// ### needs serious checkings
static PxU8 gPxcBoxFaceByEdge[] = {
0,5, // Edge 0-1
0,1, // Edge 1-2
0,4, // Edge 2-3
0,3, // Edge 3-0
2,4, // Edge 7-6
1,2, // Edge 6-5
2,5, // Edge 5-4
2,3, // Edge 4-7
1,5, // Edge 1-5
1,4, // Edge 6-2
3,4, // Edge 3-7
3,5, // Edge 4-0
};
static PxU32 SelectClosestEdgeCB_Box(const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localDirection)
{
PX_UNUSED(scaling);
PxReal maxDp;
// ##might not be needed
PxU32 closest = ::selectClosestPolygon(maxDp, 6, data.mPolygons, localDirection);
PxU32 numEdges = 12;
const PxVec3* PX_RESTRICT edgeNormals = gPxcBoxEdgeNormals;
//Loop through edges
PxU32 closestEdge = 0xffffffff;
for(PxU32 i=0; i < numEdges; i++)
{
//Test normal of current edge
const float dp = edgeNormals[i].dot(localDirection);
if(dp>maxDp)
{
maxDp = dp;
closestEdge = i;
}
}
if(closestEdge!=0xffffffff)
{
const Gu::EdgeDescData* PX_RESTRICT ED = gPxcBoxEdgeDesc;
const PxU8* PX_RESTRICT FBE = gPxcBoxFaceByEdge;
PX_ASSERT(ED[closestEdge].Count==2);
const PxU32 f0 = FBE[ED[closestEdge].Offset];
const PxU32 f1 = FBE[ED[closestEdge].Offset+1];
const PxReal dp0 = data.mPolygons[f0].mPlane.n.dot(localDirection);
const PxReal dp1 = data.mPolygons[f1].mPlane.n.dot(localDirection);
if(dp0>dp1)
closest = f0;
else
closest = f1;
}
return closest;
}
static PX_FORCE_INLINE void projectBox(PxVec3& p, const PxVec3& localDir, const PxVec3& extents)
{
// PT: the original code didn't have branches or FPU comparisons. Why rewrite it ?
// p.x = (localDir.x >= 0) ? extents.x : -extents.x;
// p.y = (localDir.y >= 0) ? extents.y : -extents.y;
// p.z = (localDir.z >= 0) ? extents.z : -extents.z;
p.x = physx::intrinsics::fsel(localDir.x, extents.x, -extents.x);
p.y = physx::intrinsics::fsel(localDir.y, extents.y, -extents.y);
p.z = physx::intrinsics::fsel(localDir.z, extents.z, -extents.z);
}
static void HullProjectionCB_Box(const PolygonalData& data, const PxVec3& dir, const PxMat34& world, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum)
{
PX_UNUSED(scaling);
const PxVec3 localDir = world.rotateTranspose(dir);
PxVec3 p;
projectBox(p, localDir, *data.mHalfSide);
const PxReal offset = world.p.dot(dir);
const PxReal tmp = p.dot(localDir);
maximum = offset + tmp;
minimum = offset - tmp;
}
PolygonalBox::PolygonalBox(const PxVec3& halfSide) : mHalfSide(halfSide)
{
//Precompute the convex data
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
PxVec3 minimum = -mHalfSide;
PxVec3 maximum = mHalfSide;
// Generate 8 corners of the bbox
mVertices[0] = PxVec3(minimum.x, minimum.y, minimum.z);
mVertices[1] = PxVec3(maximum.x, minimum.y, minimum.z);
mVertices[2] = PxVec3(maximum.x, maximum.y, minimum.z);
mVertices[3] = PxVec3(minimum.x, maximum.y, minimum.z);
mVertices[4] = PxVec3(minimum.x, minimum.y, maximum.z);
mVertices[5] = PxVec3(maximum.x, minimum.y, maximum.z);
mVertices[6] = PxVec3(maximum.x, maximum.y, maximum.z);
mVertices[7] = PxVec3(minimum.x, maximum.y, maximum.z);
//Setup the polygons
for(PxU8 i=0; i < 6; i++)
{
mPolygons[i].mNbVerts = 4;
mPolygons[i].mVRef8 = PxU16(i*4);
}
// ### planes needs *very* careful checks
// X axis
mPolygons[1].mPlane.n = PxVec3(1.0f, 0.0f, 0.0f);
mPolygons[1].mPlane.d = -mHalfSide.x;
mPolygons[3].mPlane.n = PxVec3(-1.0f, 0.0f, 0.0f);
mPolygons[3].mPlane.d = -mHalfSide.x;
mPolygons[1].mMinIndex = 0;
mPolygons[3].mMinIndex = 1;
// mPolygons[1].mMinObsolete = -mHalfSide.x;
// mPolygons[3].mMinObsolete = -mHalfSide.x;
PX_ASSERT(mPolygons[1].getMin(mVertices) == -mHalfSide.x);
PX_ASSERT(mPolygons[3].getMin(mVertices) == -mHalfSide.x);
// Y axis
mPolygons[4].mPlane.n = PxVec3(0.f, 1.0f, 0.0f);
mPolygons[4].mPlane.d = -mHalfSide.y;
mPolygons[5].mPlane.n = PxVec3(0.0f, -1.0f, 0.0f);
mPolygons[5].mPlane.d = -mHalfSide.y;
mPolygons[4].mMinIndex = 0;
mPolygons[5].mMinIndex = 2;
// mPolygons[4].mMinObsolete = -mHalfSide.y;
// mPolygons[5].mMinObsolete = -mHalfSide.y;
PX_ASSERT(mPolygons[4].getMin(mVertices) == -mHalfSide.y);
PX_ASSERT(mPolygons[5].getMin(mVertices) == -mHalfSide.y);
// Z axis
mPolygons[2].mPlane.n = PxVec3(0.f, 0.0f, 1.0f);
mPolygons[2].mPlane.d = -mHalfSide.z;
mPolygons[0].mPlane.n = PxVec3(0.0f, 0.0f, -1.0f);
mPolygons[0].mPlane.d = -mHalfSide.z;
mPolygons[2].mMinIndex = 0;
mPolygons[0].mMinIndex = 4;
// mPolygons[2].mMinObsolete = -mHalfSide.z;
// mPolygons[0].mMinObsolete = -mHalfSide.z;
PX_ASSERT(mPolygons[2].getMin(mVertices) == -mHalfSide.z);
PX_ASSERT(mPolygons[0].getMin(mVertices) == -mHalfSide.z);
}
void PolygonalBox::getPolygonalData(PolygonalData* PX_RESTRICT dst) const
{
dst->mCenter = PxVec3(0.0f, 0.0f, 0.0f);
dst->mNbVerts = 8;
dst->mNbPolygons = 6;
dst->mPolygons = mPolygons;
dst->mNbEdges = 0;
dst->mVerts = mVertices;
dst->mPolygonVertexRefs = gPxcBoxPolygonData;
dst->mFacesByEdges = NULL;
dst->mInternal.mRadius = 0.0f;
dst->mInternal.mExtents[0] = 0.0f;
dst->mInternal.mExtents[1] = 0.0f;
dst->mInternal.mExtents[2] = 0.0f;
// dst->mBigData = NULL;
dst->mHalfSide = &mHalfSide;
dst->mProjectHull = HullProjectionCB_Box;
dst->mSelectClosestEdgeCB = SelectClosestEdgeCB_Box;
}
| 15,899 | C++ | 29.813953 | 184 | 0.678596 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMesh.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_CONVEX_MESH_H
#define GU_CONVEX_MESH_H
#include "foundation/PxBitAndData.h"
#include "common/PxMetaData.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "foundation/PxUserAllocated.h"
#include "CmRefCountable.h"
#include "common/PxRenderOutput.h"
#include "GuConvexMeshData.h"
namespace physx
{
class BigConvexData;
namespace Gu
{
class MeshFactory;
struct HullPolygonData;
PX_INLINE PxU32 computeBufferSize(const Gu::ConvexHullData& data, PxU32 nb)
{
PxU32 bytesNeeded = sizeof(Gu::HullPolygonData) * data.mNbPolygons;
bytesNeeded += sizeof(PxVec3) * data.mNbHullVertices;
bytesNeeded += sizeof(PxU8) * data.mNbEdges * 2; // mFacesByEdges8
bytesNeeded += sizeof(PxU8) * data.mNbHullVertices * 3; // mFacesByVertices8;
bytesNeeded += data.mNbEdges.isBitSet() ? (sizeof(PxU16) * data.mNbEdges * 2) : 0; // mEdges;
bytesNeeded += sizeof(PxU8) * nb; // mVertexData8
//4 align the whole thing!
const PxU32 mod = bytesNeeded % sizeof(PxReal);
if (mod)
bytesNeeded += sizeof(PxReal) - mod;
return bytesNeeded;
}
struct ConvexHullInitData
{
ConvexHullData mHullData;
PxU32 mNb;
PxReal mMass;
PxMat33 mInertia;
BigConvexData* mBigConvexData;
SDF* mSdfData;
};
// 0: includes raycast map
// 1: discarded raycast map
// 2: support map not always there
// 3: support stackless trees for non-recursive collision queries
// 4: no more opcode model
// 5: valencies table and gauss map combined, only exported over a vertex count treshold that depends on the platform cooked for.
// 6: removed support for edgeData16.
// 7: removed support for edge8Data.
// 8: removed support for triangles.
// 9: removed local sphere.
//10: removed geometric center.
//11: removed mFlags, and mERef16 from Poly; nbVerts is just a byte.
//12: removed explicit minimum, maximum from Poly
//13: internal objects
//14: SDF
#define PX_CONVEX_VERSION 14
class ConvexMesh : public PxConvexMesh, public PxUserAllocated
{
public:
// PX_SERIALIZATION
ConvexMesh(PxBaseFlags baseFlags) : PxConvexMesh(baseFlags), mHullData(PxEmpty), mNb(PxEmpty)
{
mNb.setBit();
}
void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); }
virtual void exportExtraData(PxSerializationContext& stream);
void importExtraData(PxDeserializationContext& context);
PX_PHYSX_COMMON_API static ConvexMesh* createObject(PxU8*& address, PxDeserializationContext& context);
PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
void resolveReferences(PxDeserializationContext&) {}
virtual void requiresObjects(PxProcessPxBaseCallback&){}
//~PX_SERIALIZATION
ConvexMesh(MeshFactory* factory);
ConvexMesh(MeshFactory* factory, ConvexHullInitData& data);
bool load(PxInputStream& stream);
// PxBase
virtual void onRefCountZero();
//~PxBase
// PxRefCounted
virtual PxU32 getReferenceCount() const;
virtual void acquireReference();
//~PxRefCounted
// PxConvexMesh
virtual void release();
virtual PxU32 getNbVertices() const { return mHullData.mNbHullVertices; }
virtual const PxVec3* getVertices() const { return mHullData.getHullVertices(); }
virtual const PxU8* getIndexBuffer() const { return mHullData.getVertexData8(); }
virtual PxU32 getNbPolygons() const { return mHullData.mNbPolygons; }
virtual bool getPolygonData(PxU32 i, PxHullPolygon& data) const;
virtual bool isGpuCompatible() const;
virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const;
virtual PxBounds3 getLocalBounds() const;
virtual const PxReal* getSDF() const;
//~PxConvexMesh
PX_FORCE_INLINE PxU32 getNbVerts() const { return mHullData.mNbHullVertices; }
PX_FORCE_INLINE const PxVec3* getVerts() const { return mHullData.getHullVertices(); }
PX_FORCE_INLINE PxU32 getNbPolygonsFast() const { return mHullData.mNbPolygons; }
PX_FORCE_INLINE const HullPolygonData& getPolygon(PxU32 i) const { return mHullData.mPolygons[i]; }
PX_FORCE_INLINE const HullPolygonData* getPolygons() const { return mHullData.mPolygons; }
PX_FORCE_INLINE PxU32 getNbEdges() const { return mHullData.mNbEdges; }
PX_FORCE_INLINE const ConvexHullData& getHull() const { return mHullData; }
PX_FORCE_INLINE ConvexHullData& getHull() { return mHullData; }
PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mHullData.mAABB; }
PX_FORCE_INLINE PxReal getMass() const { return mMass; }
PX_FORCE_INLINE void setMass(PxReal mass) { mMass = mass; }
PX_FORCE_INLINE const PxMat33& getInertia() const { return mInertia; }
PX_FORCE_INLINE void setInertia(const PxMat33& inertia) { mInertia = inertia; }
PX_FORCE_INLINE BigConvexData* getBigConvexData() const { return mBigConvexData; }
PX_FORCE_INLINE void setBigConvexData(BigConvexData* bcd) { mBigConvexData = bcd; }
PX_FORCE_INLINE PxU32 getBufferSize() const { return computeBufferSize(mHullData, getNb()); }
virtual ~ConvexMesh();
PX_FORCE_INLINE void setMeshFactory(MeshFactory* f) { mMeshFactory = f; }
PX_FORCE_INLINE void setNb(PxU32 nb) { mNb = nb; }
protected:
ConvexHullData mHullData;
PxBitAndDword mNb; // ### PT: added for serialization. Try to remove later?
SDF* mSdfData;
BigConvexData* mBigConvexData; //!< optional, only for large meshes! PT: redundant with ptr in chull data? Could also be end of other buffer
PxReal mMass; //this is mass assuming a unit density that can be scaled by instances!
PxMat33 mInertia; //in local space of mesh!
private:
MeshFactory* mMeshFactory; // PT: changed to pointer for serialization
PX_FORCE_INLINE PxU32 getNb() const { return mNb; }
PX_FORCE_INLINE PxU32 ownsMemory() const { return PxU32(!mNb.isBitSet()); }
};
PX_FORCE_INLINE const Gu::ConvexHullData* _getHullData(const PxConvexMeshGeometry& convexGeom)
{
return &static_cast<const Gu::ConvexMesh*>(convexGeom.convexMesh)->getHull();
}
} // namespace Gu
}
#endif
| 8,303 | C | 42.705263 | 149 | 0.69505 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuHillClimbing.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/PxAssert.h"
#include "foundation/PxUserAllocated.h"
#include "GuHillClimbing.h"
#include "GuBigConvexData2.h"
namespace physx
{
void localSearch(PxU32& id, const PxVec3& dir, const PxVec3* verts, const Gu::BigConvexRawData* val)
{
// WARNING: there is a problem on x86 with a naive version of this code, where truncation
// of values from 80 bits to 32 bits as they're stored in memory means that iteratively moving to
// an adjacent vertex of greater support can go into an infinite loop. So we use a version which
// never visits a vertex twice. Note - this might not be enough for GJK, since local
// termination of the support function might not be enough to ensure convergence of GJK itself.
// if we got here, we'd better have vertices and valencies
PX_ASSERT(verts && val);
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; }
};
TinyBitMap visited;
const Gu::Valency* Valencies = val->mValencies;
const PxU8* Adj = val->mAdjacentVerts;
PX_ASSERT(Valencies && Adj);
// Get the initial value and the initial vertex
float MaxVal = dir.dot(verts[id]);
PxU32 NextVtx = id;
do
{
PxU16 NbNeighbors = Valencies[NextVtx].mCount;
const PxU8* Run = Adj + Valencies[NextVtx].mOffset;
id = NextVtx;
while(NbNeighbors--)
{
const PxU8 Neighbor = *Run++;
if(!visited.get(Neighbor))
{
visited.set(Neighbor);
const float CurVal = dir.dot(verts[Neighbor]);
if(CurVal>MaxVal)
{
MaxVal = CurVal;
NextVtx = Neighbor;
}
}
}
} while(NextVtx!=id);
}
}
| 3,521 | C++ | 36.073684 | 100 | 0.714002 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexHelper.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_CONVEXHELPER_H
#define GU_CONVEXHELPER_H
#include "GuShapeConvex.h"
namespace physx
{
class PxConvexMeshGeometry;
namespace Gu
{
///////////////////////////////////////////////////////////////////////////
void getScaledConvex( PxVec3*& scaledVertices, PxU8*& scaledIndices, PxVec3* dstVertices, PxU8* dstIndices,
bool idtConvexScale, const PxVec3* srcVerts, const PxU8* srcIndices, PxU32 nbVerts, const Cm::FastVertex2ShapeScaling& convexScaling);
// PT: calling this correctly isn't trivial so let's macroize it. At least we limit the damage since it immediately calls a real function.
#define GET_SCALEX_CONVEX(scaledVertices, stackIndices, idtScaling, nbVerts, scaling, srcVerts, srcIndices) \
getScaledConvex(scaledVertices, stackIndices, \
idtScaling ? NULL : reinterpret_cast<PxVec3*>(PxAlloca(nbVerts * sizeof(PxVec3))), \
idtScaling ? NULL : reinterpret_cast<PxU8*>(PxAlloca(nbVerts * sizeof(PxU8))), \
idtScaling, srcVerts, srcIndices, nbVerts, scaling);
bool getConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData);
struct ConvexEdge
{
PxU8 vref0;
PxU8 vref1;
PxVec3 normal; // warning: non-unit vector!
};
PxU32 findUniqueConvexEdges(PxU32 maxNbEdges, ConvexEdge* PX_RESTRICT edges, PxU32 numPolygons, const Gu::HullPolygonData* PX_RESTRICT polygons, const PxU8* PX_RESTRICT vertexData);
}
}
#endif
| 3,167 | C | 47.738461 | 182 | 0.743606 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuBigConvexData.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/PxIntrinsics.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxAllocator.h"
#include "GuBigConvexData2.h"
#include "GuCubeIndex.h"
#include "CmUtils.h"
#include "CmSerialize.h"
#include "foundation/PxUtilities.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
BigConvexData::BigConvexData() : mVBuffer(NULL)
{
mData.mSubdiv = 0;
mData.mNbSamples = 0;
mData.mSamples = NULL;
//////
mData.mNbVerts = 0;
mData.mNbAdjVerts = 0;
mData.mValencies = NULL;
mData.mAdjacentVerts = NULL;
}
BigConvexData::~BigConvexData()
{
PX_FREE(mData.mSamples);
///////////
if(mVBuffer)
{
PX_FREE(mVBuffer);
}
else
{
// Allocated from somewhere else!!
PX_FREE(mData.mValencies);
PX_FREE(mData.mAdjacentVerts);
}
}
void BigConvexData::CreateOffsets()
{
// Create offsets (radix style)
mData.mValencies[0].mOffset = 0;
for(PxU32 i=1;i<mData.mNbVerts;i++)
mData.mValencies[i].mOffset = PxU16(mData.mValencies[i-1].mOffset + mData.mValencies[i-1].mCount);
}
bool BigConvexData::VLoad(PxInputStream& stream)
{
// Import header
PxU32 Version;
bool Mismatch;
if(!ReadHeader('V', 'A', 'L', 'E', Version, Mismatch, stream))
return false;
mData.mNbVerts = readDword(Mismatch, stream);
mData.mNbAdjVerts = readDword(Mismatch, stream);
PX_FREE(mVBuffer);
// PT: align Gu::Valency?
const PxU32 numVerts = (mData.mNbVerts+3)&~3;
const PxU32 TotalSize = sizeof(Gu::Valency)*numVerts + sizeof(PxU8)*mData.mNbAdjVerts;
mVBuffer = PX_ALLOC(TotalSize, "BigConvexData data");
mData.mValencies = reinterpret_cast<Gu::Valency*>(mVBuffer);
mData.mAdjacentVerts = (reinterpret_cast<PxU8*>(mVBuffer)) + sizeof(Gu::Valency)*numVerts;
PX_ASSERT(0 == (size_t(mData.mAdjacentVerts) & 0xf));
PX_ASSERT(Version==2);
{
PxU16* temp = reinterpret_cast<PxU16*>(mData.mValencies);
PxU32 MaxIndex = readDword(Mismatch, stream);
ReadIndices(PxTo16(MaxIndex), mData.mNbVerts, temp, stream, Mismatch);
// We transform from:
//
// |5555|4444|3333|2222|1111|----|----|----|----|----|
//
// to:
//
// |5555|4444|4444|2222|3333|----|2222|----|1111|----|
//
for(PxU32 i=0;i<mData.mNbVerts;i++)
mData.mValencies[mData.mNbVerts-i-1].mCount = temp[mData.mNbVerts-i-1];
}
stream.read(mData.mAdjacentVerts, mData.mNbAdjVerts);
// Recreate offsets
CreateOffsets();
return true;
}
PxU32 BigConvexData::ComputeOffset(const PxVec3& dir) const
{
return ComputeCubemapOffset(dir, mData.mSubdiv);
}
PxU32 BigConvexData::ComputeNearestOffset(const PxVec3& dir) const
{
return ComputeCubemapNearestOffset(dir, mData.mSubdiv);
}
bool BigConvexData::Load(PxInputStream& stream)
{
// Import header
PxU32 Version;
bool Mismatch;
if(!ReadHeader('S', 'U', 'P', 'M', Version, Mismatch, stream))
return false;
// Load base gaussmap
// if(!GaussMap::Load(stream)) return false;
// Import header
if(!ReadHeader('G', 'A', 'U', 'S', Version, Mismatch, stream))
return false;
// Import basic info
mData.mSubdiv = PxTo16(readDword(Mismatch, stream));
mData.mNbSamples = PxTo16(readDword(Mismatch, stream));
// Load map data
mData.mSamples = reinterpret_cast<PxU8*>(PX_ALLOC(sizeof(PxU8)*mData.mNbSamples*2, "BigConvex Samples Data"));
// These byte buffers shouldn't need converting
stream.read(mData.mSamples, sizeof(PxU8)*mData.mNbSamples*2);
//load the valencies
return VLoad(stream);
}
// PX_SERIALIZATION
void BigConvexData::exportExtraData(PxSerializationContext& stream)
{
if(mData.mSamples)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mData.mSamples, sizeof(PxU8)*mData.mNbSamples*2);
}
if(mData.mValencies)
{
stream.alignData(PX_SERIAL_ALIGN);
PxU32 numVerts = (mData.mNbVerts+3)&~3;
const PxU32 TotalSize = sizeof(Gu::Valency)*numVerts + sizeof(PxU8)*mData.mNbAdjVerts;
stream.writeData(mData.mValencies, TotalSize);
}
}
void BigConvexData::importExtraData(PxDeserializationContext& context)
{
if(mData.mSamples)
mData.mSamples = context.readExtraData<PxU8, PX_SERIAL_ALIGN>(PxU32(mData.mNbSamples*2));
if(mData.mValencies)
{
context.alignExtraData();
PxU32 numVerts = (mData.mNbVerts+3)&~3;
mData.mValencies = context.readExtraData<Gu::Valency>(numVerts);
mData.mAdjacentVerts = context.readExtraData<PxU8>(mData.mNbAdjVerts);
}
}
//~PX_SERIALIZATION
| 6,006 | C++ | 28.591133 | 111 | 0.727439 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuCubeIndex.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_CUBE_INDEX_H
#define GU_CUBE_INDEX_H
#include "foundation/PxVec3.h"
#include "foundation/PxFPU.h"
namespace physx
{
enum CubeIndex
{
CUBE_RIGHT,
CUBE_LEFT,
CUBE_TOP,
CUBE_BOTTOM,
CUBE_FRONT,
CUBE_BACK,
CUBE_FORCE_DWORD = 0x7fffffff
};
/*
It's pretty straightforwards in concept (though the execution in hardware is
a bit crufty and complex). You use a 3D texture coord to look up a texel in
a cube map. First you find which of the axis has the largest value (i.e.
X,Y,Z), and then the sign of that axis decides which face you are going to
use. Which is why the faces are called +X, -X, +Y, -Y, +Z, -Z - after their
principle axis. Then you scale the vector so that the largest value is +/-1.
Then use the other two as 2D coords to look up your texel (with a 0.5 scale
& offset).
For example, vector (0.4, -0.2, -0.5). Largest value is the Z axis, and it's
-ve, so we're reading from the -Z map. Scale so that this Z axis is +/-1,
and you get the vector (0.8, -0.4, -1.0). So now use the other two values to
look up your texel. So we look up texel (0.8, -0.4). The scale & offset move
the -1->+1 range into the usual 0->1 UV range, so we actually look up texel
(0.9, 0.3). The filtering is extremely complex, especially where three maps
meet, but that's a hardware problem :-)
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Cubemap lookup function.
*
* To transform returned uvs into mapping coordinates :
* u += 1.0f; u *= 0.5f;
* v += 1.0f; v *= 0.5f;
*
* \fn CubemapLookup(const PxVec3& direction, float& u, float& v)
* \param direction [in] a direction vector
* \param u [out] impact coordinate on the unit cube, in [-1,1]
* \param v [out] impact coordinate on the unit cube, in [-1,1]
* \return cubemap texture index
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PX_INLINE CubeIndex CubemapLookup(const PxVec3& direction, float& u, float& v);
PX_INLINE PxU32 ComputeCubemapOffset(const PxVec3& dir, PxU32 subdiv)
{
float u,v;
const CubeIndex CI = CubemapLookup(dir, u, v);
// Remap to [0, subdiv[
const float Coeff = 0.5f * float(subdiv-1);
u += 1.0f; u *= Coeff;
v += 1.0f; v *= Coeff;
// Compute offset
return PxU32(CI)*(subdiv*subdiv) + PxU32(u)*subdiv + PxU32(v);
}
PX_INLINE PxU32 ComputeCubemapNearestOffset(const PxVec3& dir, PxU32 subdiv)
{
float u,v;
const CubeIndex CI = CubemapLookup(dir, u, v);
// Remap to [0, subdiv]
const float Coeff = 0.5f * float(subdiv-1);
u += 1.0f; u *= Coeff;
v += 1.0f; v *= Coeff;
// Compute offset
return PxU32(CI)*(subdiv*subdiv) + PxU32(u + 0.5f)*subdiv + PxU32(v + 0.5f);
}
PX_INLINE CubeIndex CubemapLookup(const PxVec3& direction, float& u, float& v)
{
const PxU32* binary = reinterpret_cast<const PxU32*>(&direction.x);
const PxU32 absPx = binary[0] & ~PX_SIGN_BITMASK;
const PxU32 absNy = binary[1] & ~PX_SIGN_BITMASK;
const PxU32 absNz = binary[2] & ~PX_SIGN_BITMASK;
PxU32 Index1 = 0; //x biggest axis
PxU32 Index2 = 1;
PxU32 Index3 = 2;
if( (absNy > absPx) & (absNy > absNz))
{
//y biggest
Index2 = 2;
Index3 = 0;
Index1 = 1;
}
else if(absNz > absPx)
{
//z biggest
Index2 = 0;
Index3 = 1;
Index1 = 2;
}
const PxF32* data = &direction.x;
const float Coeff = 1.0f / fabsf(data[Index1]);
u = data[Index2] * Coeff;
v = data[Index3] * Coeff;
const PxU32 Sign = binary[Index1]>>31;
return CubeIndex(Sign|(Index1+Index1));
}
}
#endif
| 5,523 | C | 34.87013 | 200 | 0.637878 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuBigConvexData2.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_BIG_CONVEX_DATA2_H
#define GU_BIG_CONVEX_DATA2_H
#include "common/PxPhysXCommonConfig.h"
#include "common/PxMetaData.h"
#include "GuBigConvexData.h"
namespace physx
{
class PxSerializationContext;
class PxDeserializationContext;
class PX_PHYSX_COMMON_API BigConvexData : public PxUserAllocated
{
public:
// PX_SERIALIZATION
BigConvexData(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
BigConvexData();
~BigConvexData();
// Support vertex map
bool Load(PxInputStream& stream);
PxU32 ComputeOffset(const PxVec3& dir) const;
PxU32 ComputeNearestOffset(const PxVec3& dir) const;
// Data access
PX_INLINE PxU32 GetSubdiv() const { return mData.mSubdiv; }
PX_INLINE PxU32 GetNbSamples() const { return mData.mNbSamples; }
//~Support vertex map
// Valencies
// Data access
PX_INLINE PxU32 GetNbVerts() const { return mData.mNbVerts; }
PX_INLINE const Gu::Valency* GetValencies() const { return mData.mValencies; }
PX_INLINE PxU16 GetValency(PxU32 i) const { return mData.mValencies[i].mCount; }
PX_INLINE PxU16 GetOffset(PxU32 i) const { return mData.mValencies[i].mOffset; }
PX_INLINE const PxU8* GetAdjacentVerts() const { return mData.mAdjacentVerts; }
PX_INLINE PxU16 GetNbNeighbors(PxU32 i) const { return mData.mValencies[i].mCount; }
PX_INLINE const PxU8* GetNeighbors(PxU32 i) const { return &mData.mAdjacentVerts[mData.mValencies[i].mOffset]; }
// PX_SERIALIZATION
void exportExtraData(PxSerializationContext& stream);
void importExtraData(PxDeserializationContext& context);
//~PX_SERIALIZATION
Gu::BigConvexRawData mData;
protected:
void* mVBuffer;
// Internal methods
void CreateOffsets();
bool VLoad(PxInputStream& stream);
//~Valencies
friend class BigConvexDataBuilder;
};
}
#endif // BIG_CONVEX_DATA_H
| 3,780 | C | 41.011111 | 121 | 0.711376 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMeshData.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_CONVEX_MESH_DATA_H
#define GU_CONVEX_MESH_DATA_H
#include "foundation/PxPlane.h"
#include "foundation/PxBitAndData.h"
#include "foundation/PxIntrinsics.h"
#include "GuCenterExtents.h"
#include "CmSerialize.h"
#include "GuSDF.h"
// Data definition
namespace physx
{
namespace Gu
{
struct BigConvexRawData;
struct HullPolygonData
{
// PT: this structure won't be allocated with PX_NEW because polygons aren't allocated alone (with a dedicated alloc).
// Instead they are part of a unique allocation/buffer containing all data for the ConvexHullData class (polygons, followed by
// hull vertices, edge data, etc). As a result, ctors for embedded classes like PxPlane won't be called.
PxPlane mPlane; //!< Plane equation for this polygon //Could drop 4th elem as it can be computed from any vertex as: d = - p.dot(n);
PxU16 mVRef8; //!< Offset of vertex references in hull vertex data (CS: can we assume indices are tightly packed and offsets are ascending?? DrawObjects makes and uses this assumption)
PxU8 mNbVerts; //!< Number of vertices/edges in the polygon
PxU8 mMinIndex; //!< Index of the polygon vertex that has minimal projection along this plane's normal.
PX_FORCE_INLINE PxReal getMin(const PxVec3* PX_RESTRICT hullVertices) const //minimum of projection of the hull along this plane normal
{
return mPlane.n.dot(hullVertices[mMinIndex]);
}
PX_FORCE_INLINE PxReal getMax() const { return -mPlane.d; } //maximum of projection of the hull along this plane normal
};
PX_FORCE_INLINE void flipData(Gu::HullPolygonData& data)
{
flip(data.mPlane.n.x);
flip(data.mPlane.n.y);
flip(data.mPlane.n.z);
flip(data.mPlane.d);
flip(data.mVRef8);
}
// PT: if this one breaks, please make sure the 'flipData' function is properly updated.
PX_COMPILE_TIME_ASSERT(sizeof(Gu::HullPolygonData) == 20);
// TEST_INTERNAL_OBJECTS
struct InternalObjectsData
{
PxReal mRadius;
PxReal mExtents[3];
PX_FORCE_INLINE void reset()
{
mRadius = 0.0f;
mExtents[0] = 0.0f;
mExtents[1] = 0.0f;
mExtents[2] = 0.0f;
}
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::InternalObjectsData) == 16);
//~TEST_INTERNAL_OBJECTS
struct ConvexHullData
{
// PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading
CenterExtents mAABB; //!< bounds TODO: compute this on the fly from first 6 vertices in the vertex array. We'll of course need to sort the most extreme ones to the front.
PxVec3 mCenterOfMass; //in local space of mesh!
// PT: WARNING: mNbHullVertices *must* appear before mBigConvexRawData for ConvX to be able to do "big raw data" surgery
PxBitAndWord mNbEdges; //!<the highest bit indicate whether we have grb data, the other 15 bits indicate the number of edges in this convex hull
PxU8 mNbHullVertices; //!< Number of vertices in the convex hull
PxU8 mNbPolygons; //!< Number of planar polygons composing the hull
HullPolygonData* mPolygons; //!< Array of mNbPolygons structures
BigConvexRawData* mBigConvexRawData; //!< Hill climbing data, only for large convexes! else NULL.
// SDF data
SDF* mSdfData;
// TEST_INTERNAL_OBJECTS
InternalObjectsData mInternal;
//~TEST_INTERNAL_OBJECTS
PX_FORCE_INLINE ConvexHullData(const PxEMPTY) : mNbEdges(PxEmpty)
{
}
PX_FORCE_INLINE ConvexHullData()
{
}
PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const
{
// PT: see compile-time assert at the end of file
return static_cast<const CenterExtentsPadded&>(mAABB);
}
PX_FORCE_INLINE const PxVec3* getHullVertices() const //!< Convex hull vertices
{
const char* tmp = reinterpret_cast<const char*>(mPolygons);
tmp += sizeof(Gu::HullPolygonData) * mNbPolygons;
return reinterpret_cast<const PxVec3*>(tmp);
}
PX_FORCE_INLINE const PxU8* getFacesByEdges8() const //!< for each edge, gives 2 adjacent polygons; used by convex-convex code to come up with all the convex' edge normals.
{
const char* tmp = reinterpret_cast<const char*>(mPolygons);
tmp += sizeof(Gu::HullPolygonData) * mNbPolygons;
tmp += sizeof(PxVec3) * mNbHullVertices;
return reinterpret_cast<const PxU8*>(tmp);
}
PX_FORCE_INLINE const PxU8* getFacesByVertices8() const //!< for each edge, gives 2 adjacent polygons; used by convex-convex code to come up with all the convex' edge normals.
{
const char* tmp = reinterpret_cast<const char*>(mPolygons);
tmp += sizeof(Gu::HullPolygonData) * mNbPolygons;
tmp += sizeof(PxVec3) * mNbHullVertices;
tmp += sizeof(PxU8) * mNbEdges * 2;
return reinterpret_cast<const PxU8*>(tmp);
}
//If we don't build the convex hull with grb data, we will return NULL pointer
PX_FORCE_INLINE const PxU16* getVerticesByEdges16() const //!< Vertex indices indexed by unique edges
{
if (mNbEdges.isBitSet())
{
const char* tmp = reinterpret_cast<const char*>(mPolygons);
tmp += sizeof(Gu::HullPolygonData) * mNbPolygons;
tmp += sizeof(PxVec3) * mNbHullVertices;
tmp += sizeof(PxU8) * mNbEdges * 2;
tmp += sizeof(PxU8) * mNbHullVertices * 3;
return reinterpret_cast<const PxU16*>(tmp);
}
return NULL;
}
PX_FORCE_INLINE const PxU8* getVertexData8() const //!< Vertex indices indexed by hull polygons
{
const char* tmp = reinterpret_cast<const char*>(mPolygons);
tmp += sizeof(Gu::HullPolygonData) * mNbPolygons;
tmp += sizeof(PxVec3) * mNbHullVertices;
tmp += sizeof(PxU8) * mNbEdges * 2;
tmp += sizeof(PxU8) * mNbHullVertices * 3;
if (mNbEdges.isBitSet())
tmp += sizeof(PxU16) * mNbEdges * 2;
return reinterpret_cast<const PxU8*>(tmp);
}
PX_FORCE_INLINE bool checkExtentRadiusRatio() const
{
const PxReal maxR = PxMax(mInternal.mExtents[0], PxMax(mInternal.mExtents[1], mInternal.mExtents[2]));
const PxReal minR = mInternal.mRadius;
const PxReal ratio = maxR/minR;
return ratio < 100.f;
}
};
#if PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(Gu::ConvexHullData) == 80);
#else
PX_COMPILE_TIME_ASSERT(sizeof(Gu::ConvexHullData) == 68);
#endif
// 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(Gu::ConvexHullData, mCenterOfMass)>=PX_OFFSET_OF(Gu::ConvexHullData, mAABB)+4);
} // namespace Gu
}
//#pragma PX_POP_PACK
#endif
| 8,057 | C | 37.555024 | 188 | 0.723967 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuShapeConvex.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_SHAPECONVEX_H
#define GU_SHAPECONVEX_H
#include "GuConvexMeshData.h"
#include "CmScaling.h"
namespace physx
{
namespace Gu
{
struct PolygonalData;
typedef void (*HullPrefetchCB) (PxU32 numVerts, const PxVec3* PX_RESTRICT verts);
typedef void (*HullProjectionCB) (const PolygonalData& data, const PxVec3& dir, const PxMat34& world2hull, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum);
typedef PxU32 (*SelectClosestEdgeCB) (const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localDirection);
struct PolygonalData
{
// Data
Gu::InternalObjectsData mInternal;
PxMeshScale mScale;
PxVec3 mCenter;
PxU32 mNbVerts;
PxU32 mNbPolygons;
PxU32 mNbEdges;
const Gu::HullPolygonData* mPolygons;
const PxVec3* mVerts;
const PxU8* mPolygonVertexRefs;
const PxU8* mFacesByEdges;
const PxU16* mVerticesByEdges;
union
{
const Gu::BigConvexRawData* mBigData; // Only for big convexes
const PxVec3* mHalfSide; // Only for boxes
};
// Code
HullProjectionCB mProjectHull;
SelectClosestEdgeCB mSelectClosestEdgeCB;
PX_FORCE_INLINE const PxU8* getPolygonVertexRefs(const Gu::HullPolygonData& poly) const
{
return mPolygonVertexRefs + poly.mVRef8;
}
};
#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 PolygonalBox
{
public:
PolygonalBox(const PxVec3& halfSide);
void getPolygonalData(PolygonalData* PX_RESTRICT dst) const;
const PxVec3& mHalfSide;
PxVec3 mVertices[8];
Gu::HullPolygonData mPolygons[6];
private:
PolygonalBox& operator=(const PolygonalBox&);
};
#if PX_VC
#pragma warning(pop)
#endif
void getPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling);
}
}
#endif
| 3,727 | C | 35.910891 | 187 | 0.738395 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexUtilsInternal.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/PxBounds3.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "GuConvexUtilsInternal.h"
#include "GuBoxConversion.h"
#include "GuConvexMesh.h"
#include "CmScaling.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
void Gu::computeHullOBB(Box& hullOBB, const PxBounds3& hullAABB, float offset,
const PxMat34& convexPose,
const PxMat34& meshPose, const FastVertex2ShapeScaling& meshScaling, bool idtScaleMesh)
{
// transform bounds = mesh space
const PxMat34 m0to1 = meshPose.transformTranspose(convexPose);
hullOBB.extents = hullAABB.getExtents() + PxVec3(offset);
hullOBB.center = m0to1.transform(hullAABB.getCenter());
hullOBB.rot = m0to1.m;
if(!idtScaleMesh)
meshScaling.transformQueryBounds(hullOBB.center, hullOBB.extents, hullOBB.rot);
}
void Gu::computeVertexSpaceOBB(Box& dst, const Box& src, const PxTransform& meshPose, const PxMeshScale& meshScale)
{
// AP scaffold failure in x64 debug in GuConvexUtilsInternal.cpp
//PX_ASSERT("Performance warning - this path shouldn't execute for identity mesh scale." && !meshScale.isIdentity());
dst = transform(meshScale.getInverse() * Matrix34FromTransform(meshPose.getInverse()), src);
}
void Gu::computeOBBAroundConvex(
Box& obb, const PxConvexMeshGeometry& convexGeom, const PxConvexMesh* cm, const PxTransform& convexPose)
{
const CenterExtents& aabb = static_cast<const Gu::ConvexMesh*>(cm)->getLocalBoundsFast();
if(convexGeom.scale.isIdentity())
{
const PxMat33Padded m(convexPose.q);
obb = Gu::Box(m.transform(aabb.mCenter) + convexPose.p, aabb.mExtents, m);
}
else
{
obb = transform(Matrix34FromTransform(convexPose) * toMat33(convexGeom.scale), Box(aabb.mCenter, aabb.mExtents, PxMat33(PxIdentity)));
}
}
| 3,474 | C++ | 42.987341 | 136 | 0.764824 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexHelper.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/PxUtilities.h"
#include "GuConvexHelper.h"
#include "GuInternal.h"
#include "GuConvexMesh.h"
using namespace physx;
using namespace Gu;
// PT: we can't call alloca in a function and we want to avoid defines or duplicating the code. This makes it a bit tricky to write.
void Gu::getScaledConvex( PxVec3*& scaledVertices, PxU8*& scaledIndices, PxVec3* dstVertices, PxU8* dstIndices,
bool idtConvexScale, const PxVec3* srcVerts, const PxU8* srcIndices, PxU32 nbVerts, const Cm::FastVertex2ShapeScaling& convexScaling)
{
//pretransform convex polygon if we have scaling!
if(idtConvexScale) // PT: the scale is always 1 for boxes so no need to test the type
{
scaledVertices = const_cast<PxVec3*>(srcVerts);
scaledIndices = const_cast<PxU8*>(srcIndices);
}
else
{
scaledIndices = dstIndices;
scaledVertices = dstVertices;
for(PxU32 i=0; i<nbVerts; i++)
{
scaledIndices[i] = PxTo8(i); //generate trivial indexing.
scaledVertices[i] = convexScaling * srcVerts[srcIndices[i]];
}
}
}
bool Gu::getConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData)
{
const bool idtScale = shapeConvex.scale.isIdentity();
if(!idtScale)
scaling.init(shapeConvex.scale);
// PT: this version removes all the FCMPs and almost all LHS. This is temporary until
// the legacy 3x3 matrix totally vanishes but meanwhile do NOT do useless matrix conversions,
// it's a perfect recipe for LHS.
const ConvexHullData* hullData = _getHullData(shapeConvex);
PX_ASSERT(!hullData->mAABB.isEmpty());
bounds = hullData->mAABB.transformFast(scaling.getVertex2ShapeSkew());
getPolygonalData_Convex(&polyData, hullData, scaling);
// PT: non-uniform scaling invalidates the "internal objects" optimization, since our internal sphere
// might become an ellipsoid or something. Just disable the optimization if scaling is used...
if(!idtScale)
polyData.mInternal.reset();
return idtScale;
}
PxU32 Gu::findUniqueConvexEdges(PxU32 maxNbEdges, ConvexEdge* PX_RESTRICT edges, PxU32 numPolygons, const Gu::HullPolygonData* PX_RESTRICT polygons, const PxU8* PX_RESTRICT vertexData)
{
PxU32 nbEdges = 0;
while(numPolygons--)
{
const HullPolygonData& polygon = *polygons++;
const PxU8* vRefBase = vertexData + polygon.mVRef8;
PxU32 numEdges = polygon.mNbVerts;
PxU32 a = numEdges - 1;
PxU32 b = 0;
while(numEdges--)
{
PxU8 vi0 = vRefBase[a];
PxU8 vi1 = vRefBase[b];
if(vi1 < vi0)
{
PxU8 tmp = vi0;
vi0 = vi1;
vi1 = tmp;
}
bool found=false;
for(PxU32 i=0;i<nbEdges;i++)
{
if(edges[i].vref0==vi0 && edges[i].vref1==vi1)
{
found = true;
edges[i].normal += polygon.mPlane.n;
break;
}
}
if(!found)
{
if(nbEdges==maxNbEdges)
{
PX_ALWAYS_ASSERT_MESSAGE("Internal error: max nb edges reached. This shouldn't be possible...");
return nbEdges;
}
edges[nbEdges].vref0 = vi0;
edges[nbEdges].vref1 = vi1;
edges[nbEdges].normal = polygon.mPlane.n;
nbEdges++;
}
a = b;
b++;
}
}
return nbEdges;
}
| 4,828 | C++ | 34.507353 | 184 | 0.725973 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuHillClimbing.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_HILL_CLIMBING_H
#define GU_HILL_CLIMBING_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
struct BigConvexRawData;
}
void localSearch(PxU32& id, const PxVec3& dir, const PxVec3* verts, const Gu::BigConvexRawData* val);
}
#endif
| 1,973 | C | 42.866666 | 102 | 0.763305 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexUtilsInternal.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_CONVEX_UTILS_INTERNALS_H
#define GU_CONVEX_UTILS_INTERNALS_H
#include "foundation/Px.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
class PxMeshScale;
class PxConvexMeshGeometry;
class PxConvexMesh;
namespace Cm
{
class FastVertex2ShapeScaling;
}
namespace Gu
{
class Box;
void computeHullOBB(
Gu::Box& hullOBB, const PxBounds3& hullAABB, float offset, const PxMat34& world0,
const PxMat34& world1, const Cm::FastVertex2ShapeScaling& meshScaling, bool idtScaleMesh);
// src = input
// computes a box in vertex space (including skewed scale) from src world box
void computeVertexSpaceOBB(Gu::Box& dst, const Gu::Box& src, const PxTransform& meshPose, const PxMeshScale& meshScale);
PX_PHYSX_COMMON_API void computeOBBAroundConvex(
Gu::Box& obb, const PxConvexMeshGeometry& convexGeom, const PxConvexMesh* cm, const PxTransform& convexPose);
} // namespace Gu
}
#endif
| 2,614 | C | 38.621212 | 121 | 0.767789 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexEdgeFlags.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_CONVEX_EDGE_FLAGS_H
#define GU_CONVEX_EDGE_FLAGS_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
namespace Gu
{
enum ExtraTrigDataFlag
{
ETD_SILHOUETTE_EDGE_01 = (1 << 0), //First edge is a silhouette edge
ETD_SILHOUETTE_EDGE_12 = (1 << 1), //Second edge is a silhouette edge
ETD_SILHOUETTE_EDGE_20 = (1 << 2), //Third edge is a silhouette edge
ETD_CONVEX_EDGE_01 = (1<<3), // PT: important value, don't change
ETD_CONVEX_EDGE_12 = (1<<4), // PT: important value, don't change
ETD_CONVEX_EDGE_20 = (1<<5), // PT: important value, don't change
ETD_CONVEX_EDGE_ALL = ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_12|ETD_CONVEX_EDGE_20
};
// PT: helper function to make sure we use the proper default flags everywhere
PX_FORCE_INLINE PxU8 getConvexEdgeFlags(const PxU8* extraTrigData, PxU32 triangleIndex)
{
return extraTrigData ? extraTrigData[triangleIndex] : PxU8(ETD_CONVEX_EDGE_ALL);
}
PX_FORCE_INLINE void flipConvexEdgeFlags(PxU8& extraData)
{
// PT: this is a fix for PX-2327. When we flip the winding we also need to flip the precomputed edge flags.
// 01 => 02
// 12 => 21
// 20 => 10
const PxU8 convex01 = extraData & Gu::ETD_CONVEX_EDGE_01;
const PxU8 convex12 = extraData & Gu::ETD_CONVEX_EDGE_12;
const PxU8 convex20 = extraData & Gu::ETD_CONVEX_EDGE_20;
const PxU8 silhouette01 = extraData & Gu::ETD_SILHOUETTE_EDGE_01;
const PxU8 silhouette12 = extraData & Gu::ETD_SILHOUETTE_EDGE_12;
const PxU8 silhouette20 = extraData & Gu::ETD_SILHOUETTE_EDGE_20;
extraData = convex12|silhouette12;
if(convex01)
extraData |= Gu::ETD_CONVEX_EDGE_20;
if(convex20)
extraData |= Gu::ETD_CONVEX_EDGE_01;
if(silhouette01)
extraData |= Gu::ETD_SILHOUETTE_EDGE_20;
if(silhouette20)
extraData |= Gu::ETD_SILHOUETTE_EDGE_01;
}
}
}
#endif
| 3,511 | C | 41.313253 | 109 | 0.733979 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepPrimitives.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 "GuVecCapsule.h"
#include "GuVecBox.h"
#include "GuVecConvexHull.h"
#include "GuVecTriangle.h"
#include "GuGJKRaycast.h"
#include "GuCCDSweepConvexMesh.h"
#include "GuGJKType.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxCustomGeometry.h"
//#define USE_VIRTUAL_GJK
namespace physx
{
namespace Gu
{
using namespace aos;
template<typename Geom> PX_FORCE_INLINE PxReal getRadius(const PxGeometry&)
{
return 0;
}
template<> PX_FORCE_INLINE PxReal getRadius<CapsuleV>(const PxGeometry& g)
{
PX_ASSERT(g.getType() == PxGeometryType::eCAPSULE || g.getType() == PxGeometryType::eSPHERE);
PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxSphereGeometry, radius) == PX_OFFSET_OF(PxCapsuleGeometry, radius));
return static_cast<const PxSphereGeometry&>(g).radius;
}
#ifdef USE_VIRTUAL_GJK
static bool virtualGjkRaycastPenetration(const GjkConvex& a, const GjkConvex& 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)
{
return gjkRaycastPenetration<GjkConvex, GjkConvex >(a, b, initialDir, initialLambda, s, r, lambda, normal, closestA, _inflation, initialOverlap);
}
#endif
template<class ConvexA, class ConvexB>
static PX_FORCE_INLINE PxReal CCDSweep( ConvexA& a, ConvexB& b, const PxTransform32& transform0, const PxTransform32& transform1, const PxTransform32& lastTm0, const PxTransform32& lastTm1,
const aos::FloatV& toiEstimate, PxVec3& worldPoint, PxVec3& worldNormal, PxReal inflation = 0.0f)
{
PX_UNUSED(toiEstimate); //KS - TODO - can we use this again?
using namespace aos;
const QuatV q0 = QuatVLoadA(&transform0.q.x);
const Vec3V p0 = V3LoadA(&lastTm0.p.x);
const QuatV q1 = QuatVLoadA(&transform1.q.x);
const Vec3V p1 = V3LoadA(&lastTm1.p.x);
const PxTransformV tr0(p0, q0);
const PxTransformV tr1(p1, q1);
const PxMatTransformV aToB(tr1.transformInv(tr0));
const Vec3V trans0p = V3LoadA(transform0.p);
const Vec3V trans1p = V3LoadA(transform1.p);
const Vec3V trA = V3Sub(trans0p, p0);
const Vec3V trB = V3Sub(trans1p, p1);
const Vec3V relTr = tr1.rotateInv(V3Sub(trB, trA));
FloatV lambda;
Vec3V closestA, normal;
const FloatV initialLambda = FZero();
const RelativeConvex<ConvexA> convexA(a, aToB);
const LocalConvex<ConvexB> convexB(b);
#ifdef USE_VIRTUAL_GJK
if(virtualGjkRaycastPenetration(convexA, convexB, aToB.p, initialLambda, V3Zero(), relTr, lambda, normal, closestA, inflation, true))
#else
if(gjkRaycastPenetration<RelativeConvex<ConvexA>, LocalConvex<ConvexB> >(convexA, convexB, aToB.p, initialLambda, V3Zero(), relTr, lambda, normal, closestA, inflation, true))
#endif
{
//Adjust closestA because it will be on the surface of convex a in its initial position (s). If the TOI > 0, we need to move
//the point along the sweep direction to get the world-space hit position.
PxF32 res;
FStore(lambda, &res);
closestA = V3ScaleAdd(trA, FMax(lambda, FZero()), tr1.transform(closestA));
normal = tr1.rotate(normal);
V3StoreU(normal, worldNormal);
V3StoreU(closestA, worldPoint);
return res;
}
return PX_MAX_REAL;
}
//
// lookup table for geometry-vs-geometry sweeps
//
PxReal UnimplementedSweep (GU_SWEEP_METHOD_ARGS_UNUSED)
{
return PX_MAX_REAL; //no impact
}
template<typename Geom0, typename Geom1>
static PxReal SweepGeomGeom(GU_SWEEP_METHOD_ARGS)
{
PX_UNUSED(outCCDFaceIndex);
PX_UNUSED(fastMovingThreshold);
const PxGeometry& g0 = *shape0.mGeometry;
const PxGeometry& g1 = *shape1.mGeometry;
typename ConvexGeom<Geom0>::Type geom0(g0);
typename ConvexGeom<Geom1>::Type geom1(g1);
return CCDSweep(geom0, geom1, transform0, transform1, lastTm0, lastTm1, FLoad(toiEstimate), worldPoint, worldNormal, restDistance+getRadius<Geom0>(g0)+getRadius<Geom1>(g1) );
}
static PxReal SweepAnyShapeCustom(GU_SWEEP_METHOD_ARGS)
{
PX_UNUSED(fastMovingThreshold);
PX_UNUSED(toiEstimate);
PX_UNUSED(restDistance);
const PxGeometry& g0 = *shape0.mGeometry;
const PxGeometry& g1 = *shape1.mGeometry;
PX_ASSERT(g1.getType() == PxGeometryType::eCUSTOM);
const PxVec3 trA = transform0.p - lastTm0.p;
const PxVec3 trB = transform1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
PxVec3 unitDir = relTr;
const PxReal length = unitDir.normalize();
PxGeomSweepHit sweepHit;
if (!static_cast<const PxCustomGeometry&>(g1).callbacks->sweep(unitDir, length, g1, lastTm1, g0, lastTm0, sweepHit, PxHitFlag::eDEFAULT, 0.0f, NULL))
return PX_MAX_REAL;
worldNormal = sweepHit.normal;
worldPoint = sweepHit.position;
outCCDFaceIndex = sweepHit.faceIndex;
return sweepHit.distance / length;
}
typedef PxReal (*SweepMethod) (GU_SWEEP_METHOD_ARGS);
PxReal SweepAnyShapeHeightfield(GU_SWEEP_METHOD_ARGS);
PxReal SweepAnyShapeMesh(GU_SWEEP_METHOD_ARGS);
SweepMethod g_SweepMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eSPHERE
UnimplementedSweep, //PxGeometryType::ePLANE
SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eCAPSULE
SweepGeomGeom<CapsuleV, BoxV>, //PxGeometryType::eBOX
SweepGeomGeom<CapsuleV, ConvexHullV>, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH
SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
UnimplementedSweep, //PxGeometryType::ePLANE
UnimplementedSweep, //PxGeometryType::eCAPSULE
UnimplementedSweep, //PxGeometryType::eBOX
UnimplementedSweep, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH
UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
UnimplementedSweep, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eCAPSULE
SweepGeomGeom<CapsuleV, BoxV>, //PxGeometryType::eBOX
SweepGeomGeom<CapsuleV, ConvexHullV>, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH
SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
SweepGeomGeom<BoxV, BoxV>, //PxGeometryType::eBOX
SweepGeomGeom<BoxV, ConvexHullV>, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH
SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
SweepGeomGeom<ConvexHullV, ConvexHullV>, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH
SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH
UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
UnimplementedSweep, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH
UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH
UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
UnimplementedSweep, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH
UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM
UnimplementedSweep, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
SweepAnyShapeCustom, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_SweepMethodTable) / sizeof(g_SweepMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
PxReal SweepShapeShape(GU_SWEEP_METHOD_ARGS)
{
const PxGeometryType::Enum type0 = shape0.mGeometry->getType();
const PxGeometryType::Enum type1 = shape1.mGeometry->getType();
return g_SweepMethodTable[type0][type1](shape0, shape1, transform0, transform1, lastTm0, lastTm1,
restDistance, worldNormal, worldPoint, toiEstimate, outCCDFaceIndex, fastMovingThreshold);
}
//
// lookup table for sweeps agains triangles
//
PxReal UnimplementedTriangleSweep(GU_TRIANGLE_SWEEP_METHOD_ARGS)
{
PX_UNUSED(shape0);
PX_UNUSED(shape1);
PX_UNUSED(transform0);
PX_UNUSED(transform1);
PX_UNUSED(lastTm0);
PX_UNUSED(lastTm1);
PX_UNUSED(restDistance);
PX_UNUSED(worldNormal);
PX_UNUSED(worldPoint);
PX_UNUSED(meshScaling);
PX_UNUSED(triangle);
PX_UNUSED(toiEstimate);
return 1e10f; //no impact
}
template<typename Geom>
PxReal SweepGeomTriangles(GU_TRIANGLE_SWEEP_METHOD_ARGS)
{
PX_UNUSED(meshScaling);
PX_UNUSED(shape1);
const PxGeometry& g = shape0;
//Geom geom(g);
typename ConvexGeom<Geom>::Type geom(g);
return CCDSweep<TriangleV, Geom>(triangle, geom, transform1, transform0, lastTm1, lastTm0, FLoad(toiEstimate), worldPoint, worldNormal, restDistance+getRadius<Geom>(g) );
}
typedef PxReal (*TriangleSweepMethod) (GU_TRIANGLE_SWEEP_METHOD_ARGS);
TriangleSweepMethod g_TriangleSweepMethodTable[] =
{
SweepGeomTriangles<CapsuleV>, //PxGeometryType::eSPHERE
UnimplementedTriangleSweep, //PxGeometryType::ePLANE
SweepGeomTriangles<CapsuleV>, //PxGeometryType::eCAPSULE
SweepGeomTriangles<BoxV>, //PxGeometryType::eBOX
SweepGeomTriangles<ConvexHullV>, //PxGeometryType::eCONVEXMESH
UnimplementedTriangleSweep, //PxGeometryType::ePARTICLESYSTEM
UnimplementedTriangleSweep, //PxGeometryType::eTETRAHEDRONMESH
UnimplementedTriangleSweep, //PxGeometryType::eTRIANGLEMESH
UnimplementedTriangleSweep, //PxGeometryType::eHEIGHTFIELD
UnimplementedTriangleSweep, //PxGeometryType::eHAIRSYSTEM
UnimplementedTriangleSweep, //PxGeometryType::eCUSTOM
};
PX_COMPILE_TIME_ASSERT(sizeof(g_TriangleSweepMethodTable) / sizeof(g_TriangleSweepMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
PxReal SweepShapeTriangle(GU_TRIANGLE_SWEEP_METHOD_ARGS)
{
const PxGeometryType::Enum type0 = shape0.getType();
const TriangleSweepMethod method = g_TriangleSweepMethodTable[type0];
return method(shape0, shape1, transform0, transform1, lastTm0, lastTm1, restDistance, worldNormal, worldPoint, meshScaling, triangle, toiEstimate);
}
}
}
| 15,925 | C++ | 37.283654 | 216 | 0.727598 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepConvexMesh.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 "GuVecCapsule.h"
#include "GuVecBox.h"
#include "GuVecConvexHull.h"
#include "GuVecTriangle.h"
#include "GuGJKRaycast.h"
#include "GuCCDSweepConvexMesh.h"
#include "GuHeightFieldUtil.h"
#include "foundation/PxInlineArray.h"
#include "GuEntityReport.h"
#include "PxContact.h"
#include "GuDistancePointTriangle.h"
#include "GuBox.h"
#include "GuInternal.h"
#include "GuBoxConversion.h"
#include "GuConvexUtilsInternal.h"
#include "GuMidphaseInterface.h"
#include "geometry/PxGeometryQuery.h"
// PT: this one makes the "behavior after impact" PEEL test "fail" (rocks stop after impact)
// It also makes these UTs fail:
// [ FAILED ] CCDReportTest.CCD_soakTest_mesh
// [ FAILED ] CCDNegativeScalingTest.SLOW_ccdNegScaledMesh
static const bool gUseGeometryQuery = false;
// PT: this one seems to work.
// Timings for PEEL's "limits of speculative contacts test2", for 3 runs:
// false: true:
// Time: 504 220
// Time: 89 7
// Time: 5 84
// Time: 8 11
// Time: 423 56
// Time: 103 14
// Time: 10 11
// Time: 10 9
// Time: 418 60
// Time: 139 17
// Time: 9 9
// Time: 9 10
static const bool gUseGeometryQueryEst = false;
//#define CCD_BASIC_PROFILING
#ifdef CCD_BASIC_PROFILING
#include <stdio.h>
#endif
namespace physx
{
namespace Gu
{
PxReal SweepShapeTriangle(GU_TRIANGLE_SWEEP_METHOD_ARGS);
using namespace aos;
namespace
{
struct AccumCallback: public MeshHitCallback<PxGeomRaycastHit>
{
PX_NOCOPY(AccumCallback)
public:
PxInlineArray<PxU32, 64>& mResult;
AccumCallback(PxInlineArray<PxU32, 64>& result)
: MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE),
mResult(result)
{
}
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const PxGeomRaycastHit& hit, const PxVec3&, const PxVec3&, const PxVec3&, PxReal&, const PxU32*)
{
mResult.pushBack(hit.faceIndex);
return true;
}
};
// PT: TODO: refactor with MidPhaseQueryLocalReport
struct EntityReportContainerCallback : public OverlapReport
{
PxInlineArray<PxU32, 64>& container;
EntityReportContainerCallback(PxInlineArray<PxU32,64>& container_) : container(container_)
{
container.forceSize_Unsafe(0);
}
virtual ~EntityReportContainerCallback() {}
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
for(PxU32 i=0; i<nb; i++)
container.pushBack(indices[i]);
return true;
}
private:
EntityReportContainerCallback& operator=(const EntityReportContainerCallback&);
};
class TriangleHelper
{
public:
TriangleHelper(const PxTriangleMeshGeometry& shapeMesh,
const Cm::FastVertex2ShapeScaling& skew, // object is not copied, beware!
const PxU32 triangleIndex);
void getBounds(PxBounds3& bounds, const physx::PxTransform& transform) const;
//non-virtuals:
PX_FORCE_INLINE const TriangleMesh* getMeshData() const { return _getMeshData(mShapeMesh); }
PxVec3 getPolygonNormal() const;
private:
TriangleHelper& operator=(const TriangleHelper&);
const PxTriangleMeshGeometry& mShapeMesh;
const Cm::FastVertex2ShapeScaling& mVertex2ShapeSkew;
const PxU32 mTriangleIndex;
};
TriangleHelper::TriangleHelper(const PxTriangleMeshGeometry& md, const Cm::FastVertex2ShapeScaling& skew, const PxU32 tg)
: mShapeMesh(md), mVertex2ShapeSkew(skew), mTriangleIndex(tg)
{
}
void TriangleHelper::getBounds(PxBounds3& bounds, const physx::PxTransform& transform) const
{
PxTriangle localTri;
getMeshData()->getLocalTriangle(localTri, mTriangleIndex, false); // PT: 'false': no need to flip winding to compute bounds
//gotta take bounds in shape space because building it in vertex space and transforming it out would skew it.
bounds = PxBounds3::empty();
bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[0]));
bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[1]));
bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[2]));
}
PxVec3 TriangleHelper::getPolygonNormal() const
{
PxTriangle localTri;
getMeshData()->getLocalTriangle(localTri, mTriangleIndex, mVertex2ShapeSkew.flipsNormal());
const PxVec3 t0 = mVertex2ShapeSkew * localTri.verts[0];
const PxVec3 t1 = mVertex2ShapeSkew * localTri.verts[1];
const PxVec3 t2 = mVertex2ShapeSkew * localTri.verts[2];
const PxVec3 v0 = t0 - t1;
const PxVec3 v1 = t0 - t2;
const PxVec3 nor = v0.cross(v1);
return nor.getNormalized();
}
}
PxReal SweepAnyShapeHeightfield(GU_SWEEP_METHOD_ARGS)
{
PX_UNUSED(toiEstimate);
PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eHEIGHTFIELD);
const HeightFieldUtil hfUtil(static_cast<const PxHeightFieldGeometry&>(*shape1.mGeometry));
PxInlineArray<PxU32,64> tempContainer;
EntityReportContainerCallback callback(tempContainer);
const PxVec3 trA = transform0.p - lastTm0.p;
const PxVec3 trB = transform1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
const PxVec3 halfRelTr = relTr * 0.5f;
const PxVec3 ext = shape0.mExtents + halfRelTr.abs() + PxVec3(restDistance);
const PxVec3 cent = shape0.mCenter + halfRelTr;
const PxBounds3 bounds0(cent - ext, cent + ext);
hfUtil.overlapAABBTriangles(transform1, bounds0, callback);
PxArray<PxU32> orderedContainer(tempContainer.size());
PxArray<PxU32> distanceEntries(tempContainer.size());
PxU32* orderedList = orderedContainer.begin();
PxF32* distances = reinterpret_cast<PxF32*>(distanceEntries.begin());
const PxVec3 origin = shape0.mCenter;
const PxVec3 extent = shape0.mExtents + PxVec3(restDistance);
PxReal minTOI = PX_MAX_REAL;
PxU32 numTrigs = tempContainer.size();
PxU32* trianglesIndices = tempContainer.begin();
PxU32 count = 0;
for(PxU32 a = 0; a < numTrigs; ++a)
{
PxTriangle tri;
hfUtil.getTriangle(shape1.mPrevTransform, tri, 0, 0, trianglesIndices[a], true, true);
PxVec3 resultNormal = -(tri.verts[1]-tri.verts[0]).cross(tri.verts[2]-tri.verts[0]);
resultNormal.normalize();
if(relTr.dot(resultNormal) >= fastMovingThreshold)
{
PxBounds3 bounds;
bounds.setEmpty();
bounds.include(tri.verts[0]);
bounds.include(tri.verts[1]);
bounds.include(tri.verts[2]);
PxF32 toi = sweepAABBAABB(origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB);
PxU32 index = 0;
if(toi <= 1.f)
{
for(PxU32 b = count; b > 0; --b)
{
if(distances[b-1] <= toi)
{
//shuffle down and swap
index = b;
break;
}
PX_ASSERT(b > 0);
PX_ASSERT(b < numTrigs);
distances[b] = distances[b-1];
orderedList[b] = orderedList[b-1];
}
PX_ASSERT(index < numTrigs);
orderedList[index] = trianglesIndices[a];
distances[index] = toi;
count++;
}
}
}
worldNormal = PxVec3(PxReal(0));
worldPoint = PxVec3(PxReal(0));
Cm::FastVertex2ShapeScaling idScale;
PxU32 ccdFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
const PxVec3 sphereCenter(shape0.mPrevTransform.p);
const PxF32 inSphereRadius = shape0.mFastMovingThreshold;
const PxF32 inRadSq = inSphereRadius * inSphereRadius;
const PxVec3 sphereCenterInTr1 = transform1.transformInv(sphereCenter);
const PxVec3 sphereCenterInTr1T0 = transform1.transformInv(lastTm0.p);
PxVec3 tempWorldNormal(0.f), tempWorldPoint(0.f);
for (PxU32 ti = 0; ti < count; ti++)
{
PxTriangle tri;
hfUtil.getTriangle(lastTm1, tri, 0, 0, orderedList[ti], false, false);
PxVec3 resultNormal, resultPoint;
TriangleV triangle(V3LoadU(tri.verts[0]), V3LoadU(tri.verts[1]), V3LoadU(tri.verts[2]));
//do sweep
PxReal res = SweepShapeTriangle(
*shape0.mGeometry, *shape1.mGeometry, transform0, transform1, lastTm0, lastTm1, restDistance,
resultNormal, resultPoint, Cm::FastVertex2ShapeScaling(), triangle,
0.f);
if(res <= 0.f)
{
res = 0.f;
const PxVec3 v0 = tri.verts[1] - tri.verts[0];
const PxVec3 v1 = tri.verts[2] - tri.verts[0];
//Now we have a 0 TOI, lets see if the in-sphere hit it!
PxF32 distanceSq = distancePointTriangleSquared( sphereCenterInTr1, tri.verts[0], v0, v1);
if(distanceSq < inRadSq)
{
const PxVec3 nor = v0.cross(v1);
const PxF32 distance = PxSqrt(distanceSq);
res = distance - inSphereRadius;
const PxF32 d = nor.dot(tri.verts[0]);
const PxF32 dd = nor.dot(sphereCenterInTr1T0);
if((dd - d) > 0.f)
{
//back side, penetration
res = -(2.f * inSphereRadius - distance);
}
}
}
if (res < minTOI)
{
const PxVec3 v0 = tri.verts[1] - tri.verts[0];
const PxVec3 v1 = tri.verts[2] - tri.verts[0];
PxVec3 resultNormal1 = v0.cross(v1);
resultNormal1.normalize();
//if(norDotRel > 1e-6f)
{
tempWorldNormal = resultNormal1;
tempWorldPoint = resultPoint;
minTOI = res;
ccdFaceIndex = orderedList[ti];
}
}
}
worldNormal = transform1.rotate(tempWorldNormal);
worldPoint = tempWorldPoint;
outCCDFaceIndex = ccdFaceIndex;
return minTOI;
}
PxReal SweepEstimateAnyShapeHeightfield(GU_SWEEP_ESTIMATE_ARGS)
{
PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eHEIGHTFIELD);
const HeightFieldUtil hfUtil(static_cast<const PxHeightFieldGeometry&>(*shape1.mGeometry));
PxInlineArray<PxU32,64> tempContainer;
EntityReportContainerCallback callback(tempContainer);
const PxTransform& transform0 = shape0.mCurrentTransform;
const PxTransform& lastTr0 = shape0.mPrevTransform;
const PxTransform& transform1 = shape1.mCurrentTransform;
const PxTransform& lastTr1 = shape1.mPrevTransform;
const PxVec3 trA = transform0.p - lastTr0.p;
const PxVec3 trB = transform1.p - lastTr1.p;
const PxVec3 relTr = trA - trB;
const PxVec3 halfRelTr = relTr * 0.5f;
const PxVec3 extents = shape0.mExtents + halfRelTr.abs() + PxVec3(restDistance);
const PxVec3 center = shape0.mCenter + halfRelTr;
const PxBounds3 bounds0(center - extents, center + extents);
hfUtil.overlapAABBTriangles(transform1, bounds0, callback);
PxVec3 origin = shape0.mCenter;
PxVec3 extent = shape0.mExtents;
PxReal minTOI = PX_MAX_REAL;
PxU32 numTrigs = tempContainer.size();
PxU32* trianglesIndices = tempContainer.begin();
for(PxU32 a = 0; a < numTrigs; ++a)
{
PxTriangle tri;
hfUtil.getTriangle(shape1.mPrevTransform, tri, 0, 0, trianglesIndices[a], true, true);
PxVec3 resultNormal = -(tri.verts[1]-tri.verts[0]).cross(tri.verts[2]-tri.verts[0]);
resultNormal.normalize();
if(relTr.dot(resultNormal) >= fastMovingThreshold)
{
PxBounds3 bounds;
bounds.setEmpty();
bounds.include(tri.verts[0]);
bounds.include(tri.verts[1]);
bounds.include(tri.verts[2]);
PxF32 toi = sweepAABBAABB(origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB);
minTOI = PxMin(minTOI, toi);
}
}
return minTOI;
}
PxReal SweepAnyShapeMesh(GU_SWEEP_METHOD_ARGS)
{
PX_UNUSED(toiEstimate);
// this is the trimesh midphase for convex vs mesh sweep. shape0 is the convex shape.
const PxVec3 trA = transform0.p - lastTm0.p;
const PxVec3 trB = transform1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
PxVec3 unitDir = relTr;
const PxReal length = unitDir.normalize();
PX_UNUSED(restDistance);
PX_UNUSED(fastMovingThreshold);
if(gUseGeometryQuery)
{
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, lastTm0, *shape1.mGeometry, lastTm1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL))
//if(!PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, transform0, *shape1.mGeometry, transform1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL))
return PX_MAX_REAL;
worldNormal = sweepHit.normal;
worldPoint = sweepHit.position;
outCCDFaceIndex = sweepHit.faceIndex;
return sweepHit.distance/length;
}
else
{
// Get actual shape data
PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eTRIANGLEMESH);
const PxTriangleMeshGeometry& shapeMesh = static_cast<const PxTriangleMeshGeometry&>(*shape1.mGeometry);
const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale);
const PxMat33 matRot(PxIdentity);
//1) Compute the swept bounds
Box sweptBox;
computeSweptBox(sweptBox, shape0.mExtents, shape0.mCenter, matRot, unitDir, length);
Box vertexSpaceBox;
if (shapeMesh.scale.isIdentity())
vertexSpaceBox = transformBoxOrthonormal(sweptBox, transform1.getInverse());
else
computeVertexSpaceOBB(vertexSpaceBox, sweptBox, transform1, shapeMesh.scale);
vertexSpaceBox.extents += PxVec3(restDistance);
PxInlineArray<PxU32, 64> tempContainer;
AccumCallback callback(tempContainer);
// AP scaffold: early out opportunities, should probably use fat raycast
Midphase::intersectOBB(_getMeshData(shapeMesh), vertexSpaceBox, callback, true);
if (tempContainer.size() == 0)
return PX_MAX_REAL;
// Intersection found, fetch triangles
PxU32 numTrigs = tempContainer.size();
const PxU32* triangleIndices = tempContainer.begin();
PxVec3 origin = shape0.mCenter;
PxVec3 extent = shape0.mExtents + PxVec3(restDistance);
PxInlineArray<PxU32, 64> orderedContainer;
orderedContainer.resize(tempContainer.size());
PxInlineArray<PxU32, 64> distanceEntries;
distanceEntries.resize(tempContainer.size());
PxU32* orderedList = orderedContainer.begin();
PxF32* distances = reinterpret_cast<PxF32*>(distanceEntries.begin());
PxReal minTOI = PX_MAX_REAL;
PxU32 count = 0;
for(PxU32 a = 0; a < numTrigs; ++a)
{
const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, triangleIndices[a]);
const PxVec3 resultNormal = -transform1.rotate(convexPartOfMesh1.getPolygonNormal());
if(relTr.dot(resultNormal) >= fastMovingThreshold)
{
PxBounds3 bounds;
convexPartOfMesh1.getBounds(bounds, lastTm1);
//OK, we have all 3 vertices, now calculate bounds...
PxF32 toi = sweepAABBAABB(origin, extent, bounds.getCenter(), bounds.getExtents() + PxVec3(0.02f, 0.02f, 0.02f), trA, trB);
PxU32 index = 0;
if(toi <= 1.f)
{
for(PxU32 b = count; b > 0; --b)
{
if(distances[b-1] <= toi)
{
//shuffle down and swap
index = b;
break;
}
PX_ASSERT(b > 0);
PX_ASSERT(b < numTrigs);
distances[b] = distances[b-1];
orderedList[b] = orderedList[b-1];
}
PX_ASSERT(index < numTrigs);
orderedList[index] = triangleIndices[a];
distances[index] = toi;
count++;
}
}
}
PxVec3 tempWorldNormal(0.f), tempWorldPoint(0.f);
Cm::FastVertex2ShapeScaling idScale;
PxU32 ccdFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
const PxVec3 sphereCenter(lastTm1.p);
const PxF32 inSphereRadius = shape0.mFastMovingThreshold;
//PxF32 inRadSq = inSphereRadius * inSphereRadius;
const PxVec3 sphereCenterInTransform1 = transform1.transformInv(sphereCenter);
const PxVec3 sphereCenterInTransform0p = transform1.transformInv(lastTm0.p);
for (PxU32 ti = 0; ti < count /*&& PxMax(minTOI, 0.f) >= distances[ti]*/; ti++)
{
const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, orderedList[ti]);
PxVec3 resultNormal, resultPoint;
PxTriangle localTri;
_getMeshData(shapeMesh)->getLocalTriangle(localTri, orderedList[ti], meshScaling.flipsNormal());
const PxVec3 v0 = meshScaling * localTri.verts[0];
const PxVec3 v1 = meshScaling * localTri.verts[1];
const PxVec3 v2 = meshScaling * localTri.verts[2];
TriangleV triangle(V3LoadU(v0), V3LoadU(v1), V3LoadU(v2));
//do sweep
PxReal res = SweepShapeTriangle(
*shape0.mGeometry, *shape1.mGeometry, transform0, transform1, lastTm0, lastTm1, restDistance,
resultNormal, resultPoint, Cm::FastVertex2ShapeScaling(), triangle,
0.f);
resultNormal = -resultNormal;
if(res <= 0.f)
{
res = 0.f;
const PxF32 inRad = inSphereRadius + restDistance;
const PxF32 inRadSq = inRad*inRad;
const PxVec3 vv0 = v1 - v0;
const PxVec3 vv1 = v2 - v0;
const PxVec3 nor = vv0.cross(vv1);
//Now we have a 0 TOI, lets see if the in-sphere hit it!
const PxF32 distanceSq = distancePointTriangleSquared( sphereCenterInTransform1, v0, vv0, vv1);
if(distanceSq < inRadSq)
{
const PxF32 distance = PxSqrt(distanceSq);
res = distance - inRad;
const PxF32 d = nor.dot(v0);
const PxF32 dd = nor.dot(sphereCenterInTransform0p);
if((dd - d) < 0.f)
{
//back side, penetration
res = -(2.f * inRad - distance);
}
}
PX_ASSERT(PxIsFinite(res));
resultNormal = transform1.rotate(convexPartOfMesh1.getPolygonNormal());
}
if (res < minTOI)
{
tempWorldNormal = resultNormal;//convexPartOfMesh1.getPolygonNormal(0);//transform1.rotate(convexPartOfMesh1.getPolygonNormal(0));
tempWorldPoint = resultPoint;
minTOI = res;
ccdFaceIndex = orderedList[ti];
}
}
worldNormal = tempWorldNormal;//transform1.rotate(tempWorldNormal);
worldPoint = tempWorldPoint;
outCCDFaceIndex = ccdFaceIndex;
return minTOI;
}
}
/**
\brief This code performs a conservative estimate of the TOI of a shape v mesh.
*/
PxReal SweepEstimateAnyShapeMesh(GU_SWEEP_ESTIMATE_ARGS)
{
// this is the trimesh midphase for convex vs mesh sweep. shape0 is the convex shape.
// Get actual shape data
PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eTRIANGLEMESH);
const PxTriangleMeshGeometry& shapeMesh = static_cast<const PxTriangleMeshGeometry&>(*shape1.mGeometry);
const PxTransform& transform0 = shape0.mCurrentTransform;
const PxTransform& lastTr0 = shape0.mPrevTransform;
const PxTransform& transform1 = shape1.mCurrentTransform;
const PxTransform& lastTr1 = shape1.mPrevTransform;
const PxVec3 trA = transform0.p - lastTr0.p;
const PxVec3 trB = transform1.p - lastTr1.p;
const PxVec3 relTr = trA - trB;
PxVec3 unitDir = relTr;
const PxReal length = unitDir.normalize();
#ifdef CCD_BASIC_PROFILING
unsigned long long time = __rdtsc();
#endif
if(gUseGeometryQueryEst)
{
PX_UNUSED(restDistance);
PX_UNUSED(fastMovingThreshold);
PX_UNUSED(shapeMesh);
{
PxGeomSweepHit sweepHit;
bool status = PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, lastTr0, *shape1.mGeometry, lastTr1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL);
#ifdef CCD_BASIC_PROFILING
unsigned long long time2 = __rdtsc();
printf("Time: %d\n", PxU32(time2 - time)/1024);
#endif
return status ? sweepHit.distance/length : PX_MAX_REAL;
}
}
else
{
const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale);
const PxMat33 matRot(PxIdentity);
//1) Compute the swept bounds
Box sweptBox;
computeSweptBox(sweptBox, shape0.mExtents, shape0.mCenter, matRot, unitDir, length);
Box vertexSpaceBox;
computeVertexSpaceOBB(vertexSpaceBox, sweptBox, transform1, shapeMesh.scale);
vertexSpaceBox.extents += PxVec3(restDistance);
// TODO: implement a cached mode that fetches the trigs from a cache rather than per opcode if there is little motion.
struct CB : MeshHitCallback<PxGeomRaycastHit>
{
PxReal minTOI;
PxReal sumFastMovingThresh;
const PxTriangleMeshGeometry& shapeMesh;
const Cm::FastVertex2ShapeScaling& meshScaling;
const PxVec3& relTr;
const PxVec3& trA;
const PxVec3& trB;
const PxTransform& transform1;
const PxVec3& origin;
const PxVec3& extent;
CB(PxReal aSumFast, const PxTriangleMeshGeometry& aShapeMesh, const Cm::FastVertex2ShapeScaling& aMeshScaling,
const PxVec3& aRelTr, const PxVec3& atrA, const PxVec3& atrB, const PxTransform& aTransform1, const PxVec3& aOrigin, const PxVec3& aExtent)
: MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE),
sumFastMovingThresh(aSumFast), shapeMesh(aShapeMesh), meshScaling(aMeshScaling), relTr(aRelTr), trA(atrA), trB(atrB),
transform1(aTransform1), origin(aOrigin), extent(aExtent)
{
minTOI = PX_MAX_REAL;
}
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const PxGeomRaycastHit& hit, const PxVec3&, const PxVec3&, const PxVec3&, PxReal& shrunkMaxT, const PxU32*)
{
const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, hit.faceIndex);
const PxVec3 resultNormal = -transform1.rotate(convexPartOfMesh1.getPolygonNormal());
if(relTr.dot(resultNormal) >= sumFastMovingThresh)
{
PxBounds3 bounds;
convexPartOfMesh1.getBounds(bounds, transform1);
//OK, we have all 3 vertices, now calculate bounds...
PxF32 toi = sweepAABBAABB(
origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB);
minTOI = PxMin(minTOI, toi);
shrunkMaxT = minTOI;
}
return (minTOI > 0.0f); // stop traversal if minTOI == 0.0f
}
void operator=(const CB&) {}
};
const PxVec3& origin = shape0.mCenter;
const PxVec3 extent = shape0.mExtents + PxVec3(restDistance);
CB callback(fastMovingThreshold, shapeMesh, meshScaling, relTr, trA, trB, transform1, origin, extent);
Midphase::intersectOBB(_getMeshData(shapeMesh), vertexSpaceBox, callback, true);
#ifdef CCD_BASIC_PROFILING
unsigned long long time2 = __rdtsc();
printf("Time: %d\n", PxU32(time2 - time)/1024);
#endif
return callback.minTOI;
}
}
}
}
| 22,864 | C++ | 30.537931 | 186 | 0.723233 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepConvexMesh.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_CCD_SWEEP_CONVEX_MESH_H
#define GU_CCD_SWEEP_CONVEX_MESH_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecTransform.h"
#include "CmScaling.h"
#define GU_TRIANGLE_SWEEP_METHOD_ARGS \
const PxGeometry& shape0, \
const PxGeometry& shape1, \
const PxTransform32& transform0, \
const PxTransform32& transform1, \
const PxTransform32& lastTm0, \
const PxTransform32& lastTm1, \
PxReal restDistance, \
PxVec3& worldNormal, \
PxVec3& worldPoint, \
const Cm::FastVertex2ShapeScaling& meshScaling, \
Gu::TriangleV& triangle, \
const PxF32 toiEstimate
#define GU_SWEEP_METHOD_ARGS \
const Gu::CCDShape& shape0, \
const Gu::CCDShape& shape1, \
const PxTransform32& transform0, \
const PxTransform32& transform1, \
const PxTransform32& lastTm0, \
const PxTransform32& lastTm1, \
PxReal restDistance, \
PxVec3& worldNormal, \
PxVec3& worldPoint, \
const PxF32 toiEstimate, \
PxU32& outCCDFaceIndex, \
const PxReal fastMovingThreshold
#define GU_SWEEP_ESTIMATE_ARGS \
const CCDShape& shape0, \
const CCDShape& shape1, \
const PxReal restDistance, \
const PxReal fastMovingThreshold
#define GU_SWEEP_METHOD_ARGS_UNUSED \
const Gu::CCDShape& /*shape0*/, \
const Gu::CCDShape& /*shape1*/, \
const PxTransform32& /*transform0*/,\
const PxTransform32& /*transform1*/,\
const PxTransform32& /*lastTm0*/, \
const PxTransform32& /*lastTm1*/, \
PxReal /*restDistance*/, \
PxVec3& /*worldNormal*/, \
PxVec3& /*worldPoint*/, \
const PxF32 /*toiEstimate*/, \
PxU32& /*outCCDFaceIndex*/, \
const PxReal /*fastMovingThreshold*/
namespace physx
{
namespace Gu
{
struct CCDShape
{
const PxGeometry* mGeometry;
PxReal mFastMovingThreshold; //The CCD threshold for this shape
PxTransform mPrevTransform; //This shape's previous transform
PxTransform mCurrentTransform; //This shape's current transform
PxVec3 mExtents; //The extents of this shape's AABB
PxVec3 mCenter; //The center of this shape's AABB
PxU32 mUpdateCount; //How many times this shape has been updated in the CCD. This is correlated with the CCD body's update count.
};
PX_FORCE_INLINE PxF32 sweepAABBAABB(const PxVec3& centerA, const PxVec3& extentsA, const PxVec3& centerB, const PxVec3& extentsB, const PxVec3& trA, const PxVec3& trB)
{
//Sweep 2 AABBs against each other, return the TOI when they hit else PX_MAX_REAL if they don't hit
const PxVec3 cAcB = centerA - centerB;
const PxVec3 sumExtents = extentsA + extentsB;
//Initial hit
if(PxAbs(cAcB.x) <= sumExtents.x &&
PxAbs(cAcB.y) <= sumExtents.y &&
PxAbs(cAcB.z) <= sumExtents.z)
return 0.f;
//No initial hit - perform the sweep
const PxVec3 relTr = trB - trA;
PxF32 tfirst = 0.f;
PxF32 tlast = 1.f;
const PxVec3 aMax = centerA + extentsA;
const PxVec3 aMin = centerA - extentsA;
const PxVec3 bMax = centerB + extentsB;
const PxVec3 bMin = centerB - extentsB;
const PxF32 eps = 1e-6f;
for(PxU32 a = 0; a < 3; ++a)
{
if(relTr[a] < -eps)
{
if(bMax[a] < aMin[a])
return PX_MAX_REAL;
if(aMax[a] < bMin[a])
tfirst = PxMax((aMax[a] - bMin[a])/relTr[a], tfirst);
if(bMax[a] > aMin[a])
tlast = PxMin((aMin[a] - bMax[a])/relTr[a], tlast);
}
else if(relTr[a] > eps)
{
if(bMin[a] > aMax[a])
return PX_MAX_REAL;
if(bMax[a] < aMin[a])
tfirst = PxMax((aMin[a] - bMax[a])/relTr[a], tfirst);
if(aMax[a] > bMin[a])
tlast = PxMin((aMax[a] - bMin[a])/relTr[a], tlast);
}
else
{
if(bMax[a] < aMin[a] || bMin[a] > aMax[a])
return PX_MAX_REAL;
}
//No hit
if(tfirst > tlast)
return PX_MAX_REAL;
}
//There was a hit so return the TOI
return tfirst;
}
PX_PHYSX_COMMON_API PxReal SweepShapeShape(GU_SWEEP_METHOD_ARGS);
PX_PHYSX_COMMON_API PxReal SweepEstimateAnyShapeHeightfield(GU_SWEEP_ESTIMATE_ARGS);
PX_PHYSX_COMMON_API PxReal SweepEstimateAnyShapeMesh(GU_SWEEP_ESTIMATE_ARGS);
}
}
#endif
| 5,755 | C | 33.674699 | 168 | 0.69609 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKPenetration.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_PENETRATION_H
#define GU_GJK_PENETRATION_H
#include "GuConvexSupportTable.h"
#include "GuGJKSimplex.h"
#include "GuVecConvexHullNoScale.h"
#include "GuGJKUtil.h"
#include "foundation/PxUtilities.h"
#include "GuGJKType.h"
#define GJK_VALIDATE 0
namespace physx
{
namespace Gu
{
class ConvexV;
PX_FORCE_INLINE void assignWarmStartValue(PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, PxU8& size_, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32 size )
{
if(aIndices)
{
PX_ASSERT(bIndices);
size_ = PxTo8(size);
for(PxU32 i=0; i<size; ++i)
{
aIndices[i] = PxTo8(aInd[i]);
bIndices[i] = PxTo8(bInd[i]);
}
}
}
PX_FORCE_INLINE void validateDuplicateVertex(const aos::Vec3V* Q, const aos::Vec3VArg support, const PxU32 size)
{
using namespace aos;
const FloatV eps = FEps();
//Get rid of the duplicate point
BoolV match = BFFFF();
for(PxU32 na = 0; na < size; ++na)
{
Vec3V dif = V3Sub(Q[na], support);
match = BOr(match, FIsGrtr(eps, V3Dot(dif, dif)));
}
//we have duplicate code
if(BAllEqTTTT(match))
{
PX_ASSERT(0);
}
}
//*Each convex has
//* a support function
//* a margin - if the shape is 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 minimum distance between the shapes is greater than the sum of the margins and the the contactDistance
//* EPA_CONTACT if shapes overlap. We treat sphere/capsule as a point/a segment and we shrunk other shapes by 10% of margin
//* GJK_CONTACT if the algorithm converges, and the distance between the shapes is less than the sum of the margins plus the contactDistance. In this case we return the closest points found
//* GJK_DEGENERATE if the algorithm doesn't converge, we return this flag to indicate the normal and closest point we return might not be accurated
template<typename ConvexA, typename ConvexB >
PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape,
PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, aos::Vec3V* PX_RESTRICT aPoints, aos::Vec3V* PX_RESTRICT bPoints, PxU8& warmStartSize,
GjkOutput& output)
{
using namespace aos;
//ML: eps is the threshold that uses to determine whether two (shrunk) shapes overlap. We calculate eps2 based on 10% of the minimum margin of two shapes
const FloatV minMargin = FMin(a.ConvexA::getMinMargin(), b.ConvexB::getMinMargin());
const FloatV eps = FMul(minMargin, FLoad(0.1f));
//const FloatV eps2 = FMul(_eps2, _eps2);
//ML: epsRel2 is the square of 0.01. This is used to scale the square distance of a closest point to origin to determine whether two shrunk shapes overlap in the margin, but
//they don't overlap.
//const FloatV epsRel2 = FMax(FLoad(0.0001), eps2);
// 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|=>(|v|*(1-epsRel) < v/|v|.dot(w)),
// 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%.
const FloatV relDif = FSub(FOne(), epsRel);
const FloatV zero = FZero();
//capsule/sphere will have margin which is its radius
const FloatV marginA = a.getMargin();
const FloatV marginB = b.getMargin();
const BoolV aQuadratic = a.isMarginEqRadius();
const BoolV bQuadratic = b.isMarginEqRadius();
const FloatV tMarginA = FSel(aQuadratic, marginA, zero);
const FloatV tMarginB = FSel(bQuadratic, marginB, zero);
const FloatV sumMargin = FAdd(tMarginA, tMarginB);
const FloatV sumExpandedMargin = FAdd(sumMargin, contactDist);
FloatV dist = FMax();
FloatV prevDist = dist;
const Vec3V zeroV = V3Zero();
Vec3V prevClos = zeroV;
const BoolV bTrue = BTTTT();
BoolV bNotTerminated = bTrue;
BoolV bNotDegenerated = bTrue;
Vec3V closest;
Vec3V Q[4];
Vec3V* A = aPoints;
Vec3V* B = bPoints;
PxI32 aInd[4];
PxI32 bInd[4];
Vec3V supportA = zeroV, supportB = zeroV, support=zeroV;
Vec3V v;
PxU32 size = 0;//_size;
//ML: if _size!=0, which means we pass in the previous frame simplex so that we can warm-start the simplex.
//In this case, GJK will normally terminate in one iteration
if(warmStartSize != 0)
{
for(PxU32 i=0; i<warmStartSize; ++i)
{
aInd[i] = aIndices[i];
bInd[i] = bIndices[i];
//de-virtualize
supportA = a.ConvexA::supportPoint(aIndices[i]);
supportB = b.ConvexB::supportPoint(bIndices[i]);
support = V3Sub(supportA, supportB);
#if GJK_VALIDATE
//ML: this is used to varify whether we will have duplicate vertices in the warm-start value. If this function get triggered,
//this means something isn't right and we need to investigate
validateDuplicateVertex(Q, support, size);
#endif
A[size] = supportA;
B[size] = supportB;
Q[size++] = support;
}
//run simplex solver to determine whether the point is closest enough so that gjk can terminate
closest = GJKCPairDoSimplex(Q, A, B, aInd, bInd, support, size);
dist = V3Length(closest);
//sDist = V3Dot(closest, closest);
v = V3ScaleInv(closest, dist);
prevDist = dist;
prevClos = closest;
bNotTerminated = FIsGrtr(dist, eps);
}
else
{
//const Vec3V _initialSearchDir = V3Sub(a.getCenter(), b.getCenter());
closest = V3Sel(FIsGrtr(V3Dot(initialSearchDir, initialSearchDir), zero), initialSearchDir, V3UnitX());
v = V3Normalize(closest);
}
// ML : termination condition
//(1)two shapes overlap. GJK will terminate based on sq(v) < eps2 and indicate that two shapes are overlapping.
//(2)two shapes are separated. If sq(vw) > sqMargin * sq(v), which means the original objects do not intesect, GJK terminate with GJK_NON_INTERSECT.
//(3)two shapes don't overlap. However, they interect within margin distance. if sq(v)- vw < epsRel2*sq(v), this means the shrunk shapes interect in the margin,
// GJK terminate with GJK_CONTACT.
while(BAllEqTTTT(bNotTerminated))
{
//prevDist, prevClos are used to store the previous iteration's closest point and the square distance from the closest point
//to origin in Mincowski space
prevDist = dist;
prevClos = closest;
//de-virtualize
supportA = a.ConvexA::support(V3Neg(closest), aInd[size]);
supportB = b.ConvexB::support(closest, bInd[size]);
//calculate the support point
support = V3Sub(supportA, supportB);
const FloatV vw = V3Dot(v, support);
if(FAllGrtr(vw, sumExpandedMargin))
{
assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size);
return GJK_NON_INTERSECT;
}
//if(FAllGrtr(FMul(epsRel, dist), FSub(dist, vw)))
if(FAllGrtr(vw, FMul(dist, relDif)))
{
assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size);
PX_ASSERT(FAllGrtr(dist, FEps()));
//const Vec3V n = V3ScaleInv(closest, dist);//normalise
output.normal = v;
Vec3V closA, closB;
getClosestPoint(Q, A, B, closest, closA, closB, size);
//ML: if one of the shape is sphere/capsule and the takeCoreShape flag is true, the contact point for sphere/capsule will be the sphere center or a point in the
//capsule segment. This will increase the stability for the manifold recycling code. Otherwise, we will return a contact point on the surface for sphere/capsule
//while the takeCoreShape flag is set to be false
if(takeCoreShape)
{
output.closestA= closA;
output.closestB = closB;
output.penDep = dist;
}
else
{
//This is for capsule/sphere want to take the surface point. For box/convex,
//we need to get rid of margin
output.closestA = V3NegScaleSub(v, tMarginA, closA);
output.closestB = V3ScaleAdd(v, tMarginB, closB);
output.penDep = FSub(dist, sumMargin);
}
return GJK_CONTACT;
}
A[size] = supportA;
B[size] = supportB;
Q[size++]=support;
PX_ASSERT(size <= 4);
//calculate the closest point between two convex hull
closest = GJKCPairDoSimplex(Q, A, B, aInd, bInd, support, size);
dist = V3Length(closest);
v = V3ScaleInv(closest, dist);
bNotDegenerated = FIsGrtr(prevDist, dist);
bNotTerminated = BAnd(FIsGrtr(dist, eps), bNotDegenerated);
}
if(BAllEqFFFF(bNotDegenerated))
{
assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size-1);
//Reset back to older closest point
dist = prevDist;
closest = prevClos;//V3Sub(closA, closB);
Vec3V closA, closB;
getClosestPoint(Q, A, B, closest, closA, closB, size);
//PX_ASSERT(FAllGrtr(dist, FEps()));
const Vec3V n = V3ScaleInv(prevClos, prevDist);//normalise
output.normal = n;
output.searchDir = v;
if(takeCoreShape)
{
output.closestA = closA;
output.closestB = closB;
output.penDep = dist;
}
else
{
//This is for capsule/sphere want to take the surface point. For box/convex,
//we need to get rid of margin
output.closestA = V3NegScaleSub(n, tMarginA, closA);
output.closestB = V3ScaleAdd(n, tMarginB, closB);
output.penDep = FSub(dist, sumMargin);
if (FAllGrtrOrEq(sumMargin, dist))
return GJK_CONTACT;
}
return GJK_DEGENERATE;
}
else
{
//this two shapes are deeply intersected with each other, we need to use EPA algorithm to calculate MTD
assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size);
return EPA_CONTACT;
}
}
template<typename ConvexA, typename ConvexB >
PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape,
PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, PxU8& warmStartSize,
GjkOutput& output)
{
aos::Vec3V aPoints[4], bPoints[4];
return gjkPenetration(a, b, initialSearchDir, contactDist, takeCoreShape, aIndices, bIndices, aPoints, bPoints, warmStartSize, output);
}
template<typename ConvexA, typename ConvexB >
PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape,
aos::Vec3V* PX_RESTRICT aPoints, aos::Vec3V* PX_RESTRICT bPoints, PxU8& warmStartSize,
GjkOutput& output)
{
PxU8 aIndices[4], bIndices[4];
return gjkPenetration(a, b, initialSearchDir, contactDist, takeCoreShape, aIndices, bIndices, aPoints, bPoints, warmStartSize, output);
}
}//Gu
}//physx
#endif
| 12,540 | C | 36.435821 | 198 | 0.708373 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecBox.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_BOX_H
#define GU_VEC_BOX_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxTransform.h"
#include "common/PxPhysXCommonConfig.h"
#include "geometry/PxBoxGeometry.h"
#include "foundation/PxVecTransform.h"
#include "GuVecConvex.h"
#include "GuConvexSupportTable.h"
namespace physx
{
PX_PHYSX_COMMON_API extern const aos::BoolV boxVertexTable[8];
namespace Gu
{
#define BOX_MARGIN_RATIO 0.15f
#define BOX_MIN_MARGIN_RATIO 0.05f
#define BOX_SWEEP_MARGIN_RATIO 0.05f
#define BOX_MARGIN_CCD_RATIO 0.01f
#define BOX_MIN_MARGIN_CCD_RATIO 0.005f
class CapsuleV;
PX_FORCE_INLINE void CalculateBoxMargin(const aos::Vec3VArg extent, PxReal& margin, PxReal& minMargin, PxReal& sweepMargin,
const PxReal marginR = BOX_MARGIN_RATIO, const PxReal minMarginR = BOX_MIN_MARGIN_RATIO)
{
using namespace aos;
PxReal minExtent;
const FloatV min = V3ExtractMin(extent);
FStore(min, &minExtent);
margin = minExtent * marginR;
minMargin = minExtent * minMarginR;
sweepMargin = minExtent * BOX_SWEEP_MARGIN_RATIO;
}
PX_FORCE_INLINE aos::FloatV CalculateBoxTolerance(const aos::Vec3VArg extent)
{
using namespace aos;
const FloatV r0 = FLoad(0.01f);
const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent)));
return FMul(min, r0);
}
//This method is called in the PCM contact gen for the refreshing contacts
PX_FORCE_INLINE aos::FloatV CalculatePCMBoxMargin(const aos::Vec3VArg extent, const PxReal toleranceLength, const PxReal toleranceMarginRatio = BOX_MARGIN_RATIO)
{
using namespace aos;
const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent)));
const FloatV toleranceMargin = FLoad(toleranceLength * toleranceMarginRatio);
return FMin(FMul(min, FLoad(BOX_MARGIN_RATIO)), toleranceMargin);
}
PX_FORCE_INLINE aos::FloatV CalculateMTDBoxMargin(const aos::Vec3VArg extent)
{
using namespace aos;
const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent)));
return FMul(min, FLoad(BOX_MARGIN_RATIO));
}
class BoxV : public ConvexV
{
public:
/**
\brief Constructor
*/
PX_INLINE BoxV() : ConvexV(ConvexType::eBOX)
{
}
PX_FORCE_INLINE BoxV(const aos::Vec3VArg origin, const aos::Vec3VArg extent) :
ConvexV(ConvexType::eBOX, origin), extents(extent)
{
CalculateBoxMargin(extent, margin, minMargin, sweepMargin);
}
//this constructor is used by the CCD system
PX_FORCE_INLINE BoxV(const PxGeometry& geom) : ConvexV(ConvexType::eBOX, aos::V3Zero())
{
using namespace aos;
const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom);
const Vec3V extent = aos::V3LoadU(boxGeom.halfExtents);
extents = extent;
CalculateBoxMargin(extent, margin, minMargin, sweepMargin, BOX_MARGIN_CCD_RATIO, BOX_MIN_MARGIN_CCD_RATIO);
}
/**
\brief Destructor
*/
PX_INLINE ~BoxV()
{
}
PX_FORCE_INLINE void resetMargin(const PxReal toleranceLength)
{
minMargin = PxMin(toleranceLength * BOX_MIN_MARGIN_RATIO, minMargin);
}
//! Assignment operator
PX_FORCE_INLINE const BoxV& operator=(const BoxV& other)
{
center = other.center;
extents = other.extents;
margin = other.margin;
minMargin = other.minMargin;
sweepMargin = other.sweepMargin;
return *this;
}
PX_FORCE_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)
}
PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const
{
using namespace aos;
const BoolV con = boxVertexTable[index];
return V3Sel(con, extents, V3Neg(extents));
}
PX_FORCE_INLINE void getIndex(const aos::BoolV con, PxI32& index)const
{
using namespace aos;
index = PxI32(BGetBitMask(con) & 0x7);
}
PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const
{
using namespace aos;
return V3Sel(V3IsGrtr(dir, V3Zero()), extents, V3Neg(extents));
}
//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;
const Vec3V point = V3Sel(V3IsGrtr(dir, V3Zero()), extents, V3Neg(extents));
max = V3Dot(dir, point);
min = FNeg(max);
}
PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const
{
//a is the current object, b is the other object, dir is in the local space of b
using namespace aos;
// const Vec3V _dir = aTob.rotateInv(dir);//relTra.rotateInv(dir);//from b to a
const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//from b to a
const Vec3V p = supportLocal(_dir);
//transfer p into the b space
return aTob.transform(p);//relTra.transform(p);
}
PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const
{
using namespace aos;
const BoolV comp = V3IsGrtr(dir, V3Zero());
getIndex(comp, index);
return V3Sel(comp, extents, V3Neg(extents));
}
PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob,
const aos::PxMatTransformV& aTobT, PxI32& index)const
{
//a is the current object, b is the other object, dir is in the local space of b
using namespace aos;
// const Vec3V _dir = aTob.rotateInv(dir);//relTra.rotateInv(dir);//from b to a
const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//from b to a
const Vec3V p = supportLocal(_dir, index);
//transfer p into the b space
return aTob.transform(p);//relTra.transform(p);
}
aos::Vec3V extents;
};
} //PX_COMPILE_TIME_ASSERT(sizeof(Gu::BoxV) == 96);
}
/** @} */
#endif
| 7,751 | C | 33.300885 | 193 | 0.722487 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKTest.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_TEST_H
#define GU_GJK_TEST_H
#include "common/PxPhysXCommonConfig.h"
#include "GuGJKUtil.h"
namespace physx
{
namespace Gu
{
struct GjkConvex;
PX_PHYSX_COMMON_API GjkStatus testGjk(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, aos::Vec3V& closestA, aos::Vec3V& closestB,
aos::Vec3V& normal, aos::FloatV& dist);
PX_PHYSX_COMMON_API bool testGjkRaycast(const GjkConvex& a, const GjkConvex& b, const aos::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, const bool initialOverlap);
PX_PHYSX_COMMON_API GjkStatus testGjkPenetration(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist,
PxU8* aIndices, PxU8* bIndices, PxU8& size, GjkOutput& output);
PX_PHYSX_COMMON_API GjkStatus testEpaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* aIndices, const PxU8* bIndices, const PxU8 size,
GjkOutput& output);
}
}
#endif
| 2,836 | C | 49.660713 | 202 | 0.765867 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPAFacet.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_FACET_H
#define GU_EPA_FACET_H
#include "foundation/PxVecMath.h"
#include "foundation/PxFPU.h"
#include "foundation/PxUtilities.h"
#include "CmIDPool.h"
#if (defined __GNUC__ && defined _DEBUG)
#define PX_EPA_FORCE_INLINE
#else
#define PX_EPA_FORCE_INLINE PX_FORCE_INLINE
#endif
#define EPA_DEBUG 0
namespace physx
{
#define MaxEdges 32
#define MaxFacets 64
#define MaxSupportPoints 64
namespace Gu
{
const PxU32 lookUp[3] = {1, 2, 0};
PX_FORCE_INLINE PxU32 incMod3(PxU32 i) { return lookUp[i]; }
class EdgeBuffer;
class Edge;
typedef Cm::InlineDeferredIDPool<MaxFacets> EPAFacetManager;
class Facet
{
public:
Facet()
{
}
PX_FORCE_INLINE Facet(const PxU32 _i0, const PxU32 _i1, const PxU32 _i2)
: m_obsolete(false), m_inHeap(false)
{
m_indices[0]= PxToI8(_i0);
m_indices[1]= PxToI8(_i1);
m_indices[2]= PxToI8(_i2);
m_adjFacets[0] = m_adjFacets[1] = m_adjFacets[2] = NULL;
m_adjEdges[0] = m_adjEdges[1] = m_adjEdges[2] = -1;
}
PX_FORCE_INLINE void invalidate()
{
m_adjFacets[0] = m_adjFacets[1] = m_adjFacets[2] = NULL;
m_adjEdges[0] = m_adjEdges[1] = m_adjEdges[2] = -1;
}
PX_FORCE_INLINE bool Valid()
{
return (m_adjFacets[0] != NULL) & (m_adjFacets[1] != NULL) & (m_adjFacets[2] != NULL);
}
PX_FORCE_INLINE PxU32 operator[](const PxU32 i) const
{
return PxU32(m_indices[i]);
}
//create ajacency information
bool link(const PxU32 edge0, Facet* PX_RESTRICT facet, const PxU32 edge1);
PX_FORCE_INLINE bool isObsolete() const { return m_obsolete; }
//calculate the signed distance from a point to a plane
PX_FORCE_INLINE aos::FloatV getPlaneDist(const aos::Vec3VArg p, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf) const;
//check to see whether the triangle is a valid triangle, calculate plane normal and plane distance at the same time
aos::BoolV 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);
//return the absolute value for the plane distance from origin
PX_FORCE_INLINE aos::FloatV getPlaneDist() const
{
return aos::FLoad(m_planeDist);
}
//return the plane normal
PX_FORCE_INLINE aos::Vec3V getPlaneNormal()const
{
return m_planeNormal;
}
//calculate the closest points for a shape pair
void getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::Vec3V& closestA,
aos::Vec3V& closestB);
//calculate the closest points for a shape pair
//void getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::FloatV& v, aos::FloatV& w);
//performs a flood fill over the boundary of the current polytope.
void silhouette(const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager);
//m_planeDist is positive
bool operator <(const Facet& b) const
{
return m_planeDist < b.m_planeDist;
}
//store all the boundary facets for the new polytope in the edgeBuffer and free indices when an old facet isn't part of the boundary anymore
PX_FORCE_INLINE void silhouette(const PxU32 index, const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer,
EPAFacetManager& manager);
aos::Vec3V m_planeNormal; //16
PxF32 m_planeDist;
#if EPA_DEBUG
PxF32 m_lambda1;
PxF32 m_lambda2;
#endif
Facet* PX_RESTRICT m_adjFacets[3]; //the triangle adjacent to edge i in this triangle //32
PxI8 m_adjEdges[3]; //the edge connected with the corresponding triangle //35
PxI8 m_indices[3]; //the index of vertices of the triangle //38
bool m_obsolete; //a flag to denote whether the triangle are still part of the bundeary of the new polytope //39
bool m_inHeap; //a flag to indicate whether the triangle is in the heap //40
PxU8 m_FacetId; //41 //73
};
class Edge
{
public:
PX_FORCE_INLINE Edge() {}
PX_FORCE_INLINE Edge(Facet * PX_RESTRICT facet, const PxU32 index) : m_facet(facet), m_index(index) {}
PX_FORCE_INLINE Edge(const Edge& other) : m_facet(other.m_facet), m_index(other.m_index){}
PX_FORCE_INLINE Edge& operator = (const Edge& other)
{
m_facet = other.m_facet;
m_index = other.m_index;
return *this;
}
PX_FORCE_INLINE Facet *getFacet() const { return m_facet; }
PX_FORCE_INLINE PxU32 getIndex() const { return m_index; }
//get out the associated start vertex index in this edge from the facet
PX_FORCE_INLINE PxU32 getSource() const
{
PX_ASSERT(m_index < 3);
return (*m_facet)[m_index];
}
//get out the associated end vertex index in this edge from the facet
PX_FORCE_INLINE PxU32 getTarget() const
{
PX_ASSERT(m_index < 3);
return (*m_facet)[incMod3(m_index)];
}
Facet* PX_RESTRICT m_facet;
PxU32 m_index;
};
class EdgeBuffer
{
public:
EdgeBuffer() : m_Size(0), m_OverFlow(false)
{
}
Edge* Insert(Facet* PX_RESTRICT facet, const PxU32 index)
{
if (m_Size < MaxEdges)
{
Edge* pEdge = &m_pEdges[m_Size++];
pEdge->m_facet = facet;
pEdge->m_index = index;
return pEdge;
}
m_OverFlow = true;
return NULL;
}
Edge* Get(const PxU32 index)
{
PX_ASSERT(index < m_Size);
return &m_pEdges[index];
}
PxU32 Size()
{
return m_Size;
}
bool IsValid()
{
return m_Size > 0 && !m_OverFlow;
}
void MakeEmpty()
{
m_Size = 0;
m_OverFlow = false;
}
Edge m_pEdges[MaxEdges];
PxU32 m_Size;
bool m_OverFlow;
};
//ML: calculate MTD points for a shape pair
PX_FORCE_INLINE void Facet::getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::Vec3V& closestA,
aos::Vec3V& closestB)
{
using namespace aos;
const Vec3V pa0(aBuf[m_indices[0]]);
const Vec3V pa1(aBuf[m_indices[1]]);
const Vec3V pa2(aBuf[m_indices[2]]);
const Vec3V pb0(bBuf[m_indices[0]]);
const Vec3V pb1(bBuf[m_indices[1]]);
const Vec3V pb2(bBuf[m_indices[2]]);
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 closestP = V3Scale(m_planeNormal, FLoad(m_planeDist));
const Vec3V v2 = V3Sub(closestP, p0);
//calculate barycentric coordinates
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 det = FNegScaleSub(d01, d01, FMul(d00, d11));//FSub( FMul(v1dv1, v2dv2), FMul(v1dv2, v1dv2) ); // non-negative
const FloatV recip = FSel(FIsGrtr(det, FEps()), FRecip(det), FZero());
const FloatV lambda1 = FMul(FNegScaleSub(d01, d21, FMul(d11, d20)), recip);
const FloatV lambda2 = FMul(FNegScaleSub(d01, d20, FMul(d00, d21)), recip);
#if EPA_DEBUG
FStore(lambda1, &m_lambda1);
FStore(lambda2, &m_lambda2);
#endif
const FloatV u = FSub(FOne(), FAdd(lambda1, lambda2));
closestA = V3ScaleAdd(pa0, u, V3ScaleAdd(pa1, lambda1, V3Scale(pa2, lambda2)));
closestB = V3ScaleAdd(pb0, u, V3ScaleAdd(pb1, lambda1, V3Scale(pb2, lambda2)));
}
//ML: create adjacency informations for both facets
PX_FORCE_INLINE bool Facet::link(const PxU32 edge0, Facet * PX_RESTRICT facet, const PxU32 edge1)
{
m_adjFacets[edge0] = facet;
m_adjEdges[edge0] = PxToI8(edge1);
facet->m_adjFacets[edge1] = this;
facet->m_adjEdges[edge1] = PxToI8(edge0);
return (m_indices[edge0] == facet->m_indices[incMod3(edge1)]) && (m_indices[incMod3(edge0)] == facet->m_indices[edge1]);
}
}
}
#endif
| 9,554 | C | 30.327869 | 172 | 0.684949 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKSimplex.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 "GuGJKSimplex.h"
namespace physx
{
namespace Gu
{
using namespace aos;
static Vec3V getClosestPtPointTriangle(Vec3V* PX_RESTRICT Q, const BoolVArg bIsOutside4, PxU32* indices, PxU32& size)
{
FloatV bestSqDist = FMax();
PxU32 _indices[3] = {0, 1, 2};
Vec3V closestPt = V3Zero();
if(BAllEqTTTT(BGetX(bIsOutside4)))
{
//use the original indices, size, v and w
bestSqDist = closestPtPointTriangleBaryCentric(Q[0], Q[1], Q[2], indices, size, closestPt);
}
if(BAllEqTTTT(BGetY(bIsOutside4)))
{
PxU32 _size = 3;
_indices[0] = 0; _indices[1] = 2; _indices[2] = 3;
Vec3V tClosestPt;
const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[0], Q[2], Q[3], _indices, _size, tClosestPt);
const BoolV con = FIsGrtr(bestSqDist, sqDist);
if(BAllEqTTTT(con))
{
closestPt = tClosestPt;
bestSqDist = sqDist;
indices[0] = _indices[0];
indices[1] = _indices[1];
indices[2] = _indices[2];
size = _size;
}
}
if(BAllEqTTTT(BGetZ(bIsOutside4)))
{
PxU32 _size = 3;
_indices[0] = 0; _indices[1] = 3; _indices[2] = 1;
Vec3V tClosestPt;
const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[0], Q[3], Q[1], _indices, _size, tClosestPt);
const BoolV con = FIsGrtr(bestSqDist, sqDist);
if(BAllEqTTTT(con))
{
closestPt = tClosestPt;
bestSqDist = sqDist;
indices[0] = _indices[0];
indices[1] = _indices[1];
indices[2] = _indices[2];
size = _size;
}
}
if(BAllEqTTTT(BGetW(bIsOutside4)))
{
PxU32 _size = 3;
_indices[0] = 1; _indices[1] = 3; _indices[2] = 2;
Vec3V tClosestPt;
const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[1], Q[3], Q[2], _indices, _size, tClosestPt);
const BoolV con = FIsGrtr(bestSqDist, sqDist);
if(BAllEqTTTT(con))
{
closestPt = tClosestPt;
bestSqDist = sqDist;
indices[0] = _indices[0];
indices[1] = _indices[1];
indices[2] = _indices[2];
size = _size;
}
}
return closestPt;
}
PX_NOALIAS Vec3V closestPtPointTetrahedron(Vec3V* PX_RESTRICT Q, Vec3V* PX_RESTRICT A, Vec3V* PX_RESTRICT B, PxU32& size)
{
const FloatV eps = FLoad(1e-4f);
const Vec3V a = Q[0];
const Vec3V b = Q[1];
const Vec3V c = Q[2];
const Vec3V d = Q[3];
//degenerated
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V n = V3Normalize(V3Cross(ab, ac));
const FloatV signDist = V3Dot(n, V3Sub(d, a));
if(FAllGrtr(eps, FAbs(signDist)))
{
size = 3;
return closestPtPointTriangle(Q, A, B, size);
}
const BoolV bIsOutside4 = PointOutsideOfPlane4(a, b, c, d);
if(BAllEqFFFF(bIsOutside4))
{
//All inside
return V3Zero();
}
PxU32 indices[3] = {0, 1, 2};
const Vec3V closest = getClosestPtPointTriangle(Q, bIsOutside4, indices, size);
const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V q2 = Q[indices[2]];
const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V a2 = A[indices[2]];
const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; const Vec3V b2 = B[indices[2]];
Q[0] = q0; Q[1] = q1; Q[2] = q2;
A[0] = a0; A[1] = a1; A[2] = a2;
B[0] = b0; B[1] = b1; B[2] = b2;
return closest;
}
PX_NOALIAS Vec3V closestPtPointTetrahedron(Vec3V* PX_RESTRICT Q, Vec3V* PX_RESTRICT A, Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32& size)
{
const FloatV eps = FLoad(1e-4f);
const Vec3V zeroV = V3Zero();
const Vec3V a = Q[0];
const Vec3V b = Q[1];
const Vec3V c = Q[2];
const Vec3V d = Q[3];
//degenerated
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V n = V3Normalize(V3Cross(ab, ac));
const FloatV signDist = V3Dot(n, V3Sub(d, a));
if(FAllGrtr(eps, FAbs(signDist)))
{
size = 3;
return closestPtPointTriangle(Q, A, B, aInd, bInd, size);
}
const BoolV bIsOutside4 = PointOutsideOfPlane4(a, b, c, d);
if(BAllEqFFFF(bIsOutside4))
{
//All inside
return zeroV;
}
PxU32 indices[3] = {0, 1, 2};
const Vec3V closest = getClosestPtPointTriangle(Q, bIsOutside4, indices, size);
const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V q2 = Q[indices[2]];
const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V a2 = A[indices[2]];
const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; const Vec3V b2 = B[indices[2]];
const PxI32 _aInd0 = aInd[indices[0]]; const PxI32 _aInd1 = aInd[indices[1]]; const PxI32 _aInd2 = aInd[indices[2]];
const PxI32 _bInd0 = bInd[indices[0]]; const PxI32 _bInd1 = bInd[indices[1]]; const PxI32 _bInd2 = bInd[indices[2]];
Q[0] = q0; Q[1] = q1; Q[2] = q2;
A[0] = a0; A[1] = a1; A[2] = a2;
B[0] = b0; B[1] = b1; B[2] = b2;
aInd[0] = _aInd0; aInd[1] = _aInd1; aInd[2] = _aInd2;
bInd[0] = _bInd0; bInd[1] = _bInd1; bInd[2] = _bInd2;
return closest;
}
}
}
| 6,611 | C++ | 29.611111 | 173 | 0.659356 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKSimplex.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_GJKSIMPLEX_H
#define GU_GJKSIMPLEX_H
#include "foundation/PxVecMath.h"
#include "GuBarycentricCoordinates.h"
#if (defined __GNUC__ && defined _DEBUG)
#define PX_GJK_INLINE PX_INLINE
#define PX_GJK_FORCE_INLINE PX_INLINE
#else
#define PX_GJK_INLINE PX_INLINE
#define PX_GJK_FORCE_INLINE PX_FORCE_INLINE
#endif
namespace physx
{
namespace Gu
{
PX_NOALIAS aos::Vec3V closestPtPointTetrahedron(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxU32& size);
PX_NOALIAS aos::Vec3V closestPtPointTetrahedron(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd,
PxU32& size);
PX_NOALIAS PX_FORCE_INLINE aos::BoolV PointOutsideOfPlane4(const aos::Vec3VArg _a, const aos::Vec3VArg _b, const aos::Vec3VArg _c, const aos::Vec3VArg _d)
{
using namespace aos;
const Vec4V zero = V4Load(0.f);
const Vec3V ab = V3Sub(_b, _a);
const Vec3V ac = V3Sub(_c, _a);
const Vec3V ad = V3Sub(_d, _a);
const Vec3V bd = V3Sub(_d, _b);
const Vec3V bc = V3Sub(_c, _b);
const Vec3V v0 = V3Cross(ab, ac);
const Vec3V v1 = V3Cross(ac, ad);
const Vec3V v2 = V3Cross(ad, ab);
const Vec3V v3 = V3Cross(bd, bc);
const FloatV signa0 = V3Dot(v0, _a);
const FloatV signa1 = V3Dot(v1, _a);
const FloatV signa2 = V3Dot(v2, _a);
const FloatV signd3 = V3Dot(v3, _a);
const FloatV signd0 = V3Dot(v0, _d);
const FloatV signd1 = V3Dot(v1, _b);
const FloatV signd2 = V3Dot(v2, _c);
const FloatV signa3 = V3Dot(v3, _b);
const Vec4V signa = V4Merge(signa0, signa1, signa2, signa3);
const Vec4V signd = V4Merge(signd0, signd1, signd2, signd3);
return V4IsGrtrOrEq(V4Mul(signa, signd), zero);//same side, outside of the plane
}
PX_NOALIAS PX_FORCE_INLINE aos::Vec3V closestPtPointSegment(aos::Vec3V* PX_RESTRICT Q, PxU32& size)
{
using namespace aos;
const Vec3V a = Q[0];
const Vec3V b = Q[1];
//const Vec3V origin = V3Zero();
const FloatV zero = FZero();
const FloatV one = FOne();
//Test degenerated case
const Vec3V ab = V3Sub(b, a);
const FloatV denom = V3Dot(ab, ab);
const Vec3V ap = V3Neg(a);//V3Sub(origin, a);
const FloatV nom = V3Dot(ap, ab);
const BoolV con = FIsGrtrOrEq(FEps(), denom);//FIsEq(denom, zero);
//TODO - can we get rid of this branch? The problem is size, which isn't a vector!
if(BAllEqTTTT(con))
{
size = 1;
return Q[0];
}
/* const PxU32 count = BAllEq(con, bTrue);
size = 2 - count;*/
const FloatV tValue = FClamp(FDiv(nom, denom), zero, one);
return V3ScaleAdd(ab, tValue, a);
}
PX_FORCE_INLINE void getClosestPoint(const aos::Vec3V* PX_RESTRICT Q, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const aos::Vec3VArg closest, aos::Vec3V& closestA, aos::Vec3V& closestB, const PxU32 size)
{
using namespace aos;
switch(size)
{
case 1:
{
closestA = A[0];
closestB = B[0];
break;
}
case 2:
{
FloatV v;
barycentricCoordinates(closest, Q[0], Q[1], v);
const Vec3V av = V3Sub(A[1], A[0]);
const Vec3V bv = V3Sub(B[1], B[0]);
closestA = V3ScaleAdd(av, v, A[0]);
closestB = V3ScaleAdd(bv, v, B[0]);
break;
}
case 3:
{
//calculate the Barycentric of closest point p in the mincowsky sum
FloatV v, w;
barycentricCoordinates(closest, Q[0], Q[1], Q[2], v, w);
const Vec3V av0 = V3Sub(A[1], A[0]);
const Vec3V av1 = V3Sub(A[2], A[0]);
const Vec3V bv0 = V3Sub(B[1], B[0]);
const Vec3V bv1 = V3Sub(B[2], B[0]);
closestA = V3Add(A[0], V3Add(V3Scale(av0, v), V3Scale(av1, w)));
closestB = V3Add(B[0], V3Add(V3Scale(bv0, v), V3Scale(bv1, w)));
}
};
}
PX_NOALIAS PX_GJK_FORCE_INLINE aos::FloatV closestPtPointTriangleBaryCentric(const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c,
PxU32* PX_RESTRICT indices, PxU32& size, aos::Vec3V& closestPt)
{
using namespace aos;
size = 3;
const FloatV zero = FZero();
const FloatV eps = FEps();
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V n = V3Cross(ab, ac);
//ML: if the shape is oblong, the degeneracy test sometime can't catch the degeneracy in the tetraheron. Therefore, we need to make sure we still can ternimate with the previous
//triangle by returning the maxinum distance.
const FloatV nn = V3Dot(n, n);
if (FAllEq(nn, zero))
return FMax();
//const FloatV va = FNegScaleSub(d5, d4, FMul(d3, d6));//edge region of BC
//const FloatV vb = FNegScaleSub(d1, d6, FMul(d5, d2));//edge region of AC
//const FloatV vc = FNegScaleSub(d3, d2, FMul(d1, d4));//edge region of AB
//const FloatV va = V3Dot(n, V3Cross(b, c));//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a
//const FloatV vb = V3Dot(n, V3Cross(c, a));//edge region of AC, signed area rac, v = S(rca)/S(abc) for b
//const FloatV vc = V3Dot(n, V3Cross(a, b));//edge region of AB, signed area rab, w = S(rab)/S(abc) for c
const VecCrossV crossA = V3PrepareCross(a);
const VecCrossV crossB = V3PrepareCross(b);
const VecCrossV crossC = V3PrepareCross(c);
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 BoolV isFacePoints = BAnd(FIsGrtrOrEq(va, zero), BAnd(FIsGrtrOrEq(vb, zero), FIsGrtrOrEq(vc, zero)));
//face region
if(BAllEqTTTT(isFacePoints))
{
const FloatV t = FDiv(V3Dot(n, a), nn);
const Vec3V q = V3Scale(n, t);
closestPt = q;
return V3Dot(q, q);
}
const Vec3V ap = V3Neg(a);
const Vec3V bp = V3Neg(b);
const Vec3V cp = V3Neg(c);
const FloatV d1 = V3Dot(ab, ap); // snom
const FloatV d2 = V3Dot(ac, ap); // tnom
const FloatV d3 = V3Dot(ab, bp); // -sdenom
const FloatV d4 = V3Dot(ac, bp); // unom = d4 - d3
const FloatV d5 = V3Dot(ab, cp); // udenom = d5 - d6
const FloatV d6 = V3Dot(ac, cp); // -tdenom
const FloatV unom = FSub(d4, d3);
const FloatV udenom = FSub(d5, d6);
size = 2;
//check if p in edge region of AB
const BoolV con30 = FIsGrtrOrEq(zero, vc);
const BoolV con31 = FIsGrtrOrEq(d1, zero);
const BoolV con32 = FIsGrtrOrEq(zero, d3);
const BoolV con3 = BAnd(con30, BAnd(con31, con32));//edge AB region
if(BAllEqTTTT(con3))
{
const FloatV toRecipAB = FSub(d1, d3);
const FloatV recipAB = FSel(FIsGrtr(FAbs(toRecipAB), eps), FRecip(toRecipAB), zero);
const FloatV t = FMul(d1, recipAB);
const Vec3V q = V3ScaleAdd(ab, t, a);
closestPt = q;
return V3Dot(q, q);
}
//check if p in edge region of BC
const BoolV con40 = FIsGrtrOrEq(zero, va);
const BoolV con41 = FIsGrtrOrEq(d4, d3);
const BoolV con42 = FIsGrtrOrEq(d5, d6);
const BoolV con4 = BAnd(con40, BAnd(con41, con42)); //edge BC region
if(BAllEqTTTT(con4))
{
const Vec3V bc = V3Sub(c, b);
const FloatV toRecipBC = FAdd(unom, udenom);
const FloatV recipBC = FSel(FIsGrtr(FAbs(toRecipBC), eps), FRecip(toRecipBC), zero);
const FloatV t = FMul(unom, recipBC);
indices[0] = indices[1];
indices[1] = indices[2];
const Vec3V q = V3ScaleAdd(bc, t, b);
closestPt = q;
return V3Dot(q, q);
}
//check if p in edge region of AC
const BoolV con50 = FIsGrtrOrEq(zero, vb);
const BoolV con51 = FIsGrtrOrEq(d2, zero);
const BoolV con52 = FIsGrtrOrEq(zero, d6);
const BoolV con5 = BAnd(con50, BAnd(con51, con52));//edge AC region
if(BAllEqTTTT(con5))
{
const FloatV toRecipAC = FSub(d2, d6);
const FloatV recipAC = FSel(FIsGrtr(FAbs(toRecipAC), eps), FRecip(toRecipAC), zero);
const FloatV t = FMul(d2, recipAC);
indices[1]=indices[2];
const Vec3V q = V3ScaleAdd(ac, t, a);
closestPt = q;
return V3Dot(q, q);
}
size = 1;
//check if p in vertex region outside a
const BoolV con00 = FIsGrtrOrEq(zero, d1); // snom <= 0
const BoolV con01 = FIsGrtrOrEq(zero, d2); // tnom <= 0
const BoolV con0 = BAnd(con00, con01); // vertex region a
if(BAllEqTTTT(con0))
{
closestPt = a;
return V3Dot(a, a);
}
//check if p in vertex region outside b
const BoolV con10 = FIsGrtrOrEq(d3, zero);
const BoolV con11 = FIsGrtrOrEq(d3, d4);
const BoolV con1 = BAnd(con10, con11); // vertex region b
if(BAllEqTTTT(con1))
{
indices[0] = indices[1];
closestPt = b;
return V3Dot(b, b);
}
//p is in vertex region outside c
indices[0] = indices[2];
closestPt = c;
return V3Dot(c, c);
}
PX_NOALIAS PX_GJK_FORCE_INLINE aos::Vec3V closestPtPointTriangle(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* A, aos::Vec3V* B, PxU32& size)
{
using namespace aos;
size = 3;
const FloatV eps = FEps();
const Vec3V a = Q[0];
const Vec3V b = Q[1];
const Vec3V c = Q[2];
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V signArea = V3Cross(ab, ac);//0.5*(abXac)
const FloatV area = V3Dot(signArea, signArea);
if(FAllGrtrOrEq(eps, area))
{
//degenerate
size = 2;
return closestPtPointSegment(Q, size);
}
PxU32 _size;
PxU32 indices[3]={0, 1, 2};
Vec3V closestPt;
closestPtPointTriangleBaryCentric(a, b, c, indices, _size, closestPt);
if(_size != 3)
{
const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]];
const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]];
const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]];
Q[0] = q0; Q[1] = q1;
A[0] = a0; A[1] = a1;
B[0] = b0; B[1] = b1;
size = _size;
}
return closestPt;
}
PX_NOALIAS PX_GJK_FORCE_INLINE aos::Vec3V closestPtPointTriangle(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* A, aos::Vec3V* B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd,
PxU32& size)
{
using namespace aos;
size = 3;
const FloatV eps = FEps();
const Vec3V a = Q[0];
const Vec3V b = Q[1];
const Vec3V c = Q[2];
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V signArea = V3Cross(ab, ac);//0.5*(abXac)
const FloatV area = V3Dot(signArea, signArea);
if(FAllGrtrOrEq(eps, area))
{
//degenerate
size = 2;
return closestPtPointSegment(Q, size);
}
PxU32 _size;
PxU32 indices[3]={0, 1, 2};
Vec3V closestPt;
closestPtPointTriangleBaryCentric(a, b, c, indices, _size, closestPt);
if(_size != 3)
{
const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]];
const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]];
const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]];
const PxI32 aInd0 = aInd[indices[0]]; const PxI32 aInd1 = aInd[indices[1]];
const PxI32 bInd0 = bInd[indices[0]]; const PxI32 bInd1 = bInd[indices[1]];
Q[0] = q0; Q[1] = q1;
A[0] = a0; A[1] = a1;
B[0] = b0; B[1] = b1;
aInd[0] = aInd0; aInd[1] = aInd1;
bInd[0] = bInd0; bInd[1] = bInd1;
size = _size;
}
return closestPt;
}
PX_NOALIAS PX_FORCE_INLINE aos::Vec3V GJKCPairDoSimplex(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, const aos::Vec3VArg support,
PxU32& size)
{
using namespace aos;
//const PxU32 tempSize = size;
//calculate a closest from origin to the simplex
switch(size)
{
case 1:
{
return support;
}
case 2:
{
return closestPtPointSegment(Q, size);
}
case 3:
{
return closestPtPointTriangle(Q, A, B, size);
}
case 4:
return closestPtPointTetrahedron(Q, A, B, size);
default:
PX_ASSERT(0);
}
return support;
}
PX_NOALIAS PX_FORCE_INLINE aos::Vec3V GJKCPairDoSimplex(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd,
const aos::Vec3VArg support, PxU32& size)
{
using namespace aos;
//const PxU32 tempSize = size;
//calculate a closest from origin to the simplex
switch(size)
{
case 1:
{
return support;
}
case 2:
{
return closestPtPointSegment(Q, size);
}
case 3:
{
return closestPtPointTriangle(Q, A, B, aInd, bInd, size);
}
case 4:
return closestPtPointTetrahedron(Q, A, B, aInd, bInd, size);
default:
PX_ASSERT(0);
}
return support;
}
}
}
#endif
| 14,055 | C | 30.305122 | 227 | 0.661615 |
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/GuContactSpherePlane.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::contactSpherePlane(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_UNUSED(cache);
PX_UNUSED(shape1);
// Get actual shape data
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
//const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape1);
//Sphere in plane space
const PxVec3 sphere = transform1.transformInv(transform0.p);
//Make sure we have a normalized plane
//The plane is implicitly n=<1,0,0> d=0 (in plane-space)
//PX_ASSERT(PxAbs(shape1.mNormal.magnitudeSquared() - 1.0f) < 0.000001f);
//Separation
const PxReal separation = sphere.x - shapeSphere.radius;
if(separation<=params.mContactDistance)
{
const PxVec3 normal = transform1.q.getBasisVector0();
const PxVec3 point = transform0.p - normal * shapeSphere.radius;
contactBuffer.contact(point, normal, separation);
return true;
}
return false;
}
| 2,688 | C++ | 41.682539 | 77 | 0.761533 |
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/GuFeatureCode.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_FEATURE_CODE_H
#define GU_FEATURE_CODE_H
namespace physx
{
namespace Gu
{
enum FeatureCode
{
FC_VERTEX0,
FC_VERTEX1,
FC_VERTEX2,
FC_EDGE01,
FC_EDGE12,
FC_EDGE20,
FC_FACE,
FC_UNDEFINED
};
bool selectNormal(PxU8 data, PxReal u, PxReal v);
}
}
#endif
| 1,982 | C | 35.722222 | 74 | 0.752775 |
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/GuQuantizer.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_QUANTIZER_H
#define GU_QUANTIZER_H
#include "foundation/Px.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
//////////////////////////////////////////////////////////////////////////
// K-means quantization class
// see http://en.wikipedia.org/wiki/K-means_clustering
// implementation from John Ratcliff http://codesuppository.blogspot.ch/2010/12/k-means-clustering-algorithm.html
class Quantizer
{
public:
// quantize the input vertices
virtual const PxVec3* kmeansQuantize3D( PxU32 vcount,
const PxVec3* vertices,
PxU32 stride,
bool denormalizeResults,
PxU32 maxVertices,
PxU32& outVertsCount) = 0;
// returns the denormalized scale
virtual const PxVec3& getDenormalizeScale() const = 0;
// returns the denormalized center
virtual const PxVec3& getDenormalizeCenter() const = 0;
// release internal data
virtual void release() = 0;
protected:
virtual ~Quantizer()
{
}
};
// creates the quantizer class
Quantizer * createQuantizer();
}
}
#endif
| 2,785 | C | 35.657894 | 114 | 0.720646 |
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/GuMeshCleaner.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_CLEANER_H
#define GU_MESH_CLEANER_H
#include "foundation/Px.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class MeshCleaner
{
public:
MeshCleaner(PxU32 nbVerts, const PxVec3* verts, PxU32 nbTris, const PxU32* indices, PxF32 meshWeldTolerance, PxF32 areaLimit);
~MeshCleaner();
PxU32 mNbVerts;
PxU32 mNbTris;
PxVec3* mVerts;
PxU32* mIndices;
PxU32* mRemap;
};
}
}
#endif
| 2,145 | C | 37.321428 | 129 | 0.755711 |
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/GuSeparatingAxes.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 "GuSeparatingAxes.h"
using namespace physx;
union FloatInt
{
float f;
PxU32 i;
};
bool Gu::SeparatingAxes::addAxis(const PxVec3& axis)
{
PxU32 numAxes = getNumAxes();
const PxVec3* PX_RESTRICT axes = getAxes();
const PxVec3* PX_RESTRICT axes_end = axes + numAxes;
while(axes<axes_end)
{
if(PxAbs(axis.dot(*axes))>0.9999f)
return false;
axes++;
}
#ifdef SEP_AXIS_FIXED_MEMORY
if(mNbAxes<SEP_AXIS_FIXED_MEMORY)
{
mAxes[mNbAxes++] = axis;
return true;
}
return false;
#else
mAxes.pushBack(axis);
return true;
#endif
}
| 2,252 | C++ | 34.203124 | 74 | 0.746892 |
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(¶ms->mLocalDir_Padded.x);
const Vec4V pvecV = V4Cross(localDirV, edge2V);
const __m128 detV = DotV(edge1V, pvecV);
if(params->mBackfaceCulling)
{
const Vec4V tvecV = V4Sub(V4LoadU(¶ms->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(¶ms->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(¶ms->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(¶ms->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(¶ms->mVerts[VRef0].x), ¶ms->mP0_PaddedAligned.x);
V4StoreA_Safe(V4LoadU_Safe(¶ms->mVerts[VRef1].x), ¶ms->mP1_PaddedAligned.x);
V4StoreA_Safe(V4LoadU_Safe(¶ms->mVerts[VRef2].x), ¶ms->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(¶ms->mP0_PaddedAligned.x);
const Vec4V P1V = V4LoadA_Safe(¶ms->mP1_PaddedAligned.x);
const Vec4V P2V = V4LoadA_Safe(¶ms->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(¶ms->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(¶ms->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(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x));
const VecI32V centerVShift = VecI32V_RightShift(centerVI, 16);
const Vec4V centerV = V4Mul(Vec4V_From_VecI32V(centerVShift), V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x));
#endif
const Vec4V fdirV = V4LoadA_Safe(¶ms->mFDir_PaddedAligned.x);
const Vec4V DV = V4Sub(V4LoadA_Safe(¶ms->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(¶ms->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(¶ms->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(¶ms->mFDir_PaddedAligned.x);
const Vec4V extentsV = V4LoadU(&extents.x);
const Vec4V DV = V4Sub(V4LoadA_Safe(¶ms->mData2_PaddedAligned.x), V4LoadU(¢er.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(¶ms->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(¶ms->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/GuBV32Build.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_BUILD_H
#define GU_BV32_BUILD_H
#include "foundation/PxSimpleTypes.h"
#include "common/PxPhysXCommonConfig.h"
#define BV32_VALIDATE 0
namespace physx
{
namespace Gu
{
class BV32Tree;
class SourceMeshBase;
bool BuildBV32Ex(BV32Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivesPerLeaf);
} // namespace Gu
}
#endif // GU_BV32_BUILD_H
| 2,078 | C | 40.579999 | 99 | 0.763234 |
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(¶ms->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, ¶ms->mP0.x);
// V4StoreU_Safe(v1V, ¶ms->mP1.x);
// V4StoreU_Safe(v2V, ¶ms->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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.