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/GuBVH.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 "foundation/PxFPU.h"
#include "foundation/PxPlane.h"
#include "geometry/PxGeometryInternal.h"
#include "GuBVH.h"
#include "GuAABBTreeQuery.h"
#include "GuAABBTreeNode.h"
#include "GuAABBTreeBuildStats.h"
#include "GuMeshFactory.h"
#include "GuQuery.h"
#include "CmSerialize.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
///////////////////////////////////////////////////////////////////////////////
// PT: these two functions moved from cooking
bool BVHData::build(PxU32 nbBounds, const void* boundsData, PxU32 boundsStride, float enlargement, PxU32 nbPrimsPerLeaf, BVHBuildStrategy bs)
{
if(!nbBounds || !boundsData || boundsStride<sizeof(PxBounds3) || enlargement<0.0f || nbPrimsPerLeaf>=16)
return false;
mBounds.init(nbBounds);
if(nbBounds)
{
const PxU8* sB = reinterpret_cast<const PxU8*>(boundsData);
for(PxU32 i=0; i<nbBounds-1; i++)
{
inflateBounds<true>(mBounds.getBounds()[i], *reinterpret_cast<const PxBounds3*>(sB), enlargement);
sB += boundsStride;
}
inflateBounds<false>(mBounds.getBounds()[nbBounds-1], *reinterpret_cast<const PxBounds3*>(sB), enlargement);
}
mNbIndices = nbBounds;
// build the BVH
BuildStats stats;
NodeAllocator nodeAllocator;
mIndices = buildAABBTree(AABBTreeBuildParams(nbPrimsPerLeaf, nbBounds, &mBounds, bs), nodeAllocator, stats);
if(!mIndices)
return false;
// store the computed hierarchy
mNbNodes = stats.getCount();
mNodes = PX_ALLOCATE(BVHNode, mNbNodes, "AABB tree nodes");
PX_ASSERT(mNbNodes==nodeAllocator.mTotalNbNodes);
// store the results into BVHNode list
if(nbPrimsPerLeaf==1)
{
// PT: with 1 prim/leaf we don't need the remap table anymore, we can just store the prim index in each tree node directly.
flattenTree(nodeAllocator, mNodes, mIndices);
PX_FREE(mIndices);
}
else
flattenTree(nodeAllocator, mNodes);
return true;
}
// A.B. move to load code
#define PX_BVH_STRUCTURE_VERSION 1
bool BVHData::save(PxOutputStream& stream, bool endian) const
{
// write header
if(!writeHeader('B', 'V', 'H', 'S', PX_BVH_STRUCTURE_VERSION, endian, stream))
return false;
// write mData members
writeDword(mNbIndices, endian, stream);
writeDword(mNbNodes, endian, stream);
// write indices and bounds
for(PxU32 i=0; i<mNbIndices; i++)
writeDword(mIndices[i], endian, stream);
const PxBounds3* bounds = mBounds.getBounds();
for(PxU32 i=0; i<mNbIndices; i++)
{
writeFloatBuffer(&bounds[i].minimum.x, 3, endian, stream);
writeFloatBuffer(&bounds[i].maximum.x, 3, endian, stream);
}
// write nodes
for(PxU32 i=0; i<mNbNodes; i++)
{
writeDword(mNodes[i].mData, endian, stream);
writeFloatBuffer(&mNodes[i].mBV.minimum.x, 3, endian, stream);
writeFloatBuffer(&mNodes[i].mBV.maximum.x, 3, endian, stream);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// PT: temporary for Kit
BVH::BVH(const PxBVHInternalData& data) :
PxBVH (PxType(PxConcreteType::eBVH), PxBaseFlags(0)),
mMeshFactory (NULL)
{
mData.mNbIndices = data.mNbIndices;
mData.mNbNodes = data.mNbNodes;
mData.mIndices = data.mIndices;
mData.mNodes = reinterpret_cast<BVHNode*>(data.mNodes);
mData.mBounds.setBounds(reinterpret_cast<PxBounds3*>(data.mBounds));
}
bool BVH::getInternalData(PxBVHInternalData& data, bool takeOwnership) const
{
data.mNbIndices = mData.mNbIndices;
data.mNbNodes = mData.mNbNodes;
data.mNodeSize = sizeof(BVHNode);
data.mNodes = mData.mNodes;
data.mIndices = mData.mIndices;
data.mBounds = const_cast<PxBounds3*>(mData.mBounds.getBounds());
if(takeOwnership)
const_cast<BVH*>(this)->mData.mBounds.takeOwnership();
return true;
}
bool physx::PxGetBVHInternalData(PxBVHInternalData& data, const PxBVH& bvh, bool takeOwnership)
{
return static_cast<const BVH&>(bvh).getInternalData(data, takeOwnership);
}
//~ PT: temporary for Kit
BVH::BVH(MeshFactory* factory) :
PxBVH (PxType(PxConcreteType::eBVH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mMeshFactory (factory)
{
}
BVH::BVH(MeshFactory* factory, BVHData& bvhData) :
PxBVH (PxType(PxConcreteType::eBVH), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mMeshFactory (factory),
mData (bvhData)
{
}
BVH::~BVH()
{
}
bool BVH::init(PxU32 nbPrims, AABBTreeBounds* bounds, const void* boundsData, PxU32 stride, BVHBuildStrategy bs, PxU32 nbPrimsPerLeaf, float enlargement)
{
if(!nbPrims)
return false;
if(bounds)
{
mData.mBounds.moveFrom(*bounds);
}
else
{
mData.mBounds.init(nbPrims);
PxBounds3* dst = mData.mBounds.getBounds();
if(stride==sizeof(PxBounds3))
{
PxMemCopy(dst, boundsData, sizeof(PxBounds3)*nbPrims);
}
else
{
if(nbPrims)
{
const PxU8* sB = reinterpret_cast<const PxU8*>(boundsData);
for(PxU32 i=0; i<nbPrims-1; i++)
{
inflateBounds<true>(mData.mBounds.getBounds()[i], *reinterpret_cast<const PxBounds3*>(sB), enlargement);
sB += stride;
}
inflateBounds<false>(mData.mBounds.getBounds()[nbPrims-1], *reinterpret_cast<const PxBounds3*>(sB), enlargement);
}
}
}
mData.mNbIndices = nbPrims;
// build the BVH
BuildStats stats;
NodeAllocator nodeAllocator;
mData.mIndices = buildAABBTree(AABBTreeBuildParams(nbPrimsPerLeaf, nbPrims, &mData.mBounds, bs), nodeAllocator, stats);
if(!mData.mIndices)
return false;
// store the computed hierarchy
mData.mNbNodes = stats.getCount();
mData.mNodes = PX_ALLOCATE(BVHNode, mData.mNbNodes, "AABB tree nodes");
PX_ASSERT(mData.mNbNodes==nodeAllocator.mTotalNbNodes);
// store the results into BVHNode list
if(nbPrimsPerLeaf==1)
{
// PT: with 1 prim/leaf we don't need the remap table anymore, we can just store the prim index in each tree node directly.
flattenTree(nodeAllocator, mData.mNodes, mData.mIndices);
PX_FREE(mData.mIndices);
}
else
flattenTree(nodeAllocator, mData.mNodes);
return true;
}
bool BVH::load(PxInputStream& stream)
{
// Import header
PxU32 version;
bool mismatch;
if(!readHeader('B', 'V', 'H', 'S', version, mismatch, stream))
return false;
// read numVolumes, numNodes together
//ReadDwordBuffer(&mData.mNbIndices, 2, mismatch, stream);
mData.mNbIndices = readDword(mismatch, stream);
mData.mNbNodes = readDword(mismatch, stream);
// read indices
mData.mIndices = PX_ALLOCATE(PxU32, mData.mNbIndices, "BVH indices");
ReadDwordBuffer(mData.mIndices, mData.mNbIndices, mismatch, stream);
// read bounds
mData.mBounds.init(mData.mNbIndices);
readFloatBuffer(&mData.mBounds.getBounds()->minimum.x, mData.mNbIndices*(3 + 3), mismatch, stream);
// read nodes
mData.mNodes = PX_ALLOCATE(BVHNode, mData.mNbNodes, "BVH nodes");
for(PxU32 i = 0; i < mData.mNbNodes; i++)
{
ReadDwordBuffer(&mData.mNodes[i].mData, 1, mismatch, stream);
readFloatBuffer(&mData.mNodes[i].mBV.minimum.x, 3 + 3, mismatch, stream);
}
return true;
}
void BVH::release()
{
decRefCount();
}
void BVH::onRefCountZero()
{
::onRefCountZero(this, mMeshFactory, false, "PxBVH::release: double deletion detected!");
}
namespace
{
struct BVHTree
{
PX_FORCE_INLINE BVHTree(const BVHData& data) : mRootNode(data.mNodes), mIndices(data.mIndices) {}
const BVHNode* getNodes() const { return mRootNode; }
const PxU32* getIndices() const { return mIndices; }
const BVHNode* mRootNode;
const PxU32* mIndices;
};
}
namespace
{
struct RaycastAdapter
{
RaycastAdapter(PxBVH::RaycastCallback& cb) : mCallback(cb), mAbort(false) {}
PX_FORCE_INLINE bool invoke(PxReal& distance, PxU32 index)
{
if(mAbort || !mCallback.reportHit(index, distance))
{
mAbort = true;
return false;
}
return true;
}
PxBVH::RaycastCallback& mCallback;
bool mAbort;
PX_NOCOPY(RaycastAdapter)
};
}
bool BVH::raycast(const PxVec3& origin, const PxVec3& unitDir, float distance, RaycastCallback& cb, PxGeometryQueryFlags flags) const
{
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
RaycastAdapter ra(cb);
if(mData.mIndices)
return AABBTreeRaycast<false, true, BVHTree, BVHNode, RaycastAdapter>()(mData.mBounds, BVHTree(mData), origin, unitDir, distance, PxVec3(0.0f), ra);
else
return AABBTreeRaycast<false, false, BVHTree, BVHNode, RaycastAdapter>()(mData.mBounds, BVHTree(mData), origin, unitDir, distance, PxVec3(0.0f), ra);
}
namespace
{
struct OverlapAdapter
{
OverlapAdapter(PxBVH::OverlapCallback& cb) : mCallback(cb), mAbort(false) {}
PX_FORCE_INLINE bool invoke(PxU32 index)
{
if(mAbort || !mCallback.reportHit(index))
{
mAbort = true;
return false;
}
return true;
}
PxBVH::OverlapCallback& mCallback;
bool mAbort;
PX_NOCOPY(OverlapAdapter)
};
}
bool BVH::overlap(const ShapeData& queryVolume, OverlapCallback& cb, PxGeometryQueryFlags flags) const
{
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
OverlapAdapter oa(cb);
switch(queryVolume.getType())
{
case PxGeometryType::eBOX:
{
if(queryVolume.isOBB())
{
const DefaultOBBAABBTest test(queryVolume);
if(mData.mIndices)
return AABBTreeOverlap<true, OBBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, OBBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
else
{
const DefaultAABBAABBTest test(queryVolume);
if(mData.mIndices)
return AABBTreeOverlap<true, AABBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, AABBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
}
case PxGeometryType::eCAPSULE:
{
const DefaultCapsuleAABBTest test(queryVolume, 1.0f);
if(mData.mIndices)
return AABBTreeOverlap<true, CapsuleAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, CapsuleAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
case PxGeometryType::eSPHERE:
{
const DefaultSphereAABBTest test(queryVolume);
if(mData.mIndices)
return AABBTreeOverlap<true, SphereAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, SphereAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
case PxGeometryType::eCONVEXMESH:
{
const DefaultOBBAABBTest test(queryVolume);
if(mData.mIndices)
return AABBTreeOverlap<true, OBBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, OBBAABBTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
default:
PX_ALWAYS_ASSERT_MESSAGE("unsupported overlap query volume geometry type");
}
return false;
}
bool BVH::overlap(const PxGeometry& geom, const PxTransform& pose, OverlapCallback& cb, PxGeometryQueryFlags flags) const
{
const ShapeData queryVolume(geom, pose, 0.0f);
return overlap(queryVolume, cb, flags);
}
bool BVH::sweep(const ShapeData& queryVolume, const PxVec3& unitDir, float distance, RaycastCallback& cb, PxGeometryQueryFlags flags) const
{
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
const PxBounds3& aabb = queryVolume.getPrunerInflatedWorldAABB();
RaycastAdapter ra(cb);
if(mData.mIndices)
return AABBTreeRaycast<true, true, BVHTree, BVHNode, RaycastAdapter>()(mData.mBounds, BVHTree(mData), aabb.getCenter(), unitDir, distance, aabb.getExtents(), ra);
else
return AABBTreeRaycast<true, false, BVHTree, BVHNode, RaycastAdapter>()(mData.mBounds, BVHTree(mData), aabb.getCenter(), unitDir, distance, aabb.getExtents(), ra);
}
bool BVH::sweep(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float distance, RaycastCallback& cb, PxGeometryQueryFlags flags) const
{
const ShapeData queryVolume(geom, pose, 0.0f);
return sweep(queryVolume, unitDir, distance, cb, flags);
}
namespace
{
PX_FORCE_INLINE bool planesAABBOverlap(const PxVec3& m, const PxVec3& d, const PxPlane* p, PxU32& outClipMask, PxU32 inClipMask)
{
PxU32 mask = 1;
PxU32 tmpOutClipMask = 0;
while(mask<=inClipMask)
{
if(inClipMask & mask)
{
const float NP = d.x*fabsf(p->n.x) + d.y*fabsf(p->n.y) + d.z*fabsf(p->n.z);
const float MP = m.x*p->n.x + m.y*p->n.y + m.z*p->n.z + p->d;
if(NP < MP)
return false;
if((-NP) < MP)
tmpOutClipMask |= mask;
}
mask+=mask;
p++;
}
outClipMask = tmpOutClipMask;
return true;
}
struct FrustumTest
{
FrustumTest(PxU32 nbPlanes, const PxPlane* planes) : mPlanes(planes), mMask((1<<nbPlanes)-1), mNbPlanes(nbPlanes), mOutClipMask(0)
{
}
PX_FORCE_INLINE PxIntBool operator()(const Vec3V boxCenter, const Vec3V boxExtents) const
{
// PT: TODO: rewrite all this in SIMD
PxVec3 center, extents;
V3StoreU(boxCenter, center);
V3StoreU(boxExtents, extents);
if(!planesAABBOverlap(center, extents, mPlanes, mOutClipMask, mMask))
return PxIntFalse;
// PT: unfortunately the AABBTreeOverlap template doesn't support this case where we know we can
// immediately dump the rest of the tree (i.e. the old "containment tests" in Opcode). We might
// want to revisit this at some point.
//
// In fact it's worse than this: we lost the necessary data to make this quick, in "flattenTree"
// when going from AABBTreeBuildNodes to BVHNodes. The BVHNodes lost the primitive-related info
// for internal (non-leaf) nodes so we cannot just dump a list of primitives when an internal
// node is fully visible (like we did in Opcode 1.x). Best we can do is keep traversing the tree
// and skip VFC tests.
//if(!outClipMask)
return PxIntTrue;
}
const PxPlane* mPlanes;
const PxU32 mMask;
const PxU32 mNbPlanes;
mutable PxU32 mOutClipMask;
PX_NOCOPY(FrustumTest)
};
}
static bool dumpNode(OverlapAdapter& oa, const BVHNode* const nodeBase, const BVHNode* node0, const PxU32* indices)
{
PxInlineArray<const BVHNode*, RAW_TRAVERSAL_STACK_SIZE> stack;
stack.forceSize_Unsafe(RAW_TRAVERSAL_STACK_SIZE);
stack[0] = node0;
PxU32 stackIndex = 1;
while(stackIndex > 0)
{
const BVHNode* node = stack[--stackIndex];
while(1)
{
if(node->isLeaf())
{
PxU32 nbPrims = node->getNbPrimitives();
const PxU32* prims = indices ? node->getPrimitives(indices) : NULL;
while(nbPrims--)
{
const PxU32 primIndex = indices ? *prims++ : node->getPrimitiveIndex();
if(!oa.invoke(primIndex))
return false;
}
break;
}
else
{
const BVHNode* children = node->getPos(nodeBase);
node = children;
stack[stackIndex++] = children + 1;
if(stackIndex == stack.capacity())
stack.resizeUninitialized(stack.capacity() * 2);
}
}
}
return true;
}
bool BVH::cull(PxU32 nbPlanes, const PxPlane* planes, OverlapCallback& cb, PxGeometryQueryFlags flags) const
{
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
OverlapAdapter oa(cb);
const FrustumTest test(nbPlanes, planes);
if(0)
{
// PT: this vanilla codepath is slower
if(mData.mIndices)
return AABBTreeOverlap<true, FrustumTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
else
return AABBTreeOverlap<false, FrustumTest, BVHTree, BVHNode, OverlapAdapter>()(mData.mBounds, BVHTree(mData), test, oa);
}
else
{
const PxBounds3* bounds = mData.mBounds.getBounds();
const bool hasIndices = mData.mIndices!=NULL;
PxInlineArray<const BVHNode*, RAW_TRAVERSAL_STACK_SIZE> stack;
stack.forceSize_Unsafe(RAW_TRAVERSAL_STACK_SIZE);
const BVHNode* const nodeBase = mData.mNodes;
stack[0] = nodeBase;
PxU32 stackIndex = 1;
while(stackIndex > 0)
{
const BVHNode* node = stack[--stackIndex];
Vec3V center, extents;
node->getAABBCenterExtentsV(¢er, &extents);
while(test(center, extents))
{
if(!test.mOutClipMask)
{
if(!dumpNode(oa, nodeBase, node, mData.mIndices))
return false;
break;
}
else
{
if(node->isLeaf())
{
PxU32 nbPrims = node->getNbPrimitives();
const bool doBoxTest = nbPrims > 1;
const PxU32* prims = hasIndices ? node->getPrimitives(mData.mIndices) : NULL;
while(nbPrims--)
{
const PxU32 primIndex = hasIndices ? *prims++ : node->getPrimitiveIndex();
if(doBoxTest)
{
Vec4V center2, extents2;
getBoundsTimesTwo(center2, extents2, bounds, primIndex);
const float half = 0.5f;
const FloatV halfV = FLoad(half);
const Vec4V extents_ = V4Scale(extents2, halfV);
const Vec4V center_ = V4Scale(center2, halfV);
if(!test(Vec3V_From_Vec4V(center_), Vec3V_From_Vec4V(extents_)))
continue;
}
if(!oa.invoke(primIndex))
return false;
}
break;
}
const BVHNode* children = node->getPos(nodeBase);
node = children;
stack[stackIndex++] = children + 1;
if(stackIndex == stack.capacity())
stack.resizeUninitialized(stack.capacity() * 2);
node->getAABBCenterExtentsV(¢er, &extents);
}
}
}
return true;
}
}
void BVH::refit()
{
mData.fullRefit(mData.mBounds.getBounds());
}
bool BVH::updateBoundsInternal(PxU32 localIndex, const PxBounds3& newBounds)
{
if(localIndex>=mData.mNbIndices)
return false;
PxBounds3* bounds = mData.mBounds.getBounds();
bounds[localIndex] = newBounds;
// Lazy-create update map
if(!mData.getUpdateMap())
mData.createUpdateMap(mData.mNbIndices);
PxU32* mMapping = mData.getUpdateMap();
if(mMapping)
{
const PxU32 treeNodeIndex = mMapping[localIndex];
if(treeNodeIndex!=0xffffffff)
{
mData.markNodeForRefit(treeNodeIndex);
return true;
}
}
return false;
}
bool BVH::updateBounds(PxU32 boundsIndex, const PxBounds3& newBounds)
{
return updateBoundsInternal(boundsIndex, newBounds);
}
void BVH::partialRefit()
{
mData.refitMarkedNodes(mData.mBounds.getBounds());
}
bool BVH::traverse(TraversalCallback& cb) const
{
// PT: copy-pasted from AABBTreeOverlap and modified
PxInlineArray<const BVHNode*, RAW_TRAVERSAL_STACK_SIZE> stack;
stack.forceSize_Unsafe(RAW_TRAVERSAL_STACK_SIZE);
const BVHNode* const nodeBase = mData.getNodes();
stack[0] = nodeBase;
PxU32 stackIndex = 1;
while(stackIndex > 0)
{
const BVHNode* node = stack[--stackIndex];
while(cb.visitNode(node->mBV))
{
if(node->isLeaf())
{
if(mData.getIndices())
{
if(!cb.reportLeaf(node->getNbPrimitives(), node->getPrimitives(mData.getIndices())))
return false;
}
else
{
PX_ASSERT(node->getNbPrimitives()==1);
const PxU32 primIndex = node->getPrimitiveIndex();
if(!cb.reportLeaf(node->getNbPrimitives(), &primIndex))
return false;
}
break;
}
const BVHNode* children = node->getPos(nodeBase);
node = children;
stack[stackIndex++] = children + 1;
if(stackIndex == stack.capacity())
stack.resizeUninitialized(stack.capacity() * 2);
}
}
return true;
}
#include "geometry/PxMeshQuery.h"
#define GU_BVH_STACK_SIZE 1024 // Default size of local stacks for non-recursive traversals.
static bool doLeafVsLeaf(PxReportCallback<PxGeomIndexPair>& callback, const BVHNode* node0, const PxBounds3* bounds0, const PxU32* indices0,
const BVHNode* node1, const PxBounds3* bounds1, const PxU32* indices1,
bool& abort)
{
PxGeomIndexPair* dst = callback.mBuffer;
PxU32 capacity = callback.mCapacity;
PxU32 currentSize = callback.mSize;
PX_ASSERT(currentSize<capacity);
bool foundHit = false;
abort = false;
const FloatV halfV = FLoad(0.5f);
PxU32 nbPrims0 = node0->getNbPrimitives();
const PxU32* prims0 = indices0 ? node0->getPrimitives(indices0) : NULL;
while(nbPrims0--)
{
const PxU32 primIndex0 = prims0 ? *prims0++ : node0->getPrimitiveIndex();
Vec3V center0, extents0;
{
Vec4V center2, extents2;
getBoundsTimesTwo(center2, extents2, bounds0, primIndex0);
extents0 = Vec3V_From_Vec4V(V4Scale(extents2, halfV));
center0 = Vec3V_From_Vec4V(V4Scale(center2, halfV));
}
PxU32 nbPrims1 = node1->getNbPrimitives();
const PxU32* prims1 = indices1 ? node1->getPrimitives(indices1) : NULL;
while(nbPrims1--)
{
const PxU32 primIndex1 = prims1 ? *prims1++ : node1->getPrimitiveIndex();
Vec3V center1, extents1;
{
Vec4V center2, extents2;
getBoundsTimesTwo(center2, extents2, bounds1, primIndex1);
extents1 = Vec3V_From_Vec4V(V4Scale(extents2, halfV));
center1 = Vec3V_From_Vec4V(V4Scale(center2, halfV));
}
if(PxIntBool(V3AllGrtrOrEq(V3Add(extents0, extents1), V3Abs(V3Sub(center1, center0)))))
{
foundHit = true;
// PT: TODO: refactor callback management code with BVH34
dst[currentSize].id0 = primIndex0;
dst[currentSize].id1 = primIndex1;
currentSize++;
if(currentSize==capacity)
{
callback.mSize = 0;
if(!callback.flushResults(currentSize, dst))
{
abort = true;
return foundHit;
}
dst = callback.mBuffer;
capacity = callback.mCapacity;
currentSize = callback.mSize;
}
}
}
}
callback.mSize = currentSize;
return foundHit;
}
static PX_FORCE_INLINE void pushChildren(PxGeomIndexPair* stack, PxU32& nb, PxU32 a, PxU32 b, PxU32 c, PxU32 d)
{
stack[nb].id0 = a;
stack[nb].id1 = b;
nb++;
stack[nb].id0 = c;
stack[nb].id1 = d;
nb++;
}
static PX_NOINLINE bool abortQuery(PxReportCallback<PxGeomIndexPair>& callback, bool& abort)
{
abort = true;
callback.mSize = 0;
return true;
}
static bool BVH_BVH(PxReportCallback<PxGeomIndexPair>& callback, const BVH& tree0, const BVH& tree1, bool& _abort)
{
const BVHNode* PX_RESTRICT node0 = tree0.getNodes();
const BVHNode* PX_RESTRICT node1 = tree1.getNodes();
PX_ASSERT(node0 && node1);
const PxBounds3* bounds0 = tree0.getData().mBounds.getBounds();
const PxBounds3* bounds1 = tree1.getData().mBounds.getBounds();
const PxU32* indices0 = tree0.getIndices();
const PxU32* indices1 = tree1.getIndices();
{
PxU32 nb=1;
PxGeomIndexPair stack[GU_BVH_STACK_SIZE];
stack[0].id0 = 0;
stack[0].id1 = 0;
bool status = false;
const BVHNode* const root0 = node0;
const BVHNode* const root1 = node1;
do
{
const PxGeomIndexPair& childData = stack[--nb];
node0 = root0 + childData.id0;
node1 = root1 + childData.id1;
if(node0->mBV.intersects(node1->mBV))
{
const PxU32 isLeaf0 = node0->isLeaf();
const PxU32 isLeaf1 = node1->isLeaf();
if(isLeaf0)
{
if(isLeaf1)
{
bool abort;
if(doLeafVsLeaf(callback, node0, bounds0, indices0, node1, bounds1, indices1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
}
else
{
const PxU32 posIndex1 = node1->getPosIndex();
pushChildren(stack, nb, childData.id0, posIndex1, childData.id0, posIndex1 + 1);
}
}
else if(isLeaf1)
{
const PxU32 posIndex0 = node0->getPosIndex();
pushChildren(stack, nb, posIndex0, childData.id1, posIndex0 + 1, childData.id1);
}
else
{
const PxU32 posIndex0 = node0->getPosIndex();
const PxU32 posIndex1 = node1->getPosIndex();
pushChildren(stack, nb, posIndex0, posIndex1, posIndex0, posIndex1 + 1);
pushChildren(stack, nb, posIndex0 + 1, posIndex1, posIndex0 + 1, posIndex1 + 1);
}
}
}while(nb);
return status;
}
}
bool physx::PxFindOverlap(PxReportCallback<PxGeomIndexPair>& callback, const PxBVH& bvh0, const PxBVH& bvh1)
{
PX_SIMD_GUARD
// PT: TODO: refactor callback management code with BVH34
PxGeomIndexPair stackBuffer[256];
bool mustResetBuffer;
if(callback.mBuffer)
{
PX_ASSERT(callback.mCapacity);
mustResetBuffer = false;
}
else
{
callback.mBuffer = stackBuffer;
PX_ASSERT(callback.mCapacity<=256);
if(callback.mCapacity==0 || callback.mCapacity>256)
{
callback.mCapacity = 256;
}
callback.mSize = 0;
mustResetBuffer = true;
}
bool abort = false;
const bool status = BVH_BVH(callback, static_cast<const BVH&>(bvh0), static_cast<const BVH&>(bvh1), abort);
if(!abort)
{
const PxU32 currentSize = callback.mSize;
if(currentSize)
{
callback.mSize = 0;
callback.flushResults(currentSize, callback.mBuffer);
}
}
if(mustResetBuffer)
callback.mBuffer = NULL;
return status;
}
| 26,115 | C++ | 27.793826 | 165 | 0.700632 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/GuCookingSDF.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 "GuCookingSDF.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "GuSDF.h"
#include "GuCooking.h"
#include "PxSDFBuilder.h"
namespace physx
{
struct MeshData
{
MeshData(const PxTriangleMeshDesc& desc)
{
m_positions.resize(desc.points.count);
m_indices.resize(desc.triangles.count * 3);
immediateCooking::gatherStrided(desc.points.data, &m_positions[0], desc.points.count, sizeof(PxVec3), desc.points.stride);
immediateCooking::gatherStrided(desc.triangles.data, &m_indices[0], desc.triangles.count, 3 * sizeof(PxU32), desc.triangles.stride);
}
void GetBounds(PxVec3& outMinExtents, PxVec3& outMaxExtents) const
{
PxVec3 minExtents(FLT_MAX);
PxVec3 maxExtents(-FLT_MAX);
for (PxU32 i = 0; i < m_positions.size(); ++i)
{
const PxVec3& a = m_positions[i];
minExtents = a.minimum(minExtents);
maxExtents = a.maximum(maxExtents);
}
outMinExtents = minExtents;
outMaxExtents = maxExtents;
}
PxArray<PxVec3> m_positions;
PxArray<PxU32> m_indices;
};
PX_PHYSX_COMMON_API void quantizeSparseSDF(PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel,
const PxArray<PxReal>& uncompressedSdfDataSubgrids, PxArray<PxU8>& compressedSdfDataSubgrids,
PxReal subgridsMinSdfValue, PxReal subgridsMaxSdfValue)
{
PxU32 bytesPerPixel = PxU32(bitsPerSubgridPixel);
compressedSdfDataSubgrids.resize(uncompressedSdfDataSubgrids.size() * bytesPerPixel);
PxReal* ptr32 = reinterpret_cast<PxReal*>(compressedSdfDataSubgrids.begin());
PxU16* ptr16 = reinterpret_cast<PxU16*>(compressedSdfDataSubgrids.begin());
PxU8* ptr8 = compressedSdfDataSubgrids.begin();
PxReal s = 1.0f / (subgridsMaxSdfValue - subgridsMinSdfValue);
for (PxU32 i = 0; i < uncompressedSdfDataSubgrids.size(); ++i)
{
PxReal v = uncompressedSdfDataSubgrids[i];
PxReal vNormalized = (v - subgridsMinSdfValue) * s;
switch (bitsPerSubgridPixel)
{
case PxSdfBitsPerSubgridPixel::e8_BIT_PER_PIXEL:
ptr8[i] = PxU8(255.0f * vNormalized);
break;
case PxSdfBitsPerSubgridPixel::e16_BIT_PER_PIXEL:
ptr16[i] = PxU16(65535.0f * vNormalized);
break;
case PxSdfBitsPerSubgridPixel::e32_BIT_PER_PIXEL:
ptr32[i] = v;
break;
}
}
}
PX_FORCE_INLINE PxU32 idxCompact(PxU32 x, PxU32 y, PxU32 z, PxU32 width, PxU32 height)
{
return z * (width) * (height)+y * (width)+x;
}
void convert16To32Bits(PxSimpleTriangleMesh mesh, PxArray<PxU32>& indices32)
{
indices32.resize(3 * mesh.triangles.count);
if (mesh.flags & PxMeshFlag::e16_BIT_INDICES)
{
// conversion; 16 bit index -> 32 bit index & stride
PxU32* dest = indices32.begin();
const PxU32* pastLastDest = indices32.begin() + 3 * mesh.triangles.count;
const PxU8* source = reinterpret_cast<const PxU8*>(mesh.triangles.data);
while (dest < pastLastDest)
{
const PxU16 * trig16 = reinterpret_cast<const PxU16*>(source);
*dest++ = trig16[0];
*dest++ = trig16[1];
*dest++ = trig16[2];
source += mesh.triangles.stride;
}
}
else
{
immediateCooking::gatherStrided(mesh.triangles.data, indices32.begin(), mesh.triangles.count, sizeof(PxU32) * 3, mesh.triangles.stride);
}
}
static bool createSDFSparse(PxTriangleMeshDesc& desc, PxSDFDesc& sdfDesc, PxArray<PxReal>& sdfCoarse, PxArray<PxU8>& sdfDataSubgrids,
PxArray<PxU32>& sdfSubgridsStartSlots)
{
PX_ASSERT(sdfDesc.subgridSize > 0);
MeshData mesh(desc);
PxVec3 meshLower, meshUpper;
if (sdfDesc.sdfBounds.isEmpty())
mesh.GetBounds(meshLower, meshUpper);
else
{
meshLower = sdfDesc.sdfBounds.minimum;
meshUpper = sdfDesc.sdfBounds.maximum;
}
PxVec3 edges = meshUpper - meshLower;
const PxReal spacing = sdfDesc.spacing;
// tweak spacing to avoid edge cases for vertices laying on the boundary
// just covers the case where an edge is a whole multiple of the spacing.
PxReal spacingEps = spacing * (1.0f - 1e-4f);
// make sure to have at least one particle in each dimension
PxI32 dx, dy, dz;
dx = spacing > edges.x ? 1 : PxI32(edges.x / spacingEps);
dy = spacing > edges.y ? 1 : PxI32(edges.y / spacingEps);
dz = spacing > edges.z ? 1 : PxI32(edges.z / spacingEps);
dx += 4;
dy += 4;
dz += 4;
//Make sure that dx, dy and dz are multiple of subgridSize
dx = ((dx + sdfDesc.subgridSize - 1) / sdfDesc.subgridSize) * sdfDesc.subgridSize;
dy = ((dy + sdfDesc.subgridSize - 1) / sdfDesc.subgridSize) * sdfDesc.subgridSize;
dz = ((dz + sdfDesc.subgridSize - 1) / sdfDesc.subgridSize) * sdfDesc.subgridSize;
PX_ASSERT(dx % sdfDesc.subgridSize == 0);
PX_ASSERT(dy % sdfDesc.subgridSize == 0);
PX_ASSERT(dz % sdfDesc.subgridSize == 0);
// we shift the voxelization bounds so that the voxel centers
// lie symmetrically to the center of the object. this reduces the
// chance of missing features, and also better aligns the particles
// with the mesh
PxVec3 meshOffset;
meshOffset.x = 0.5f * (spacing - (edges.x - (dx - 1)*spacing));
meshOffset.y = 0.5f * (spacing - (edges.y - (dy - 1)*spacing));
meshOffset.z = 0.5f * (spacing - (edges.z - (dz - 1)*spacing));
meshLower -= meshOffset;
sdfDesc.meshLower = meshLower;
sdfDesc.dims.x = dx;
sdfDesc.dims.y = dy;
sdfDesc.dims.z = dz;
PxArray<PxU32> indices32;
PxArray<PxVec3> vertices;
const PxVec3* verticesPtr = NULL;
bool baseMeshSpecified = sdfDesc.baseMesh.triangles.data && sdfDesc.baseMesh.points.data;
if (baseMeshSpecified)
{
convert16To32Bits(sdfDesc.baseMesh, indices32);
if (sdfDesc.baseMesh.points.stride != sizeof(PxVec3))
{
vertices.resize(sdfDesc.baseMesh.points.count);
immediateCooking::gatherStrided(sdfDesc.baseMesh.points.data, vertices.begin(), sdfDesc.baseMesh.points.count, sizeof(PxVec3), sdfDesc.baseMesh.points.stride);
verticesPtr = vertices.begin();
}
else
verticesPtr = reinterpret_cast<const PxVec3*>(sdfDesc.baseMesh.points.data);
}
PxReal subgridsMinSdfValue = 0.0f;
PxReal subgridsMaxSdfValue = 1.0f;
PxReal narrowBandThickness = sdfDesc.narrowBandThicknessRelativeToSdfBoundsDiagonal * edges.magnitude();
if (sdfDesc.sdfBuilder == NULL)
{
PxArray<PxReal> denseSdf;
PxArray<PxReal> sparseSdf;
Gu::SDFUsingWindingNumbersSparse(
baseMeshSpecified ? verticesPtr : &mesh.m_positions[0],
baseMeshSpecified ? indices32.begin() : &mesh.m_indices[0],
baseMeshSpecified ? indices32.size() : mesh.m_indices.size(),
dx, dy, dz,
meshLower, meshLower + PxVec3(static_cast<PxReal>(dx), static_cast<PxReal>(dy), static_cast<PxReal>(dz)) * spacing, narrowBandThickness, sdfDesc.subgridSize,
sdfCoarse, sdfSubgridsStartSlots, sparseSdf, denseSdf, subgridsMinSdfValue, subgridsMaxSdfValue, 16, sdfDesc.sdfBuilder);
PxArray<PxReal> uncompressedSdfDataSubgrids;
Gu::convertSparseSDFTo3DTextureLayout(dx, dy, dz, sdfDesc.subgridSize, sdfSubgridsStartSlots.begin(), sparseSdf.begin(), sparseSdf.size(), uncompressedSdfDataSubgrids,
sdfDesc.sdfSubgrids3DTexBlockDim.x, sdfDesc.sdfSubgrids3DTexBlockDim.y, sdfDesc.sdfSubgrids3DTexBlockDim.z);
if (sdfDesc.bitsPerSubgridPixel == 4)
{
//32bit values are stored as normal floats while 16bit and 8bit values are scaled to 0...1 range and then scaled back to original range
subgridsMinSdfValue = 0.0f;
subgridsMaxSdfValue = 1.0f;
}
quantizeSparseSDF(sdfDesc.bitsPerSubgridPixel, uncompressedSdfDataSubgrids, sdfDataSubgrids,
subgridsMinSdfValue, subgridsMaxSdfValue);
}
else
{
PxU32* indices = baseMeshSpecified ? indices32.begin() : &mesh.m_indices[0];
PxU32 numTriangleIndices = baseMeshSpecified ? indices32.size() : mesh.m_indices.size();
const PxVec3* verts = baseMeshSpecified ? verticesPtr : &mesh.m_positions[0];
PxU32 numVertices = baseMeshSpecified ? sdfDesc.baseMesh.points.count : mesh.m_positions.size();
PxArray<PxU32> repairedIndices;
//Analyze the mesh to catch and fix some special cases
//There are meshes where every triangle is present once with cw and once with ccw orientation. Try to filter out only one set
Gu::analyzeAndFixMesh(verts, indices, numTriangleIndices, repairedIndices);
const PxU32* ind = repairedIndices.size() > 0 ? repairedIndices.begin() : indices;
if (repairedIndices.size() > 0)
numTriangleIndices = repairedIndices.size();
//The GPU SDF builder does sparse SDF, 3d texture layout and quantization in one go to best utilize the gpu
sdfDesc.sdfBuilder->buildSparseSDF(verts,
numVertices,
ind,
numTriangleIndices,
dx, dy, dz,
meshLower, meshLower + PxVec3(static_cast<PxReal>(dx), static_cast<PxReal>(dy), static_cast<PxReal>(dz)) * spacing, narrowBandThickness, sdfDesc.subgridSize, sdfDesc.bitsPerSubgridPixel,
sdfCoarse, sdfSubgridsStartSlots, sdfDataSubgrids, subgridsMinSdfValue, subgridsMaxSdfValue,
sdfDesc.sdfSubgrids3DTexBlockDim.x, sdfDesc.sdfSubgrids3DTexBlockDim.y, sdfDesc.sdfSubgrids3DTexBlockDim.z, 0);
}
sdfDesc.sdf.count = sdfCoarse.size();
sdfDesc.sdf.stride = sizeof(PxReal);
sdfDesc.sdf.data = sdfCoarse.begin();
sdfDesc.sdfSubgrids.count = sdfDataSubgrids.size();
sdfDesc.sdfSubgrids.stride = sizeof(PxU8);
sdfDesc.sdfSubgrids.data = sdfDataSubgrids.begin();
sdfDesc.sdfStartSlots.count = sdfSubgridsStartSlots.size();
sdfDesc.sdfStartSlots.stride = sizeof(PxU32);
sdfDesc.sdfStartSlots.data = sdfSubgridsStartSlots.begin();
sdfDesc.subgridsMinSdfValue = subgridsMinSdfValue;
sdfDesc.subgridsMaxSdfValue = subgridsMaxSdfValue;
return true;
}
static bool createSDF(PxTriangleMeshDesc& desc, PxSDFDesc& sdfDesc, PxArray<PxReal>& sdf, PxArray<PxU8>& sdfDataSubgrids, PxArray<PxU32>& sdfSubgridsStartSlots)
{
if (sdfDesc.subgridSize > 0)
{
return createSDFSparse(desc, sdfDesc, sdf, sdfDataSubgrids, sdfSubgridsStartSlots);
}
MeshData mesh(desc);
PxVec3 meshLower, meshUpper;
if (sdfDesc.sdfBounds.isEmpty())
mesh.GetBounds(meshLower, meshUpper);
else
{
meshLower = sdfDesc.sdfBounds.minimum;
meshUpper = sdfDesc.sdfBounds.maximum;
}
PxVec3 edges = meshUpper - meshLower;
const PxReal spacing = sdfDesc.spacing;
// tweak spacing to avoid edge cases for vertices laying on the boundary
// just covers the case where an edge is a whole multiple of the spacing.
PxReal spacingEps = spacing * (1.0f - 1e-4f);
// make sure to have at least one particle in each dimension
PxI32 dx, dy, dz;
dx = spacing > edges.x ? 1 : PxI32(edges.x / spacingEps);
dy = spacing > edges.y ? 1 : PxI32(edges.y / spacingEps);
dz = spacing > edges.z ? 1 : PxI32(edges.z / spacingEps);
dx += 4;
dy += 4;
dz += 4;
const PxU32 numVoxels = dx * dy * dz;
// we shift the voxelization bounds so that the voxel centers
// lie symmetrically to the center of the object. this reduces the
// chance of missing features, and also better aligns the particles
// with the mesh
PxVec3 meshOffset;
meshOffset.x = 0.5f * (spacing - (edges.x - (dx - 1)*spacing));
meshOffset.y = 0.5f * (spacing - (edges.y - (dy - 1)*spacing));
meshOffset.z = 0.5f * (spacing - (edges.z - (dz - 1)*spacing));
meshLower -= meshOffset;
sdfDesc.meshLower = meshLower;
sdfDesc.dims.x = dx;
sdfDesc.dims.y = dy;
sdfDesc.dims.z = dz;
sdf.resize(numVoxels);
PxArray<PxU32> indices32;
PxArray<PxVec3> vertices;
const PxVec3* verticesPtr = NULL;
bool baseMeshSpecified = sdfDesc.baseMesh.triangles.data && sdfDesc.baseMesh.points.data;
if (baseMeshSpecified)
{
convert16To32Bits(sdfDesc.baseMesh, indices32);
if (sdfDesc.baseMesh.points.stride != sizeof(PxVec3))
{
vertices.resize(sdfDesc.baseMesh.points.count);
immediateCooking::gatherStrided(sdfDesc.baseMesh.points.data, vertices.begin(), sdfDesc.baseMesh.points.count, sizeof(PxVec3), sdfDesc.baseMesh.points.stride);
verticesPtr = vertices.begin();
}
else
verticesPtr = reinterpret_cast<const PxVec3*>(sdfDesc.baseMesh.points.data);
}
PxU32* indices = baseMeshSpecified ? indices32.begin() : &mesh.m_indices[0];
PxU32 numTriangleIndices = baseMeshSpecified ? indices32.size() : mesh.m_indices.size();
const PxVec3* verts = baseMeshSpecified ? verticesPtr : &mesh.m_positions[0];
PxU32 numVertices = baseMeshSpecified ? sdfDesc.baseMesh.points.count : mesh.m_positions.size();
if (sdfDesc.sdfBuilder == NULL)
{
Gu::SDFUsingWindingNumbers(verts, indices, numTriangleIndices, dx, dy, dz, &sdf[0], meshLower,
meshLower + PxVec3(static_cast<PxReal>(dx), static_cast<PxReal>(dy), static_cast<PxReal>(dz)) * spacing, NULL, true,
sdfDesc.numThreadsForSdfConstruction, sdfDesc.sdfBuilder);
}
else
{
PxArray<PxU32> repairedIndices;
//Analyze the mesh to catch and fix some special cases
//There are meshes where every triangle is present once with cw and once with ccw orientation. Try to filter out only one set
Gu::analyzeAndFixMesh(verts, indices, numTriangleIndices, repairedIndices);
const PxU32* ind = repairedIndices.size() > 0 ? repairedIndices.begin() : indices;
if (repairedIndices.size() > 0)
numTriangleIndices = repairedIndices.size();
sdfDesc.sdfBuilder->buildSDF(verts, numVertices, ind, numTriangleIndices, dx, dy, dz, meshLower,
meshLower + PxVec3(static_cast<PxReal>(dx), static_cast<PxReal>(dy), static_cast<PxReal>(dz)) * spacing, true, &sdf[0]);
}
sdfDesc.sdf.count = sdfDesc.dims.x * sdfDesc.dims.y * sdfDesc.dims.z;
sdfDesc.sdf.stride = sizeof(PxReal);
sdfDesc.sdf.data = &sdf[0];
return true;
}
bool buildSDF(PxTriangleMeshDesc& desc, PxArray<PxReal>& sdf, PxArray<PxU8>& sdfDataSubgrids, PxArray<PxU32>& sdfSubgridsStartSlots)
{
PxSDFDesc& sdfDesc = *desc.sdfDesc;
if (!sdfDesc.sdf.data && sdfDesc.spacing > 0.f)
{
// Calculate signed distance field here if no sdf data provided.
createSDF(desc, sdfDesc, sdf, sdfDataSubgrids, sdfSubgridsStartSlots);
sdfDesc.sdf.stride = sizeof(PxReal);
}
return true;
}
}
| 15,609 | C++ | 37.54321 | 190 | 0.72503 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointBox.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_DISTANCE_POINT_BOX_H
#define GU_DISTANCE_POINT_BOX_H
#include "GuBox.h"
namespace physx
{
namespace Gu
{
/**
Return the square of the minimum distance from the surface of the box to the given point.
\param point The point
\param boxOrigin The origin of the box
\param boxExtent The extent of the box
\param boxBase The orientation of the box
\param boxParam Set to coordinates of the closest point on the box in its local space
*/
PX_PHYSX_COMMON_API PxReal distancePointBoxSquared( const PxVec3& point,
const PxVec3& boxOrigin,
const PxVec3& boxExtent,
const PxMat33& boxBase,
PxVec3* boxParam=NULL);
/**
Return the square of the minimum distance from the surface of the box to the given point.
\param point The point
\param box The box
\param boxParam Set to coordinates of the closest point on the box in its local space
*/
PX_FORCE_INLINE PxReal distancePointBoxSquared( const PxVec3& point,
const Gu::Box& box,
PxVec3* boxParam=NULL)
{
return distancePointBoxSquared(point, box.center, box.extents, box.rot, boxParam);
}
} // namespace Gu
}
#endif
| 2,855 | C | 39.799999 | 90 | 0.745009 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceTriangleTriangle.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_DISTANCE_TRIANGLE_TRIANGLE_H
#define GU_DISTANCE_TRIANGLE_TRIANGLE_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVec3.h"
namespace physx
{
namespace Gu
{
float distanceTriangleTriangleSquared(PxVec3& cp, PxVec3& cq, const PxVec3p p[3], const PxVec3p q[3]);
} // namespace Gu
}
#endif
| 2,017 | C | 43.844443 | 103 | 0.765989 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointBox.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 "GuDistancePointBox.h"
using namespace physx;
PxReal Gu::distancePointBoxSquared( const PxVec3& point,
const PxVec3& boxOrigin, const PxVec3& boxExtent, const PxMat33& boxBase,
PxVec3* boxParam)
{
// Compute coordinates of point in box coordinate system
const PxVec3 diff = point - boxOrigin;
PxVec3 closest( boxBase.column0.dot(diff),
boxBase.column1.dot(diff),
boxBase.column2.dot(diff));
// Project test point onto box
PxReal sqrDistance = 0.0f;
for(PxU32 ax=0; ax<3; ax++)
{
if(closest[ax] < -boxExtent[ax])
{
const PxReal delta = closest[ax] + boxExtent[ax];
sqrDistance += delta*delta;
closest[ax] = -boxExtent[ax];
}
else if(closest[ax] > boxExtent[ax])
{
const PxReal delta = closest[ax] - boxExtent[ax];
sqrDistance += delta*delta;
closest[ax] = boxExtent[ax];
}
}
if(boxParam) *boxParam = closest;
return sqrDistance;
}
| 2,617 | C++ | 38.666666 | 83 | 0.733665 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceSegmentBox.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 "GuDistanceSegmentBox.h"
#include "GuDistancePointBox.h"
#include "GuDistanceSegmentSegment.h"
#include "GuDistancePointSegment.h"
#include "GuIntersectionRayBox.h"
using namespace physx;
static void face(unsigned int i0, unsigned int i1, unsigned int i2, PxVec3& rkPnt, const PxVec3& rkDir, const PxVec3& extents, const PxVec3& rkPmE, PxReal* pfLParam, PxReal& rfSqrDistance)
{
PxVec3 kPpE;
PxReal fLSqr, fInv, fTmp, fParam, fT, fDelta;
kPpE[i1] = rkPnt[i1] + extents[i1];
kPpE[i2] = rkPnt[i2] + extents[i2];
if(rkDir[i0]*kPpE[i1] >= rkDir[i1]*rkPmE[i0])
{
if(rkDir[i0]*kPpE[i2] >= rkDir[i2]*rkPmE[i0])
{
// v[i1] >= -e[i1], v[i2] >= -e[i2] (distance = 0)
if(pfLParam)
{
rkPnt[i0] = extents[i0];
fInv = 1.0f/rkDir[i0];
rkPnt[i1] -= rkDir[i1]*rkPmE[i0]*fInv;
rkPnt[i2] -= rkDir[i2]*rkPmE[i0]*fInv;
*pfLParam = -rkPmE[i0]*fInv;
}
}
else
{
// v[i1] >= -e[i1], v[i2] < -e[i2]
fLSqr = rkDir[i0]*rkDir[i0] + rkDir[i2]*rkDir[i2];
fTmp = fLSqr*kPpE[i1] - rkDir[i1]*(rkDir[i0]*rkPmE[i0] + rkDir[i2]*kPpE[i2]);
if(fTmp <= 2.0f*fLSqr*extents[i1])
{
fT = fTmp/fLSqr;
fLSqr += rkDir[i1]*rkDir[i1];
fTmp = kPpE[i1] - fT;
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*fTmp + rkDir[i2]*kPpE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + fTmp*fTmp + kPpE[i2]*kPpE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = fT - extents[i1];
rkPnt[i2] = -extents[i2];
}
}
else
{
fLSqr += rkDir[i1]*rkDir[i1];
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*rkPmE[i1] + rkDir[i2]*kPpE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + rkPmE[i1]*rkPmE[i1] + kPpE[i2]*kPpE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = extents[i1];
rkPnt[i2] = -extents[i2];
}
}
}
}
else
{
if ( rkDir[i0]*kPpE[i2] >= rkDir[i2]*rkPmE[i0] )
{
// v[i1] < -e[i1], v[i2] >= -e[i2]
fLSqr = rkDir[i0]*rkDir[i0] + rkDir[i1]*rkDir[i1];
fTmp = fLSqr*kPpE[i2] - rkDir[i2]*(rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1]);
if(fTmp <= 2.0f*fLSqr*extents[i2])
{
fT = fTmp/fLSqr;
fLSqr += rkDir[i2]*rkDir[i2];
fTmp = kPpE[i2] - fT;
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1] + rkDir[i2]*fTmp;
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + kPpE[i1]*kPpE[i1] + fTmp*fTmp + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = -extents[i1];
rkPnt[i2] = fT - extents[i2];
}
}
else
{
fLSqr += rkDir[i2]*rkDir[i2];
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1] + rkDir[i2]*rkPmE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + kPpE[i1]*kPpE[i1] + rkPmE[i2]*rkPmE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = -extents[i1];
rkPnt[i2] = extents[i2];
}
}
}
else
{
// v[i1] < -e[i1], v[i2] < -e[i2]
fLSqr = rkDir[i0]*rkDir[i0]+rkDir[i2]*rkDir[i2];
fTmp = fLSqr*kPpE[i1] - rkDir[i1]*(rkDir[i0]*rkPmE[i0] + rkDir[i2]*kPpE[i2]);
if(fTmp >= 0.0f)
{
// v[i1]-edge is closest
if ( fTmp <= 2.0f*fLSqr*extents[i1] )
{
fT = fTmp/fLSqr;
fLSqr += rkDir[i1]*rkDir[i1];
fTmp = kPpE[i1] - fT;
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*fTmp + rkDir[i2]*kPpE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + fTmp*fTmp + kPpE[i2]*kPpE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = fT - extents[i1];
rkPnt[i2] = -extents[i2];
}
}
else
{
fLSqr += rkDir[i1]*rkDir[i1];
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*rkPmE[i1] + rkDir[i2]*kPpE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + rkPmE[i1]*rkPmE[i1] + kPpE[i2]*kPpE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = extents[i1];
rkPnt[i2] = -extents[i2];
}
}
return;
}
fLSqr = rkDir[i0]*rkDir[i0] + rkDir[i1]*rkDir[i1];
fTmp = fLSqr*kPpE[i2] - rkDir[i2]*(rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1]);
if(fTmp >= 0.0f)
{
// v[i2]-edge is closest
if(fTmp <= 2.0f*fLSqr*extents[i2])
{
fT = fTmp/fLSqr;
fLSqr += rkDir[i2]*rkDir[i2];
fTmp = kPpE[i2] - fT;
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1] + rkDir[i2]*fTmp;
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + kPpE[i1]*kPpE[i1] + fTmp*fTmp + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = -extents[i1];
rkPnt[i2] = fT - extents[i2];
}
}
else
{
fLSqr += rkDir[i2]*rkDir[i2];
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1] + rkDir[i2]*rkPmE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + kPpE[i1]*kPpE[i1] + rkPmE[i2]*rkPmE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = -extents[i1];
rkPnt[i2] = extents[i2];
}
}
return;
}
// (v[i1],v[i2])-corner is closest
fLSqr += rkDir[i2]*rkDir[i2];
fDelta = rkDir[i0]*rkPmE[i0] + rkDir[i1]*kPpE[i1] + rkDir[i2]*kPpE[i2];
fParam = -fDelta/fLSqr;
rfSqrDistance += rkPmE[i0]*rkPmE[i0] + kPpE[i1]*kPpE[i1] + kPpE[i2]*kPpE[i2] + fDelta*fParam;
if(pfLParam)
{
*pfLParam = fParam;
rkPnt[i0] = extents[i0];
rkPnt[i1] = -extents[i1];
rkPnt[i2] = -extents[i2];
}
}
}
}
static void caseNoZeros(PxVec3& rkPnt, const PxVec3& rkDir, const PxVec3& extents, PxReal* pfLParam, PxReal& rfSqrDistance)
{
PxVec3 kPmE(rkPnt.x - extents.x, rkPnt.y - extents.y, rkPnt.z - extents.z);
PxReal fProdDxPy, fProdDyPx, fProdDzPx, fProdDxPz, fProdDzPy, fProdDyPz;
fProdDxPy = rkDir.x*kPmE.y;
fProdDyPx = rkDir.y*kPmE.x;
if(fProdDyPx >= fProdDxPy)
{
fProdDzPx = rkDir.z*kPmE.x;
fProdDxPz = rkDir.x*kPmE.z;
if(fProdDzPx >= fProdDxPz)
{
// line intersects x = e0
face(0, 1, 2, rkPnt, rkDir, extents, kPmE, pfLParam, rfSqrDistance);
}
else
{
// line intersects z = e2
face(2, 0, 1, rkPnt, rkDir, extents, kPmE, pfLParam, rfSqrDistance);
}
}
else
{
fProdDzPy = rkDir.z*kPmE.y;
fProdDyPz = rkDir.y*kPmE.z;
if(fProdDzPy >= fProdDyPz)
{
// line intersects y = e1
face(1, 2, 0, rkPnt, rkDir, extents, kPmE, pfLParam, rfSqrDistance);
}
else
{
// line intersects z = e2
face(2, 0, 1, rkPnt, rkDir, extents, kPmE, pfLParam, rfSqrDistance);
}
}
}
static void case0(unsigned int i0, unsigned int i1, unsigned int i2, PxVec3& rkPnt, const PxVec3& rkDir, const PxVec3& extents, PxReal* pfLParam, PxReal& rfSqrDistance)
{
PxReal fPmE0 = rkPnt[i0] - extents[i0];
PxReal fPmE1 = rkPnt[i1] - extents[i1];
PxReal fProd0 = rkDir[i1]*fPmE0;
PxReal fProd1 = rkDir[i0]*fPmE1;
PxReal fDelta, fInvLSqr, fInv;
if(fProd0 >= fProd1)
{
// line intersects P[i0] = e[i0]
rkPnt[i0] = extents[i0];
PxReal fPpE1 = rkPnt[i1] + extents[i1];
fDelta = fProd0 - rkDir[i0]*fPpE1;
if(fDelta >= 0.0f)
{
fInvLSqr = 1.0f/(rkDir[i0]*rkDir[i0] + rkDir[i1]*rkDir[i1]);
rfSqrDistance += fDelta*fDelta*fInvLSqr;
if(pfLParam)
{
rkPnt[i1] = -extents[i1];
*pfLParam = -(rkDir[i0]*fPmE0+rkDir[i1]*fPpE1)*fInvLSqr;
}
}
else
{
if(pfLParam)
{
fInv = 1.0f/rkDir[i0];
rkPnt[i1] -= fProd0*fInv;
*pfLParam = -fPmE0*fInv;
}
}
}
else
{
// line intersects P[i1] = e[i1]
rkPnt[i1] = extents[i1];
PxReal fPpE0 = rkPnt[i0] + extents[i0];
fDelta = fProd1 - rkDir[i1]*fPpE0;
if(fDelta >= 0.0f)
{
fInvLSqr = 1.0f/(rkDir[i0]*rkDir[i0] + rkDir[i1]*rkDir[i1]);
rfSqrDistance += fDelta*fDelta*fInvLSqr;
if(pfLParam)
{
rkPnt[i0] = -extents[i0];
*pfLParam = -(rkDir[i0]*fPpE0+rkDir[i1]*fPmE1)*fInvLSqr;
}
}
else
{
if(pfLParam)
{
fInv = 1.0f/rkDir[i1];
rkPnt[i0] -= fProd1*fInv;
*pfLParam = -fPmE1*fInv;
}
}
}
if(rkPnt[i2] < -extents[i2])
{
fDelta = rkPnt[i2] + extents[i2];
rfSqrDistance += fDelta*fDelta;
rkPnt[i2] = -extents[i2];
}
else if ( rkPnt[i2] > extents[i2] )
{
fDelta = rkPnt[i2] - extents[i2];
rfSqrDistance += fDelta*fDelta;
rkPnt[i2] = extents[i2];
}
}
static void case00(unsigned int i0, unsigned int i1, unsigned int i2, PxVec3& rkPnt, const PxVec3& rkDir, const PxVec3& extents, PxReal* pfLParam, PxReal& rfSqrDistance)
{
PxReal fDelta;
if(pfLParam)
*pfLParam = (extents[i0] - rkPnt[i0])/rkDir[i0];
rkPnt[i0] = extents[i0];
if(rkPnt[i1] < -extents[i1])
{
fDelta = rkPnt[i1] + extents[i1];
rfSqrDistance += fDelta*fDelta;
rkPnt[i1] = -extents[i1];
}
else if(rkPnt[i1] > extents[i1])
{
fDelta = rkPnt[i1] - extents[i1];
rfSqrDistance += fDelta*fDelta;
rkPnt[i1] = extents[i1];
}
if(rkPnt[i2] < -extents[i2])
{
fDelta = rkPnt[i2] + extents[i2];
rfSqrDistance += fDelta*fDelta;
rkPnt[i2] = -extents[i2];
}
else if(rkPnt[i2] > extents[i2])
{
fDelta = rkPnt[i2] - extents[i2];
rfSqrDistance += fDelta*fDelta;
rkPnt[i2] = extents[i2];
}
}
static void case000(PxVec3& rkPnt, const PxVec3& extents, PxReal& rfSqrDistance)
{
PxReal fDelta;
if(rkPnt.x < -extents.x)
{
fDelta = rkPnt.x + extents.x;
rfSqrDistance += fDelta*fDelta;
rkPnt.x = -extents.x;
}
else if(rkPnt.x > extents.x)
{
fDelta = rkPnt.x - extents.x;
rfSqrDistance += fDelta*fDelta;
rkPnt.x = extents.x;
}
if(rkPnt.y < -extents.y)
{
fDelta = rkPnt.y + extents.y;
rfSqrDistance += fDelta*fDelta;
rkPnt.y = -extents.y;
}
else if(rkPnt.y > extents.y)
{
fDelta = rkPnt.y - extents.y;
rfSqrDistance += fDelta*fDelta;
rkPnt.y = extents.y;
}
if(rkPnt.z < -extents.z)
{
fDelta = rkPnt.z + extents.z;
rfSqrDistance += fDelta*fDelta;
rkPnt.z = -extents.z;
}
else if(rkPnt.z > extents.z)
{
fDelta = rkPnt.z - extents.z;
rfSqrDistance += fDelta*fDelta;
rkPnt.z = extents.z;
}
}
//! Compute the smallest distance from the (infinite) line to the box.
static PxReal distanceLineBoxSquared(const PxVec3& lineOrigin, const PxVec3& lineDirection,
const PxVec3& boxOrigin, const PxVec3& boxExtent, const PxMat33& boxBase,
PxReal* lineParam,
PxVec3* boxParam)
{
const PxVec3& axis0 = boxBase.column0;
const PxVec3& axis1 = boxBase.column1;
const PxVec3& axis2 = boxBase.column2;
// compute coordinates of line in box coordinate system
const PxVec3 diff = lineOrigin - boxOrigin;
PxVec3 pnt(diff.dot(axis0), diff.dot(axis1), diff.dot(axis2));
PxVec3 dir(lineDirection.dot(axis0), lineDirection.dot(axis1), lineDirection.dot(axis2));
// Apply reflections so that direction vector has nonnegative components.
bool reflect[3];
for(unsigned int i=0;i<3;i++)
{
if(dir[i]<0.0f)
{
pnt[i] = -pnt[i];
dir[i] = -dir[i];
reflect[i] = true;
}
else
{
reflect[i] = false;
}
}
PxReal sqrDistance = 0.0f;
if(dir.x>0.0f)
{
if(dir.y>0.0f)
{
if(dir.z>0.0f) caseNoZeros(pnt, dir, boxExtent, lineParam, sqrDistance); // (+,+,+)
else case0(0, 1, 2, pnt, dir, boxExtent, lineParam, sqrDistance); // (+,+,0)
}
else
{
if(dir.z>0.0f) case0(0, 2, 1, pnt, dir, boxExtent, lineParam, sqrDistance); // (+,0,+)
else case00(0, 1, 2, pnt, dir, boxExtent, lineParam, sqrDistance); // (+,0,0)
}
}
else
{
if(dir.y>0.0f)
{
if(dir.z>0.0f) case0(1, 2, 0, pnt, dir, boxExtent, lineParam, sqrDistance); // (0,+,+)
else case00(1, 0, 2, pnt, dir, boxExtent, lineParam, sqrDistance); // (0,+,0)
}
else
{
if(dir.z>0.0f) case00(2, 0, 1, pnt, dir, boxExtent, lineParam, sqrDistance); // (0,0,+)
else
{
case000(pnt, boxExtent, sqrDistance); // (0,0,0)
if(lineParam)
*lineParam = 0.0f;
}
}
}
if(boxParam)
{
// undo reflections
for(unsigned int i=0;i<3;i++)
{
if(reflect[i])
pnt[i] = -pnt[i];
}
*boxParam = pnt;
}
return sqrDistance;
}
//! Compute the smallest distance from the (finite) line segment to the box.
PxReal Gu::distanceSegmentBoxSquared( const PxVec3& segmentPoint0, const PxVec3& segmentPoint1,
const PxVec3& boxOrigin, const PxVec3& boxExtent, const PxMat33& boxBase,
PxReal* segmentParam,
PxVec3* boxParam)
{
// compute coordinates of line in box coordinate system
PxReal lp;
PxVec3 bp;
PxReal sqrDistance = distanceLineBoxSquared(segmentPoint0, segmentPoint1 - segmentPoint0, boxOrigin, boxExtent, boxBase, &lp, &bp);
if(lp>=0.0f)
{
if(lp<=1.0f)
{
if(segmentParam)
*segmentParam = lp;
if(boxParam)
*boxParam = bp;
return sqrDistance;
}
else
{
if(segmentParam)
*segmentParam = 1.0f;
return Gu::distancePointBoxSquared(segmentPoint1, boxOrigin, boxExtent, boxBase, boxParam);
}
}
else
{
if(segmentParam)
*segmentParam = 0.0f;
return Gu::distancePointBoxSquared(segmentPoint0, boxOrigin, boxExtent, boxBase, boxParam);
}
}
| 14,831 | C++ | 26.016393 | 188 | 0.621873 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointSegment.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_DISTANCE_POINT_SEGMENT_H
#define GU_DISTANCE_POINT_SEGMENT_H
#include "common/PxPhysXCommonConfig.h"
#include "GuSegment.h"
namespace physx
{
namespace Gu
{
// dir = p1 - p0
PX_FORCE_INLINE PxReal distancePointSegmentSquaredInternal(const PxVec3& p0, const PxVec3& dir, const PxVec3& point, PxReal* param=NULL)
{
PxVec3 diff = point - p0;
PxReal fT = diff.dot(dir);
if(fT<=0.0f)
{
fT = 0.0f;
}
else
{
const PxReal sqrLen = dir.magnitudeSquared();
if(fT>=sqrLen)
{
fT = 1.0f;
diff -= dir;
}
else
{
fT /= sqrLen;
diff -= fT*dir;
}
}
if(param)
*param = fT;
return diff.magnitudeSquared();
}
/**
A segment is defined by S(t) = mP0 * (1 - t) + mP1 * t, with 0 <= t <= 1
Alternatively, a segment is S(t) = Origin + t * Direction for 0 <= t <= 1.
Direction is not necessarily unit length. The end points are Origin = mP0 and Origin + Direction = mP1.
*/
PX_FORCE_INLINE PxReal distancePointSegmentSquared(const PxVec3& p0, const PxVec3& p1, const PxVec3& point, PxReal* param=NULL)
{
return distancePointSegmentSquaredInternal(p0, p1 - p0, point, param);
}
PX_INLINE PxReal distancePointSegmentSquared(const Gu::Segment& segment, const PxVec3& point, PxReal* param=NULL)
{
return distancePointSegmentSquared(segment.p0, segment.p1, point, param);
}
} // namespace Gu
}
#endif
| 3,070 | C | 33.122222 | 137 | 0.72215 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointTetrahedron.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_DISTANCE_POINT_TETRAHEDRON_H
#define GU_DISTANCE_POINT_TETRAHEDRON_H
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#include "GuDistancePointTriangle.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
PX_PHYSX_COMMON_API PxVec4 PointOutsideOfPlane4(const PxVec3& p, const PxVec3& _a, const PxVec3& _b,
const PxVec3& _c, const PxVec3& _d);
PX_PHYSX_COMMON_API PxVec3 closestPtPointTetrahedron(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxVec4& result);
PX_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTetrahedron(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d)
{
const PxVec3 ab = b - a;
const PxVec3 ac = c - a;
const PxVec3 ad = d - a;
const PxVec3 bc = c - b;
const PxVec3 bd = d - b;
//point to face 0, 1, 2
PxVec3 bestClosestPt = closestPtPointTriangle2(p, a, b, c, ab, ac);
PxReal bestSqDist = bestClosestPt.dot(bestClosestPt);
// 0, 2, 3
PxVec3 closestPt = closestPtPointTriangle2(p, a, c, d, ac, ad);
PxReal sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
// 0, 3, 1
closestPt = closestPtPointTriangle2(p, a, d, b, ad, ab);
sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
// 1, 3, 2
closestPt = closestPtPointTriangle2(p, b, d, c, bd, bc);
sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
return bestClosestPt;
}
}
}
#endif
| 3,389 | C | 35.451613 | 162 | 0.720271 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointTetrahedron.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 "GuDistancePointTetrahedron.h"
#include "GuDistancePointTriangle.h"
using namespace physx;
PxVec4 Gu::PointOutsideOfPlane4(const PxVec3& p, const PxVec3& _a, const PxVec3& _b,
const PxVec3& _c, const PxVec3& _d)
{
const PxVec3 ap = p - _a;
const PxVec3 ab = _b - _a;
const PxVec3 ac = _c - _a;
const PxVec3 ad = _d - _a;
const PxVec3 v0 = ab.cross(ac);
const float signa0 = v0.dot(ap);
const float signd0 = v0.dot(ad);// V3Dot(v0, _d);
const PxVec3 v1 = ac.cross(ad);
const float signa1 = v1.dot(ap);
const float signd1 = v1.dot(ab);
const PxVec3 v2 = ad.cross(ab);
const float signa2 = v2.dot(ap);
const float signd2 = v2.dot(ac);// V3Dot(v2, _c);
const PxVec3 bd = _d - _b;
const PxVec3 bc = _c - _b;
const PxVec3 v3 = bd.cross(bc);
const float signd3 = v3.dot(p - _b);
const float signa3 = v3.dot(_a - _b);
//if combined signDist is leass zero, p is outside of that face
PxVec4 result = PxVec4(signa0 * signd0, signa1 * signd1, signa2 * signd2, signa3 * signd3);
return result;
}
PxVec3 Gu::closestPtPointTetrahedron(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxVec4& result)
{
const PxVec3 ab = b - a;
const PxVec3 ac = c - a;
const PxVec3 ad = d - a;
const PxVec3 bc = c - b;
const PxVec3 bd = d - b;
//point is outside of this face
PxVec3 bestClosestPt(0.f, 0.f, 0.f);
PxReal bestSqDist = PX_MAX_F32;
if (result.x < 0.f)
{
// 0, 1, 2
bestClosestPt = closestPtPointTriangle2(p, a, b, c, ab, ac);
bestSqDist = bestClosestPt.dot(bestClosestPt);
}
if (result.y < 0.f)
{
// 0, 2, 3
const PxVec3 closestPt = closestPtPointTriangle2(p, a, c, d, ac, ad);
const PxReal sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
}
if (result.z < 0.f)
{
// 0, 3, 1
const PxVec3 closestPt = closestPtPointTriangle2(p, a, d, b, ad, ab);
const PxReal sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
}
if (result.w < 0.f)
{
// 1, 3, 2
const PxVec3 closestPt = closestPtPointTriangle2(p, b, d, c, bd, bc);
const PxReal sqDist = closestPt.dot(closestPt);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
}
return bestClosestPt;
}
| 4,036 | C++ | 32.090164 | 143 | 0.700942 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceTriangleTriangle.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 "GuDistanceTriangleTriangle.h"
#include "foundation/PxVecMath.h"
using namespace physx;
using namespace Gu;
using namespace aos;
void edgeEdgeDist(PxVec3& x, PxVec3& y, const PxVec3& p, const PxVec3& a, const PxVec3& q, const PxVec3& b);
float Gu::distanceTriangleTriangleSquared(PxVec3& cp, PxVec3& cq, const PxVec3p p[3], const PxVec3p q[3])
{
PxVec3p Sv[3];
V4StoreU(V4Sub(V4LoadU(&p[1].x), V4LoadU(&p[0].x)), &Sv[0].x);
V4StoreU(V4Sub(V4LoadU(&p[2].x), V4LoadU(&p[1].x)), &Sv[1].x);
V4StoreU(V4Sub(V4LoadU(&p[0].x), V4LoadU(&p[2].x)), &Sv[2].x);
PxVec3p Tv[3];
V4StoreU(V4Sub(V4LoadU(&q[1].x), V4LoadU(&q[0].x)), &Tv[0].x);
V4StoreU(V4Sub(V4LoadU(&q[2].x), V4LoadU(&q[1].x)), &Tv[1].x);
V4StoreU(V4Sub(V4LoadU(&q[0].x), V4LoadU(&q[2].x)), &Tv[2].x);
PxVec3 minP, minQ;
bool shown_disjoint = false;
float mindd = PX_MAX_F32;
for(PxU32 i=0;i<3;i++)
{
for(PxU32 j=0;j<3;j++)
{
edgeEdgeDist(cp, cq, p[i], Sv[i], q[j], Tv[j]);
const PxVec3 V = cq - cp;
const float dd = V.dot(V);
if(dd<=mindd)
{
minP = cp;
minQ = cq;
mindd = dd;
PxU32 id = i+2;
if(id>=3)
id-=3;
PxVec3 Z = p[id] - cp;
float a = Z.dot(V);
id = j+2;
if(id>=3)
id-=3;
Z = q[id] - cq;
float b = Z.dot(V);
if((a<=0.0f) && (b>=0.0f))
return V.dot(V);
if(a<=0.0f) a = 0.0f;
else if(b>0.0f) b = 0.0f;
if((mindd - a + b) > 0.0f)
shown_disjoint = true;
}
}
}
PxVec3 Sn = Sv[0].cross(Sv[1]);
float Snl = Sn.dot(Sn);
if(Snl>1e-15f)
{
const PxVec3 Tp((p[0] - q[0]).dot(Sn),
(p[0] - q[1]).dot(Sn),
(p[0] - q[2]).dot(Sn));
int index = -1;
if((Tp[0]>0.0f) && (Tp[1]>0.0f) && (Tp[2]>0.0f))
{
if(Tp[0]<Tp[1]) index = 0; else index = 1;
if(Tp[2]<Tp[index]) index = 2;
}
else if((Tp[0]<0.0f) && (Tp[1]<0.0f) && (Tp[2]<0.0f))
{
if(Tp[0]>Tp[1]) index = 0; else index = 1;
if(Tp[2]>Tp[index]) index = 2;
}
if(index >= 0)
{
shown_disjoint = true;
const PxVec3& qIndex = q[index];
PxVec3 V = qIndex - p[0];
PxVec3 Z = Sn.cross(Sv[0]);
if(V.dot(Z)>0.0f)
{
V = qIndex - p[1];
Z = Sn.cross(Sv[1]);
if(V.dot(Z)>0.0f)
{
V = qIndex - p[2];
Z = Sn.cross(Sv[2]);
if(V.dot(Z)>0.0f)
{
cp = qIndex + Sn * Tp[index]/Snl;
cq = qIndex;
return (cp - cq).magnitudeSquared();
}
}
}
}
}
PxVec3 Tn = Tv[0].cross(Tv[1]);
float Tnl = Tn.dot(Tn);
if(Tnl>1e-15f)
{
const PxVec3 Sp((q[0] - p[0]).dot(Tn),
(q[0] - p[1]).dot(Tn),
(q[0] - p[2]).dot(Tn));
int index = -1;
if((Sp[0]>0.0f) && (Sp[1]>0.0f) && (Sp[2]>0.0f))
{
if(Sp[0]<Sp[1]) index = 0; else index = 1;
if(Sp[2]<Sp[index]) index = 2;
}
else if((Sp[0]<0.0f) && (Sp[1]<0.0f) && (Sp[2]<0.0f))
{
if(Sp[0]>Sp[1]) index = 0; else index = 1;
if(Sp[2]>Sp[index]) index = 2;
}
if(index >= 0)
{
shown_disjoint = true;
const PxVec3& pIndex = p[index];
PxVec3 V = pIndex - q[0];
PxVec3 Z = Tn.cross(Tv[0]);
if(V.dot(Z)>0.0f)
{
V = pIndex - q[1];
Z = Tn.cross(Tv[1]);
if(V.dot(Z)>0.0f)
{
V = pIndex - q[2];
Z = Tn.cross(Tv[2]);
if(V.dot(Z)>0.0f)
{
cp = pIndex;
cq = pIndex + Tn * Sp[index]/Tnl;
return (cp - cq).magnitudeSquared();
}
}
}
}
}
if(shown_disjoint)
{
cp = minP;
cq = minQ;
return mindd;
}
else return 0.0f;
}
| 5,125 | C++ | 25.153061 | 108 | 0.590634 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceSegmentTriangle.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_DISTANCE_SEGMENT_TRIANGLE_H
#define GU_DISTANCE_SEGMENT_TRIANGLE_H
#include "common/PxPhysXCommonConfig.h"
#include "GuSegment.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
PX_PHYSX_COMMON_API PxReal distanceSegmentTriangleSquared(
const PxVec3& segmentOrigin, const PxVec3& segmentExtent,
const PxVec3& triangleOrigin, const PxVec3& triangleEdge0, const PxVec3& triangleEdge1,
PxReal* t=NULL, PxReal* u=NULL, PxReal* v=NULL);
PX_INLINE PxReal distanceSegmentTriangleSquared(
const Gu::Segment& segment,
const PxVec3& triangleOrigin, const PxVec3& triangleEdge0, const PxVec3& triangleEdge1,
PxReal* t=NULL, PxReal* u=NULL, PxReal* v=NULL)
{
return distanceSegmentTriangleSquared(
segment.p0, segment.computeDirection(), triangleOrigin, triangleEdge0, triangleEdge1, t, u, v);
}
// closest0 is the closest point on segment pq
// closest1 is the closest point on triangle abc
PX_PHYSX_COMMON_API aos::FloatV distanceSegmentTriangleSquared(
const aos::Vec3VArg p, const aos::Vec3VArg q,
const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c,
aos::Vec3V& closest0, aos::Vec3V& closest1);
} // namespace Gu
}
#endif
| 2,896 | C | 43.56923 | 98 | 0.765539 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistancePointTriangle.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 "GuDistancePointTriangle.h"
using namespace physx;
// Based on Christer Ericson's book
PxVec3 Gu::closestPtPointTriangle(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& s, float& t)
{
// 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;
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;
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;
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;
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;
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;
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;
return a + ab*v + ac*w;
}
//aos::FloatV Gu::distancePointTriangleSquared( const aos::Vec3VArg p,
// const aos::Vec3VArg a,
// const aos::Vec3VArg b,
// const aos::Vec3VArg c,
// aos::FloatV& u,
// aos::FloatV& v,
// aos::Vec3V& closestP)
//{
// using namespace aos;
//
// const FloatV zero = FZero();
// const FloatV one = FOne();
// //const Vec3V zero = V3Zero();
// const Vec3V ab = V3Sub(b, a);
// const Vec3V ac = V3Sub(c, a);
// const Vec3V bc = V3Sub(c, b);
// const Vec3V ap = V3Sub(p, a);
// const Vec3V bp = V3Sub(p, b);
// const Vec3V cp = V3Sub(p, 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);
//
// //check if p in vertex region outside a
// const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0
// const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0
// const BoolV con0 = BAnd(con00, con01); // vertex region a
// const FloatV u0 = zero;
// const FloatV v0 = zero;
//
// //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
// const FloatV u1 = one;
// const FloatV v1 = zero;
//
// //check if p in vertex region outside c
// const BoolV con20 = FIsGrtrOrEq(d6, zero);
// const BoolV con21 = FIsGrtrOrEq(d6, d5);
// const BoolV con2 = BAnd(con20, con21); // vertex region c
// const FloatV u2 = zero;
// const FloatV v2 = one;
//
// //check if p in edge region of AB
// const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2));
//
// const BoolV con30 = FIsGrtr(zero, vc);
// const BoolV con31 = FIsGrtrOrEq(d1, zero);
// const BoolV con32 = FIsGrtr(zero, d3);
// const BoolV con3 = BAnd(con30, BAnd(con31, con32));
// const FloatV sScale = FDiv(d1, FSub(d1, d3));
// const Vec3V closest3 = V3Add(a, V3Scale(ab, sScale));
// const FloatV u3 = sScale;
// const FloatV v3 = zero;
//
// //check if p in edge region of BC
// const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4));
// const BoolV con40 = FIsGrtr(zero, va);
// const BoolV con41 = FIsGrtrOrEq(d4, d3);
// const BoolV con42 = FIsGrtrOrEq(d5, d6);
// const BoolV con4 = BAnd(con40, BAnd(con41, con42));
// const FloatV uScale = FDiv(unom, FAdd(unom, udenom));
// const Vec3V closest4 = V3Add(b, V3Scale(bc, uScale));
// const FloatV u4 = FSub(one, uScale);
// const FloatV v4 = uScale;
//
// //check if p in edge region of AC
// const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6));
// const BoolV con50 = FIsGrtr(zero, vb);
// const BoolV con51 = FIsGrtrOrEq(d2, zero);
// const BoolV con52 = FIsGrtr(zero, d6);
// const BoolV con5 = BAnd(con50, BAnd(con51, con52));
// const FloatV tScale = FDiv(d2, FSub(d2, d6));
// const Vec3V closest5 = V3Add(a, V3Scale(ac, tScale));
// const FloatV u5 = zero;
// const FloatV v5 = tScale;
//
// //P must project inside face region. Compute Q using Barycentric coordinates
// const FloatV denom = FRecip(FAdd(va, FAdd(vb, vc)));
// const FloatV t = FMul(vb, denom);
// const FloatV w = FMul(vc, denom);
// const Vec3V bCom = V3Scale(ab, t);
// const Vec3V cCom = V3Scale(ac, w);
// const Vec3V closest6 = V3Add(a, V3Add(bCom, cCom));
// const FloatV u6 = t;
// const FloatV v6 = w;
//
// const Vec3V closest= V3Sel(con0, a, V3Sel(con1, b, V3Sel(con2, c, V3Sel(con3, closest3, V3Sel(con4, closest4, V3Sel(con5, closest5, closest6))))));
// u = FSel(con0, u0, FSel(con1, u1, FSel(con2, u2, FSel(con3, u3, FSel(con4, u4, FSel(con5, u5, u6))))));
// v = FSel(con0, v0, FSel(con1, v1, FSel(con2, v2, FSel(con3, v3, FSel(con4, v4, FSel(con5, v5, v6))))));
// closestP = closest;
//
// const Vec3V vv = V3Sub(p, closest);
//
// return V3Dot(vv, vv);
//}
PX_PHYSX_COMMON_API aos::FloatV Gu::distancePointTriangleSquared2UnitBox(
const aos::Vec3VArg queryPoint,
const aos::Vec3VArg triA,
const aos::Vec3VArg triB,
const aos::Vec3VArg triC,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP)
{
using namespace aos;
const Vec3V min = V3Min(V3Min(triA, triB), V3Min(triC, queryPoint));
const Vec3V max = V3Max(V3Max(triA, triB), V3Max(triC, queryPoint));
const Vec3V size = V3Sub(max, min);
FloatV invScaling = FMax(FLoad(1e-12f), V3ExtractMax(size));
const FloatV one = FOne();
FloatV scaling = FDiv(one, invScaling);
const Vec3V p = V3Scale(V3Sub(queryPoint, min), scaling);
const Vec3V a = V3Scale(V3Sub(triA, min), scaling);
const Vec3V b = V3Scale(V3Sub(triB, min), scaling);
const Vec3V c = V3Scale(V3Sub(triC, min), scaling);
Vec3V cp;
FloatV result = Gu::distancePointTriangleSquared(p, a, b, c, u, v, cp);
closestP = V3Add(V3Scale(cp, invScaling), min);
return FMul(result, FMul(invScaling, invScaling));
}
aos::FloatV Gu::distancePointTriangleSquared( const aos::Vec3VArg p,
const aos::Vec3VArg a,
const aos::Vec3VArg b,
const aos::Vec3VArg c,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP)
{
using namespace aos;
const FloatV zero = FZero();
const FloatV one = FOne();
//const Vec3V zero = V3Zero();
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V bc = V3Sub(c, b);
const Vec3V ap = V3Sub(p, a);
const Vec3V bp = V3Sub(p, b);
const Vec3V cp = V3Sub(p, 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);
//check if p in vertex region outside a
const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0
const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0
const BoolV con0 = BAnd(con00, con01); // vertex region a
if(BAllEqTTTT(con0))
{
u = zero;
v = zero;
const Vec3V vv = V3Sub(p, a);
closestP = a;
return V3Dot(vv, vv);
}
//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))
{
u = one;
v = zero;
const Vec3V vv = V3Sub(p, b);
closestP = b;
return V3Dot(vv, vv);
}
//check if p in vertex region outside c
const BoolV con20 = FIsGrtrOrEq(d6, zero);
const BoolV con21 = FIsGrtrOrEq(d6, d5);
const BoolV con2 = BAnd(con20, con21); // vertex region c
if(BAllEqTTTT(con2))
{
u = zero;
v = one;
const Vec3V vv = V3Sub(p, c);
closestP = c;
return V3Dot(vv, vv);
}
//check if p in edge region of AB
const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2));
const BoolV con30 = FIsGrtr(zero, vc);
const BoolV con31 = FIsGrtrOrEq(d1, zero);
const BoolV con32 = FIsGrtr(zero, d3);
const BoolV con3 = BAnd(con30, BAnd(con31, con32));
if(BAllEqTTTT(con3))
{
const FloatV sScale = FDiv(d1, FSub(d1, d3));
const Vec3V closest3 = V3Add(a, V3Scale(ab, sScale));
u = sScale;
v = zero;
const Vec3V vv = V3Sub(p, closest3);
closestP = closest3;
return V3Dot(vv, vv);
}
//check if p in edge region of BC
const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4));
const BoolV con40 = FIsGrtr(zero, va);
const BoolV con41 = FIsGrtrOrEq(d4, d3);
const BoolV con42 = FIsGrtrOrEq(d5, d6);
const BoolV con4 = BAnd(con40, BAnd(con41, con42));
if(BAllEqTTTT(con4))
{
const FloatV uScale = FDiv(unom, FAdd(unom, udenom));
const Vec3V closest4 = V3Add(b, V3Scale(bc, uScale));
u = FSub(one, uScale);
v = uScale;
const Vec3V vv = V3Sub(p, closest4);
closestP = closest4;
return V3Dot(vv, vv);
}
//check if p in edge region of AC
const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6));
const BoolV con50 = FIsGrtr(zero, vb);
const BoolV con51 = FIsGrtrOrEq(d2, zero);
const BoolV con52 = FIsGrtr(zero, d6);
const BoolV con5 = BAnd(con50, BAnd(con51, con52));
if(BAllEqTTTT(con5))
{
const FloatV tScale = FDiv(d2, FSub(d2, d6));
const Vec3V closest5 = V3Add(a, V3Scale(ac, tScale));
u = zero;
v = tScale;
const Vec3V vv = V3Sub(p, closest5);
closestP = closest5;
return V3Dot(vv, vv);
}
//P must project inside face region. Compute Q using Barycentric coordinates
const FloatV denom = FRecip(FAdd(va, FAdd(vb, vc)));
const FloatV t = FMul(vb, denom);
const FloatV w = FMul(vc, denom);
const Vec3V bCom = V3Scale(ab, t);
const Vec3V cCom = V3Scale(ac, w);
const Vec3V closest6 = V3Add(a, V3Add(bCom, cCom));
u = t;
v = w;
closestP = closest6;
const Vec3V vv = V3Sub(p, closest6);
return V3Dot(vv, vv);
}
| 12,541 | C++ | 31.746736 | 150 | 0.649709 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceSegmentSegment.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 "GuDistanceSegmentSegment.h"
using namespace physx;
using namespace aos;
static const float ZERO_TOLERANCE = 1e-06f;
// S0 = origin + extent * dir;
// S1 = origin - extent * dir;
PxReal Gu::distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& dir0, PxReal extent0,
const PxVec3& origin1, const PxVec3& dir1, PxReal extent1,
PxReal* param0, PxReal* param1)
{
const PxVec3 kDiff = origin0 - origin1;
const PxReal fA01 = -dir0.dot(dir1);
const PxReal fB0 = kDiff.dot(dir0);
const PxReal fB1 = -kDiff.dot(dir1);
const PxReal fC = kDiff.magnitudeSquared();
const PxReal fDet = PxAbs(1.0f - fA01*fA01);
PxReal fS0, fS1, fSqrDist, fExtDet0, fExtDet1, fTmpS0, fTmpS1;
if (fDet >= ZERO_TOLERANCE)
{
// segments are not parallel
fS0 = fA01*fB1-fB0;
fS1 = fA01*fB0-fB1;
fExtDet0 = extent0*fDet;
fExtDet1 = extent1*fDet;
if (fS0 >= -fExtDet0)
{
if (fS0 <= fExtDet0)
{
if (fS1 >= -fExtDet1)
{
if (fS1 <= fExtDet1) // region 0 (interior)
{
// minimum at two interior points of 3D lines
PxReal fInvDet = 1.0f/fDet;
fS0 *= fInvDet;
fS1 *= fInvDet;
fSqrDist = fS0*(fS0+fA01*fS1+2.0f*fB0) + fS1*(fA01*fS0+fS1+2.0f*fB1)+fC;
}
else // region 3 (side)
{
fS1 = extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 < -extent0)
{
fS0 = -extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 <= extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
}
}
else // region 7 (side)
{
fS1 = -extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 < -extent0)
{
fS0 = -extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 <= extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
}
}
else
{
if (fS1 >= -fExtDet1)
{
if (fS1 <= fExtDet1) // region 1 (side)
{
fS0 = extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 < -extent1)
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 <= extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0)+fC;
}
else
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
else // region 2 (corner)
{
fS1 = extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 < -extent0)
{
fS0 = -extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 <= extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 < -extent1)
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 <= extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0) + fC;
}
else
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
}
}
else // region 8 (corner)
{
fS1 = -extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 < -extent0)
{
fS0 = -extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 <= extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 > extent1)
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 >= -extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0) + fC;
}
else
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
}
}
}
else
{
if (fS1 >= -fExtDet1)
{
if (fS1 <= fExtDet1) // region 5 (side)
{
fS0 = -extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 < -extent1)
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 <= extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0)+fC;
}
else
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
else // region 4 (corner)
{
fS1 = extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 > extent0)
{
fS0 = extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 >= -extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = -extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 < -extent1)
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 <= extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0) + fC;
}
else
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
}
}
else // region 6 (corner)
{
fS1 = -extent1;
fTmpS0 = -(fA01*fS1+fB0);
if (fTmpS0 > extent0)
{
fS0 = extent0;
fSqrDist = fS0*(fS0-2.0f*fTmpS0) + fS1*(fS1+2.0f*fB1)+fC;
}
else if (fTmpS0 >= -extent0)
{
fS0 = fTmpS0;
fSqrDist = -fS0*fS0+fS1*(fS1+2.0f*fB1)+fC;
}
else
{
fS0 = -extent0;
fTmpS1 = -(fA01*fS0+fB1);
if (fTmpS1 < -extent1)
{
fS1 = -extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
else if (fTmpS1 <= extent1)
{
fS1 = fTmpS1;
fSqrDist = -fS1*fS1+fS0*(fS0+2.0f*fB0) + fC;
}
else
{
fS1 = extent1;
fSqrDist = fS1*(fS1-2.0f*fTmpS1) + fS0*(fS0+2.0f*fB0)+fC;
}
}
}
}
}
else
{
// The segments are parallel.
PxReal fE0pE1 = extent0 + extent1;
PxReal fSign = (fA01 > 0.0f ? -1.0f : 1.0f);
PxReal b0Avr = 0.5f*(fB0 - fSign*fB1);
PxReal fLambda = -b0Avr;
if(fLambda < -fE0pE1)
{
fLambda = -fE0pE1;
}
else if(fLambda > fE0pE1)
{
fLambda = fE0pE1;
}
fS1 = -fSign*fLambda*extent1/fE0pE1;
fS0 = fLambda + fSign*fS1;
fSqrDist = fLambda*(fLambda + 2.0f*b0Avr) + fC;
}
if(param0)
*param0 = fS0;
if(param1)
*param1 = fS1;
// account for numerical round-off error
return physx::intrinsics::selectMax(0.0f, fSqrDist);
}
PxReal Gu::distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& extent0,
const PxVec3& origin1, const PxVec3& extent1,
PxReal* param0,
PxReal* param1)
{
// Some conversion is needed between the old & new code
// Old:
// segment (s0, s1)
// origin = s0
// extent = s1 - s0
//
// New:
// s0 = origin + extent * dir;
// s1 = origin - extent * dir;
// dsequeira: is this really sensible? We use a highly optimized Wild Magic routine,
// then use a segment representation that requires an expensive conversion to/from...
PxVec3 dir0 = extent0;
const PxVec3 center0 = origin0 + extent0*0.5f;
PxReal length0 = extent0.magnitude(); //AM: change to make it work for degenerate (zero length) segments.
const bool b0 = length0 != 0.0f;
PxReal oneOverLength0 = 0.0f;
if(b0)
{
oneOverLength0 = 1.0f / length0;
dir0 *= oneOverLength0;
length0 *= 0.5f;
}
PxVec3 dir1 = extent1;
const PxVec3 center1 = origin1 + extent1*0.5f;
PxReal length1 = extent1.magnitude();
const bool b1 = length1 != 0.0f;
PxReal oneOverLength1 = 0.0f;
if(b1)
{
oneOverLength1 = 1.0f / length1;
dir1 *= oneOverLength1;
length1 *= 0.5f;
}
// the return param vals have -extent = s0, extent = s1
const PxReal d2 = distanceSegmentSegmentSquared(center0, dir0, length0,
center1, dir1, length1,
param0, param1);
//ML : This is wrong for some reason, I guess it has precision issue
//// renormalize into the 0 = s0, 1 = s1 range
//if (param0)
// *param0 = b0 ? ((*param0) * oneOverLength0 * 0.5f + 0.5f) : 0.0f;
//if (param1)
// *param1 = b1 ? ((*param1) * oneOverLength1 * 0.5f + 0.5f) : 0.0f;
if(param0)
*param0 = b0 ? ((length0 + (*param0))*oneOverLength0) : 0.0f;
if(param1)
*param1 = b1 ? ((length1 + (*param1))*oneOverLength1) : 0.0f;
return d2;
}
/*
S0 = origin + extent * dir;
S1 = origin + extent * dir;
dir is the vector from start to end point
p1 is the start point of segment1
d1 is the direction vector(q1 - p1)
p2 is the start point of segment2
d2 is the direction vector(q2 - p2)
*/
FloatV Gu::distanceSegmentSegmentSquared( const Vec3VArg p1,
const Vec3VArg d1,
const Vec3VArg p2,
const Vec3VArg d2,
FloatV& s,
FloatV& t)
{
const FloatV zero = FZero();
const FloatV one = FOne();
const FloatV eps = FEps();
const Vec3V r = V3Sub(p1, p2);
const Vec4V combinedDot = V3Dot4(d1, d1, d2, d2, d1, d2, d1, r);
const Vec4V combinedRecip = V4Sel(V4IsGrtr(combinedDot, V4Splat(eps)), V4Recip(combinedDot), V4Splat(zero));
const FloatV a = V4GetX(combinedDot);
const FloatV e = V4GetY(combinedDot);
const FloatV b = V4GetZ(combinedDot);
const FloatV c = V4GetW(combinedDot);
const FloatV aRecip = V4GetX(combinedRecip);//FSel(FIsGrtr(a, eps), FRecip(a), zero);
const FloatV eRecip = V4GetY(combinedRecip);//FSel(FIsGrtr(e, eps), FRecip(e), zero);
const FloatV f = V3Dot(d2, r);
/*
s = (b*f - c*e)/(a*e - b*b);
t = (a*f - b*c)/(a*e - b*b);
s = (b*t - c)/a;
t = (b*s + f)/e;
*/
//if segments not parallel, the general non-degenerated case, compute closest point on two segments and clamp to segment1
const FloatV denom = FSub(FMul(a, e), FMul(b, b));
const FloatV temp = FSub(FMul(b, f), FMul(c, e));
const FloatV s0 = FClamp(FDiv(temp, denom), zero, one);
//if segment is parallel, demon < eps
const BoolV con2 = FIsGrtr(eps, denom);//FIsEq(denom, zero);
const FloatV sTmp = FSel(con2, FHalf(), s0);
//compute point on segment2 closest to segment1
//const FloatV tTmp = FMul(FAdd(FMul(b, sTmp), f), eRecip);
const FloatV tTmp = FMul(FScaleAdd(b, sTmp, f), eRecip);
//if t is in [zero, one], done. otherwise clamp t
const FloatV t2 = FClamp(tTmp, zero, one);
//recompute s for the new value
const FloatV comp = FMul(FSub(FMul(b,t2), c), aRecip);
const FloatV s2 = FClamp(comp, zero, one);
s = s2;
t = t2;
const Vec3V closest1 = V3ScaleAdd(d1, s2, p1);//V3Add(p1, V3Scale(d1, tempS));
const Vec3V closest2 = V3ScaleAdd(d2, t2, p2);//V3Add(p2, V3Scale(d2, tempT));
const Vec3V vv = V3Sub(closest1, closest2);
return V3Dot(vv, vv);
}
/*
segment (p, d) and segment (p02, d02)
segment (p, d) and segment (p12, d12)
segment (p, d) and segment (p22, d22)
segment (p, d) and segment (p32, d32)
*/
Vec4V Gu::distanceSegmentSegmentSquared4( const Vec3VArg p, const Vec3VArg d0,
const Vec3VArg p02, const Vec3VArg d02,
const Vec3VArg p12, const Vec3VArg d12,
const Vec3VArg p22, const Vec3VArg d22,
const Vec3VArg p32, const Vec3VArg d32,
Vec4V& s, Vec4V& t)
{
const Vec4V zero = V4Zero();
const Vec4V one = V4One();
const Vec4V eps = V4Eps();
const Vec4V half = V4Splat(FHalf());
const Vec4V d0X = V4Splat(V3GetX(d0));
const Vec4V d0Y = V4Splat(V3GetY(d0));
const Vec4V d0Z = V4Splat(V3GetZ(d0));
const Vec4V pX = V4Splat(V3GetX(p));
const Vec4V pY = V4Splat(V3GetY(p));
const Vec4V pZ = V4Splat(V3GetZ(p));
Vec4V d024 = Vec4V_From_Vec3V(d02);
Vec4V d124 = Vec4V_From_Vec3V(d12);
Vec4V d224 = Vec4V_From_Vec3V(d22);
Vec4V d324 = Vec4V_From_Vec3V(d32);
Vec4V p024 = Vec4V_From_Vec3V(p02);
Vec4V p124 = Vec4V_From_Vec3V(p12);
Vec4V p224 = Vec4V_From_Vec3V(p22);
Vec4V p324 = Vec4V_From_Vec3V(p32);
Vec4V d0123X, d0123Y, d0123Z;
Vec4V p0123X, p0123Y, p0123Z;
PX_TRANSPOSE_44_34(d024, d124, d224, d324, d0123X, d0123Y, d0123Z);
PX_TRANSPOSE_44_34(p024, p124, p224, p324, p0123X, p0123Y, p0123Z);
const Vec4V rX = V4Sub(pX, p0123X);
const Vec4V rY = V4Sub(pY, p0123Y);
const Vec4V rZ = V4Sub(pZ, p0123Z);
//TODO - store this in a transposed state and avoid so many dot products?
const FloatV dd = V3Dot(d0, d0);
const Vec4V e = V4MulAdd(d0123Z, d0123Z, V4MulAdd(d0123X, d0123X, V4Mul(d0123Y, d0123Y)));
const Vec4V b = V4MulAdd(d0Z, d0123Z, V4MulAdd(d0X, d0123X, V4Mul(d0Y, d0123Y)));
const Vec4V c = V4MulAdd(d0Z, rZ, V4MulAdd(d0X, rX, V4Mul(d0Y, rY)));
const Vec4V f = V4MulAdd(d0123Z, rZ, V4MulAdd(d0123X, rX, V4Mul(d0123Y, rY)));
const Vec4V a(V4Splat(dd));
const Vec4V aRecip(V4Recip(a));
const Vec4V eRecip(V4Recip(e));
//if segments not parallell, compute closest point on two segments and clamp to segment1
const Vec4V denom = V4Sub(V4Mul(a, e), V4Mul(b, b));
const Vec4V temp = V4Sub(V4Mul(b, f), V4Mul(c, e));
const Vec4V s0 = V4Clamp(V4Div(temp, denom), zero, one);
//test whether segments are parallel
const BoolV con2 = V4IsGrtrOrEq(eps, denom);
const Vec4V sTmp = V4Sel(con2, half, s0);
//compute point on segment2 closest to segment1
const Vec4V tTmp = V4Mul(V4Add(V4Mul(b, sTmp), f), eRecip);
//if t is in [zero, one], done. otherwise clamp t
const Vec4V t2 = V4Clamp(tTmp, zero, one);
//recompute s for the new value
const Vec4V comp = V4Mul(V4Sub(V4Mul(b,t2), c), aRecip);
const BoolV aaNearZero = V4IsGrtrOrEq(eps, a); // check if aRecip is valid (aa>eps)
const Vec4V s2 = V4Sel(aaNearZero, V4Zero(), V4Clamp(comp, zero, one));
/* s = V4Sel(con0, zero, V4Sel(con1, cd, s2));
t = V4Sel(con1, zero, V4Sel(con0, cg, t2)); */
s = s2;
t = t2;
const Vec4V closest1X = V4MulAdd(d0X, s2, pX);
const Vec4V closest1Y = V4MulAdd(d0Y, s2, pY);
const Vec4V closest1Z = V4MulAdd(d0Z, s2, pZ);
const Vec4V closest2X = V4MulAdd(d0123X, t2, p0123X);
const Vec4V closest2Y = V4MulAdd(d0123Y, t2, p0123Y);
const Vec4V closest2Z = V4MulAdd(d0123Z, t2, p0123Z);
const Vec4V vvX = V4Sub(closest1X, closest2X);
const Vec4V vvY = V4Sub(closest1Y, closest2Y);
const Vec4V vvZ = V4Sub(closest1Z, closest2Z);
const Vec4V vd = V4MulAdd(vvX, vvX, V4MulAdd(vvY, vvY, V4Mul(vvZ, vvZ)));
return vd;
}
| 20,431 | C++ | 34.595819 | 122 | 0.484509 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/distance/GuDistanceSegmentTriangle.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 "GuDistanceSegmentTriangle.h"
#include "GuDistancePointTriangle.h"
#include "GuDistanceSegmentSegment.h"
#include "GuBarycentricCoordinates.h"
using namespace physx;
using namespace Gu;
// ptchernev:
// The Magic Software code uses a relative error test for parallel case.
// The Novodex code does not presumably as an optimization.
// Since the Novodex code is working in the trunk I see no reason
// to reintroduce the relative error test here.
// PT: this might just be because the relative error test has been added
// after we grabbed the code. I don't remember making this change. A good
// idea would be NOT to refactor Magic's code, to easily grab updated
// versions from the website.............................................
// ptchernev:
// The code has been modified to use a relative error test since the absolute
// test would break down for small geometries. (TTP 4021)
static PX_FORCE_INLINE void updateClosestHit( PxReal fSqrDist0, PxReal fR0, PxReal fS0, PxReal fT0,
PxReal& fSqrDist, PxReal& fR, PxReal& fS, PxReal& fT)
{
if(fSqrDist0 < fSqrDist)
{
fSqrDist = fSqrDist0;
fR = fR0;
fS = fS0;
fT = fT0;
}
}
PxReal Gu::distanceSegmentTriangleSquared( const PxVec3& origin, const PxVec3& dir,
const PxVec3& p0, const PxVec3& triEdge0, const PxVec3& triEdge1,
PxReal* t, PxReal* u, PxReal* v)
{
const PxReal fA00 = dir.magnitudeSquared();
if(fA00 < 1e-6f*1e-6f)
{
if(t)
*t = 0.0f;
return distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, u, v);
}
const PxVec3 kDiff = p0 - origin;
const PxReal fA01 = -(dir.dot(triEdge0));
const PxReal fA02 = -(dir.dot(triEdge1));
const PxReal fA11 = triEdge0.magnitudeSquared();
const PxReal fA12 = triEdge0.dot(triEdge1);
const PxReal fA22 = triEdge1.dot(triEdge1);
const PxReal fB0 = -(kDiff.dot(dir));
const PxReal fB1 = kDiff.dot(triEdge0);
const PxReal fB2 = kDiff.dot(triEdge1);
const PxReal fCof00 = fA11*fA22-fA12*fA12;
const PxReal fCof01 = fA02*fA12-fA01*fA22;
const PxReal fCof02 = fA01*fA12-fA02*fA11;
const PxReal fDet = fA00*fCof00+fA01*fCof01+fA02*fCof02;
PxReal fSqrDist, fSqrDist0, fR, fS, fT, fR0, fS0, fT0;
// Set up for a relative error test on the angle between ray direction
// and triangle normal to determine parallel/nonparallel status.
const PxVec3 kNormal = triEdge0.cross(triEdge1);
const PxReal fDot = kNormal.dot(dir);
if(fDot*fDot >= 1e-6f*dir.magnitudeSquared()*kNormal.magnitudeSquared())
{
const PxReal fCof11 = fA00*fA22-fA02*fA02;
const PxReal fCof12 = fA02*fA01-fA00*fA12;
const PxReal fCof22 = fA00*fA11-fA01*fA01;
const PxReal fInvDet = fDet == 0.0f ? 0.0f : 1.0f/fDet;
const PxReal fRhs0 = -fB0*fInvDet;
const PxReal fRhs1 = -fB1*fInvDet;
const PxReal fRhs2 = -fB2*fInvDet;
fR = fCof00*fRhs0+fCof01*fRhs1+fCof02*fRhs2;
fS = fCof01*fRhs0+fCof11*fRhs1+fCof12*fRhs2;
fT = fCof02*fRhs0+fCof12*fRhs1+fCof22*fRhs2;
if(fR < 0.0f)
{
if(fS+fT <= 1.0f)
{
if(fS < 0.0f)
{
if(fT < 0.0f) // region 4m
{
// minimum on face s=0 or t=0 or r=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR0, &fS0);
fT0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 3m
{
// minimum on face s=0 or r=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
}
fSqrDist0 = distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else if(fT < 0.0f) // region 5m
{
// minimum on face t=0 or r=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
fSqrDist0 = distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 0m
{
// minimum on face r=0
fSqrDist = distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, &fS, &fT);
fR = 0.0f;
}
}
else
{
if(fS < 0.0f) // region 2m
{
// minimum on face s=0 or s+t=1 or r=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else if(fT < 0.0f) // region 6m
{
// minimum on face t=0 or s+t=1 or r=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 1m
{
// minimum on face s+t=1 or r=0
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR, &fT);
fS = 1.0f-fT;
}
fSqrDist0 = distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
}
else if(fR <= 1.0f)
{
if(fS+fT <= 1.0f)
{
if(fS < 0.0f)
{
if(fT < 0.0f) // region 4
{
// minimum on face s=0 or t=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR0, &fS0);
fT0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 3
{
// minimum on face s=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
}
}
else if(fT < 0.0f) // region 5
{
// minimum on face t=0
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
}
else // region 0
{
// global minimum is interior, done
fSqrDist = fR*(fA00*fR+fA01*fS+fA02*fT+2.0f*fB0)
+fS*(fA01*fR+fA11*fS+fA12*fT+2.0f*fB1)
+fT*(fA02*fR+fA12*fS+fA22*fT+2.0f*fB2)
+kDiff.magnitudeSquared();
}
}
else
{
if(fS < 0.0f) // region 2
{
// minimum on face s=0 or s+t=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else if(fT < 0.0f) // region 6
{
// minimum on face t=0 or s+t=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 1
{
// minimum on face s+t=1
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR, &fT);
fS = 1.0f-fT;
}
}
}
else // fR > 1
{
if(fS+fT <= 1.0f)
{
if(fS < 0.0f)
{
if(fT < 0.0f) // region 4p
{
// minimum on face s=0 or t=0 or r=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR0, &fS0);
fT0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 3p
{
// minimum on face s=0 or r=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
}
const PxVec3 kPt = origin+dir;
fSqrDist0 = distancePointTriangleSquared(kPt, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 1.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else if(fT < 0.0f) // region 5p
{
// minimum on face t=0 or r=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
const PxVec3 kPt = origin+dir;
fSqrDist0 = distancePointTriangleSquared(kPt, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 1.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 0p
{
// minimum face on r=1
const PxVec3 kPt = origin+dir;
fSqrDist = distancePointTriangleSquared(kPt, p0, triEdge0, triEdge1, &fS, &fT);
fR = 1.0f;
}
}
else
{
if(fS < 0.0f) // region 2p
{
// minimum on face s=0 or s+t=1 or r=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR, &fT);
fS = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else if(fT < 0.0f) // region 6p
{
// minimum on face t=0 or s+t=1 or r=1
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
else // region 1p
{
// minimum on face s+t=1 or r=1
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1-triEdge0;
fSqrDist = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR, &fT);
fS = 1.0f-fT;
}
const PxVec3 kPt = origin+dir;
fSqrDist0 = distancePointTriangleSquared(kPt, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 1.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
}
}
else
{
// segment and triangle are parallel
fSqrDist = distanceSegmentSegmentSquared(origin, dir, p0, triEdge0, &fR, &fS);
fT = 0.0f;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, p0, triEdge1, &fR0, &fT0);
fS0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
const PxVec3 kTriSegOrig = p0+triEdge0;
const PxVec3 kTriSegDir = triEdge1 - triEdge0;
fSqrDist0 = distanceSegmentSegmentSquared(origin, dir, kTriSegOrig, kTriSegDir, &fR0, &fT0);
fS0 = 1.0f-fT0;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
fSqrDist0 = distancePointTriangleSquared(origin, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 0.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
const PxVec3 kPt = origin+dir;
fSqrDist0 = distancePointTriangleSquared(kPt, p0, triEdge0, triEdge1, &fS0, &fT0);
fR0 = 1.0f;
updateClosestHit(fSqrDist0, fR0, fS0, fT0, fSqrDist, fR, fS, fT);
}
if(t) *t = fR;
if(u) *u = fS;
if(v) *v = fT;
// account for numerical round-off error
return physx::intrinsics::selectMax(0.0f, fSqrDist);
}
// closest0 is the closest point on segment pq
// closest1 is the closest point on triangle abc
aos::FloatV Gu::distanceSegmentTriangleSquared( const aos::Vec3VArg p, const aos::Vec3VArg q,
const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c,
aos::Vec3V& closest0, aos::Vec3V& closest1)
{
using namespace aos;
const FloatV zero = FZero();
//const FloatV one = FOne();
//const FloatV parallelTolerance = FloatV_From_F32(PX_PARALLEL_TOLERANCE);
const Vec3V pq = V3Sub(q, p);
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V bc = V3Sub(c, b);
const Vec3V ap = V3Sub(p, a);
const Vec3V aq = V3Sub(q, a);
//This is used to calculate the barycentric coordinate
const FloatV d00 = V3Dot(ab,ab);
const FloatV d01 = V3Dot(ab, ac);
const FloatV d11 = V3Dot(ac, ac);
const FloatV tDenom = FSub(FMul(d00, d11), FMul(d01, d01));
const FloatV bdenom = FSel(FIsGrtr(tDenom, zero), FRecip(tDenom), zero);
const Vec3V n = V3Normalize(V3Cross(ab, ac)); // normalize vector
//compute the closest point of p and triangle plane abc
const FloatV dist3 = V3Dot(ap, n);
const FloatV sqDist3 = FMul(dist3, dist3);
//compute the closest point of q and triangle plane abc
const FloatV dist4 = V3Dot(aq, n);
const FloatV sqDist4 = FMul(dist4, dist4);
const FloatV dMul = FMul(dist3, dist4);
const BoolV con = FIsGrtr(zero, dMul);
// intersect with the plane
if(BAllEqTTTT(con))
{
//compute the intersect point
const FloatV nom = FNeg(V3Dot(n, ap));
const FloatV denom = FRecip(V3Dot(n, pq));
const FloatV t = FMul(nom, denom);
const Vec3V ip = V3ScaleAdd(pq, t, p);//V3Add(p, V3Scale(pq, t));
const Vec3V v2 = V3Sub(ip, a);
const FloatV d20 = V3Dot(v2, ab);
const FloatV d21 = V3Dot(v2, ac);
const FloatV v0 = FMul(FSub(FMul(d11, d20), FMul(d01, d21)), bdenom);
const FloatV w0 = FMul(FSub(FMul(d00, d21), FMul(d01, d20)), bdenom);
const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0);
if(BAllEqTTTT(con0))
{
closest0 = closest1 = ip;
return zero;
}
}
Vec4V t40, t41;
const Vec4V sqDist44 = distanceSegmentSegmentSquared4(p,pq,a,ab, b,bc, a,ac, a,ab, t40, t41);
const FloatV t00 = V4GetX(t40);
const FloatV t10 = V4GetY(t40);
const FloatV t20 = V4GetZ(t40);
const FloatV t01 = V4GetX(t41);
const FloatV t11 = V4GetY(t41);
const FloatV t21 = V4GetZ(t41);
const FloatV sqDist0(V4GetX(sqDist44));
const FloatV sqDist1(V4GetY(sqDist44));
const FloatV sqDist2(V4GetZ(sqDist44));
const Vec3V closestP00 = V3ScaleAdd(pq, t00, p);
const Vec3V closestP01 = V3ScaleAdd(ab, t01, a);
const Vec3V closestP10 = V3ScaleAdd(pq, t10, p);
const Vec3V closestP11 = V3ScaleAdd(bc, t11, b);
const Vec3V closestP20 = V3ScaleAdd(pq, t20, p);
const Vec3V closestP21 = V3ScaleAdd(ac, t21, a);
//Get the closest point of all edges
const BoolV con20 = FIsGrtr(sqDist1, sqDist0);
const BoolV con21 = FIsGrtr(sqDist2, sqDist0);
const BoolV con2 = BAnd(con20,con21);
const BoolV con30 = FIsGrtrOrEq(sqDist0, sqDist1);
const BoolV con31 = FIsGrtr(sqDist2, sqDist1);
const BoolV con3 = BAnd(con30, con31);
const FloatV sqDistPE = FSel(con2, sqDist0, FSel(con3, sqDist1, sqDist2));
//const FloatV tValue = FSel(con2, t00, FSel(con3, t10, t20));
const Vec3V closestPE0 = V3Sel(con2, closestP00, V3Sel(con3, closestP10, closestP20)); // closestP on segment
const Vec3V closestPE1 = V3Sel(con2, closestP01, V3Sel(con3, closestP11, closestP21)); // closestP on triangle
const Vec3V closestP31 = V3NegScaleSub(n, dist3, p);//V3Sub(p, V3Scale(n, dist3));
const Vec3V closestP30 = p;
//Compute the barycentric coordinate for project point of q
const Vec3V pV20 = V3Sub(closestP31, a);
const FloatV pD20 = V3Dot(pV20, ab);
const FloatV pD21 = V3Dot(pV20, ac);
const FloatV v0 = FMul(FSub(FMul(d11, pD20), FMul(d01, pD21)), bdenom);
const FloatV w0 = FMul(FSub(FMul(d00, pD21), FMul(d01, pD20)), bdenom);
//check closestP3 is inside the triangle
const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0);
const Vec3V closestP41 = V3NegScaleSub(n, dist4, q);// V3Sub(q, V3Scale(n, dist4));
const Vec3V closestP40 = q;
//Compute the barycentric coordinate for project point of q
const Vec3V qV20 = V3Sub(closestP41, a);
const FloatV qD20 = V3Dot(qV20, ab);
const FloatV qD21 = V3Dot(qV20, ac);
const FloatV v1 = FMul(FSub(FMul(d11, qD20), FMul(d01, qD21)), bdenom);
const FloatV w1 = FMul(FSub(FMul(d00, qD21), FMul(d01, qD20)), bdenom);
const BoolV con1 = isValidTriangleBarycentricCoord(v1, w1);
// p is interior point but not q
const BoolV d0 = FIsGrtr(sqDistPE, sqDist3);
const Vec3V c00 = V3Sel(d0, closestP30, closestPE0);
const Vec3V c01 = V3Sel(d0, closestP31, closestPE1);
// q is interior point but not p
const BoolV d1 = FIsGrtr(sqDistPE, sqDist4);
const Vec3V c10 = V3Sel(d1, closestP40, closestPE0);
const Vec3V c11 = V3Sel(d1, closestP41, closestPE1);
// p and q are interior point
const BoolV d2 = FIsGrtr(sqDist4, sqDist3);
const Vec3V c20 = V3Sel(d2, closestP30, closestP40);
const Vec3V c21 = V3Sel(d2, closestP31, closestP41);
const BoolV cond2 = BAnd(con0, con1);
const Vec3V closestP0 = V3Sel(cond2, c20, V3Sel(con0, c00, V3Sel(con1, c10, closestPE0)));
const Vec3V closestP1 = V3Sel(cond2, c21, V3Sel(con0, c01, V3Sel(con1, c11, closestPE1)));
const Vec3V vv = V3Sub(closestP1, closestP0);
closest0 = closestP0;
closest1 = closestP1;
return V3Dot(vv, vv);
}
| 19,157 | C++ | 35.701149 | 111 | 0.671295 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereSphere.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 "GuSweepSphereSphere.h"
#include "foundation/PxUtilities.h"
using namespace physx;
using namespace Gu;
// Adapted from Gamasutra (Gomez article)
// Return true if r1 and r2 are real
static PX_FORCE_INLINE bool quadraticFormula(const PxReal a, const PxReal b, const PxReal c, PxReal& r1, PxReal& r2)
{
const PxReal q = b*b - 4*a*c;
if(q>=0.0f)
{
PX_ASSERT(a!=0.0f);
const PxReal sq = PxSqrt(q);
const PxReal d = 1.0f / (2.0f*a);
r1 = (-b + sq) * d;
r2 = (-b - sq) * d;
return true;//real roots
}
else
{
return false;//complex roots
}
}
static bool sphereSphereSweep( const PxReal ra, //radius of sphere A
const PxVec3& A0, //previous position of sphere A
const PxVec3& A1, //current position of sphere A
const PxReal rb, //radius of sphere B
const PxVec3& B0, //previous position of sphere B
const PxVec3& B1, //current position of sphere B
PxReal& u0, //normalized time of first collision
PxReal& u1 //normalized time of second collision
)
{
const PxVec3 va = A1 - A0;
const PxVec3 vb = B1 - B0;
const PxVec3 AB = B0 - A0;
const PxVec3 vab = vb - va; // relative velocity (in normalized time)
const PxReal rab = ra + rb;
const PxReal a = vab.dot(vab); //u*u coefficient
const PxReal b = 2.0f*(vab.dot(AB)); //u coefficient
const PxReal c = (AB.dot(AB)) - rab*rab; //constant term
//check if they're currently overlapping
if(c<=0.0f || a==0.0f)
{
u0 = 0.0f;
u1 = 0.0f;
return true;
}
//check if they hit each other during the frame
if(quadraticFormula(a, b, c, u0, u1))
{
if(u0>u1)
PxSwap(u0, u1);
// u0<u1
// if(u0<0.0f || u1>1.0f) return false;
if(u1<0.0f || u0>1.0f) return false;
return true;
}
return false;
}
bool Gu::sweepSphereSphere(const PxVec3& center0, PxReal radius0, const PxVec3& center1, PxReal radius1, const PxVec3& motion, PxReal& d, PxVec3& nrm)
{
const PxVec3 movedCenter = center1 + motion;
PxReal tmp;
if(!sphereSphereSweep(radius0, center0, center0, radius1, center1, movedCenter, d, tmp))
return false;
// Compute normal
// PT: if spheres initially overlap, the convention is that returned normal = -sweep direction
if(d==0.0f)
nrm = -motion;
else
nrm = (center1 + d * motion) - center0;
nrm.normalize();
return true;
}
| 4,000 | C++ | 33.491379 | 150 | 0.7035 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleCapsule.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_CAPSULE_CAPSULE_H
#define GU_SWEEP_CAPSULE_CAPSULE_H
#include "foundation/PxVec3.h"
namespace physx
{
namespace Gu
{
class Capsule;
bool sweepCapsuleCapsule(const Capsule& capsule0, const Capsule& capsule1, const PxVec3& dir, PxReal length, PxReal& min_dist, PxVec3& ip, PxVec3& normal, PxU32 inHitFlags, PxU16& outHitFlags);
} // namespace Gu
}
#endif
| 2,076 | C | 43.191488 | 194 | 0.764451 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleTriangle.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 "GuSweepCapsuleTriangle.h"
#include "GuIntersectionCapsuleTriangle.h"
#include "GuDistanceSegmentTriangle.h"
#include "GuIntersectionTriangleBox.h"
#include "GuSweepSphereTriangle.h"
#include "GuInternal.h"
using namespace physx;
using namespace Gu;
using namespace physx::aos;
#define COLINEARITY_EPSILON 0.00001f
///////////////////////////////////////////////////////////////////////////////
#define OUTPUT_TRI(pp0, pp1, pp2){ \
extrudedTris[nbExtrudedTris].verts[0] = pp0; \
extrudedTris[nbExtrudedTris].verts[1] = pp1; \
extrudedTris[nbExtrudedTris].verts[2] = pp2; \
extrudedTris[nbExtrudedTris].denormalizedNormal(extrudedTrisNormals[nbExtrudedTris]); \
nbExtrudedTris++;}
#define OUTPUT_TRI2(p0, p1, p2, d){ \
PxTriangle& tri = extrudedTris[nbExtrudedTris]; \
tri.verts[0] = p0; \
tri.verts[1] = p1; \
tri.verts[2] = p2; \
PxVec3 nrm; \
tri.denormalizedNormal(nrm); \
if(nrm.dot(d)>0.0f) { \
PxVec3 tmp = tri.verts[1]; \
tri.verts[1] = tri.verts[2]; \
tri.verts[2] = tmp; \
nrm = -nrm; \
} \
extrudedTrisNormals[nbExtrudedTris] = nrm; \
nbExtrudedTris++; }
//#define NEW_VERSION
bool Gu::sweepCapsuleTriangles_Precise( PxU32 nbTris, const PxTriangle* PX_RESTRICT triangles, // Triangle data
const Capsule& capsule, // Capsule data
const PxVec3& unitDir, const PxReal distance, // Ray data
const PxU32* PX_RESTRICT cachedIndex, // Cache data
PxGeomSweepHit& hit, PxVec3& triNormalOut, // Results
PxHitFlags hitFlags, bool isDoubleSided, // Query modifiers
const BoxPadded* cullBox) // Cull data
{
if(!nbTris)
return false;
const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES;
const bool doBackfaceCulling = !isDoubleSided && !meshBothSides;
const bool anyHit = hitFlags & PxHitFlag::eMESH_ANY;
const bool testInitialOverlap = !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP);
// PT: we can fallback to sphere sweep:
// - if the capsule is degenerate (i.e. it's a sphere)
// - if the sweep direction is the same as the capsule axis, in which case we can just sweep the top or bottom sphere
const PxVec3 extrusionDir = (capsule.p0 - capsule.p1)*0.5f; // Extrusion dir = capsule segment
const PxReal halfHeight = extrusionDir.magnitude();
bool mustExtrude = halfHeight!=0.0f;
if(!mustExtrude)
{
// PT: capsule is a sphere. Switch to sphere path (intersectCapsuleTriangle doesn't work for degenerate capsules)
return sweepSphereTriangles(nbTris, triangles, capsule.p0, capsule.radius, unitDir, distance, cachedIndex, hit, triNormalOut, isDoubleSided, meshBothSides, anyHit, testInitialOverlap);
}
else
{
const PxVec3 capsuleAxis = extrusionDir/halfHeight;
const PxReal colinearity = PxAbs(capsuleAxis.dot(unitDir));
mustExtrude = (colinearity < (1.0f - COLINEARITY_EPSILON));
}
const PxVec3 capsuleCenter = capsule.computeCenter();
if(!mustExtrude)
{
CapsuleTriangleOverlapData params;
params.init(capsule);
// PT: unfortunately we need to do IO test with the *capsule*, even though we're in the sphere codepath. So we
// can't directly reuse the sphere function.
const PxVec3 sphereCenter = capsuleCenter + unitDir * halfHeight;
// PT: this is a copy of 'sweepSphereTriangles' but with a capsule IO test. Saves double backface culling....
{
PxU32 index = PX_INVALID_U32;
const PxU32 initIndex = getInitIndex(cachedIndex, nbTris);
PxReal curT = distance;
const PxReal dpc0 = sphereCenter.dot(unitDir);
PxReal bestAlignmentValue = 2.0f;
PxVec3 bestTriNormal(0.0f);
for(PxU32 ii=0; ii<nbTris; ii++) // We need i for returned triangle index
{
const PxU32 i = getTriangleIndex(ii, initIndex);
const PxTriangle& currentTri = triangles[i];
if(rejectTriangle(sphereCenter, unitDir, curT, capsule.radius, currentTri.verts, dpc0))
continue;
PxVec3 triNormal;
currentTri.denormalizedNormal(triNormal);
// Backface culling
if(doBackfaceCulling && (triNormal.dot(unitDir) > 0.0f))
continue;
if(testInitialOverlap && intersectCapsuleTriangle(triNormal, currentTri.verts[0], currentTri.verts[1], currentTri.verts[2], capsule, params))
{
triNormalOut = -unitDir;
return setInitialOverlapResults(hit, unitDir, i);
}
const PxReal magnitude = triNormal.magnitude();
if(magnitude==0.0f)
continue;
triNormal /= magnitude;
PxReal currentDistance;
bool unused;
if(!sweepSphereVSTri(currentTri.verts, triNormal, sphereCenter, capsule.radius, unitDir, currentDistance, unused, false))
continue;
const PxReal hitDot = computeAlignmentValue(triNormal, unitDir);
if(keepTriangle(currentDistance, hitDot, curT, bestAlignmentValue, distance))
{
curT = PxMin(curT, currentDistance); // exact lower bound
index = i;
bestAlignmentValue = hitDot;
bestTriNormal = triNormal;
if(anyHit)
break;
}
//
else if(keepTriangleBasic(currentDistance, curT, distance))
{
curT = PxMin(curT, currentDistance); // exact lower bound
}
//
}
return computeSphereTriangleImpactData(hit, triNormalOut, index, curT, sphereCenter, unitDir, bestTriNormal, triangles, isDoubleSided, meshBothSides);
}
}
// PT: extrude mesh on the fly. This is a modified copy of sweepSphereTriangles, unfortunately
PxTriangle extrudedTris[7];
PxVec3 extrudedTrisNormals[7]; // Not normalized
hit.faceIndex = PX_INVALID_U32;
const PxU32 initIndex = getInitIndex(cachedIndex, nbTris);
const PxReal radius = capsule.radius;
PxReal curT = distance;
const PxReal dpc0 = capsuleCenter.dot(unitDir);
// PT: we will copy the best triangle here. Using indices alone doesn't work
// since we extrude on-the-fly (and we don't want to re-extrude later)
PxTriangle bestTri;
PxVec3 bestTriNormal(0.0f);
PxReal mostOpposingHitDot = 2.0f;
CapsuleTriangleOverlapData params;
params.init(capsule);
for(PxU32 ii=0; ii<nbTris; ii++) // We need i for returned triangle index
{
const PxU32 i = getTriangleIndex(ii, initIndex);
const PxTriangle& currentSrcTri = triangles[i]; // PT: src tri, i.e. non-extruded
///////////// PT: this part comes from "ExtrudeMesh"
// Create triangle normal
PxVec3 denormalizedNormal;
currentSrcTri.denormalizedNormal(denormalizedNormal);
// Backface culling
if(doBackfaceCulling && (denormalizedNormal.dot(unitDir) > 0.0f))
continue;
if(cullBox)
{
if(!intersectTriangleBox(*cullBox, currentSrcTri.verts[0], currentSrcTri.verts[1], currentSrcTri.verts[2]))
continue;
}
if(testInitialOverlap && intersectCapsuleTriangle(denormalizedNormal, currentSrcTri.verts[0], currentSrcTri.verts[1], currentSrcTri.verts[2], capsule, params))
{
triNormalOut = -unitDir;
return setInitialOverlapResults(hit, unitDir, i);
}
// Extrude mesh on the fly
PxU32 nbExtrudedTris=0;
const PxVec3 p0 = currentSrcTri.verts[0] - extrusionDir;
const PxVec3 p1 = currentSrcTri.verts[1] - extrusionDir;
const PxVec3 p2 = currentSrcTri.verts[2] - extrusionDir;
const PxVec3 p0b = currentSrcTri.verts[0] + extrusionDir;
const PxVec3 p1b = currentSrcTri.verts[1] + extrusionDir;
const PxVec3 p2b = currentSrcTri.verts[2] + extrusionDir;
if(denormalizedNormal.dot(extrusionDir) >= 0.0f) OUTPUT_TRI(p0b, p1b, p2b)
else OUTPUT_TRI(p0, p1, p2)
// ### it's probably useless to extrude all the shared edges !!!!!
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE12)
{
OUTPUT_TRI2(p1, p1b, p2b, unitDir)
OUTPUT_TRI2(p1, p2b, p2, unitDir)
}
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE20)
{
OUTPUT_TRI2(p0, p2, p2b, unitDir)
OUTPUT_TRI2(p0, p2b, p0b, unitDir)
}
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE01)
{
OUTPUT_TRI2(p0b, p1b, p1, unitDir)
OUTPUT_TRI2(p0b, p1, p0, unitDir)
}
/////////////
// PT: TODO: this one is new, to fix the tweak issue. However this wasn't
// here before so the perf hit should be analyzed.
denormalizedNormal.normalize();
const PxReal hitDot1 = computeAlignmentValue(denormalizedNormal, unitDir);
#ifdef NEW_VERSION
float localDistance = FLT_MAX;
PxU32 localIndex = 0xffffffff;
#endif
for(PxU32 j=0;j<nbExtrudedTris;j++)
{
const PxTriangle& currentTri = extrudedTris[j];
PxVec3& triNormal = extrudedTrisNormals[j];
// Backface culling
if(doBackfaceCulling && (triNormal.dot(unitDir)) > 0.0f)
continue;
// PT: beware, culling is only ok on the sphere I think
if(rejectTriangle(capsuleCenter, unitDir, curT, radius, currentTri.verts, dpc0))
continue;
const PxReal magnitude = triNormal.magnitude();
if(magnitude==0.0f)
continue;
triNormal /= magnitude;
PxReal currentDistance;
bool unused;
if(!sweepSphereVSTri(currentTri.verts, triNormal, capsuleCenter, radius, unitDir, currentDistance, unused, false))
continue;
#ifndef NEW_VERSION
if(keepTriangle(currentDistance, hitDot1, curT, mostOpposingHitDot, distance))
{
curT = PxMin(curT, currentDistance); // exact lower bound
hit.faceIndex = i;
mostOpposingHitDot = hitDot1; // arbitrary bias. works for hitDot1=-1, prevHitDot=0
bestTri = currentTri;
bestTriNormal = denormalizedNormal;
if(anyHit)
goto Exit; // PT: using goto to have one test per hit, not test per triangle ('break' doesn't work here)
}
//
else if(keepTriangleBasic(currentDistance, curT, distance))
{
curT = PxMin(curT, currentDistance); // exact lower bound
}
//
#endif
#ifdef NEW_VERSION
if(keepTriangleBasic(currentDistance, localDistance, distance))
{
localDistance = currentDistance;
localIndex = j;
}
#endif
}
#ifdef NEW_VERSION
if(localIndex!=0xffffffff)
{
if(keepTriangle(localDistance, hitDot1, curT, mostOpposingHitDot, distance))
{
curT = PxMin(curT, localDistance); // exact lower bound
hit.faceIndex = i;
mostOpposingHitDot = hitDot1; // arbitrary bias. works for hitDot1=-1, prevHitDot=0
bestTri = currentSrcTri;
bestTriNormal = denormalizedNormal;
if(anyHit)
goto Exit; // PT: using goto to have one test per hit, not test per triangle ('break' doesn't work here)
}
//
else if(keepTriangleBasic(localDistance, curT, distance))
{
curT = PxMin(curT, localDistance); // exact lower bound
}
}
#endif
}
Exit:
if(hit.faceIndex==PX_INVALID_U32)
return false; // We didn't touch any triangle
hit.distance = curT;
triNormalOut = bestTriNormal;
// Compute impact data only once, using best triangle
computeSphereTriImpactData(hit.position, hit.normal, capsuleCenter, unitDir, hit.distance, bestTri);
// PT: by design, returned normal is opposed to the sweep direction.
if(shouldFlipNormal(hit.normal, meshBothSides, isDoubleSided, bestTriNormal, unitDir))
hit.normal = -hit.normal;
// PT: revisit this
if(hit.faceIndex!=PX_INVALID_U32)
{
// PT: we need to recompute a hit here because the hit between the *capsule* and the source mesh can be very
// different from the hit between the *sphere* and the extruded mesh.
// Touched tri
const PxVec3& p0 = triangles[hit.faceIndex].verts[0];
const PxVec3& p1 = triangles[hit.faceIndex].verts[1];
const PxVec3& p2 = triangles[hit.faceIndex].verts[2];
// AP: measured to be a bit faster than the scalar version
const PxVec3 delta = unitDir*hit.distance;
Vec3V pointOnSeg, pointOnTri;
distanceSegmentTriangleSquared(
V3LoadU(capsule.p0 + delta), V3LoadU(capsule.p1 + delta),
V3LoadU(p0), V3LoadU(p1), V3LoadU(p2),
pointOnSeg, pointOnTri);
V3StoreU(pointOnTri, hit.position);
hit.flags = PxHitFlag::eNORMAL|PxHitFlag::ePOSITION;
}
return true;
}
| 13,508 | C++ | 34.088312 | 186 | 0.708543 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxTriangle_FeatureBased.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_BOX_TRIANGLE_FEATURE_BASED_H
#define GU_SWEEP_BOX_TRIANGLE_FEATURE_BASED_H
#include "foundation/PxVec3.h"
#include "foundation/PxPlane.h"
namespace physx
{
class PxTriangle;
namespace Gu
{
/**
Sweeps a box against a triangle, using a 'feature-based' approach.
This is currently only used for computing the box-sweep impact data, in a second pass,
after the best triangle has been identified using faster approaches (SAT/GJK).
\warning Returned impact normal is not normalized
\param tri [in] the triangle
\param box [in] the box
\param motion [in] (box) motion vector
\param oneOverMotion [in] precomputed inverse of motion vector
\param hit [out] impact point
\param normal [out] impact normal (warning: not normalized)
\param d [in/out] impact distance (please initialize with best current distance)
\param isDoubleSided [in] whether triangle is double-sided or not
\return true if an impact has been found
*/
bool sweepBoxTriangle( const PxTriangle& tri, const PxBounds3& box,
const PxVec3& motion, const PxVec3& oneOverMotion,
PxVec3& hit, PxVec3& normal, PxReal& d, bool isDoubleSided=false);
} // namespace Gu
}
#endif
| 2,916 | C | 43.196969 | 88 | 0.75 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereTriangle.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 "GuSweepSphereTriangle.h"
#include "GuIntersectionRaySphere.h"
#include "GuIntersectionRayCapsule.h"
#include "GuIntersectionRayTriangle.h"
#include "GuCapsule.h"
#include "GuInternal.h"
#include "foundation/PxUtilities.h"
#include "GuDistancePointTriangle.h"
//#define PX_2413_FIX // Works in VT, but UT fails
#ifdef PX_2413_FIX
#define FIXUP_UVS u += du; v += dv;
#else
#define FIXUP_UVS
#endif
static const bool gSanityCheck = false;
//static const float gEpsilon = 0.1f;
#define gEpsilon 0.1f // PT: because otherwise compiler complains that this is unused
// PT: alternative version that checks 2 capsules max and avoids the questionable heuristic and the whole du/dv fix
static const bool gUseAlternativeImplementation = true;
using namespace physx;
using namespace Gu;
// PT: using GU_CULLING_EPSILON_RAY_TRIANGLE fails here, in capsule-vs-mesh's triangle extrusion, when
// the sweep dir is almost the same as the capsule's dir (i.e. when we usually fallback to the sphere codepath).
// I suspect det becomes so small that we lose all accuracy when dividing by det and using the result in computing
// impact distance.
#define LOCAL_EPSILON 0.00001f
// PT: special version computing (u,v) even when the ray misses the tri. Version working on precomputed edges.
static PX_FORCE_INLINE PxU32 rayTriSpecial(const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, PxReal& t, PxReal& u, PxReal& v)
{
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2);
// If determinant is near zero, ray lies in plane of triangle
const PxReal det = edge1.dot(pvec);
// the non-culling branch
// if(det>-GU_CULLING_EPSILON_RAY_TRIANGLE && det<GU_CULLING_EPSILON_RAY_TRIANGLE)
if(det>-LOCAL_EPSILON && det<LOCAL_EPSILON)
return 0;
const PxReal oneOverDet = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter
u = (tvec.dot(pvec)) * oneOverDet;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter
v = (dir.dot(qvec)) * oneOverDet;
if(u<0.0f || u>1.0f)
return 1;
if(v<0.0f || u+v>1.0f)
return 1;
// Calculate t, ray intersects triangle
t = (edge2.dot(qvec)) * oneOverDet;
return 2;
}
#ifdef PX_2413_FIX
static PX_FORCE_INLINE PxU32 rayTriSpecial3(const PxVec3& orig, const PxVec3& offset, const PxVec3& dir, const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, PxReal& t, PxReal& u, PxReal& v, PxReal& du, PxReal& dv)
{
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2);
// If determinant is near zero, ray lies in plane of triangle
const PxReal det = edge1.dot(pvec);
// the non-culling branch
// if(det>-GU_CULLING_EPSILON_RAY_TRIANGLE && det<GU_CULLING_EPSILON_RAY_TRIANGLE)
if(det>-LOCAL_EPSILON && det<LOCAL_EPSILON)
return 0;
const PxReal oneOverDet = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter
u = (tvec.dot(pvec)) * oneOverDet;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter
v = (dir.dot(qvec)) * oneOverDet;
if(u<0.0f || u>1.0f || v<0.0f || u+v>1.0f)
{
du = (offset.dot(pvec)) * oneOverDet;
const PxVec3 qvec = offset.cross(edge1);
dv = (dir.dot(qvec)) * oneOverDet;
return 1;
}
// Calculate t, ray intersects triangle
t = (edge2.dot(qvec)) * oneOverDet;
return 2;
}
#endif
// Returns true if sphere can be tested against triangle vertex, false if edge test should be performed
//
// Uses a conservative approach to work for "sliver triangles" (long & thin) as well.
static PX_FORCE_INLINE bool edgeOrVertexTest(const PxVec3& planeIntersectPoint, const PxVec3* PX_RESTRICT tri, PxU32 vertIntersectCandidate, PxU32 vert0, PxU32 vert1, PxU32& secondEdgeVert)
{
{
const PxVec3 edge0 = tri[vertIntersectCandidate] - tri[vert0];
const PxReal edge0LengthSqr = edge0.dot(edge0);
const PxVec3 diff = planeIntersectPoint - tri[vert0];
if (edge0.dot(diff) < edge0LengthSqr) // If the squared edge length is used for comparison, the edge vector does not need to be normalized
{
secondEdgeVert = vert0;
return false;
}
}
{
const PxVec3 edge1 = tri[vertIntersectCandidate] - tri[vert1];
const PxReal edge1LengthSqr = edge1.dot(edge1);
const PxVec3 diff = planeIntersectPoint - tri[vert1];
if (edge1.dot(diff) < edge1LengthSqr)
{
secondEdgeVert = vert1;
return false;
}
}
return true;
}
static PX_FORCE_INLINE bool testRayVsSphereOrCapsule(PxReal& impactDistance, bool testSphere, const PxVec3& center, PxReal radius, const PxVec3& dir, const PxVec3* PX_RESTRICT verts, PxU32 e0, PxU32 e1)
{
if(testSphere)
{
PxReal t;
if(intersectRaySphere(center, dir, PX_MAX_F32, verts[e0], radius, t))
{
impactDistance = t;
return true;
}
}
else
{
PxReal t;
if(intersectRayCapsule(center, dir, verts[e0], verts[e1], radius, t))
{
if(t>=0.0f/* && t<MinDist*/)
{
impactDistance = t;
return true;
}
}
}
return false;
}
bool Gu::sweepSphereVSTri(const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, const PxVec3& center, PxReal radius, const PxVec3& dir, PxReal& impactDistance, bool& directHit, bool testInitialOverlap)
{
// Ok, this new version is now faster than the original code. Needs more testing though.
directHit = false;
const PxVec3 edge10 = triVerts[1] - triVerts[0];
const PxVec3 edge20 = triVerts[2] - triVerts[0];
if(testInitialOverlap) // ### brute force version that always works, but we can probably do better
{
const PxVec3 cp = closestPtPointTriangle2(center, triVerts[0], triVerts[1], triVerts[2], edge10, edge20);
if((cp - center).magnitudeSquared() <= radius*radius)
{
impactDistance = 0.0f;
return true;
}
}
#define INTERSECT_POINT (triVerts[1]*u) + (triVerts[2]*v) + (triVerts[0] * (1.0f-u-v))
PxReal u,v;
#ifdef PX_2413_FIX
float du, dv;
#endif
{
PxVec3 R = normal * radius;
if(dir.dot(R) >= 0.0f)
R = -R;
// The first point of the sphere to hit the triangle plane is the point of the sphere nearest to
// the triangle plane. Hence, we use center - (normal*radius) below.
// PT: casting against the extruded triangle in direction R is the same as casting from a ray moved by -R
PxReal t;
#ifdef PX_2413_FIX
const PxU32 r = rayTriSpecial3(center-R, R, dir, triVerts[0], edge10, edge20, t, u, v, du, dv);
#else
const PxU32 r = rayTriSpecial(center-R, dir, triVerts[0], edge10, edge20, t, u, v);
#endif
if(!r)
return false;
if(r==2)
{
if(t<0.0f)
return false;
impactDistance = t;
directHit = true;
return true;
}
}
float referenceMinDist = PX_MAX_F32;
bool referenceHit = false;
if(gSanityCheck)
{
PxReal t;
if(intersectRayCapsule(center, dir, triVerts[0], triVerts[1], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(intersectRayCapsule(center, dir, triVerts[1], triVerts[2], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(intersectRayCapsule(center, dir, triVerts[2], triVerts[0], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(!gUseAlternativeImplementation)
{
if(referenceHit)
impactDistance = referenceMinDist;
return referenceHit;
}
}
//
// Let's do some art!
//
// The triangle gets divided into the following areas (based on the barycentric coordinates (u,v)):
//
// \ A0 /
// \ /
// \ /
// \/ 0
// A02 * A01
// u / / \ \ v
// * / \ *
// / \ .
// 2 / \ 1
// ------*--------------*-------
// / \ .
// A2 / A12 \ A1
//
//
// Based on the area where the computed triangle plane intersection point lies in, a different sweep test will be applied.
//
// A) A01, A02, A12 : Test sphere against the corresponding edge
// B) A0, A1, A2 : Test sphere against the corresponding vertex
//
// Unfortunately, B) does not work for long, thin triangles. Hence there is some extra code which does a conservative check and
// switches to edge tests if necessary.
//
if(gUseAlternativeImplementation)
{
bool testTwoEdges = false;
PxU32 e0,e1,e2=0;
if(u<0.0f)
{
if(v<0.0f)
{
// 0 or 0-1 or 0-2
testTwoEdges = true;
e0 = 0;
e1 = 1;
e2 = 2;
}
else if(u+v>1.0f)
{
// 2 or 2-0 or 2-1
testTwoEdges = true;
e0 = 2;
e1 = 0;
e2 = 1;
}
else
{
// 0-2
e0 = 0;
e1 = 2;
}
}
else
{
if(v<0.0f)
{
if(u+v>1.0f)
{
// 1 or 1-0 or 1-2
testTwoEdges = true;
e0 = 1;
e1 = 0;
e2 = 2;
}
else
{
// 0-1
e0 = 0;
e1 = 1;
}
}
else
{
PX_ASSERT(u+v>=1.0f); // Else hit triangle
// 1-2
e0 = 1;
e1 = 2;
}
}
bool hit = false;
PxReal t;
if(intersectRayCapsule(center, dir, triVerts[e0], triVerts[e1], radius, t) && t>=0.0f)
{
impactDistance = t;
hit = true;
}
if(testTwoEdges && intersectRayCapsule(center, dir, triVerts[e0], triVerts[e2], radius, t) && t>=0.0f)
{
if(!hit || t<impactDistance)
{
impactDistance = t;
hit = true;
}
}
if(gSanityCheck)
{
PX_ASSERT(referenceHit==hit);
if(referenceHit==hit)
PX_ASSERT(fabsf(referenceMinDist-impactDistance)<gEpsilon);
}
return hit;
}
else
{
bool TestSphere;
PxU32 e0,e1;
if(u<0.0f)
{
if(v<0.0f)
{
// 0 or 0-1 or 0-2
e0 = 0;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT;
TestSphere = edgeOrVertexTest(intersectPoint, triVerts, 0, 1, 2, e1);
}
else if(u+v>1.0f)
{
// 2 or 2-0 or 2-1
e0 = 2;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT;
TestSphere = edgeOrVertexTest(intersectPoint, triVerts, 2, 0, 1, e1);
}
else
{
// 0-2
TestSphere = false;
e0 = 0;
e1 = 2;
}
}
else
{
if(v<0.0f)
{
if(u+v>1.0f)
{
// 1 or 1-0 or 1-2
e0 = 1;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT;
TestSphere = edgeOrVertexTest(intersectPoint, triVerts, 1, 0, 2, e1);
}
else
{
// 0-1
TestSphere = false;
e0 = 0;
e1 = 1;
}
}
else
{
PX_ASSERT(u+v>=1.0f); // Else hit triangle
// 1-2
TestSphere = false;
e0 = 1;
e1 = 2;
}
}
return testRayVsSphereOrCapsule(impactDistance, TestSphere, center, radius, dir, triVerts, e0, e1);
}
}
bool Gu::sweepSphereTriangles( PxU32 nbTris, const PxTriangle* PX_RESTRICT triangles, // Triangle data
const PxVec3& center, const PxReal radius, // Sphere data
const PxVec3& unitDir, PxReal distance, // Ray data
const PxU32* PX_RESTRICT cachedIndex, // Cache data
PxGeomSweepHit& h, PxVec3& triNormalOut, // Results
bool isDoubleSided, bool meshBothSides, bool anyHit, bool testInitialOverlap) // Query modifiers
{
if(!nbTris)
return false;
const bool doBackfaceCulling = !isDoubleSided && !meshBothSides;
PxU32 index = PX_INVALID_U32;
const PxU32 initIndex = getInitIndex(cachedIndex, nbTris);
PxReal curT = distance;
const PxReal dpc0 = center.dot(unitDir);
PxReal bestAlignmentValue = 2.0f;
PxVec3 bestTriNormal(0.0f);
for(PxU32 ii=0; ii<nbTris; ii++) // We need i for returned triangle index
{
const PxU32 i = getTriangleIndex(ii, initIndex);
const PxTriangle& currentTri = triangles[i];
if(rejectTriangle(center, unitDir, curT, radius, currentTri.verts, dpc0))
continue;
PxVec3 triNormal;
currentTri.denormalizedNormal(triNormal);
// Backface culling
if(doBackfaceCulling && (triNormal.dot(unitDir) > 0.0f))
continue;
const PxReal magnitude = triNormal.magnitude();
if(magnitude==0.0f)
continue;
triNormal /= magnitude;
PxReal currentDistance;
bool unused;
if(!sweepSphereVSTri(currentTri.verts, triNormal, center, radius, unitDir, currentDistance, unused, testInitialOverlap))
continue;
const PxReal hitDot = computeAlignmentValue(triNormal, unitDir);
if(keepTriangle(currentDistance, hitDot, curT, bestAlignmentValue, distance))
{
if(currentDistance==0.0f)
{
triNormalOut = -unitDir;
return setInitialOverlapResults(h, unitDir, i);
}
curT = PxMin(curT, currentDistance); // exact lower bound
index = i;
bestAlignmentValue = hitDot;
bestTriNormal = triNormal;
if(anyHit)
break;
}
//
else if(keepTriangleBasic(currentDistance, curT, distance))
{
curT = PxMin(curT, currentDistance); // exact lower bound
}
//
}
return computeSphereTriangleImpactData(h, triNormalOut, index, curT, center, unitDir, bestTriNormal, triangles, isDoubleSided, meshBothSides);
}
static PX_FORCE_INLINE PxU32 rayQuadSpecial2(const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, float& t, float& u, float& v)
{
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2);
// If determinant is near zero, ray lies in plane of triangle
const float det = edge1.dot(pvec);
// the non-culling branch
if(det>-LOCAL_EPSILON && det<LOCAL_EPSILON)
return 0;
const float oneOverDet = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter
u = tvec.dot(pvec) * oneOverDet;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter
v = dir.dot(qvec) * oneOverDet;
if(u<0.0f || u>1.0f)
return 1;
if(v<0.0f || v>1.0f)
return 1;
// Calculate t, ray intersects triangle
t = edge2.dot(qvec) * oneOverDet;
return 2;
}
#ifdef PX_2413_FIX
static PX_FORCE_INLINE PxU32 rayQuadSpecial3(const PxVec3& orig, const PxVec3& offset, const PxVec3& dir, const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, float& t, float& u, float& v, float& du, float& dv)
{
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2);
// If determinant is near zero, ray lies in plane of triangle
const float det = edge1.dot(pvec);
// the non-culling branch
if(det>-LOCAL_EPSILON && det<LOCAL_EPSILON)
return 0;
const float oneOverDet = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter
u = tvec.dot(pvec) * oneOverDet;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter
v = dir.dot(qvec) * oneOverDet;
if(u<0.0f || u>1.0f || v<0.0f || v>1.0f)
{
du = (offset.dot(pvec)) * oneOverDet;
const PxVec3 qvec = offset.cross(edge1);
dv = (dir.dot(qvec)) * oneOverDet;
return 1;
}
// Calculate t, ray intersects triangle
t = edge2.dot(qvec) * oneOverDet;
return 2;
}
#endif
bool Gu::sweepSphereVSQuad(const PxVec3* PX_RESTRICT quadVerts, const PxVec3& normal, const PxVec3& center, float radius, const PxVec3& dir, float& impactDistance)
{
// Quad formed by 2 tris:
// p0 p1 p2
// p2 p1 p3 = p3 p2 p1
//
// p0___p2
// | /|
// | / |
// | / |
// |/ |
// p1---p3
//
// Edge10 = p1 - p0
// Edge20 = p2 - p0
// Impact point = Edge10*u + Edge20*v + p0
// => u is along Y, between 0.0 (p0;p2) and 1.0 (p1;p3)
// => v is along X, between 0.0 (p0;p1) and 1.0 (p2;p3)
//
// For the second triangle,
// Edge10b = p2 - p3 = -Edge10
// Edge20b = p1 - p3 = -Edge20
const PxVec3 Edge10 = quadVerts[1] - quadVerts[0];
const PxVec3 Edge20 = quadVerts[2] - quadVerts[0];
if(1) // ### brute force version that always works, but we can probably do better
{
const float r2 = radius*radius;
{
const PxVec3 Cp = closestPtPointTriangle2(center, quadVerts[0], quadVerts[1], quadVerts[2], Edge10, Edge20);
if((Cp - center).magnitudeSquared() <= r2)
{
impactDistance = 0.0f;
return true;
}
}
{
const PxVec3 Cp = closestPtPointTriangle2(center, quadVerts[3], quadVerts[2], quadVerts[1], -Edge10, -Edge20);
if((Cp - center).magnitudeSquared() <= r2)
{
impactDistance = 0.0f;
return true;
}
}
}
float u,v;
#ifdef PX_2413_FIX
float du, dv;
#endif
if(1)
{
PxVec3 R = normal * radius;
if(dir.dot(R) >= 0.0f)
R = -R;
// The first point of the sphere to hit the quad plane is the point of the sphere nearest to
// the quad plane. Hence, we use center - (normal*radius) below.
// PT: casting against the extruded quad in direction R is the same as casting from a ray moved by -R
float t;
#ifdef PX_2413_FIX
const PxU32 r = rayQuadSpecial3(center-R, R, dir, quadVerts[0], Edge10, Edge20, t, u, v, du, dv);
#else
PxU32 r = rayQuadSpecial2(center-R, dir, quadVerts[0], Edge10, Edge20, t, u, v);
#endif
if(!r)
return false;
if(r==2)
{
if(t<0.0f)
return false;
impactDistance = t;
return true;
}
}
bool referenceHit = false;
float referenceMinDist = PX_MAX_F32;
if(gSanityCheck)
{
PxReal t;
if(intersectRayCapsule(center, dir, quadVerts[0], quadVerts[1], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(intersectRayCapsule(center, dir, quadVerts[1], quadVerts[3], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(intersectRayCapsule(center, dir, quadVerts[3], quadVerts[2], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(intersectRayCapsule(center, dir, quadVerts[2], quadVerts[0], radius, t) && t>=0.0f)
{
referenceHit = true;
referenceMinDist = PxMin(referenceMinDist, t);
}
if(!gUseAlternativeImplementation)
{
if(referenceHit)
impactDistance = referenceMinDist;
return referenceHit;
}
}
PxSwap(u, v);
if(gUseAlternativeImplementation)
{
bool testTwoEdges = false;
PxU32 e0,e1,e2=0;
if(u<0.0f)
{
if(v<0.0f)
{
// 0 or 0-1 or 0-2
testTwoEdges = true;
e0 = 0;
e1 = 1;
e2 = 2;
}
else if(v>1.0f)
{
// 1 or 1-0 or 1-3
testTwoEdges = true;
e0 = 1;
e1 = 0;
e2 = 3;
}
else
{
// 0-1
e0 = 0;
e1 = 1;
}
}
else if(u>1.0f)
{
if(v<0.0f)
{
// 2 or 2-0 or 2-3
testTwoEdges = true;
e0 = 2;
e1 = 0;
e2 = 3;
}
else if(v>1.0f)
{
// 3 or 3-1 or 3-2
testTwoEdges = true;
e0 = 3;
e1 = 1;
e2 = 2;
}
else
{
// 2-3
e0 = 2;
e1 = 3;
}
}
else
{
if(v<0.0f)
{
// 0-2
e0 = 0;
e1 = 2;
}
else
{
PX_ASSERT(v>=1.0f); // Else hit quad
// 1-3
e0 = 1;
e1 = 3;
}
}
bool hit = false;
PxReal t;
if(intersectRayCapsule(center, dir, quadVerts[e0], quadVerts[e1], radius, t) && t>=0.0f)
{
impactDistance = t;
hit = true;
}
if(testTwoEdges && intersectRayCapsule(center, dir, quadVerts[e0], quadVerts[e2], radius, t) && t>=0.0f)
{
if(!hit || t<impactDistance)
{
impactDistance = t;
hit = true;
}
}
if(gSanityCheck)
{
PX_ASSERT(referenceHit==hit);
if(referenceHit==hit)
PX_ASSERT(fabsf(referenceMinDist-impactDistance)<gEpsilon);
}
return hit;
}
else
{
#define INTERSECT_POINT_Q (quadVerts[1]*u) + (quadVerts[2]*v) + (quadVerts[0] * (1.0f-u-v))
bool TestSphere;
PxU32 e0,e1;
if(u<0.0f)
{
if(v<0.0f)
{
// 0 or 0-1 or 0-2
e0 = 0;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT_Q;
TestSphere = edgeOrVertexTest(intersectPoint, quadVerts, 0, 1, 2, e1);
}
else if(v>1.0f)
{
// 1 or 1-0 or 1-3
e0 = 1;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT_Q;
TestSphere = edgeOrVertexTest(intersectPoint, quadVerts, 1, 0, 3, e1);
}
else
{
// 0-1
TestSphere = false;
e0 = 0;
e1 = 1;
}
}
else if(u>1.0f)
{
if(v<0.0f)
{
// 2 or 2-0 or 2-3
e0 = 2;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT_Q;
TestSphere = edgeOrVertexTest(intersectPoint, quadVerts, 2, 0, 3, e1);
}
else if(v>1.0f)
{
// 3 or 3-1 or 3-2
e0 = 3;
FIXUP_UVS
const PxVec3 intersectPoint = INTERSECT_POINT_Q;
TestSphere = edgeOrVertexTest(intersectPoint, quadVerts, 3, 1, 2, e1);
}
else
{
// 2-3
TestSphere = false;
e0 = 2;
e1 = 3;
}
}
else
{
if(v<0.0f)
{
// 0-2
TestSphere = false;
e0 = 0;
e1 = 2;
}
else
{
PX_ASSERT(v>=1.0f); // Else hit quad
// 1-3
TestSphere = false;
e0 = 1;
e1 = 3;
}
}
return testRayVsSphereOrCapsule(impactDistance, TestSphere, center, radius, dir, quadVerts, e0, e1);
}
}
| 22,757 | C++ | 24.202658 | 224 | 0.643011 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxSphere.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 "GuSweepBoxSphere.h"
#include "GuOverlapTests.h"
#include "GuSphere.h"
#include "GuBoxConversion.h"
#include "GuCapsule.h"
#include "GuIntersectionRayCapsule.h"
#include "GuIntersectionRayBox.h"
#include "GuIntersectionSphereBox.h"
#include "GuDistancePointSegment.h"
#include "GuInternal.h"
using namespace physx;
using namespace Gu;
namespace
{
// PT: TODO: get rid of this copy
static const PxVec3 gNearPlaneNormal[] =
{
PxVec3(1.0f, 0.0f, 0.0f),
PxVec3(0.0f, 1.0f, 0.0f),
PxVec3(0.0f, 0.0f, 1.0f),
PxVec3(-1.0f, 0.0f, 0.0f),
PxVec3(0.0f, -1.0f, 0.0f),
PxVec3(0.0f, 0.0f, -1.0f)
};
}
bool Gu::sweepBoxSphere(const Box& box, PxReal sphereRadius, const PxVec3& spherePos, const PxVec3& dir, PxReal length, PxReal& min_dist, PxVec3& normal, PxHitFlags hitFlags)
{
if(!(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP))
{
// PT: test if shapes initially overlap
if(intersectSphereBox(Sphere(spherePos, sphereRadius), box))
{
// Overlap
min_dist = 0.0f;
normal = -dir;
return true;
}
}
PxVec3 boxPts[8];
box.computeBoxPoints(boxPts);
const PxU8* PX_RESTRICT edges = getBoxEdges();
PxReal MinDist = length;
bool Status = false;
for(PxU32 i=0; i<12; i++)
{
const PxU8 e0 = *edges++;
const PxU8 e1 = *edges++;
const Capsule capsule(boxPts[e0], boxPts[e1], sphereRadius);
PxReal t;
if(intersectRayCapsule(spherePos, dir, capsule, t))
{
if(t>=0.0f && t<=MinDist)
{
MinDist = t;
const PxVec3 ip = spherePos + t*dir;
distancePointSegmentSquared(capsule, ip, &t);
PxVec3 ip2;
capsule.computePoint(ip2, t);
normal = (ip2 - ip);
normal.normalize();
Status = true;
}
}
}
PxVec3 localPt;
{
PxMat34 M2;
buildMatrixFromBox(M2, box);
localPt = M2.rotateTranspose(spherePos - M2.p);
}
const PxVec3* boxNormals = gNearPlaneNormal;
const PxVec3 localDir = box.rotateInv(dir);
// PT: when the box exactly touches the sphere, the test for initial overlap can fail on some platforms.
// In this case we reach the sweep code below, which may return a slightly negative time of impact (it should be 0.0
// but it ends up a bit negative because of limited FPU accuracy). The epsilon ensures that we correctly detect a hit
// in this case.
const PxReal epsilon = -1e-5f;
PxReal tnear, tfar;
PxVec3 extents = box.extents;
extents.x += sphereRadius;
int plane = intersectRayAABB(-extents, extents, localPt, localDir, tnear, tfar);
if(plane!=-1 && tnear>=epsilon && tnear <= MinDist)
{
MinDist = PxMax(tnear, 0.0f);
normal = box.rotate(boxNormals[plane]);
Status = true;
}
extents = box.extents;
extents.y += sphereRadius;
plane = intersectRayAABB(-extents, extents, localPt, localDir, tnear, tfar);
if(plane!=-1 && tnear>=epsilon && tnear <= MinDist)
{
MinDist = PxMax(tnear, 0.0f);
normal = box.rotate(boxNormals[plane]);
Status = true;
}
extents = box.extents;
extents.z += sphereRadius;
plane = intersectRayAABB(-extents, extents, localPt, localDir, tnear, tfar);
if(plane!=-1 && tnear>=epsilon && tnear <= MinDist)
{
MinDist = PxMax(tnear, 0.0f);
normal = box.rotate(boxNormals[plane]);
Status = true;
}
min_dist = MinDist;
return Status;
}
| 4,893 | C++ | 30.171974 | 174 | 0.712855 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_SPHERE_TRIANGLE_H
#define GU_SWEEP_SPHERE_TRIANGLE_H
#include "GuSweepTriangleUtils.h"
namespace physx
{
namespace Gu
{
/**
Sweeps a sphere against a triangle.
All input parameters (sphere, triangle, sweep direction) must be in the same space. Sweep length is assumed to be infinite.
By default, 'testInitialOverlap' must be set to true to properly handle the case where the sphere already overlaps the triangle
at the start of the sweep. In such a case, returned impact distance is exactly 0.0f. If it is known ahead of time that the sphere
cannot overlap the triangle at t=0.0, then 'testInitialOverlap' can be set to false to skip the initial overlap test and make the
function run faster.
If the ray defined by the sphere's center and the unit direction directly intersects the triangle-related part of the TSS (*) (i.e.
the prism from the Minkowski sum of the inflated triangle) then 'directHit' is set to true. Otherwise it is set to false.
(*) For Triangle Swept Sphere, see http://gamma.cs.unc.edu/SSV/ssv.pdf for the origin of these names.
\param triVerts [in] triangle vertices
\param triUnitNormal [in] triangle's normalized normal
\param sphereCenter [in] sphere's center
\param sphereRadius [in] sphere's radius
\param unitDir [in] normalized sweep direction.
\param impactDistance [out] impact distance, if a hit has been found. Does not need to be initialized before calling the function.
\param directHit [out] true if a direct hit has been found, see comments above.
\param testInitialOverlap [in] true if an initial sphere-vs-triangle overlap test must be performed, see comments above.
\return true if an impact has been found (in which case returned result values are valid)
*/
bool sweepSphereVSTri( const PxVec3* PX_RESTRICT triVerts, const PxVec3& triUnitNormal,// Triangle data
const PxVec3& sphereCenter, PxReal sphereRadius, // Sphere data
const PxVec3& unitDir, // Ray data
PxReal& impactDistance, bool& directHit, // Results
bool testInitialOverlap); // Query modifier
/**
Sweeps a sphere against a quad.
All input parameters (sphere, quad, sweep direction) must be in the same space. Sweep length is assumed to be infinite.
Quad must be formed by 2 tris like this:
p0___p2
| /|
| / |
| / |
|/ |
p1---p3
\param quadVerts [in] quad vertices
\param quadUnitNormal [in] quad's normalized normal
\param sphereCenter [in] sphere's center
\param sphereRadius [in] sphere's radius
\param unitDir [in] normalized sweep direction.
\param impactDistance [out] impact distance, if a hit has been found. Does not need to be initialized before calling the function.
\return true if an impact has been found (in which case returned result values are valid)
*/
bool sweepSphereVSQuad( const PxVec3* PX_RESTRICT quadVerts, const PxVec3& quadUnitNormal, // Quad data
const PxVec3& sphereCenter, float sphereRadius, // Sphere data
const PxVec3& unitDir, // Ray data
float& impactDistance); // Results
// PT: computes proper impact data for sphere-sweep-vs-tri, after the closest tri has been found
PX_FORCE_INLINE bool computeSphereTriangleImpactData(PxGeomSweepHit& h, PxVec3& triNormalOut, PxU32 index, PxReal curT,
const PxVec3& center, const PxVec3& unitDir, const PxVec3& bestTriNormal,
const PxTriangle* PX_RESTRICT triangles,
bool isDoubleSided, bool meshBothSides)
{
if(index==PX_INVALID_U32)
return false; // We didn't touch any triangle
// Compute impact data only once, using best triangle
PxVec3 hitPos, normal;
computeSphereTriImpactData(hitPos, normal, center, unitDir, curT, triangles[index]);
// PT: by design, returned normal is opposed to the sweep direction.
if(shouldFlipNormal(normal, meshBothSides, isDoubleSided, bestTriNormal, unitDir))
normal = -normal;
h.position = hitPos;
h.normal = normal;
h.distance = curT;
h.faceIndex = index;
h.flags = PxHitFlag::eNORMAL|PxHitFlag::ePOSITION;
triNormalOut = bestTriNormal;
return true;
}
/**
Sweeps a sphere against a set of triangles.
\param nbTris [in] number of triangles in input array
\param triangles [in] array of input triangles
\param center [in] sphere's center
\param radius [in] sphere's radius
\param unitDir [in] sweep's unit direcion
\param distance [in] sweep's length
\param cachedIndex [in] cached triangle index, or NULL. Cached triangle will be tested first.
\param hit [out] results
\param triNormalOut [out] triangle normal
\param isDoubleSided [in] true if input triangles are double-sided
\param meshBothSides [in] true if PxHitFlag::eMESH_BOTH_SIDES is used
\param anyHit [in] true if PxHitFlag::eMESH_ANY is used
\param testInitialOverlap [in] true if PxHitFlag::eASSUME_NO_INITIAL_OVERLAP is not used
\return true if an impact has been found
*/
bool sweepSphereTriangles( PxU32 nbTris, const PxTriangle* PX_RESTRICT triangles, // Triangle data
const PxVec3& center, const PxReal radius, // Sphere data
const PxVec3& unitDir, PxReal distance, // Ray data
const PxU32* PX_RESTRICT cachedIndex, // Cache data
PxGeomSweepHit& hit, PxVec3& triNormalOut, // Results
bool isDoubleSided, bool meshBothSides, bool anyHit, bool testInitialOverlap); // Query modifiers
} // namespace Gu
}
#endif
| 7,221 | C | 45.294872 | 132 | 0.729816 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereSphere.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_SPHERE_SPHERE_H
#define GU_SWEEP_SPHERE_SPHERE_H
#include "foundation/PxVec3.h"
namespace physx
{
namespace Gu
{
bool sweepSphereSphere(const PxVec3& center0, PxReal radius0, const PxVec3& center1, PxReal radius1, const PxVec3& motion, PxReal& d, PxVec3& nrm);
} // namespace Gu
}
#endif
| 2,009 | C | 43.666666 | 148 | 0.763564 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleBox.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 "foundation/PxTransform.h"
#include "foundation/PxSIMDHelpers.h"
#include "geometry/PxTriangle.h"
#include "GuSweepCapsuleBox.h"
#include "GuSweepSphereTriangle.h"
#include "GuCapsule.h"
#include "GuDistanceSegmentBox.h"
#include "GuInternal.h"
#include "foundation/PxAlloca.h"
using namespace physx;
using namespace Gu;
namespace
{
/**
* Returns triangles.
* \return 36 indices (12 triangles) indexing the list returned by ComputePoints()
*/
static const PxU8* getBoxTriangles()
{
static PxU8 Indices[] = {
0,2,1, 0,3,2,
1,6,5, 1,2,6,
5,7,4, 5,6,7,
4,3,0, 4,7,3,
3,6,2, 3,7,6,
5,0,1, 5,4,0
};
return Indices;
}
}
#define OUTPUT_TRI(t, p0, p1, p2){ \
t->verts[0] = p0; \
t->verts[1] = p1; \
t->verts[2] = p2; \
t++;}
#define OUTPUT_TRI2(t, p0, p1, p2, d){ \
t->verts[0] = p0; \
t->verts[1] = p1; \
t->verts[2] = p2; \
t->denormalizedNormal(denormalizedNormal); \
if((denormalizedNormal.dot(d))>0.0f) { \
PxVec3 Tmp = t->verts[1]; \
t->verts[1] = t->verts[2]; \
t->verts[2] = Tmp; \
} \
t++; *ids++ = i; }
static PxU32 extrudeMesh( PxU32 nbTris, const PxTriangle* triangles,
const PxVec3& extrusionDir, PxTriangle* tris, PxU32* ids, const PxVec3& dir)
{
const PxU32* base = ids;
for(PxU32 i=0; i<nbTris; i++)
{
const PxTriangle& currentTriangle = triangles[i];
// Create triangle normal
PxVec3 denormalizedNormal;
currentTriangle.denormalizedNormal(denormalizedNormal);
// Backface culling
const bool culled = (denormalizedNormal.dot(dir)) > 0.0f;
if(culled) continue;
PxVec3 p0 = currentTriangle.verts[0];
PxVec3 p1 = currentTriangle.verts[1];
PxVec3 p2 = currentTriangle.verts[2];
PxVec3 p0b = p0 + extrusionDir;
PxVec3 p1b = p1 + extrusionDir;
PxVec3 p2b = p2 + extrusionDir;
p0 -= extrusionDir;
p1 -= extrusionDir;
p2 -= extrusionDir;
if(denormalizedNormal.dot(extrusionDir) >= 0.0f) OUTPUT_TRI(tris, p0b, p1b, p2b)
else OUTPUT_TRI(tris, p0, p1, p2)
*ids++ = i;
// ### it's probably useless to extrude all the shared edges !!!!!
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE12)
{
OUTPUT_TRI2(tris, p1, p1b, p2b, dir)
OUTPUT_TRI2(tris, p1, p2b, p2, dir)
}
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE20)
{
OUTPUT_TRI2(tris, p0, p2, p2b, dir)
OUTPUT_TRI2(tris, p0, p2b, p0b, dir)
}
//if(CurrentFlags & TriangleCollisionFlag::eACTIVE_EDGE01)
{
OUTPUT_TRI2(tris, p0b, p1b, p1, dir)
OUTPUT_TRI2(tris, p0b, p1, p0, dir)
}
}
return PxU32(ids-base);
}
static PxU32 extrudeBox(const PxBounds3& localBox, const PxTransform* world, const PxVec3& extrusionDir, PxTriangle* tris, const PxVec3& dir)
{
// Handle the box as a mesh
PxTriangle boxTris[12];
PxVec3 p[8];
computeBoxPoints(localBox, p);
const PxU8* PX_RESTRICT indices = getBoxTriangles();
for(PxU32 i=0; i<12; i++)
{
const PxU8 VRef0 = indices[i*3+0];
const PxU8 VRef1 = indices[i*3+1];
const PxU8 VRef2 = indices[i*3+2];
PxVec3 p0 = p[VRef0];
PxVec3 p1 = p[VRef1];
PxVec3 p2 = p[VRef2];
if(world)
{
p0 = world->transform(p0);
p1 = world->transform(p1);
p2 = world->transform(p2);
}
boxTris[i].verts[0] = p0;
boxTris[i].verts[1] = p1;
boxTris[i].verts[2] = p2;
}
PxU32 fakeIDs[12*7];
return extrudeMesh(12, boxTris, extrusionDir, tris, fakeIDs, dir);
}
//
// The problem of testing a swept capsule against a box is transformed into sweeping a sphere (lying at the center
// of the capsule) against the extruded triangles of the box. The box triangles are extruded along the
// capsule segment axis.
//
bool Gu::sweepCapsuleBox(const Capsule& capsule, const PxTransform& boxWorldPose, const PxVec3& boxDim, const PxVec3& dir, PxReal length, PxVec3& hit, PxReal& min_dist, PxVec3& normal, PxHitFlags hitFlags)
{
if(!(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP))
{
// PT: test if shapes initially overlap
if(distanceSegmentBoxSquared(capsule.p0, capsule.p1, boxWorldPose.p, boxDim, PxMat33Padded(boxWorldPose.q)) < capsule.radius*capsule.radius)
{
min_dist = 0.0f;
normal = -dir;
return true;
}
}
// Extrusion dir = capsule segment
const PxVec3 extrusionDir = (capsule.p1 - capsule.p0)*0.5f;
// Extrude box
PxReal MinDist = length;
bool Status = false;
{
const PxBounds3 aabb(-boxDim, boxDim);
PX_ALLOCA(triangles, PxTriangle, 12*7);
const PxU32 nbTris = extrudeBox(aabb, &boxWorldPose, extrusionDir, triangles, dir);
PX_ASSERT(nbTris<=12*7);
// Sweep sphere vs extruded box
PxGeomSweepHit h; // PT: TODO: ctor!
PxVec3 bestNormal;
if(sweepSphereTriangles(nbTris, triangles, capsule.computeCenter(), capsule.radius, dir, length, NULL, h, bestNormal, false, false, false, false))
{
hit = h.position;
MinDist = h.distance;
normal = h.normal;
Status = true;
}
}
min_dist = MinDist;
return Status;
}
| 6,614 | C++ | 29.625 | 205 | 0.695192 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxTriangle_FeatureBased.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/PxTriangle.h"
#include "GuSweepBoxTriangle_FeatureBased.h"
#include "GuIntersectionRayBox.h"
#include "GuSweepTriangleUtils.h"
#include "GuInternal.h"
using namespace physx;
using namespace Gu;
#define LOCAL_EPSILON 0.00001f // PT: this value makes the 'basicAngleTest' pass. Fails because of a ray almost parallel to a triangle
namespace
{
static const PxReal gFatTriangleCoeff = 0.02f;
static const PxVec3 gNearPlaneNormal[] =
{
PxVec3(1.0f, 0.0f, 0.0f),
PxVec3(0.0f, 1.0f, 0.0f),
PxVec3(0.0f, 0.0f, 1.0f),
PxVec3(-1.0f, 0.0f, 0.0f),
PxVec3(0.0f, -1.0f, 0.0f),
PxVec3(0.0f, 0.0f, -1.0f)
};
}
#define INVSQRT3 0.577350269189f //!< 1 / sqrt(3)
/**
Returns vertex normals.
\return 24 floats (8 normals)
*/
static const PxF32* getBoxVertexNormals()
{
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
static PxF32 VertexNormals[] =
{
-INVSQRT3, -INVSQRT3, -INVSQRT3,
INVSQRT3, -INVSQRT3, -INVSQRT3,
INVSQRT3, INVSQRT3, -INVSQRT3,
-INVSQRT3, INVSQRT3, -INVSQRT3,
-INVSQRT3, -INVSQRT3, INVSQRT3,
INVSQRT3, -INVSQRT3, INVSQRT3,
INVSQRT3, INVSQRT3, INVSQRT3,
-INVSQRT3, INVSQRT3, INVSQRT3
};
return VertexNormals;
}
static PxTriangle inflateTriangle(const PxTriangle& triangle, PxReal fat_coeff)
{
PxTriangle fatTri = triangle;
// Compute triangle center
const PxVec3& p0 = triangle.verts[0];
const PxVec3& p1 = triangle.verts[1];
const PxVec3& p2 = triangle.verts[2];
const PxVec3 center = (p0 + p1 + p2)*0.333333333f;
// Don't normalize?
// Normalize => add a constant border, regardless of triangle size
// Don't => add more to big triangles
for(PxU32 i=0;i<3;i++)
{
const PxVec3 v = fatTri.verts[i] - center;
fatTri.verts[i] += v * fat_coeff;
}
return fatTri;
}
// PT: special version to fire N parallel rays against the same tri
static PX_FORCE_INLINE PxIntBool rayTriPrecaCull( const PxVec3& orig, const PxVec3& dir,
const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, const PxVec3& pvec,
PxReal det, PxReal oneOverDet, PxReal& t)
{
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter and test bounds
PxReal u = tvec.dot(pvec);
if((u < 0.0f) || u>det)
return 0;
// Prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
PxReal v = dir.dot(qvec);
if((v < 0.0f) || u+v>det)
return 0;
// Calculate t, scale parameters, ray intersects triangle
t = edge2.dot(qvec);
t *= oneOverDet;
return 1;
}
static PX_FORCE_INLINE PxIntBool rayTriPrecaNoCull( const PxVec3& orig, const PxVec3& dir,
const PxVec3& vert0, const PxVec3& edge1, const PxVec3& edge2, const PxVec3& pvec,
PxReal /*det*/, PxReal oneOverDet, PxReal& t)
{
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter and test bounds
PxReal u = (tvec.dot(pvec)) * oneOverDet;
if((u < 0.0f) || u>1.0f)
return 0;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
PxReal v = (dir.dot(qvec)) * oneOverDet;
if((v < 0.0f) || u+v>1.0f)
return 0;
// Calculate t, ray intersects triangle
t = (edge2.dot(qvec)) * oneOverDet;
return 1;
}
// PT: specialized version where oneOverDir is available
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON_RAY_BOX PX_EPS_F32
//#define LOCAL_EPSILON_RAY_BOX 0.0001f
static PX_FORCE_INLINE int intersectRayAABB2(const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& ro, const PxVec3& /*rd*/, const PxVec3& oneOverDir,
float& tnear, float& tfar,
bool fbx, bool fby, bool fbz)
{
// PT: this unrolled loop is a lot faster on Xbox
if(fbx)
if(ro.x<minimum.x || ro.x>maximum.x)
{
// tnear = FLT_MAX;
return -1;
}
if(fby)
if(ro.y<minimum.y || ro.y>maximum.y)
{
// tnear = FLT_MAX;
return -1;
}
if(fbz)
if(ro.z<minimum.z || ro.z>maximum.z)
{
// tnear = FLT_MAX;
return -1;
}
PxReal t1x = (minimum.x - ro.x) * oneOverDir.x;
PxReal t2x = (maximum.x - ro.x) * oneOverDir.x;
PxReal t1y = (minimum.y - ro.y) * oneOverDir.y;
PxReal t2y = (maximum.y - ro.y) * oneOverDir.y;
PxReal t1z = (minimum.z - ro.z) * oneOverDir.z;
PxReal t2z = (maximum.z - ro.z) * oneOverDir.z;
int bx;
int by;
int bz;
if(t1x>t2x)
{
PxReal t=t1x; t1x=t2x; t2x=t;
bx = 3;
}
else
{
bx = 0;
}
if(t1y>t2y)
{
PxReal t=t1y; t1y=t2y; t2y=t;
by = 4;
}
else
{
by = 1;
}
if(t1z>t2z)
{
PxReal t=t1z; t1z=t2z; t2z=t;
bz = 5;
}
else
{
bz = 2;
}
int ret;
if(!fbx)
{
// if(t1x>tnear) // PT: no need to test for the first value
{
tnear = t1x;
ret = bx;
}
// tfar = Px::intrinsics::selectMin(tfar, t2x);
tfar = t2x; // PT: no need to test for the first value
}
else
{
ret=-1;
tnear = -PX_MAX_F32;
tfar = PX_MAX_F32;
}
if(!fby)
{
if(t1y>tnear)
{
tnear = t1y;
ret = by;
}
tfar = physx::intrinsics::selectMin(tfar, t2y);
}
if(!fbz)
{
if(t1z>tnear)
{
tnear = t1z;
ret = bz;
}
tfar = physx::intrinsics::selectMin(tfar, t2z);
}
if(tnear>tfar || tfar<LOCAL_EPSILON_RAY_BOX)
return -1;
return ret;
}
// PT: force-inlining this saved 500.000 cycles in the benchmark. Ok to inline, only used once anyway.
static PX_FORCE_INLINE bool intersectEdgeEdge3(const PxPlane& plane, const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& v1,
const PxVec3& p3, const PxVec3& p4,
PxReal& dist, PxVec3& ip, PxU32 i, PxU32 j, const PxReal coeff)
{
// 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);
const 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;
const PxReal temp2 = plane.n.dot(v2);
if(temp2==0.0f) return false; // ### epsilon would be better
// compute intersection point of plane and colliding edge (p3,p4)
ip = p3-v2*(d3/temp2);
// 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
const PxReal temp3 = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z);
return temp3<0.0f;
}
namespace
{
static const PxReal gFatBoxEdgeCoeff = 0.01f;
#define INVSQRT2 0.707106781188f //!< 1 / sqrt(2)
static const PxVec3 EdgeNormals[] =
{
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
};
static const PxVec3* getBoxLocalEdgeNormals()
{
return EdgeNormals;
}
}
static PX_FORCE_INLINE void closestAxis2(const PxVec3& v, PxU32& j, PxU32& k)
{
// find largest 2D plane projection
const PxF32 absPx = physx::intrinsics::abs(v.x);
const PxF32 absPy = physx::intrinsics::abs(v.y);
const PxF32 absPz = physx::intrinsics::abs(v.z);
//PxU32 m = 0; //x biggest axis
j = 1;
k = 2;
if( absPy > absPx && absPy > absPz)
{
//y biggest
j = 2;
k = 0;
//m = 1;
}
else if(absPz > absPx)
{
//z biggest
j = 0;
k = 1;
//m = 2;
}
// return m;
}
bool Gu::sweepBoxTriangle( const PxTriangle& tri, const PxBounds3& box,
const PxVec3& motion, const PxVec3& oneOverMotion,
PxVec3& hit, PxVec3& normal, PxReal& d, bool isDoubleSided)
{
// Create triangle normal
PxVec3 denormalizedTriNormal;
tri.denormalizedNormal(denormalizedTriNormal);
// Backface culling
const bool doBackfaceCulling = !isDoubleSided;
if(doBackfaceCulling && (denormalizedTriNormal.dot(motion)) >= 0.0f) // ">=" is important !
return false;
/////////////////////////
PxVec3 boxVertices[8];
computeBoxPoints(box, boxVertices);
/////////////////////////
// Make fat triangle
const PxTriangle fatTri = inflateTriangle(tri, gFatTriangleCoeff);
PxReal minDist = d; // Initialize with current best distance
int col = -1;
// Box vertices VS triangle
{
// ### cull using box-plane distance ?
const PxVec3 edge1 = fatTri.verts[1] - fatTri.verts[0];
const PxVec3 edge2 = fatTri.verts[2] - fatTri.verts[0];
const PxVec3 PVec = motion.cross(edge2);
const PxReal Det = edge1.dot(PVec);
// We can't use stamps here since we can still find a better TOI for a given vertex,
// even if that vertex has already been tested successfully against another triangle.
const PxVec3* VN = reinterpret_cast<const PxVec3*>(getBoxVertexNormals());
const PxReal oneOverDet = Det!=0.0f ? 1.0f / Det : 0.0f;
PxU32 hitIndex=0;
if(doBackfaceCulling)
{
if(Det>=LOCAL_EPSILON)
{
for(PxU32 i=0;i<8;i++)
{
// Orientation culling
if((VN[i].dot(denormalizedTriNormal) >= 0.0f)) // Can't rely on triangle normal for double-sided faces
continue;
// ### test this
// ### ok, this causes the bug in level3's v-shaped desk. Not really a real "bug", it just happens
// that this VF test fixes this case, so it's a bad idea to cull it. Oh, well.
// If we use a penetration-depth code to fixup bad cases, we can enable this culling again. (also
// if we find a better way to handle that desk)
// Discard back vertices
// if(VN[i].dot(motion)<0.0f)
// continue;
// Shoot a ray from vertex against triangle, in direction "motion"
PxReal t;
if(!rayTriPrecaCull(boxVertices[i], motion, fatTri.verts[0], edge1, edge2, PVec, Det, oneOverDet, t))
continue;
//if(t<=OffsetLength) t=0.0f;
// Only consider positive distances, closer than current best
// ### we could test that first on tri vertices & discard complete tri if it's further than current best (or equal!)
if(t < 0.0f || t > minDist)
continue;
minDist = t;
col = 0;
// hit = boxVertices[i] + t * motion;
hitIndex = i;
}
}
}
else
{
if(Det<=-LOCAL_EPSILON || Det>=LOCAL_EPSILON)
{
for(PxU32 i=0;i<8;i++)
{
// ### test this
// ### ok, this causes the bug in level3's v-shaped desk. Not really a real "bug", it just happens
// that this VF test fixes this case, so it's a bad idea to cull it. Oh, well.
// If we use a penetration-depth code to fixup bad cases, we can enable this culling again. (also
// if we find a better way to handle that desk)
// Discard back vertices
// if(!VN[i].SameDirection(motion))
// continue;
// Shoot a ray from vertex against triangle, in direction "motion"
PxReal t;
if(!rayTriPrecaNoCull(boxVertices[i], motion, fatTri.verts[0], edge1, edge2, PVec, Det, oneOverDet, t))
continue;
//if(t<=OffsetLength) t=0.0f;
// Only consider positive distances, closer than current best
// ### we could test that first on tri vertices & discard complete tri if it's further than current best (or equal!)
if(t < 0.0f || t > minDist)
continue;
minDist = t;
col = 0;
// hit = boxVertices[i] + t * motion;
hitIndex = i;
}
}
}
// Only copy this once, if needed
if(col==0)
{
// PT: hit point on triangle
hit = boxVertices[hitIndex] + minDist * motion;
normal = denormalizedTriNormal;
}
}
// Triangle vertices VS box
{
const PxVec3 negMotion = -motion;
const PxVec3 negInvMotion = -oneOverMotion;
// PT: precompute fabs-test for ray-box
// - doing this outside of the ray-box function gets rid of 3 fabs/fcmp per call
// - doing this with integer code removes the 3 remaining fabs/fcmps totally
// - doing this outside reduces the LHS
const bool b0 = physx::intrinsics::abs(negMotion.x)<LOCAL_EPSILON_RAY_BOX;
const bool b1 = physx::intrinsics::abs(negMotion.y)<LOCAL_EPSILON_RAY_BOX;
const bool b2 = physx::intrinsics::abs(negMotion.z)<LOCAL_EPSILON_RAY_BOX;
// ### have this as a param ?
const PxVec3& Min = box.minimum;
const PxVec3& Max = box.maximum;
const PxVec3* boxNormals = gNearPlaneNormal;
// ### use stamps not to shoot shared vertices multiple times
// ### discard non-convex verts
for(PxU32 i=0;i<3;i++)
{
PxReal tnear, tfar;
const int plane = ::intersectRayAABB2(Min, Max, tri.verts[i], negMotion, negInvMotion, tnear, tfar, b0, b1, b2);
PX_ASSERT(plane == intersectRayAABB(Min, Max, tri.verts[i], negMotion, tnear, tfar));
// The following works as well but we need to call "intersectRayAABB" to get a plane index compatible with BoxNormals.
// We could fix this by unifying the plane indices returned by the different ray-aabb functions...
//PxVec3 coord;
//PxReal t;
//PxU32 status = rayAABBIntersect2(Min, Max, tri.verts[i], -motion, coord, t);
// ### don't test -1 ?
if(plane==-1 || tnear<0.0f) continue;
// if(tnear<0.0f) continue;
if(tnear <= minDist)
{
minDist = tnear; // ### warning, tnear => flips normals
normal = boxNormals[plane];
col = 1;
// PT: hit point on triangle
hit = tri.verts[i];
}
}
}
PxU32 saved_j = PX_INVALID_U32;
PxU32 saved_k = PX_INVALID_U32;
PxVec3 p1s;
PxVec3 v1s;
// Edge-vs-edge
{
// Loop through box edges
const PxU8* PX_RESTRICT edges = getBoxEdges();
const PxVec3* PX_RESTRICT edgeNormals = getBoxLocalEdgeNormals();
for(PxU32 i=0;i<12;i++) // 12 edges
{
// PT: TODO: skip this if edge is culled
PxVec3 p1 = boxVertices[*edges++];
PxVec3 p2 = boxVertices[*edges++];
makeFatEdge(p1, p2, gFatBoxEdgeCoeff);
if(edgeNormals[i].dot(motion) < 0.0f)
continue;
// While we're at it, precompute some more data for EE tests
const PxVec3 v1 = p2 - p1;
// Build plane P based on edge (p1, p2) and direction (dir)
const PxVec3 planeNormal = v1.cross(motion);
const PxPlane plane(planeNormal, -(planeNormal.dot(p1)));
// find largest 2D plane projection
PxU32 closest_i, closest_j;
// closestAxis(plane.normal, ii, jj);
closestAxis2(planeNormal, closest_i, closest_j);
const PxReal coeff = 1.0f / (v1[closest_i]*motion[closest_j] - v1[closest_j]*motion[closest_i]);
// Loop through triangle edges
for(PxU32 j=0; j<3; j++)
{
// Catch current triangle edge
// j=0 => 0-1
// j=1 => 1-2
// j=2 => 2-0
// => this is compatible with EdgeList
const PxU32 k = PxGetNextIndex3(j);
PxReal dist;
PxVec3 ip;
if(intersectEdgeEdge3(plane, p1, p2, motion, v1, tri.verts[j], tri.verts[k], dist, ip, closest_i, closest_j, coeff))
{
if(dist<=minDist)
{
p1s = p1;
v1s = v1;
saved_j = j;
saved_k = k;
col = 2;
minDist = dist;
// PT: hit point on triangle
hit = ip + motion*dist;
}
}
}
}
}
if(col==-1)
return false;
if(col==2)
{
PX_ASSERT(saved_j != PX_INVALID_U32);
PX_ASSERT(saved_k != PX_INVALID_U32);
const PxVec3& p3 = tri.verts[saved_j];
const PxVec3& p4 = tri.verts[saved_k];
computeEdgeEdgeNormal(normal, p1s, v1s, p3, p4-p3, motion, minDist);
}
d = minDist;
return true;
}
| 17,961 | C++ | 27.831461 | 141 | 0.649964 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepTriangleUtils.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 "GuSweepTriangleUtils.h"
#include "GuDistancePointTriangle.h"
#include "GuVecTriangle.h"
#include "GuVecBox.h"
#include "GuSweepBoxTriangle_FeatureBased.h"
#include "GuInternal.h"
#include "GuGJK.h"
using namespace physx;
using namespace Gu;
using namespace physx::aos;
#define GU_SAFE_DISTANCE_FOR_NORMAL_COMPUTATION 0.1f
void Gu::computeSphereTriImpactData(PxVec3& hit, PxVec3& normal, const PxVec3& center, const PxVec3& dir, float t, const PxTriangle& tri)
{
const PxVec3 newSphereCenter = center + dir*t;
// We need the impact point, not computed by the new code
PxReal u_unused, v_unused;
const PxVec3 localHit = closestPtPointTriangle(newSphereCenter, tri.verts[0], tri.verts[1], tri.verts[2], u_unused, v_unused);
PX_UNUSED(u_unused);
PX_UNUSED(v_unused);
// This is responsible for the cap-vs-box stuck while jumping. However it's needed to slide on box corners!
// PT: this one is also dubious since the sphere/capsule center can be far away from the hit point when the radius is big!
PxVec3 localNormal = newSphereCenter - localHit;
const PxReal m = localNormal.normalize();
if(m<1e-3f)
tri.normal(localNormal);
hit = localHit;
normal = localNormal;
}
// PT: not inlining this rarely-run function makes the benchmark ~500.000 cycles faster...
// PT: using this version all the time makes the benchmark ~300.000 cycles slower. So we just use it as a backup.
static bool runBackupProcedure(PxVec3& hit, PxVec3& normal, const PxVec3& localMotion, const PxVec3& boxExtents, const PxTriangle& triInBoxSpace)
{
const Vec3V v0 = V3LoadU(triInBoxSpace.verts[0]);
const Vec3V v1 = V3LoadU(triInBoxSpace.verts[1]);
const Vec3V v2 = V3LoadU(triInBoxSpace.verts[2]);
const TriangleV triangleV(v0, v1, v2);
// PT: the box is in the triangle's space already
//BoxV boxV(V3LoadU(PxVec3(0.0f)), V3LoadU(boxExtents),
// V3LoadU(PxVec3(1.0f, 0.0f, 0.0f)), V3LoadU(PxVec3(0.0f, 1.0f, 0.0f)), V3LoadU(PxVec3(0.0f, 0.0f, 1.0f)));
const BoxV boxV(V3Zero(), V3LoadU(boxExtents));
Vec3V closestA;
Vec3V closestB;
Vec3V normalV;
FloatV distV;
const LocalConvex<TriangleV> convexA(triangleV);
const LocalConvex<BoxV> convexB(boxV);
const Vec3V initialSearchDir = V3Sub(triangleV.getCenter(), boxV.getCenter());
const FloatV contactDist = FMax();
GjkStatus status_ = gjk<LocalConvex<TriangleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, contactDist, closestA, closestB, normalV, distV);
if(status_==GJK_CONTACT)
return false;
PxVec3 ml_closestB;
PxVec3 ml_normal;
V3StoreU(closestB, ml_closestB);
V3StoreU(normalV, ml_normal);
hit = ml_closestB + localMotion;
// normal = -ml_normal;
if((ml_normal.dot(localMotion))>0.0f)
ml_normal = -ml_normal;
normal = ml_normal;
return true;
}
void Gu::computeBoxTriImpactData(PxVec3& hit, PxVec3& normal, const PxVec3& boxExtents, const PxVec3& localDir, const PxTriangle& triInBoxSpace, PxReal impactDist)
{
// PT: the triangle is in "box space", i.e. the box can be seen as an AABB centered around the origin.
// PT: compute impact point/normal in a second pass. Here we simply re-sweep the box against the best triangle,
// using the feature-based code (which computes impact point and normal). This is not great because:
// - we know there's an impact so why do all tests again?
// - the SAT test & the feature-based tests could return different results because of FPU accuracy.
// The backup procedure makes sure we compute a proper answer even when the SAT and feature-based versions differ.
const PxBounds3 aabb(-boxExtents, boxExtents);
const PxVec3 oneOverDir(
localDir.x!=0.0f ? 1.0f/localDir.x : 0.0f,
localDir.y!=0.0f ? 1.0f/localDir.y : 0.0f,
localDir.z!=0.0f ? 1.0f/localDir.z : 0.0f);
// PT: TODO: this is the only place left using sweepBoxTriangle()
// Backface culling could be removed here since we know we want a hit no matter what. Plus, it's sometimes
// incorrectly culled and we hit the backup procedure for no reason. On Win32Modern for unknown reasons
// returned normal is sometimes (0,0,0). In these cases we also switch to the backup procedure.
float t = PX_MAX_F32; // PT: no need to initialize with best dist here since we want a hit no matter what
if(!sweepBoxTriangle(triInBoxSpace, aabb, localDir, oneOverDir, hit, normal, t) || normal.isZero())
{
// PT: move triangle close to box
const PxVec3 localMotion = localDir*impactDist;
const PxVec3 delta = localMotion - localDir*GU_SAFE_DISTANCE_FOR_NORMAL_COMPUTATION;
const PxTriangle movedTriangle(
triInBoxSpace.verts[0] - delta,
triInBoxSpace.verts[1] - delta,
triInBoxSpace.verts[2] - delta);
if(!runBackupProcedure(hit, normal, localMotion, boxExtents, movedTriangle))
{
// PT: if the backup procedure fails, we give up
hit = PxVec3(0.0f);
normal = -localDir;
}
}
}
// PT: copy where we know that input vectors are not zero
static PX_FORCE_INLINE void edgeEdgeDistNoZeroVector( PxVec3& x, PxVec3& y, // closest points
const PxVec3& p, const PxVec3& a, // seg 1 origin, vector
const PxVec3& q, const PxVec3& b) // seg 2 origin, vector
{
const PxVec3 T = q - p;
const PxReal ADotA = a.dot(a);
const PxReal BDotB = b.dot(b);
PX_ASSERT(ADotA!=0.0f);
PX_ASSERT(BDotB!=0.0f);
const PxReal ADotB = a.dot(b);
const PxReal ADotT = a.dot(T);
const PxReal BDotT = b.dot(T);
// t parameterizes ray (p, a)
// u parameterizes ray (q, b)
// Compute t for the closest point on ray (p, a) to ray (q, b)
const PxReal Denom = ADotA*BDotB - ADotB*ADotB;
PxReal t; // We will clamp result so t is on the segment (p, a)
if(Denom!=0.0f)
t = PxClamp((ADotT*BDotB - BDotT*ADotB) / Denom, 0.0f, 1.0f);
else
t = 0.0f;
// find u for point on ray (q, b) closest to point at t
PxReal u;
{
u = (t*ADotB - BDotT) / BDotB;
// if u is on segment (q, b), t and u correspond to closest points, otherwise, clamp u, recompute and clamp t
if(u<0.0f)
{
u = 0.0f;
t = PxClamp(ADotT / ADotA, 0.0f, 1.0f);
}
else if(u > 1.0f)
{
u = 1.0f;
t = PxClamp((ADotB + ADotT) / ADotA, 0.0f, 1.0f);
}
}
x = p + a * t;
y = q + b * u;
}
void Gu::computeEdgeEdgeNormal(PxVec3& normal, const PxVec3& p1, const PxVec3& p2_p1, const PxVec3& p3, const PxVec3& p4_p3, const PxVec3& dir, float d)
{
// PT: cross-product doesn't produce nice normals so we use an edge-edge distance function itself
// PT: move the edges "0.1" units from each other before the computation. If the edges are too far
// away, computed normal tend to align itself with the swept direction. If the edges are too close,
// closest points x and y become identical and we can't compute a proper normal.
const PxVec3 p1s = p1 + dir*(d-GU_SAFE_DISTANCE_FOR_NORMAL_COMPUTATION);
PxVec3 x, y;
edgeEdgeDistNoZeroVector(x, y, p1s, p2_p1, p3, p4_p3);
normal = x - y;
}
| 8,561 | C++ | 39.966507 | 163 | 0.722696 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_BOX_BOX_H
#define GU_SWEEP_BOX_BOX_H
#include "foundation/PxVec3.h"
#include "PxQueryReport.h"
namespace physx
{
namespace Gu
{
class Box;
bool sweepBoxBox(const Box& box0, const Box& box1, const PxVec3& dir, PxReal length, PxHitFlags hitFlags, PxGeomSweepHit& sweepHit);
} // namespace Gu
}
#endif
| 2,022 | C | 41.145832 | 133 | 0.761622 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleCapsule.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/PxTriangle.h"
#include "PxQueryReport.h"
#include "GuSweepCapsuleCapsule.h"
#include "GuCapsule.h"
#include "GuDistancePointSegment.h"
#include "GuDistanceSegmentSegment.h"
#include "GuIntersectionRayCapsule.h"
using namespace physx;
using namespace Gu;
#define LOCAL_EPSILON 0.00001f // PT: this value makes the 'basicAngleTest' pass. Fails because of a ray almost parallel to a triangle
void edgeEdgeDist(PxVec3& x, PxVec3& y, // closest points
const PxVec3& p, const PxVec3& a, // seg 1 origin, vector
const PxVec3& q, const PxVec3& b) // seg 2 origin, vector
{
const PxVec3 T = q - p;
const PxReal ADotA = a.dot(a);
const PxReal BDotB = b.dot(b);
const PxReal ADotB = a.dot(b);
const PxReal ADotT = a.dot(T);
const PxReal BDotT = b.dot(T);
// t parameterizes ray (p, a)
// u parameterizes ray (q, b)
// Compute t for the closest point on ray (p, a) to ray (q, b)
const PxReal Denom = ADotA*BDotB - ADotB*ADotB;
PxReal t; // We will clamp result so t is on the segment (p, a)
if(Denom!=0.0f)
t = PxClamp((ADotT*BDotB - BDotT*ADotB) / Denom, 0.0f, 1.0f);
else
t = 0.0f;
// find u for point on ray (q, b) closest to point at t
PxReal u;
if(BDotB!=0.0f)
{
u = (t*ADotB - BDotT) / BDotB;
// if u is on segment (q, b), t and u correspond to closest points, otherwise, clamp u, recompute and clamp t
if(u<0.0f)
{
u = 0.0f;
if(ADotA!=0.0f)
t = PxClamp(ADotT / ADotA, 0.0f, 1.0f);
else
t = 0.0f;
}
else if(u > 1.0f)
{
u = 1.0f;
if(ADotA!=0.0f)
t = PxClamp((ADotB + ADotT) / ADotA, 0.0f, 1.0f);
else
t = 0.0f;
}
}
else
{
u = 0.0f;
if(ADotA!=0.0f)
t = PxClamp(ADotT / ADotA, 0.0f, 1.0f);
else
t = 0.0f;
}
x = p + a * t;
y = q + b * u;
}
static bool rayQuad(const PxVec3& orig, const PxVec3& dir, const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxReal& t, PxReal& u, PxReal& v, bool cull)
{
// Find vectors for two edges sharing vert0
const PxVec3 edge1 = vert1 - vert0;
const PxVec3 edge2 = vert2 - vert0;
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2);
// If determinant is near zero, ray lies in plane of triangle
const PxReal det = edge1.dot(pvec);
if(cull)
{
if(det<LOCAL_EPSILON)
return false;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter and test bounds
u = tvec.dot(pvec);
if(u<0.0f || u>det)
return false;
// Prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
v = dir.dot(qvec);
if(v<0.0f || v>det)
return false;
// Calculate t, scale parameters, ray intersects triangle
t = edge2.dot(qvec);
const PxReal oneOverDet = 1.0f / det;
t *= oneOverDet;
u *= oneOverDet;
v *= oneOverDet;
}
else
{
// the non-culling branch
if(det>-LOCAL_EPSILON && det<LOCAL_EPSILON)
return false;
const PxReal oneOverDet = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter and test bounds
u = (tvec.dot(pvec)) * oneOverDet;
if(u<0.0f || u>1.0f)
return false;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
v = (dir.dot(qvec)) * oneOverDet;
if(v<0.0f || v>1.0f)
return false;
// Calculate t, ray intersects triangle
t = (edge2.dot(qvec)) * oneOverDet;
}
return true;
}
bool Gu::sweepCapsuleCapsule(const Capsule& capsule0, const Capsule& capsule1, const PxVec3& dir, PxReal length, PxReal& min_dist, PxVec3& ip, PxVec3& normal, PxU32 inHitFlags, PxU16& outHitFlags)
{
const PxReal radiusSum = capsule0.radius + capsule1.radius;
if(!(inHitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP))
{
// PT: test if shapes initially overlap
// PT: It would be better not to use the same code path for spheres and capsules. The segment-segment distance
// function doesn't work for degenerate capsules so we need to test all combinations here anyway.
bool initialOverlapStatus;
if(capsule0.p0==capsule0.p1)
initialOverlapStatus = distancePointSegmentSquared(capsule1, capsule0.p0)<radiusSum*radiusSum;
else if(capsule1.p0==capsule1.p1)
initialOverlapStatus = distancePointSegmentSquared(capsule0, capsule1.p0)<radiusSum*radiusSum;
else
initialOverlapStatus = distanceSegmentSegmentSquared(capsule0, capsule1)<radiusSum*radiusSum;
if(initialOverlapStatus)
{
min_dist = 0.0f;
normal = -dir;
outHitFlags = PxHitFlag::eNORMAL;
return true;
}
}
// 1. Extrude capsule0 by capsule1's length
// 2. Inflate extruded shape by capsule1's radius
// 3. Raycast against resulting shape
const PxVec3 capsuleExtent1 = capsule1.p1 - capsule1.p0;
// Extrusion dir = capsule segment
const PxVec3 D = capsuleExtent1*0.5f;
const PxVec3 p0 = capsule0.p0 - D;
const PxVec3 p1 = capsule0.p1 - D;
const PxVec3 p0b = capsule0.p0 + D;
const PxVec3 p1b = capsule0.p1 + D;
PxTriangle T(p0b, p1b, p1);
PxVec3 Normal;
T.normal(Normal);
PxReal MinDist = length;
bool Status = false;
PxVec3 pa,pb,pc;
if((Normal.dot(dir)) >= 0) // Same direction
{
Normal *= radiusSum;
pc = p0 - Normal;
pa = p1 - Normal;
pb = p1b - Normal;
}
else
{
Normal *= radiusSum;
pb = p0 + Normal;
pa = p1 + Normal;
pc = p1b + Normal;
}
PxReal t, u, v;
const PxVec3 center = capsule1.computeCenter();
if(rayQuad(center, dir, pa, pb, pc, t, u, v, true) && t>=0.0f && t<MinDist)
{
MinDist = t;
Status = true;
}
// PT: optimization: if we hit one of the quad we can't possibly get a better hit, so let's skip all
// the remaining tests!
if(!Status)
{
Capsule Caps[4];
Caps[0] = Capsule(p0, p1, radiusSum);
Caps[1] = Capsule(p1, p1b, radiusSum);
Caps[2] = Capsule(p1b, p0b, radiusSum);
Caps[3] = Capsule(p0, p0b, radiusSum);
// ### a lot of ray-sphere tests could be factored out of the ray-capsule tests...
for(PxU32 i=0;i<4;i++)
{
PxReal w;
if(intersectRayCapsule(center, dir, Caps[i], w))
{
if(w>=0.0f && w<= MinDist)
{
MinDist = w;
Status = true;
}
}
}
}
if(Status)
{
outHitFlags = PxHitFlags(0);
if(inHitFlags & PxU32(PxHitFlag::ePOSITION|PxHitFlag::eNORMAL))
{
const PxVec3 p00 = capsule0.p0 - MinDist * dir;
const PxVec3 p01 = capsule0.p1 - MinDist * dir;
// const PxVec3 p10 = capsule1.p0;// - MinDist * dir;
// const PxVec3 p11 = capsule1.p1;// - MinDist * dir;
const PxVec3 edge0 = p01 - p00;
const PxVec3 edge1 = capsuleExtent1;
PxVec3 x, y;
edgeEdgeDist(x, y, p00, edge0, capsule1.p0, edge1);
if(inHitFlags & PxHitFlag::eNORMAL)
{
normal = (x - y);
const float epsilon = 0.001f;
if(normal.normalize()<epsilon)
{
// PT: happens when radiuses are zero
normal = edge1.cross(edge0);
if(normal.normalize()<epsilon)
{
// PT: happens when edges are parallel
const PxVec3 capsuleExtent0 = capsule0.p1 - capsule0.p0;
edgeEdgeDist(x, y, capsule0.p0, capsuleExtent0, capsule1.p0, edge1);
normal = (x - y);
normal.normalize();
}
}
outHitFlags |= PxHitFlag::eNORMAL;
}
if(inHitFlags & PxHitFlag::ePOSITION)
{
ip = (capsule1.radius*x + capsule0.radius*y)/(capsule0.radius+capsule1.radius);
outHitFlags |= PxHitFlag::ePOSITION;
}
}
min_dist = MinDist;
}
return Status;
}
| 9,147 | C++ | 28.04127 | 196 | 0.677818 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxSphere.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_BOX_SPHERE_H
#define GU_SWEEP_BOX_SPHERE_H
#include "foundation/PxVec3.h"
#include "PxQueryReport.h"
namespace physx
{
namespace Gu
{
class Box;
bool sweepBoxSphere(const Box& box, PxReal sphereRadius, const PxVec3& spherePos, const PxVec3& dir, PxReal length, PxReal& min_dist, PxVec3& normal, PxHitFlags hitFlags);
} // namespace Gu
}
#endif
| 2,067 | C | 42.083332 | 172 | 0.762941 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxTriangle_SAT.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_BOX_TRIANGLE_SAT_H
#define GU_SWEEP_BOX_TRIANGLE_SAT_H
#include "geometry/PxTriangle.h"
#include "GuSweepSharedTests.h"
#include "GuInternal.h"
#define RetType int
#define MTDType bool
namespace physx
{
namespace Gu
{
// We have separation if one of those conditions is true:
// -BoxExt > TriMax (box strictly to the right of the triangle)
// BoxExt < TriMin (box strictly to the left of the triangle
// <=> d0 = -BoxExt - TriMax > 0
// d1 = BoxExt - TriMin < 0
// Hence we have overlap if d0 <= 0 and d1 >= 0
// overlap = (d0<=0.0f && d1>=0.0f)
#define TEST_OVERLAP \
const float d0 = -BoxExt - TriMax; \
const float d1 = BoxExt - TriMin; \
const bool bIntersect = (d0<=0.0f && d1>=0.0f); \
bValidMTD &= bIntersect;
// PT: inlining this one is important. Returning floats looks bad but is faster on Xbox.
static PX_FORCE_INLINE RetType testAxis(const PxTriangle& tri, const PxVec3& extents, const PxVec3& dir, const PxVec3& axis, MTDType& bValidMTD, float& tfirst, float& tlast)
{
const float d0t = tri.verts[0].dot(axis);
const float d1t = tri.verts[1].dot(axis);
const float d2t = tri.verts[2].dot(axis);
float TriMin = PxMin(d0t, d1t);
float TriMax = PxMax(d0t, d1t);
TriMin = PxMin(TriMin, d2t);
TriMax = PxMax(TriMax, d2t);
////////
const float BoxExt = PxAbs(axis.x)*extents.x + PxAbs(axis.y)*extents.y + PxAbs(axis.z)*extents.z;
TEST_OVERLAP
const float v = dir.dot(axis);
if(PxAbs(v) < 1.0E-6f)
return bIntersect;
const float oneOverV = -1.0f / v;
// float t0 = d0 * oneOverV;
// float t1 = d1 * oneOverV;
// if(t0 > t1) TSwap(t0, t1);
const float t0_ = d0 * oneOverV;
const float t1_ = d1 * oneOverV;
float t0 = PxMin(t0_, t1_);
float t1 = PxMax(t0_, t1_);
if(t0 > tlast) return false;
if(t1 < tfirst) return false;
// if(t1 < tlast) tlast = t1;
tlast = PxMin(t1, tlast);
// if(t0 > tfirst) tfirst = t0;
tfirst = PxMax(t0, tfirst);
return true;
}
template<const int XYZ>
static PX_FORCE_INLINE RetType testAxisXYZ(const PxTriangle& tri, const PxVec3& extents, const PxVec3& dir, float oneOverDir, MTDType& bValidMTD, float& tfirst, float& tlast)
{
const float d0t = tri.verts[0][XYZ];
const float d1t = tri.verts[1][XYZ];
const float d2t = tri.verts[2][XYZ];
float TriMin = PxMin(d0t, d1t);
float TriMax = PxMax(d0t, d1t);
TriMin = PxMin(TriMin, d2t);
TriMax = PxMax(TriMax, d2t);
////////
const float BoxExt = extents[XYZ];
TEST_OVERLAP
const float v = dir[XYZ];
if(PxAbs(v) < 1.0E-6f)
return bIntersect;
const float oneOverV = -oneOverDir;
// float t0 = d0 * oneOverV;
// float t1 = d1 * oneOverV;
// if(t0 > t1) TSwap(t0, t1);
const float t0_ = d0 * oneOverV;
const float t1_ = d1 * oneOverV;
float t0 = PxMin(t0_, t1_);
float t1 = PxMax(t0_, t1_);
if(t0 > tlast) return false;
if(t1 < tfirst) return false;
// if(t1 < tlast) tlast = t1;
tlast = PxMin(t1, tlast);
// if(t0 > tfirst) tfirst = t0;
tfirst = PxMax(t0, tfirst);
return true;
}
PX_FORCE_INLINE int testSeparationAxes( const PxTriangle& tri, const PxVec3& extents,
const PxVec3& normal, const PxVec3& dir, const PxVec3& oneOverDir, float tmax, float& tcoll)
{
bool bValidMTD = true;
float tfirst = -FLT_MAX;
float tlast = FLT_MAX;
// Triangle normal
if(!testAxis(tri, extents, dir, normal, bValidMTD, tfirst, tlast))
return 0;
// Box normals
if(!testAxisXYZ<0>(tri, extents, dir, oneOverDir.x, bValidMTD, tfirst, tlast))
return 0;
if(!testAxisXYZ<1>(tri, extents, dir, oneOverDir.y, bValidMTD, tfirst, tlast))
return 0;
if(!testAxisXYZ<2>(tri, extents, dir, oneOverDir.z, bValidMTD, tfirst, tlast))
return 0;
// Edges
for(PxU32 i=0; i<3; i++)
{
int ip1 = int(i+1);
if(i>=2) ip1 = 0;
const PxVec3 TriEdge = tri.verts[ip1] - tri.verts[i];
{
const PxVec3 Sep = cross100(TriEdge);
if((Sep.dot(Sep))>=1.0E-6f && !testAxis(tri, extents, dir, Sep, bValidMTD, tfirst, tlast))
return 0;
}
{
const PxVec3 Sep = cross010(TriEdge);
if((Sep.dot(Sep))>=1.0E-6f && !testAxis(tri, extents, dir, Sep, bValidMTD, tfirst, tlast))
return 0;
}
{
const PxVec3 Sep = cross001(TriEdge);
if((Sep.dot(Sep))>=1.0E-6f && !testAxis(tri, extents, dir, Sep, bValidMTD, tfirst, tlast))
return 0;
}
}
if(tfirst > tmax || tlast < 0.0f)
return 0;
if(tfirst <= 0.0f)
{
if(!bValidMTD)
return 0;
tcoll = 0.0f;
}
else tcoll = tfirst;
return 1;
}
//! Inlined version of triBoxSweepTestBoxSpace. See that other function for comments.
PX_FORCE_INLINE int triBoxSweepTestBoxSpace_inlined(const PxTriangle& tri, const PxVec3& extents, const PxVec3& dir, const PxVec3& oneOverDir, float tmax, float& toi, PxU32 doBackfaceCulling)
{
// Create triangle normal
PxVec3 triNormal;
tri.denormalizedNormal(triNormal);
// Backface culling
if(doBackfaceCulling && (triNormal.dot(dir)) >= 0.0f) // ">=" is important !
return 0;
// The SAT test will properly detect initial overlaps, no need for extra tests
return testSeparationAxes(tri, extents, triNormal, dir, oneOverDir, tmax, toi);
}
/**
Sweeps a box against a triangle, using a 'SAT' approach (Separating Axis Theorem).
The test is performed in box-space, i.e. the box is axis-aligned and its center is (0,0,0). In other words it is
defined by its extents alone. The triangle must have been transformed to this "box-space" before calling the function.
\param tri [in] triangle in box-space
\param extents [in] box extents
\param dir [in] sweep direction. Does not need to be normalized.
\param oneOverDir [in] precomputed inverse of sweep direction
\param tmax [in] sweep length
\param toi [out] time of impact/impact distance. Does not need to be initialized before calling the function.
\param doBackfaceCulling [in] true to enable backface culling, false for double-sided triangles
\return non-zero value if an impact has been found (in which case returned 'toi' value is valid)
*/
int triBoxSweepTestBoxSpace(const PxTriangle& tri, const PxVec3& extents, const PxVec3& dir, const PxVec3& oneOverDir, float tmax, float& toi, bool doBackfaceCulling);
} // namespace Gu
}
#endif
| 7,962 | C | 32.599156 | 192 | 0.686385 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_CAPSULE_BOX_H
#define GU_SWEEP_CAPSULE_BOX_H
#include "foundation/PxVec3.h"
#include "PxQueryReport.h"
namespace physx
{
namespace Gu
{
class Capsule;
bool sweepCapsuleBox(const Capsule& capsule, const PxTransform& boxWorldPose, const PxVec3& boxDim, const PxVec3& dir, PxReal length, PxVec3& hit, PxReal& min_dist, PxVec3& normal, PxHitFlags hitFlags);
} // namespace Gu
}
#endif
| 2,104 | C | 42.854166 | 203 | 0.764259 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereCapsule.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_SPHERE_CAPSULE_H
#define GU_SWEEP_SPHERE_CAPSULE_H
#include "foundation/PxVec3.h"
#include "PxQueryReport.h"
namespace physx
{
namespace Gu
{
class Sphere;
class Capsule;
bool sweepSphereCapsule(const Sphere& sphere, const Capsule& lss, const PxVec3& dir, PxReal length, PxReal& d, PxVec3& ip, PxVec3& nrm, PxHitFlags hitFlags);
} // namespace Gu
}
#endif
| 2,080 | C | 41.469387 | 158 | 0.7625 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepCapsuleTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_CAPSULE_TRIANGLE_H
#define GU_SWEEP_CAPSULE_TRIANGLE_H
#include "foundation/PxVec3.h"
#include "PxQueryReport.h"
namespace physx
{
class PxTriangle;
namespace Gu
{
class BoxPadded;
class Capsule;
/**
Sweeps a capsule against a set of triangles.
\param nbTris [in] number of triangles in input array
\param triangles [in] array of input triangles
\param capsule [in] the capsule
\param unitDir [in] sweep's unit direcion
\param distance [in] sweep's length
\param cachedIndex [in] cached triangle index, or NULL. Cached triangle will be tested first.
\param hit [out] results
\param triNormalOut [out] triangle normal
\param hitFlags [in] query modifiers
\param isDoubleSided [in] true if input triangles are double-sided
\param cullBox [in] additional/optional culling box. Triangles not intersecting the box are quickly discarded.
\warning if using a cullbox, make sure all triangles can be safely V4Loaded (i.e. allocate 4 more bytes after last triangle)
\return true if an impact has been found
*/
bool sweepCapsuleTriangles_Precise( PxU32 nbTris, const PxTriangle* PX_RESTRICT triangles, // Triangle data
const Capsule& capsule, // Capsule data
const PxVec3& unitDir, const PxReal distance, // Ray data
const PxU32* PX_RESTRICT cachedIndex, // Cache data
PxGeomSweepHit& hit, PxVec3& triNormalOut, // Results
PxHitFlags hitFlags, bool isDoubleSided, // Query modifiers
const BoxPadded* cullBox=NULL); // Cull data
} // namespace Gu
}
#endif
| 3,292 | C | 43.499999 | 125 | 0.741495 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepSphereCapsule.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 "GuSweepSphereCapsule.h"
#include "GuSphere.h"
#include "GuCapsule.h"
#include "GuDistancePointSegment.h"
#include "GuSweepSphereSphere.h"
#include "GuIntersectionRayCapsule.h"
using namespace physx;
using namespace Gu;
bool Gu::sweepSphereCapsule(const Sphere& sphere, const Capsule& lss, const PxVec3& dir, PxReal length, PxReal& d, PxVec3& ip, PxVec3& nrm, PxHitFlags hitFlags)
{
const PxReal radiusSum = lss.radius + sphere.radius;
if(!(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP))
{
// PT: test if shapes initially overlap
if(distancePointSegmentSquared(lss.p0, lss.p1, sphere.center)<radiusSum*radiusSum)
{
d = 0.0f;
nrm = -dir;
return true;
}
}
if(lss.p0 == lss.p1)
{
// Sphere vs. sphere
if(sweepSphereSphere(sphere.center, sphere.radius, lss.p0, lss.radius, -dir*length, d, nrm))
{
d*=length;
// if(hitFlags & PxHitFlag::ePOSITION) // PT: TODO
ip = sphere.center + nrm * sphere.radius;
return true;
}
return false;
}
// Create inflated capsule
Capsule Inflated(lss.p0, lss.p1, radiusSum);
// Raycast against it
PxReal t = 0.0f;
if(intersectRayCapsule(sphere.center, dir, Inflated, t))
{
if(t>=0.0f && t<=length)
{
d = t;
// PT: TODO:
// const PxIntBool needsImpactPoint = hitFlags & PxHitFlag::ePOSITION;
// if(needsImpactPoint || hitFlags & PxHitFlag::eNORMAL)
{
// Move capsule against sphere
const PxVec3 tdir = t*dir;
Inflated.p0 -= tdir;
Inflated.p1 -= tdir;
// Compute closest point between moved capsule & sphere
distancePointSegmentSquared(Inflated, sphere.center, &t);
Inflated.computePoint(ip, t);
// Normal
nrm = (ip - sphere.center);
nrm.normalize();
// if(needsImpactPoint) // PT: TODO
ip -= nrm * lss.radius;
}
return true;
}
}
return false;
}
| 3,516 | C++ | 33.145631 | 160 | 0.717861 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxBox.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 "GuSweepBoxBox.h"
#include "GuBox.h"
#include "GuIntersectionBoxBox.h"
#include "GuIntersectionRayBox.h"
#include "GuIntersectionEdgeEdge.h"
#include "GuSweepSharedTests.h"
#include "foundation/PxMat34.h"
#include "GuSweepTriangleUtils.h"
#include "GuInternal.h"
using namespace physx;
using namespace Gu;
namespace
{
// PT: TODO: get rid of this copy
static const PxReal gFatBoxEdgeCoeff = 0.01f;
// PT: TODO: get rid of this copy
static const PxVec3 gNearPlaneNormal[] =
{
PxVec3(1.0f, 0.0f, 0.0f),
PxVec3(0.0f, 1.0f, 0.0f),
PxVec3(0.0f, 0.0f, 1.0f),
PxVec3(-1.0f, 0.0f, 0.0f),
PxVec3(0.0f, -1.0f, 0.0f),
PxVec3(0.0f, 0.0f, -1.0f)
};
#define INVSQRT2 0.707106781188f //!< 1 / sqrt(2)
static PxVec3 EdgeNormals[] =
{
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
};
// PT: TODO: get rid of this copy
static const PxVec3* getBoxLocalEdgeNormals()
{
return EdgeNormals;
}
/**
Returns world edge normal
\param edgeIndex [in] 0 <= edge index < 12
\param worldNormal [out] edge normal in world space
*/
static void computeBoxWorldEdgeNormal(const Box& box, PxU32 edgeIndex, PxVec3& worldNormal)
{
PX_ASSERT(edgeIndex<12);
worldNormal = box.rotate(getBoxLocalEdgeNormals()[edgeIndex]);
}
}
// ### optimize! and refactor. And optimize for aabbs
bool Gu::sweepBoxBox(const Box& box0, const Box& box1, const PxVec3& dir, PxReal length, PxHitFlags hitFlags, PxGeomSweepHit& sweepHit)
{
if(!(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP))
{
// PT: test if shapes initially overlap
if(intersectOBBOBB(box0.extents, box0.center, box0.rot, box1.extents, box1.center, box1.rot, true))
{
sweepHit.flags = PxHitFlag::eNORMAL;
sweepHit.distance = 0.0f;
sweepHit.normal = -dir;
return true;
}
}
PxVec3 boxVertices0[8]; box0.computeBoxPoints(boxVertices0);
PxVec3 boxVertices1[8]; box1.computeBoxPoints(boxVertices1);
// float MinDist = PX_MAX_F32;
PxReal MinDist = length;
int col = -1;
// In following VF tests:
// - the direction is FW/BK since we project one box onto the other *and vice versa*
// - the normal reaction is FW/BK for the same reason
// Vertices1 against Box0
{
// We need:
// - Box0 in local space
const PxVec3 Min0 = -box0.extents;
const PxVec3 Max0 = box0.extents;
// - Vertices1 in Box0 space
PxMat34 worldToBox0;
computeWorldToBoxMatrix(worldToBox0, box0);
// - the dir in Box0 space
const PxVec3 localDir0 = worldToBox0.rotate(dir);
const PxVec3* boxNormals0 = gNearPlaneNormal;
for(PxU32 i=0; i<8; i++)
{
PxReal tnear, tfar;
const int plane = intersectRayAABB(Min0, Max0, worldToBox0.transform(boxVertices1[i]), -localDir0, tnear, tfar);
if(plane==-1 || tnear<0.0f)
continue;
if(tnear <= MinDist)
{
MinDist = tnear;
sweepHit.normal = box0.rotate(boxNormals0[plane]);
sweepHit.position = boxVertices1[i];
col = 0;
}
}
}
// Vertices0 against Box1
{
// We need:
// - Box1 in local space
const PxVec3 Min1 = -box1.extents;
const PxVec3 Max1 = box1.extents;
// - Vertices0 in Box1 space
PxMat34 worldToBox1;
computeWorldToBoxMatrix(worldToBox1, box1);
// - the dir in Box1 space
const PxVec3 localDir1 = worldToBox1.rotate(dir);
const PxVec3* boxNormals1 = gNearPlaneNormal;
for(PxU32 i=0; i<8; i++)
{
PxReal tnear, tfar;
const int plane = intersectRayAABB(Min1, Max1, worldToBox1.transform(boxVertices0[i]), localDir1, tnear, tfar);
if(plane==-1 || tnear<0.0f)
continue;
if(tnear <= MinDist)
{
MinDist = tnear;
sweepHit.normal = box1.rotate(-boxNormals1[plane]);
sweepHit.position = boxVertices0[i] + tnear * dir;
col = 1;
}
}
}
PxVec3 p1s, p2s, p3s, p4s;
{
const PxU8* PX_RESTRICT edges0 = getBoxEdges();
const PxU8* PX_RESTRICT edges1 = getBoxEdges();
PxVec3 edgeNormals0[12];
PxVec3 edgeNormals1[12];
for(PxU32 i=0; i<12; i++)
computeBoxWorldEdgeNormal(box0, i, edgeNormals0[i]);
for(PxU32 i=0; i<12; i++)
computeBoxWorldEdgeNormal(box1, i, edgeNormals1[i]);
// Loop through box edges
for(PxU32 i=0; i<12; i++) // 12 edges
{
if(!(edgeNormals0[i].dot(dir) >= 0.0f))
continue;
// Catch current box edge // ### one vertex already known using line-strips
// Make it fat ###
PxVec3 p1 = boxVertices0[edges0[i*2+0]];
PxVec3 p2 = boxVertices0[edges0[i*2+1]];
makeFatEdge(p1, p2, gFatBoxEdgeCoeff);
// Loop through box edges
for(PxU32 j=0;j<12;j++)
{
if(edgeNormals1[j].dot(dir) >= 0.0f)
continue;
// Orientation culling
// PT: this was commented for some reason, but it fixes the "stuck" bug reported by Ubi.
// So I put it back. We'll have to see whether it produces Bad Things in particular cases.
if(edgeNormals0[i].dot(edgeNormals1[j]) >= 0.0f)
continue;
// Catch current box edge
// Make it fat ###
PxVec3 p3 = boxVertices1[edges1[j*2+0]];
PxVec3 p4 = boxVertices1[edges1[j*2+1]];
makeFatEdge(p3, p4, gFatBoxEdgeCoeff);
PxReal Dist;
PxVec3 ip;
if(intersectEdgeEdge(p1, p2, dir, p3, p4, Dist, ip))
{
if(Dist<=MinDist)
{
p1s = p1;
p2s = p2;
p3s = p3;
p4s = p4;
sweepHit.position = ip + Dist * dir;
col = 2;
MinDist = Dist;
}
}
}
}
}
if(col==-1)
return false;
if(col==2)
{
computeEdgeEdgeNormal(sweepHit.normal, p1s, p2s-p1s, p3s, p4s-p3s, dir, MinDist);
sweepHit.normal.normalize();
}
sweepHit.flags = PxHitFlag::eNORMAL|PxHitFlag::ePOSITION;
sweepHit.distance = MinDist;
return true;
}
| 7,686 | C++ | 27.365314 | 135 | 0.68319 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepTriangleUtils.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_TRIANGLE_UTILS_H
#define GU_SWEEP_TRIANGLE_UTILS_H
#include "geometry/PxTriangle.h"
#include "PxQueryReport.h"
#include "GuSweepSharedTests.h"
#include "GuInternal.h"
namespace physx
{
namespace Gu
{
// PT: computes proper impact data for sphere-sweep-vs-tri, after the closest tri has been found.
void computeSphereTriImpactData(PxVec3& hit, PxVec3& normal, const PxVec3& center, const PxVec3& dir, float t, const PxTriangle& tri);
// PT: computes proper impact data for box-sweep-vs-tri, after the closest tri has been found.
void computeBoxTriImpactData(PxVec3& hit, PxVec3& normal, const PxVec3& boxExtents, const PxVec3& localDir, const PxTriangle& triInBoxSpace, PxReal impactDist);
// PT: computes impact normal between two edges. Produces better normals than just the EE cross product.
// This version properly computes the closest points between two colliding edges and makes a normal from these.
void computeEdgeEdgeNormal(PxVec3& normal, const PxVec3& p1, const PxVec3& p2_p1, const PxVec3& p3, const PxVec3& p4_p3, const PxVec3& dir, float d);
// PT: small function just to avoid duplicating the code.
// Returns index of first triangle we should process (when processing arrays of input triangles)
PX_FORCE_INLINE PxU32 getInitIndex(const PxU32* PX_RESTRICT cachedIndex, PxU32 nbTris)
{
PxU32 initIndex = 0; // PT: by default the first triangle to process is just the first one in the array
if(cachedIndex) // PT: but if we cached the last closest triangle from a previous call...
{
PX_ASSERT(*cachedIndex < nbTris);
PX_UNUSED(nbTris);
initIndex = *cachedIndex; // PT: ...then we should start with that one, to potentially shrink the ray as early as possible
}
return initIndex;
}
// PT: quick triangle rejection for sphere-based sweeps.
// Please refer to %SDKRoot%\InternalDocumentation\GU\cullTriangle.png for details & diagram.
PX_FORCE_INLINE bool cullTriangle(const PxVec3* PX_RESTRICT triVerts, const PxVec3& dir, PxReal radius, PxReal t, const PxReal dpc0)
{
// PT: project triangle on axis
const PxReal dp0 = triVerts[0].dot(dir);
const PxReal dp1 = triVerts[1].dot(dir);
const PxReal dp2 = triVerts[2].dot(dir);
// PT: keep min value = earliest possible impact distance
PxReal dp = dp0;
dp = physx::intrinsics::selectMin(dp, dp1);
dp = physx::intrinsics::selectMin(dp, dp2);
// PT: make sure we keep triangles that are about as close as best current distance
radius += 0.001f + GU_EPSILON_SAME_DISTANCE;
// PT: if earliest possible impact distance for this triangle is already larger than
// sphere's current best known impact distance, we can skip the triangle
if(dp>dpc0 + t + radius)
{
//PX_ASSERT(resx == 0.0f);
return false;
}
// PT: if triangle is fully located before the sphere's initial position, skip it too
const PxReal dpc1 = dpc0 - radius;
if(dp0<dpc1 && dp1<dpc1 && dp2<dpc1)
{
//PX_ASSERT(resx == 0.0f);
return false;
}
//PX_ASSERT(resx != 0.0f);
return true;
}
// PT: quick quad rejection for sphere-based sweeps. Same as for triangle, adapted for one more vertex.
PX_FORCE_INLINE bool cullQuad(const PxVec3* PX_RESTRICT quadVerts, const PxVec3& dir, PxReal radius, PxReal t, const PxReal dpc0)
{
// PT: project quad on axis
const PxReal dp0 = quadVerts[0].dot(dir);
const PxReal dp1 = quadVerts[1].dot(dir);
const PxReal dp2 = quadVerts[2].dot(dir);
const PxReal dp3 = quadVerts[3].dot(dir);
// PT: keep min value = earliest possible impact distance
PxReal dp = dp0;
dp = physx::intrinsics::selectMin(dp, dp1);
dp = physx::intrinsics::selectMin(dp, dp2);
dp = physx::intrinsics::selectMin(dp, dp3);
// PT: make sure we keep quads that are about as close as best current distance
radius += 0.001f + GU_EPSILON_SAME_DISTANCE;
// PT: if earliest possible impact distance for this quad is already larger than
// sphere's current best known impact distance, we can skip the quad
if(dp>dpc0 + t + radius)
return false;
// PT: if quad is fully located before the sphere's initial position, skip it too
const float dpc1 = dpc0 - radius;
if(dp0<dpc1 && dp1<dpc1 && dp2<dpc1 && dp3<dpc1)
return false;
return true;
}
// PT: computes distance between a point 'point' and a segment. The segment is defined as a starting point 'p0'
// and a direction vector 'dir' plus a length 't'. Segment's endpoint is p0 + dir * t.
//
// point
// o
// __/|
// __/ / |
// __/ / |(B)
// __/ (A)/ |
// __/ / | dir
// p0 o/---------o---------------o-- -->
// t (t<=fT) t (t>fT)
// return (A)^2 return (B)^2
//
// |<-------------->|
// fT
//
PX_FORCE_INLINE PxReal squareDistance(const PxVec3& p0, const PxVec3& dir, PxReal t, const PxVec3& point)
{
PxVec3 diff = point - p0;
PxReal fT = diff.dot(dir);
fT = physx::intrinsics::selectMax(fT, 0.0f);
fT = physx::intrinsics::selectMin(fT, t);
diff -= fT*dir;
return diff.magnitudeSquared();
}
// PT: quick triangle culling for sphere-based sweeps
// Please refer to %SDKRoot%\InternalDocumentation\GU\coarseCulling.png for details & diagram.
PX_FORCE_INLINE bool coarseCullingTri(const PxVec3& center, const PxVec3& dir, PxReal t, PxReal radius, const PxVec3* PX_RESTRICT triVerts)
{
// PT: compute center of triangle ### could be precomputed?
const PxVec3 triCenter = (triVerts[0] + triVerts[1] + triVerts[2]) * (1.0f/3.0f);
// PT: distance between the triangle center and the swept path (an LSS)
// Same as: distancePointSegmentSquared(center, center+dir*t, TriCenter);
PxReal d = PxSqrt(squareDistance(center, dir, t, triCenter)) - radius - 0.0001f;
if (d < 0.0f) // The triangle center lies inside the swept sphere
return true;
d*=d;
// PT: coarse capsule-vs-triangle overlap test ### distances could be precomputed?
if(1)
{
if(d <= (triCenter-triVerts[0]).magnitudeSquared())
return true;
if(d <= (triCenter-triVerts[1]).magnitudeSquared())
return true;
if(d <= (triCenter-triVerts[2]).magnitudeSquared())
return true;
}
else
{
const float d0 = (triCenter-triVerts[0]).magnitudeSquared();
const float d1 = (triCenter-triVerts[1]).magnitudeSquared();
const float d2 = (triCenter-triVerts[2]).magnitudeSquared();
float triRadius = physx::intrinsics::selectMax(d0, d1);
triRadius = physx::intrinsics::selectMax(triRadius, d2);
if(d <= triRadius)
return true;
}
return false;
}
// PT: quick quad culling for sphere-based sweeps. Same as for triangle, adapted for one more vertex.
PX_FORCE_INLINE bool coarseCullingQuad(const PxVec3& center, const PxVec3& dir, PxReal t, PxReal radius, const PxVec3* PX_RESTRICT quadVerts)
{
// PT: compute center of quad ### could be precomputed?
const PxVec3 quadCenter = (quadVerts[0] + quadVerts[1] + quadVerts[2] + quadVerts[3]) * (1.0f/4.0f);
// PT: distance between the quad center and the swept path (an LSS)
PxReal d = PxSqrt(squareDistance(center, dir, t, quadCenter)) - radius - 0.0001f;
if (d < 0.0f) // The quad center lies inside the swept sphere
return true;
d*=d;
// PT: coarse capsule-vs-quad overlap test ### distances could be precomputed?
if(1)
{
if(d <= (quadCenter-quadVerts[0]).magnitudeSquared())
return true;
if(d <= (quadCenter-quadVerts[1]).magnitudeSquared())
return true;
if(d <= (quadCenter-quadVerts[2]).magnitudeSquared())
return true;
if(d <= (quadCenter-quadVerts[3]).magnitudeSquared())
return true;
}
return false;
}
// PT: combined triangle culling for sphere-based sweeps
PX_FORCE_INLINE bool rejectTriangle(const PxVec3& center, const PxVec3& unitDir, PxReal curT, PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxReal dpc0)
{
if(!coarseCullingTri(center, unitDir, curT, radius, triVerts))
return true;
if(!cullTriangle(triVerts, unitDir, radius, curT, dpc0))
return true;
return false;
}
// PT: combined quad culling for sphere-based sweeps
PX_FORCE_INLINE bool rejectQuad(const PxVec3& center, const PxVec3& unitDir, PxReal curT, PxReal radius, const PxVec3* PX_RESTRICT quadVerts, const PxReal dpc0)
{
if(!coarseCullingQuad(center, unitDir, curT, radius, quadVerts))
return true;
if(!cullQuad(quadVerts, unitDir, radius, curT, dpc0))
return true;
return false;
}
PX_FORCE_INLINE bool shouldFlipNormal(const PxVec3& normal, bool meshBothSides, bool isDoubleSided, const PxVec3& triangleNormal, const PxVec3& dir)
{
// PT: this function assumes that input normal is opposed to the ray/sweep direction. This is always
// what we want except when we hit a single-sided back face with 'meshBothSides' enabled.
if(!meshBothSides || isDoubleSided)
return false;
PX_ASSERT(normal.dot(dir) <= 0.0f); // PT: if this fails, the logic below cannot be applied
PX_UNUSED(normal);
return triangleNormal.dot(dir) > 0.0f; // PT: true for back-facing hits
}
PX_FORCE_INLINE bool shouldFlipNormal(const PxVec3& normal, bool meshBothSides, bool isDoubleSided, const PxTriangle& triangle, const PxVec3& dir, const PxTransform* pose)
{
// PT: this function assumes that input normal is opposed to the ray/sweep direction. This is always
// what we want except when we hit a single-sided back face with 'meshBothSides' enabled.
if(!meshBothSides || isDoubleSided)
return false;
PX_ASSERT(normal.dot(dir) <= 0.0f); // PT: if this fails, the logic below cannot be applied
PX_UNUSED(normal);
PxVec3 triangleNormal;
triangle.denormalizedNormal(triangleNormal);
if(pose)
triangleNormal = pose->rotate(triangleNormal);
return triangleNormal.dot(dir) > 0.0f; // PT: true for back-facing hits
}
// PT: implements the spec for IO sweeps in a single place (to ensure consistency)
PX_FORCE_INLINE bool setInitialOverlapResults(PxGeomSweepHit& hit, const PxVec3& unitDir, PxU32 faceIndex)
{
// PT: please write these fields in the order they are listed in the struct.
hit.faceIndex = faceIndex;
hit.flags = PxHitFlag::eNORMAL|PxHitFlag::eFACE_INDEX;
hit.normal = -unitDir;
hit.distance = 0.0f;
return true; // PT: true indicates a hit, saves some lines in calling code
}
PX_FORCE_INLINE void computeBoxLocalImpact( PxVec3& pos, PxVec3& normal, PxHitFlags& outFlags,
const Box& box, const PxVec3& localDir, const PxTriangle& triInBoxSpace,
const PxHitFlags inFlags, bool isDoubleSided, bool meshBothSides, PxReal impactDist)
{
if(inFlags & (PxHitFlag::eNORMAL|PxHitFlag::ePOSITION))
{
PxVec3 localPos, localNormal;
computeBoxTriImpactData(localPos, localNormal, box.extents, localDir, triInBoxSpace, impactDist);
if(inFlags & PxHitFlag::eNORMAL)
{
localNormal.normalize();
// PT: doing this after the 'rotate' minimizes errors when normal and dir are close to perpendicular
// ....but we must do it before the rotate now, because triangleNormal is in box space (and thus we
// need the normal with the proper orientation, in box space. We can't fix it after it's been rotated
// to box space.
// Technically this one is only here because of the EE cross product in the feature-based sweep.
// PT: TODO: revisit corresponding code in computeImpactData, get rid of ambiguity
// PT: TODO: this may not be needed anymore
if((localNormal.dot(localDir))>0.0f)
localNormal = -localNormal;
// PT: this one is to ensure the normal respects the mesh-both-sides/double-sided convention
if(shouldFlipNormal(localNormal, meshBothSides, isDoubleSided, triInBoxSpace, localDir, NULL))
localNormal = -localNormal;
normal = box.rotate(localNormal);
outFlags |= PxHitFlag::eNORMAL;
}
if(inFlags & PxHitFlag::ePOSITION)
{
pos = box.transform(localPos);
outFlags |= PxHitFlag::ePOSITION;
}
}
}
} // namespace Gu
}
#endif
| 13,699 | C | 39.532544 | 172 | 0.703555 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/sweep/GuSweepBoxTriangle_SAT.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 "GuSweepBoxTriangle_SAT.h"
using namespace physx;
using namespace Gu;
// PT: SAT-based version, in box space
int Gu::triBoxSweepTestBoxSpace(const PxTriangle& tri, const PxVec3& extents, const PxVec3& dir, const PxVec3& oneOverDir, float tmax, float& toi, bool doBackfaceCulling)
{
return triBoxSweepTestBoxSpace_inlined(tri, extents, dir, oneOverDir, tmax, toi, PxU32(doBackfaceCulling));
}
| 2,102 | C++ | 52.923076 | 170 | 0.769267 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexPolygonsBuilder.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_COOKING_CONVEX_POLYGONS_BUILDER_H
#define GU_COOKING_CONVEX_POLYGONS_BUILDER_H
#include "GuCookingConvexHullBuilder.h"
#include "GuTriangle.h"
namespace physx
{
//////////////////////////////////////////////////////////////////////////
// extended convex hull builder for a case where we build polygons from input triangles
class ConvexPolygonsBuilder : public ConvexHullBuilder
{
public:
ConvexPolygonsBuilder(Gu::ConvexHullData* hull, const bool buildGRBData);
~ConvexPolygonsBuilder();
bool computeHullPolygons(const PxU32& nbVerts,const PxVec3* verts, const PxU32& nbTriangles, const PxU32* triangles);
PX_FORCE_INLINE PxU32 getNbFaces()const { return mNbHullFaces; }
PX_FORCE_INLINE const Gu::IndexedTriangle32* getFaces() const { return mFaces; }
private:
bool createPolygonData();
bool createTrianglesFromPolygons();
PxU32 mNbHullFaces; //!< Number of faces in the convex hull
Gu::IndexedTriangle32* mFaces; //!< Triangles.
};
}
#endif
| 2,768 | C | 43.66129 | 129 | 0.723266 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingTetrahedronMesh.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.
#ifndef GU_COOKING_TETRAHEDRON_MESH_H
#define GU_COOKING_TETRAHEDRON_MESH_H
#include "cooking/PxCooking.h"
#include "GuMeshData.h"
namespace physx
{
class TetrahedronMeshBuilder
{
PX_NOCOPY(TetrahedronMeshBuilder)
public:
static bool loadFromDesc(const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
PxSoftBodySimulationDataDesc softbodyDataDesc, Gu::TetrahedronMeshData& simulationMesh, Gu::SoftBodySimulationData& simulationData,
Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData, Gu::CollisionMeshMappingData& mappingData, const PxCookingParams& params, bool validateMesh = false);
static bool saveTetrahedronMeshData(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params,
const Gu::TetrahedronMeshData& mesh);
static bool saveSoftBodyMeshData(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params,
const Gu::TetrahedronMeshData& simulationMesh, const Gu::SoftBodySimulationData& simulationData, const Gu::TetrahedronMeshData& collisionMesh,
const Gu::SoftBodyCollisionData& collisionData, const Gu::CollisionMeshMappingData& mappingData);
//PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH34; }
static bool createMidPhaseStructure(Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData, const PxCookingParams& params);
static void saveMidPhaseStructure(PxOutputStream& stream, bool mismatch, const Gu::SoftBodyCollisionData& collisionData);
static void computeTetData(const PxTetrahedronMeshDesc& desc, Gu::TetrahedronMeshData& mesh);
static bool createGRBMidPhaseAndData(const PxU32 originalTriangleCount, Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData, const PxCookingParams& params);
static void computeSimData(const PxTetrahedronMeshDesc& desc, Gu::TetrahedronMeshData& simulationMesh, Gu::SoftBodySimulationData& simulationData, const PxCookingParams& params);
static void computeModelsMapping(Gu::TetrahedronMeshData& simulationMesh, const Gu::TetrahedronMeshData& collisionMesh, const Gu::SoftBodyCollisionData& collisionData,
Gu::CollisionMeshMappingData& mappingData, bool buildGPUData, const PxBoundedData* vertexToTet);
static void createCollisionModelMapping(const Gu::TetrahedronMeshData& collisionMesh, const Gu::SoftBodyCollisionData& collisionData, Gu::CollisionMeshMappingData& mappingData);
static void recordTetrahedronIndices(const Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData, bool buildGPUData);
static bool importMesh(const PxTetrahedronMeshDesc& collisionMeshDesc, const PxCookingParams& params,
Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData, bool validate = false);
static bool computeCollisionData(const PxTetrahedronMeshDesc& collisionMeshDesc, Gu::TetrahedronMeshData& collisionMesh, Gu::SoftBodyCollisionData& collisionData,
const PxCookingParams& params, bool validateMesh = false);
};
class BV32TetrahedronMeshBuilder
{
public:
static bool createMidPhaseStructure(const PxCookingParams& params, Gu::TetrahedronMeshData& meshData, Gu::BV32Tree& bv32Tree, Gu::SoftBodyCollisionData& collisionData);
static void saveMidPhaseStructure(Gu::BV32Tree* tree, PxOutputStream& stream, bool mismatch);
};
}
#endif
| 5,021 | C | 63.384615 | 191 | 0.799442 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexMesh.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 "GuCooking.h"
#include "GuCookingConvexMeshBuilder.h"
#include "GuCookingQuickHullConvexHullLib.h"
#include "GuConvexMesh.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxFPU.h"
#include "common/PxInsertionCallback.h"
using namespace physx;
using namespace Gu;
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
// cook convex mesh from given desc, internal function to be shared between create/cook convex mesh
static bool cookConvexMeshInternal(const PxCookingParams& params, const PxConvexMeshDesc& desc_, ConvexMeshBuilder& meshBuilder, ConvexHullLib* hullLib, PxConvexMeshCookingResult::Enum* condition)
{
if(condition)
*condition = PxConvexMeshCookingResult::eFAILURE;
if(!desc_.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Cooking::cookConvexMesh: user-provided convex mesh descriptor is invalid!");
if(params.areaTestEpsilon <= 0.0f)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Cooking::cookConvexMesh: provided cooking parameter areaTestEpsilon is invalid!");
if(params.planeTolerance < 0.0f)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Cooking::cookConvexMesh: provided cooking parameter planeTolerance is invalid!");
PxConvexMeshDesc desc = desc_;
bool polygonsLimitReached = false;
// the convex will be cooked from provided points
if(desc_.flags & PxConvexFlag::eCOMPUTE_CONVEX)
{
PX_ASSERT(hullLib);
// clean up the indices information, it could have been set by accident
desc.flags &= ~PxConvexFlag::e16_BIT_INDICES;
desc.indices.count = 0;
desc.indices.data = NULL;
desc.indices.stride = 0;
desc.polygons.count = 0;
desc.polygons.data = NULL;
desc.polygons.stride = 0;
PxConvexMeshCookingResult::Enum res = hullLib->createConvexHull();
if(res == PxConvexMeshCookingResult::eSUCCESS || res == PxConvexMeshCookingResult::ePOLYGONS_LIMIT_REACHED)
{
if(res == PxConvexMeshCookingResult::ePOLYGONS_LIMIT_REACHED)
polygonsLimitReached = true;
hullLib->fillConvexMeshDesc(desc);
}
else
{
if((res == PxConvexMeshCookingResult::eZERO_AREA_TEST_FAILED) && condition)
{
*condition = PxConvexMeshCookingResult::eZERO_AREA_TEST_FAILED;
}
return false;
}
}
if(desc.points.count >= 256)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: user-provided hull must have less than 256 vertices!");
if(desc.polygons.count >= 256)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: user-provided hull must have less than 256 faces!");
if ((desc.flags & PxConvexFlag::eGPU_COMPATIBLE) || params.buildGPUData)
{
if (desc.points.count > 64)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: GPU-compatible user-provided hull must have less than 65 vertices!");
if (desc.polygons.count > 64)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: GPU-compatible user-provided hull must have less than 65 faces!");
}
if(!meshBuilder.build(desc, params.gaussMapLimit, false, hullLib))
return false;
PxConvexMeshCookingResult::Enum result = PxConvexMeshCookingResult::eSUCCESS;
if (polygonsLimitReached)
result = PxConvexMeshCookingResult::ePOLYGONS_LIMIT_REACHED;
// AD: we check this outside of the actual convex cooking because we can still cook a valid convex hull
// but we won't be able to use it on GPU.
if (((desc.flags & PxConvexFlag::eGPU_COMPATIBLE) || params.buildGPUData) && !meshBuilder.checkExtentRadiusRatio())
{
result = PxConvexMeshCookingResult::eNON_GPU_COMPATIBLE;
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Cooking::cookConvexMesh: GPU-compatible convex hull could not be built because of oblong shape. Will fall back to CPU collision, particles and deformables will not collide with this mesh!");
}
if(condition)
*condition = result;
return true;
}
static ConvexHullLib* createHullLib(PxConvexMeshDesc& desc, const PxCookingParams& params)
{
if(desc.flags & PxConvexFlag::eCOMPUTE_CONVEX)
{
const PxU16 gpuMaxVertsLimit = 64;
const PxU16 gpuMaxFacesLimit = 64;
// GRB supports 64 verts max
if((desc.flags & PxConvexFlag::eGPU_COMPATIBLE) || params.buildGPUData)
{
desc.vertexLimit = PxMin(desc.vertexLimit, gpuMaxVertsLimit);
desc.polygonLimit = PxMin(desc.polygonLimit, gpuMaxFacesLimit);
}
return PX_NEW(QuickHullConvexHullLib) (desc, params);
}
return NULL;
}
bool immediateCooking::cookConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc_, PxOutputStream& stream, PxConvexMeshCookingResult::Enum* condition)
{
PX_FPU_GUARD;
// choose cooking library if needed
PxConvexMeshDesc desc = desc_;
ConvexHullLib* hullLib = createHullLib(desc, params);
ConvexMeshBuilder meshBuilder(params.buildGPUData);
if(!cookConvexMeshInternal(params, desc, meshBuilder, hullLib, condition))
{
PX_DELETE(hullLib);
return false;
}
// save the cooked results into stream
if(!meshBuilder.save(stream, platformMismatch()))
{
if(condition)
*condition = PxConvexMeshCookingResult::eFAILURE;
PX_DELETE(hullLib);
return false;
}
PX_DELETE(hullLib);
return true;
}
PxConvexMesh* immediateCooking::createConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc_, PxInsertionCallback& insertionCallback, PxConvexMeshCookingResult::Enum* condition)
{
PX_FPU_GUARD;
// choose cooking library if needed
PxConvexMeshDesc desc = desc_;
ConvexHullLib* hullLib = createHullLib(desc, params);
// cook the mesh
ConvexMeshBuilder meshBuilder(params.buildGPUData);
if(!cookConvexMeshInternal(params, desc, meshBuilder, hullLib, condition))
{
PX_DELETE(hullLib);
return NULL;
}
// copy the constructed data into the new mesh
ConvexHullInitData meshData;
meshBuilder.copy(meshData);
// insert into physics
PxConvexMesh* convexMesh = static_cast<PxConvexMesh*>(insertionCallback.buildObjectFromData(PxConcreteType::eCONVEX_MESH, &meshData));
if(!convexMesh)
{
if(condition)
*condition = PxConvexMeshCookingResult::eFAILURE;
PX_DELETE(hullLib);
return NULL;
}
PX_DELETE(hullLib);
return convexMesh;
}
bool immediateCooking::validateConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc)
{
ConvexMeshBuilder mesh(params.buildGPUData);
return mesh.build(desc, params.gaussMapLimit, true);
}
bool immediateCooking::computeHullPolygons(const PxCookingParams& params, const PxSimpleTriangleMesh& mesh, PxAllocatorCallback& inCallback, PxU32& nbVerts, PxVec3*& vertices,
PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& hullPolygons)
{
PxVec3* geometry = reinterpret_cast<PxVec3*>(PxAlloca(sizeof(PxVec3)*mesh.points.count));
immediateCooking::gatherStrided(mesh.points.data, geometry, mesh.points.count, sizeof(PxVec3), mesh.points.stride);
PxU32* topology = reinterpret_cast<PxU32*>(PxAlloca(sizeof(PxU32)*3*mesh.triangles.count));
if(mesh.flags & PxMeshFlag::e16_BIT_INDICES)
{
// conversion; 16 bit index -> 32 bit index & stride
PxU32* dest = topology;
const PxU32* pastLastDest = topology + 3*mesh.triangles.count;
const PxU8* source = reinterpret_cast<const PxU8*>(mesh.triangles.data);
while (dest < pastLastDest)
{
const PxU16 * trig16 = reinterpret_cast<const PxU16*>(source);
*dest++ = trig16[0];
*dest++ = trig16[1];
*dest++ = trig16[2];
source += mesh.triangles.stride;
}
}
else
{
immediateCooking::gatherStrided(mesh.triangles.data, topology, mesh.triangles.count, sizeof(PxU32) * 3, mesh.triangles.stride);
}
ConvexMeshBuilder meshBuilder(params.buildGPUData);
if(!meshBuilder.computeHullPolygons(mesh.points.count, geometry, mesh.triangles.count, topology, inCallback, nbVerts, vertices, nbIndices, indices, nbPolygons, hullPolygons))
return false;
return true;
}
| 9,695 | C++ | 37.023529 | 244 | 0.744714 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingGrbTriangleMesh.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_COOKING_GRB_TRIANGLE_MESH_H
#define GU_COOKING_GRB_TRIANGLE_MESH_H
#include "foundation/PxPlane.h"
#include "foundation/PxSort.h"
#include "GuMeshData.h"
#include "GuTriangle.h"
#include "GuEdgeList.h"
#include "cooking/PxCooking.h"
#include "CmRadixSort.h"
//#define CHECK_OLD_CODE_VS_NEW_CODE
namespace physx
{
namespace Gu
{
PX_ALIGN_PREFIX(16)
struct uint4
{
unsigned int x, y, z, w;
}
PX_ALIGN_SUFFIX(16);
// TODO avoroshilov: remove duplicate definitions
static const PxU32 BOUNDARY = 0xffffffff;
static const PxU32 NONCONVEX_FLAG = 0x80000000;
#ifdef CHECK_OLD_CODE_VS_NEW_CODE
struct EdgeTriLookup
{
PxU32 edgeId0, edgeId1;
PxU32 triId;
bool operator < (const EdgeTriLookup& edge1) const
{
return edgeId0 < edge1.edgeId0 || (edgeId0 == edge1.edgeId0 && edgeId1 < edge1.edgeId1);
}
bool operator <=(const EdgeTriLookup& edge1) const
{
return edgeId0 < edge1.edgeId0 || (edgeId0 == edge1.edgeId0 && edgeId1 <= edge1.edgeId1);
}
};
static PxU32 binarySearch(const EdgeTriLookup* __restrict data, const PxU32 numElements, const EdgeTriLookup& value)
{
PxU32 left = 0;
PxU32 right = numElements;
while ((right - left) > 1)
{
const PxU32 pos = (left + right) / 2;
const EdgeTriLookup& element = data[pos];
if (element <= value)
{
left = pos;
}
else
{
right = pos;
}
}
return left;
}
// slightly different behavior from collide2: boundary edges are filtered out
static PxU32 findAdjacent(const PxVec3* triVertices, const PxVec3* triNormals, const IndexedTriangle32* triIndices,
PxU32 nbTris, PxU32 i0, PxU32 i1, const PxPlane& plane,
EdgeTriLookup* triLookups, PxU32 triangleIndex)
{
PxU32 result = BOUNDARY;
PxReal bestCos = -FLT_MAX;
EdgeTriLookup lookup;
lookup.edgeId0 = PxMin(i0, i1);
lookup.edgeId1 = PxMax(i0, i1);
PxU32 startIndex = binarySearch(triLookups, nbTris * 3, lookup);
for (PxU32 a = startIndex; a > 0; --a)
{
if (triLookups[a - 1].edgeId0 == lookup.edgeId0 && triLookups[a - 1].edgeId1 == lookup.edgeId1)
startIndex = a - 1;
else
break;
}
for (PxU32 a = startIndex; a < nbTris * 3; ++a)
{
const EdgeTriLookup& edgeTri = triLookups[a];
if (edgeTri.edgeId0 != lookup.edgeId0 || edgeTri.edgeId1 != lookup.edgeId1)
break;
if (edgeTri.triId == triangleIndex)
continue;
const IndexedTriangle32& triIdx = triIndices[edgeTri.triId];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
const PxU32 other = vIdx0 + vIdx1 + vIdx2 - (i0 + i1);
const PxReal c = plane.n.dot(triNormals[edgeTri.triId]);
if (plane.distance(triVertices[other]) >= 0 && c > 0.f)
return NONCONVEX_FLAG | edgeTri.triId;
if (c>bestCos)
{
bestCos = c;
result = edgeTri.triId;
}
}
return result;
}
#endif
static PxU32 findAdjacent(const PxVec3* triVertices, const PxVec3* triNormals, const IndexedTriangle32* triIndices, const PxU32* faceByEdge, PxU32 nbTris, PxU32 i0, PxU32 i1, const PxPlane& plane, PxU32 triangleIndex)
{
PxU32 result = BOUNDARY;
PxReal bestCos = -FLT_MAX;
for(PxU32 i=0; i<nbTris; i++)
{
const PxU32 candidateTriIndex = faceByEdge[i];
if(triangleIndex==candidateTriIndex)
continue;
const IndexedTriangle32& triIdx = triIndices[candidateTriIndex];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
const PxU32 other = vIdx0 + vIdx1 + vIdx2 - (i0 + i1);
const PxReal c = plane.n.dot(triNormals[candidateTriIndex]);
if(plane.distance(triVertices[other]) >= 0 && c > 0.f)
return NONCONVEX_FLAG | candidateTriIndex;
if(c>bestCos)
{
bestCos = c;
result = candidateTriIndex;
}
}
return result;
}
static void buildAdjacencies(uint4* triAdjacencies, PxVec3* tempNormalsPerTri_prealloc, const PxVec3* triVertices, const IndexedTriangle32* triIndices, PxU32 nbTris)
{
#ifdef CHECK_OLD_CODE_VS_NEW_CODE
{
EdgeTriLookup* edgeLookups = PX_ALLOCATE(EdgeTriLookup, (nbTris * 3), "edgeLookups");
for (PxU32 i = 0; i < nbTris; i++)
{
const IndexedTriangle32& triIdx = triIndices[i];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
tempNormalsPerTri_prealloc[i] = (triVertices[vIdx1] - triVertices[vIdx0]).cross(triVertices[vIdx2] - triVertices[vIdx0]).getNormalized();
edgeLookups[i * 3].edgeId0 = PxMin(vIdx0, vIdx1);
edgeLookups[i * 3].edgeId1 = PxMax(vIdx0, vIdx1);
edgeLookups[i * 3].triId = i;
edgeLookups[i * 3 + 1].edgeId0 = PxMin(vIdx1, vIdx2);
edgeLookups[i * 3 + 1].edgeId1 = PxMax(vIdx1, vIdx2);
edgeLookups[i * 3 + 1].triId = i;
edgeLookups[i * 3 + 2].edgeId0 = PxMin(vIdx0, vIdx2);
edgeLookups[i * 3 + 2].edgeId1 = PxMax(vIdx0, vIdx2);
edgeLookups[i * 3 + 2].triId = i;
}
PxSort<EdgeTriLookup>(edgeLookups, PxU32(nbTris * 3));
for (PxU32 i = 0; i < nbTris; i++)
{
const IndexedTriangle32& triIdx = triIndices[i];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
const PxPlane triPlane(triVertices[vIdx0], tempNormalsPerTri_prealloc[i]);
uint4 triAdjIdx;
triAdjIdx.x = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, nbTris, vIdx0, vIdx1, triPlane, edgeLookups, i);
triAdjIdx.y = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, nbTris, vIdx1, vIdx2, triPlane, edgeLookups, i);
triAdjIdx.z = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, nbTris, vIdx2, vIdx0, triPlane, edgeLookups, i);
triAdjIdx.w = 0;
triAdjacencies[i] = triAdjIdx;
}
PX_FREE(edgeLookups);
}
#endif
if(1)
{
EDGELISTCREATE create;
create.NbFaces = nbTris;
create.DFaces = triIndices->mRef;
create.WFaces = NULL;
create.FacesToEdges = true;
create.EdgesToFaces = true;
// PT: important: do NOT set the vertices, it triggers computation of edge flags that we don't need
//create.Verts = triVertices;
EdgeList edgeList;
if(edgeList.init(create))
{
for(PxU32 i=0; i<nbTris; i++)
{
const IndexedTriangle32& triIdx = triIndices[i];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
tempNormalsPerTri_prealloc[i] = (triVertices[vIdx1] - triVertices[vIdx0]).cross(triVertices[vIdx2] - triVertices[vIdx0]).getNormalized();
}
const EdgeTriangleData* edgeTriangleData = edgeList.getEdgeTriangles();
const EdgeDescData* edgeToTriangle = edgeList.getEdgeToTriangles();
const PxU32* faceByEdge = edgeList.getFacesByEdges();
PX_ASSERT(edgeList.getNbFaces()==nbTris);
for(PxU32 i=0; i<nbTris; i++)
{
const IndexedTriangle32& triIdx = triIndices[i];
const PxU32 vIdx0 = triIdx.mRef[0];
const PxU32 vIdx1 = triIdx.mRef[1];
const PxU32 vIdx2 = triIdx.mRef[2];
const PxPlane triPlane(triVertices[vIdx0], tempNormalsPerTri_prealloc[i]);
const EdgeTriangleData& edgeTri = edgeTriangleData[i];
const EdgeDescData& edgeData0 = edgeToTriangle[edgeTri.mLink[0] & MSH_EDGE_LINK_MASK];
const EdgeDescData& edgeData1 = edgeToTriangle[edgeTri.mLink[1] & MSH_EDGE_LINK_MASK];
const EdgeDescData& edgeData2 = edgeToTriangle[edgeTri.mLink[2] & MSH_EDGE_LINK_MASK];
uint4 triAdjIdx;
triAdjIdx.x = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, faceByEdge + edgeData0.Offset, edgeData0.Count, vIdx0, vIdx1, triPlane, i);
triAdjIdx.y = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, faceByEdge + edgeData1.Offset, edgeData1.Count, vIdx1, vIdx2, triPlane, i);
triAdjIdx.z = findAdjacent(triVertices, tempNormalsPerTri_prealloc, triIndices, faceByEdge + edgeData2.Offset, edgeData2.Count, vIdx2, vIdx0, triPlane, i);
triAdjIdx.w = 0;
#ifdef CHECK_OLD_CODE_VS_NEW_CODE
PX_ASSERT(triAdjacencies[i].x == triAdjIdx.x);
PX_ASSERT(triAdjacencies[i].y == triAdjIdx.y);
PX_ASSERT(triAdjacencies[i].z == triAdjIdx.z);
#endif
triAdjacencies[i] = triAdjIdx;
}
}
}
}
}
}
#endif
| 9,740 | C | 31.254967 | 217 | 0.715708 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingHF.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 "GuCooking.h"
#include "GuHeightField.h"
#include "foundation/PxFPU.h"
#include "common/PxInsertionCallback.h"
#include "CmUtils.h"
using namespace physx;
using namespace Gu;
bool immediateCooking::cookHeightField(const PxHeightFieldDesc& desc, PxOutputStream& stream)
{
if(!desc.isValid())
return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Cooking::cookHeightField: user-provided heightfield descriptor is invalid!");
PX_FPU_GUARD;
HeightField hf(NULL);
if(!hf.loadFromDesc(desc))
{
hf.releaseMemory();
return false;
}
if(!hf.save(stream, platformMismatch()))
{
hf.releaseMemory();
return false;
}
hf.releaseMemory();
return true;
}
PxHeightField* immediateCooking::createHeightField(const PxHeightFieldDesc& desc, PxInsertionCallback& insertionCallback)
{
if(!desc.isValid())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Cooking::createHeightField: user-provided heightfield descriptor is invalid!");
return NULL;
}
PX_FPU_GUARD;
HeightField* hf;
PX_NEW_SERIALIZED(hf, HeightField)(NULL);
if(!hf->loadFromDesc(desc))
{
PX_DELETE(hf);
return NULL;
}
// create heightfield and set the HF data
HeightField* heightField = static_cast<HeightField*>(insertionCallback.buildObjectFromData(PxConcreteType::eHEIGHTFIELD, &hf->mData));
if(!heightField)
{
PX_DELETE(hf);
return NULL;
}
// copy the HeightField variables
heightField->mSampleStride = hf->mSampleStride;
heightField->mNbSamples = hf->mNbSamples;
heightField->mMinHeight = hf->mMinHeight;
heightField->mMaxHeight = hf->mMaxHeight;
heightField->mModifyCount = hf->mModifyCount;
PX_DELETE(hf);
return heightField;
}
| 3,394 | C++ | 32.613861 | 151 | 0.755745 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingBVH.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 "GuCooking.h"
#include "GuBVH.h"
#include "foundation/PxFPU.h"
#include "cooking/PxBVHDesc.h"
#include "common/PxInsertionCallback.h"
using namespace physx;
using namespace Gu;
static bool buildBVH(const PxBVHDesc& desc, BVHData& data, const char* errorMessage)
{
if(!desc.isValid())
return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, errorMessage);
BVHBuildStrategy bs;
if(desc.buildStrategy==PxBVHBuildStrategy::eFAST)
bs = BVH_SPLATTER_POINTS;
else if(desc.buildStrategy==PxBVHBuildStrategy::eDEFAULT)
bs = BVH_SPLATTER_POINTS_SPLIT_GEOM_CENTER;
else //if(desc.buildStrategy==PxBVHBuildStrategy::eSAH)
bs = BVH_SAH;
return data.build(desc.bounds.count, desc.bounds.data, desc.bounds.stride, desc.enlargement, desc.numPrimsPerLeaf, bs);
}
bool immediateCooking::cookBVH(const PxBVHDesc& desc, PxOutputStream& stream)
{
PX_FPU_GUARD;
BVHData bvhData;
if(!buildBVH(desc, bvhData, "Cooking::cookBVH: user-provided BVH descriptor is invalid!"))
return false;
return bvhData.save(stream, platformMismatch());
}
PxBVH* immediateCooking::createBVH(const PxBVHDesc& desc, PxInsertionCallback& insertionCallback)
{
PX_FPU_GUARD;
BVHData bvhData;
if(!buildBVH(desc, bvhData, "Cooking::createBVH: user-provided BVH descriptor is invalid!"))
return NULL;
return static_cast<PxBVH*>(insertionCallback.buildObjectFromData(PxConcreteType::eBVH, &bvhData));
}
| 3,110 | C++ | 39.93421 | 120 | 0.767524 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingBigConvexDataBuilder.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_COOKING_BIG_CONVEX_DATA_BUILDER_H
#define GU_COOKING_BIG_CONVEX_DATA_BUILDER_H
#include "foundation/PxMemory.h"
#include "foundation/PxVecMath.h"
namespace physx
{
class BigConvexData;
class ConvexHullBuilder;
class BigConvexDataBuilder : public PxUserAllocated
{
public:
BigConvexDataBuilder(const Gu::ConvexHullData* hull, BigConvexData* gm, const PxVec3* hullVerts);
~BigConvexDataBuilder();
// Support vertex map
bool precompute(PxU32 subdiv);
bool initialize();
bool save(PxOutputStream& stream, bool platformMismatch) const;
bool computeValencies(const ConvexHullBuilder& meshBuilder);
//~Support vertex map
// Valencies
bool saveValencies(PxOutputStream& stream, bool platformMismatch) const;
//~Valencies
protected:
PX_FORCE_INLINE void precomputeSample(const PxVec3& dir, PxU8& startIndex, float negativeDir);
private:
const Gu::ConvexHullData* mHull;
BigConvexData* mSVM;
const PxVec3* mHullVerts;
};
}
#endif // BIG_CONVEX_DATA_BUILDER_H
| 2,761 | C | 37.901408 | 106 | 0.750453 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingVolumeIntegration.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_COOKING_VOLUME_INTEGRATION_H
#define GU_COOKING_VOLUME_INTEGRATION_H
/** \addtogroup foundation
@{
*/
#include "foundation/Px.h"
#include "foundation/PxVec3.h"
#include "foundation/PxMat33.h"
namespace physx
{
class PxSimpleTriangleMesh;
class PxConvexMeshDesc;
/**
\brief Data structure used to store mass properties.
*/
struct PxIntegrals
{
PxVec3 COM; //!< Center of mass
PxF64 mass; //!< Total mass
PxF64 inertiaTensor[3][3]; //!< Inertia tensor (mass matrix) relative to the origin
PxF64 COMInertiaTensor[3][3]; //!< Inertia tensor (mass matrix) relative to the COM
/**
\brief Retrieve the inertia tensor relative to the center of mass.
\param inertia Inertia tensor.
*/
void getInertia(PxMat33& inertia)
{
for(PxU32 j=0;j<3;j++)
{
for(PxU32 i=0;i<3;i++)
{
inertia(i,j) = PxF32(COMInertiaTensor[i][j]);
}
}
}
/**
\brief Retrieve the inertia tensor relative to the origin.
\param inertia Inertia tensor.
*/
void getOriginInertia(PxMat33& inertia)
{
for(PxU32 j=0;j<3;j++)
{
for(PxU32 i=0;i<3;i++)
{
inertia(i,j) = PxF32(inertiaTensor[i][j]);
}
}
}
};
bool computeVolumeIntegrals(const PxSimpleTriangleMesh& mesh, PxReal density, PxIntegrals& integrals);
// specialized method taking polygons directly, so we don't need to compute and store triangles for each polygon
bool computeVolumeIntegralsEberly(const PxConvexMeshDesc& mesh, PxReal density, PxIntegrals& integrals, const PxVec3& origin, bool useSimd); // Eberly simplified method
}
/** @} */
#endif
| 3,254 | C | 33.263158 | 171 | 0.734481 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingVolumeIntegration.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.
/*
* This code computes volume integrals needed to compute mass properties of polyhedral bodies.
* Based on public domain code by Brian Mirtich.
*/
#include "foundation/PxMemory.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "cooking/PxConvexMeshDesc.h"
#include "GuCookingVolumeIntegration.h"
#include "GuConvexMeshData.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVecMath.h"
// PT: code archeology: this initially came from ICE (IceVolumeIntegration.h/cpp). Consider revisiting.
namespace physx
{
using namespace aos;
namespace
{
class VolumeIntegrator
{
PX_NOCOPY(VolumeIntegrator)
public:
VolumeIntegrator(const PxSimpleTriangleMesh& mesh, PxF64 density) : mMass(0.0), mDensity(density), mMesh(mesh) {}
~VolumeIntegrator() {}
bool computeVolumeIntegrals(PxIntegrals& ir);
private:
struct Normal
{
PxVec3 normal;
PxF32 w;
};
struct Face
{
PxF64 Norm[3];
PxF64 w;
PxU32 Verts[3];
};
// Data structures
PxF64 mMass; //!< Mass
PxF64 mDensity; //!< Density
const PxSimpleTriangleMesh& mMesh;
PxU32 mA; //!< Alpha
PxU32 mB; //!< Beta
PxU32 mC; //!< Gamma
// Projection integrals
PxF64 mP1;
PxF64 mPa; //!< Pi Alpha
PxF64 mPb; //!< Pi Beta
PxF64 mPaa; //!< Pi Alpha^2
PxF64 mPab; //!< Pi AlphaBeta
PxF64 mPbb; //!< Pi Beta^2
PxF64 mPaaa; //!< Pi Alpha^3
PxF64 mPaab; //!< Pi Alpha^2Beta
PxF64 mPabb; //!< Pi AlphaBeta^2
PxF64 mPbbb; //!< Pi Beta^3
// Face integrals
PxF64 mFa; //!< FAlpha
PxF64 mFb; //!< FBeta
PxF64 mFc; //!< FGamma
PxF64 mFaa; //!< FAlpha^2
PxF64 mFbb; //!< FBeta^2
PxF64 mFcc; //!< FGamma^2
PxF64 mFaaa; //!< FAlpha^3
PxF64 mFbbb; //!< FBeta^3
PxF64 mFccc; //!< FGamma^3
PxF64 mFaab; //!< FAlpha^2Beta
PxF64 mFbbc; //!< FBeta^2Gamma
PxF64 mFcca; //!< FGamma^2Alpha
// The 10 volume integrals
PxF64 mT0; //!< ~Total mass
PxF64 mT1[3]; //!< Location of the center of mass
PxF64 mT2[3]; //!< Moments of inertia
PxF64 mTP[3]; //!< Products of inertia
// Internal methods
// bool Init();
PxVec3 computeCenterOfMass();
void computeInertiaTensor(PxF64* J);
void computeCOMInertiaTensor(PxF64* J);
void computeFaceNormal(Face & f, PxU32 * indices);
void computeProjectionIntegrals(const Face& f);
void computeFaceIntegrals(const Face& f);
};
#define X 0u
#define Y 1u
#define Z 2u
void VolumeIntegrator::computeFaceNormal(Face & f, PxU32 * indices)
{
const PxU8 * vertPointer = reinterpret_cast<const PxU8*>(mMesh.points.data);
const PxU32 stride = mMesh.points.stride;
//two edges
const PxVec3 d1 = (*reinterpret_cast<const PxVec3 *>(vertPointer + stride * indices[1] )) - (*reinterpret_cast<const PxVec3 *>(vertPointer + stride * indices[0] ));
const PxVec3 d2 = (*reinterpret_cast<const PxVec3 *>(vertPointer + stride * indices[2] )) - (*reinterpret_cast<const PxVec3 *>(vertPointer + stride * indices[1] ));
PxVec3 normal = d1.cross(d2);
normal.normalizeSafe();
f.w = - PxF64(normal.dot((*reinterpret_cast<const PxVec3 *>(vertPointer + stride * indices[0] )) ));
f.Norm[0] = PxF64(normal.x);
f.Norm[1] = PxF64(normal.y);
f.Norm[2] = PxF64(normal.z);
}
/**
* Computes volume integrals for a polyhedron by summing surface integrals over its faces.
* \param ir [out] a result structure.
* \return true if success
*/
bool VolumeIntegrator::computeVolumeIntegrals(PxIntegrals& ir)
{
// Clear all integrals
mT0 = mT1[X] = mT1[Y] = mT1[Z] = mT2[X] = mT2[Y] = mT2[Z] = mTP[X] = mTP[Y] = mTP[Z] = 0;
Face f;
const PxU8* trigPointer = reinterpret_cast<const PxU8*>(mMesh.triangles.data);
const PxU32 nbTris = mMesh.triangles.count;
const PxU32 stride = mMesh.triangles.stride;
for(PxU32 i=0;i<nbTris;i++, trigPointer += stride)
{
if (mMesh.flags & PxMeshFlag::e16_BIT_INDICES)
{
f.Verts[0] = (reinterpret_cast<const PxU16 *>(trigPointer))[0];
f.Verts[1] = (reinterpret_cast<const PxU16 *>(trigPointer))[1];
f.Verts[2] = (reinterpret_cast<const PxU16 *>(trigPointer))[2];
}
else
{
f.Verts[0] = (reinterpret_cast<const PxU32 *>(trigPointer)[0]);
f.Verts[1] = (reinterpret_cast<const PxU32 *>(trigPointer)[1]);
f.Verts[2] = (reinterpret_cast<const PxU32 *>(trigPointer)[2]);
}
if (mMesh.flags & PxMeshFlag::eFLIPNORMALS)
{
PxU32 t = f.Verts[1];
f.Verts[1] = f.Verts[2];
f.Verts[2] = t;
}
//compute face normal:
computeFaceNormal(f,f.Verts);
if(f.Norm[X] * f.Norm[X] + f.Norm[Y] * f.Norm[Y] + f.Norm[Z] * f.Norm[Z] < 1e-20)
continue;
// Compute alpha/beta/gamma as the right-handed permutation of (x,y,z) that maximizes |n|
const PxF64 nx = fabs(f.Norm[X]);
const PxF64 ny = fabs(f.Norm[Y]);
const PxF64 nz = fabs(f.Norm[Z]);
if (nx > ny && nx > nz) mC = X;
else mC = (ny > nz) ? Y : Z;
mA = (mC + 1) % 3;
mB = (mA + 1) % 3;
// Compute face contribution
computeFaceIntegrals(f);
// Update integrals
mT0 += f.Norm[X] * ((mA == X) ? mFa : ((mB == X) ? mFb : mFc));
mT1[mA] += f.Norm[mA] * mFaa;
mT1[mB] += f.Norm[mB] * mFbb;
mT1[mC] += f.Norm[mC] * mFcc;
mT2[mA] += f.Norm[mA] * mFaaa;
mT2[mB] += f.Norm[mB] * mFbbb;
mT2[mC] += f.Norm[mC] * mFccc;
mTP[mA] += f.Norm[mA] * mFaab;
mTP[mB] += f.Norm[mB] * mFbbc;
mTP[mC] += f.Norm[mC] * mFcca;
}
mT1[X] /= 2; mT1[Y] /= 2; mT1[Z] /= 2;
mT2[X] /= 3; mT2[Y] /= 3; mT2[Z] /= 3;
mTP[X] /= 2; mTP[Y] /= 2; mTP[Z] /= 2;
// Fill result structure
ir.COM = computeCenterOfMass();
computeInertiaTensor(reinterpret_cast<PxF64*>(ir.inertiaTensor));
computeCOMInertiaTensor(reinterpret_cast<PxF64*>(ir.COMInertiaTensor));
ir.mass = mMass;
return true;
}
/**
* Computes the center of mass.
* \return The center of mass.
*/
PxVec3 VolumeIntegrator::computeCenterOfMass()
{
// Compute center of mass
PxVec3 COM(0.0f);
if(mT0!=0.0)
{
COM.x = float(mT1[X] / mT0);
COM.y = float(mT1[Y] / mT0);
COM.z = float(mT1[Z] / mT0);
}
return COM;
}
/**
* Setups the inertia tensor relative to the origin.
* \param it [out] the returned inertia tensor.
*/
void VolumeIntegrator::computeInertiaTensor(PxF64* it)
{
PxF64 J[3][3];
// Compute inertia tensor
J[X][X] = mDensity * (mT2[Y] + mT2[Z]);
J[Y][Y] = mDensity * (mT2[Z] + mT2[X]);
J[Z][Z] = mDensity * (mT2[X] + mT2[Y]);
J[X][Y] = J[Y][X] = - mDensity * mTP[X];
J[Y][Z] = J[Z][Y] = - mDensity * mTP[Y];
J[Z][X] = J[X][Z] = - mDensity * mTP[Z];
PxMemCopy(it, J, 9*sizeof(PxF64));
}
/**
* Setups the inertia tensor relative to the COM.
* \param it [out] the returned inertia tensor.
*/
void VolumeIntegrator::computeCOMInertiaTensor(PxF64* it)
{
PxF64 J[3][3];
mMass = mDensity * mT0;
const PxVec3 COM = computeCenterOfMass();
const PxVec3 MassCOM(PxF32(mMass) * COM);
const PxVec3 MassCOM2(MassCOM.x * COM.x, MassCOM.y * COM.y, MassCOM.z * COM.z);
// Compute initial inertia tensor
computeInertiaTensor(reinterpret_cast<PxF64*>(J));
// Translate inertia tensor to center of mass
// Huyghens' theorem:
// Jx'x' = Jxx - m*(YG^2+ZG^2)
// Jy'y' = Jyy - m*(ZG^2+XG^2)
// Jz'z' = Jzz - m*(XG^2+YG^2)
// XG, YG, ZG = new origin
// YG^2+ZG^2 = dx^2
J[X][X] -= PxF64(MassCOM2.y + MassCOM2.z);
J[Y][Y] -= PxF64(MassCOM2.z + MassCOM2.x);
J[Z][Z] -= PxF64(MassCOM2.x + MassCOM2.y);
// Huyghens' theorem:
// Jx'y' = Jxy - m*XG*YG
// Jy'z' = Jyz - m*YG*ZG
// Jz'x' = Jzx - m*ZG*XG
// ### IS THE SIGN CORRECT ?
J[X][Y] = J[Y][X] += PxF64(MassCOM.x * COM.y);
J[Y][Z] = J[Z][Y] += PxF64(MassCOM.y * COM.z);
J[Z][X] = J[X][Z] += PxF64(MassCOM.z * COM.x);
PxMemCopy(it, J, 9*sizeof(PxF64));
}
/**
* Computes integrals over a face projection from the coordinates of the projections vertices.
* \param f [in] a face structure.
*/
void VolumeIntegrator::computeProjectionIntegrals(const Face& f)
{
mP1 = mPa = mPb = mPaa = mPab = mPbb = mPaaa = mPaab = mPabb = mPbbb = 0.0;
const PxU8* vertPointer = reinterpret_cast<const PxU8*>(mMesh.points.data);
const PxU32 stride = mMesh.points.stride;
for(PxU32 i=0;i<3;i++)
{
const PxVec3& p0 = *reinterpret_cast<const PxVec3 *>(vertPointer + stride * (f.Verts[i]) );
const PxVec3& p1 = *reinterpret_cast<const PxVec3 *>(vertPointer + stride * (f.Verts[(i+1) % 3]) );
const PxF64 a0 = PxF64(p0[mA]);
const PxF64 b0 = PxF64(p0[mB]);
const PxF64 a1 = PxF64(p1[mA]);
const PxF64 b1 = PxF64(p1[mB]);
const PxF64 da = a1 - a0; // DeltaA
const PxF64 db = b1 - b0; // DeltaB
const PxF64 a0_2 = a0 * a0; // Alpha0^2
const PxF64 a0_3 = a0_2 * a0; // ...
const PxF64 a0_4 = a0_3 * a0;
const PxF64 b0_2 = b0 * b0;
const PxF64 b0_3 = b0_2 * b0;
const PxF64 b0_4 = b0_3 * b0;
const PxF64 a1_2 = a1 * a1;
const PxF64 a1_3 = a1_2 * a1;
const PxF64 b1_2 = b1 * b1;
const PxF64 b1_3 = b1_2 * b1;
const PxF64 C1 = a1 + a0;
const PxF64 Ca = a1*C1 + a0_2;
const PxF64 Caa = a1*Ca + a0_3;
const PxF64 Caaa = a1*Caa + a0_4;
const PxF64 Cb = b1*(b1 + b0) + b0_2;
const PxF64 Cbb = b1*Cb + b0_3;
const PxF64 Cbbb = b1*Cbb + b0_4;
const PxF64 Cab = 3*a1_2 + 2*a1*a0 + a0_2;
const PxF64 Kab = a1_2 + 2*a1*a0 + 3*a0_2;
const PxF64 Caab = a0*Cab + 4*a1_3;
const PxF64 Kaab = a1*Kab + 4*a0_3;
const PxF64 Cabb = 4*b1_3 + 3*b1_2*b0 + 2*b1*b0_2 + b0_3;
const PxF64 Kabb = b1_3 + 2*b1_2*b0 + 3*b1*b0_2 + 4*b0_3;
mP1 += db*C1;
mPa += db*Ca;
mPaa += db*Caa;
mPaaa += db*Caaa;
mPb += da*Cb;
mPbb += da*Cbb;
mPbbb += da*Cbbb;
mPab += db*(b1*Cab + b0*Kab);
mPaab += db*(b1*Caab + b0*Kaab);
mPabb += da*(a1*Cabb + a0*Kabb);
}
mP1 /= 2.0;
mPa /= 6.0;
mPaa /= 12.0;
mPaaa /= 20.0;
mPb /= -6.0;
mPbb /= -12.0;
mPbbb /= -20.0;
mPab /= 24.0;
mPaab /= 60.0;
mPabb /= -60.0;
}
#define SQR(x) ((x)*(x)) //!< Returns x square
#define CUBE(x) ((x)*(x)*(x)) //!< Returns x cube
/**
* Computes surface integrals over a polyhedral face from the integrals over its projection.
* \param f [in] a face structure.
*/
void VolumeIntegrator::computeFaceIntegrals(const Face& f)
{
computeProjectionIntegrals(f);
const PxF64 w = f.w;
const PxF64* n = f.Norm;
const PxF64 k1 = 1 / n[mC];
const PxF64 k2 = k1 * k1;
const PxF64 k3 = k2 * k1;
const PxF64 k4 = k3 * k1;
mFa = k1 * mPa;
mFb = k1 * mPb;
mFc = -k2 * (n[mA]*mPa + n[mB]*mPb + w*mP1);
mFaa = k1 * mPaa;
mFbb = k1 * mPbb;
mFcc = k3 * (SQR(n[mA])*mPaa + 2*n[mA]*n[mB]*mPab + SQR(n[mB])*mPbb + w*(2*(n[mA]*mPa + n[mB]*mPb) + w*mP1));
mFaaa = k1 * mPaaa;
mFbbb = k1 * mPbbb;
mFccc = -k4 * (CUBE(n[mA])*mPaaa + 3*SQR(n[mA])*n[mB]*mPaab
+ 3*n[mA]*SQR(n[mB])*mPabb + CUBE(n[mB])*mPbbb
+ 3*w*(SQR(n[mA])*mPaa + 2*n[mA]*n[mB]*mPab + SQR(n[mB])*mPbb)
+ w*w*(3*(n[mA]*mPa + n[mB]*mPb) + w*mP1));
mFaab = k1 * mPaab;
mFbbc = -k2 * (n[mA]*mPabb + n[mB]*mPbbb + w*mPbb);
mFcca = k3 * (SQR(n[mA])*mPaaa + 2*n[mA]*n[mB]*mPaab + SQR(n[mB])*mPabb + w*(2*(n[mA]*mPaa + n[mB]*mPab) + w*mPa));
}
/*
* This code computes volume integrals needed to compute mass properties of polyhedral bodies.
* Based on public domain code by David Eberly.
*/
class VolumeIntegratorEberly
{
PX_NOCOPY(VolumeIntegratorEberly)
public:
VolumeIntegratorEberly(const PxConvexMeshDesc& desc, PxF64 density) : mDesc(desc), mMass(0), mMassR(0), mDensity(density) {}
~VolumeIntegratorEberly() {}
bool computeVolumeIntegralsSIMD(PxIntegrals& ir, const PxVec3& origin);
bool computeVolumeIntegrals(PxIntegrals& ir, const PxVec3& origin);
private:
const PxConvexMeshDesc& mDesc;
PxF64 mMass;
PxReal mMassR;
PxF64 mDensity;
};
PX_FORCE_INLINE void subexpressions(PxF64 w0, PxF64 w1, PxF64 w2, PxF64& f1, PxF64& f2, PxF64& f3, PxF64& g0, PxF64& g1, PxF64& g2)
{
PxF64 temp0 = w0 + w1;
f1 = temp0 + w2;
PxF64 temp1 = w0*w0;
PxF64 temp2 = temp1 + w1*temp0;
f2 = temp2 + w2*f1;
f3 = w0*temp1 + w1*temp2 + w2*f2;
g0 = f2 + w0*(f1 + w0);
g1 = f2 + w1*(f1 + w1);
g2 = f2 + w2*(f1 + w2);
}
PX_FORCE_INLINE void subexpressionsSIMD(const Vec4V& w0, const Vec4V& w1, const Vec4V& w2,
Vec4V& f1, Vec4V& f2, Vec4V& f3, Vec4V& g0, Vec4V& g1, Vec4V& g2)
{
const Vec4V temp0 = V4Add(w0, w1);
f1 = V4Add(temp0, w2);
const Vec4V temp1 = V4Mul(w0,w0);
const Vec4V temp2 = V4MulAdd(w1, temp0, temp1);
f2 = V4MulAdd(w2, f1, temp2);
// f3 = w0.multiply(temp1) + w1.multiply(temp2) + w2.multiply(f2);
const Vec4V ad0 = V4Mul(w0, temp1);
const Vec4V ad1 = V4MulAdd(w1, temp2, ad0);
f3 = V4MulAdd(w2, f2, ad1);
g0 = V4MulAdd(w0, V4Add(f1, w0), f2); // f2 + w0.multiply(f1 + w0);
g1 = V4MulAdd(w1, V4Add(f1, w1), f2); // f2 + w1.multiply(f1 + w1);
g2 = V4MulAdd(w2, V4Add(f1, w2), f2); // f2 + w2.multiply(f1 + w2);
}
/**
* Computes volume integrals for a polyhedron by summing surface integrals over its faces. SIMD version
* \param ir [out] a result structure.
* \param origin [in] the origin of the mesh vertices. All vertices will be shifted accordingly prior to computing the volume integrals.
Can improve accuracy, for example, if the centroid is used in the case of a convex mesh. Note: the returned inertia will not be relative to this origin but relative to (0,0,0).
* \return true if success
*/
bool VolumeIntegratorEberly::computeVolumeIntegralsSIMD(PxIntegrals& ir, const PxVec3& origin)
{
FloatV mult = FLoad(1.0f/6.0f);
const Vec4V multV = V4Load(1.0f/24.0f);
const Vec4V multV2 = V4Load(1.0f/60.0f);
const Vec4V multVV = V4Load(1.0f/120.0f);
// order: 1, x, y, z, x^2, y^2, z^2, xy, yz, zx
FloatV intg = FLoad(0.0f);
Vec4V intgV = V4Load(0.0f);
Vec4V intgV2 = V4Load(0.0f);
Vec4V intgVV = V4Load(0.0f);
const Vec4V originV = Vec4V_From_PxVec3_WUndefined(origin);
const FloatV zeroV = FLoad(0.0f);
const PxVec3* hullVerts = static_cast<const PxVec3*> (mDesc.points.data);
const Gu::HullPolygonData* hullPolygons = static_cast<const Gu::HullPolygonData*> (mDesc.polygons.data);
for (PxU32 i = 0; i < mDesc.polygons.count; i++)
{
const Gu::HullPolygonData& polygon = hullPolygons[i];
const PxU8* data = static_cast<const PxU8*>(mDesc.indices.data) + polygon.mVRef8;
const PxU32 nbVerts = polygon.mNbVerts;
PX_ASSERT(nbVerts > 2);
const Vec4V normalV = V4LoadU(&polygon.mPlane.n.x);
for (PxU32 j = 0; j < nbVerts - 2; j++)
{
// Should be safe to V4Load, we allocate one more vertex each time
const Vec4V vertex0 = V4LoadU(&hullVerts[data[0]].x);
const Vec4V vertex1 = V4LoadU(&hullVerts[data[j + 1]].x);
const Vec4V vertex2 = V4LoadU(&hullVerts[data[j + 2]].x);
const Vec4V p0 = V4Sub(vertex0, originV);
Vec4V p1 = V4Sub(vertex1, originV);
Vec4V p2 = V4Sub(vertex2, originV);
const Vec4V p0YZX = V4PermYZXW(p0);
const Vec4V p1YZX = V4PermYZXW(p1);
const Vec4V p2YZX = V4PermYZXW(p2);
// get edges and cross product of edges
Vec4V d = V4Cross(V4Sub(p1, p0), V4Sub(p2, p0)); // (p1 - p0).cross(p2 - p0);
const FloatV dist = V4Dot3(d, normalV);
//if(cp.dot(normalV) < 0)
if(FAllGrtr(zeroV, dist))
{
d = V4Neg(d);
Vec4V temp = p1;
p1 = p2;
p2 = temp;
}
// compute integral terms
Vec4V f1; Vec4V f2; Vec4V f3; Vec4V g0; Vec4V g1; Vec4V g2;
subexpressionsSIMD(p0, p1, p2, f1, f2, f3, g0, g1, g2);
// update integrals
intg = FScaleAdd(V4GetX(d), V4GetX(f1), intg); //intg += d.x*f1.x;
intgV = V4MulAdd(d, f2, intgV); // intgV +=d.multiply(f2);
intgV2 = V4MulAdd(d, f3, intgV2); // intgV2 += d.multiply(f3);
const Vec4V ad0 = V4Mul(p0YZX, g0);
const Vec4V ad1 = V4MulAdd(p1YZX, g1, ad0);
const Vec4V ad2 = V4MulAdd(p2YZX, g2, ad1);
intgVV = V4MulAdd(d, ad2, intgVV); //intgVV += d.multiply(p0YZX.multiply(g0) + p1YZX.multiply(g1) + p2YZX.multiply(g2));
}
}
intg = FMul(intg, mult); // intg *= mult;
intgV = V4Mul(intgV, multV);
intgV2 = V4Mul(intgV2, multV2);
intgVV = V4Mul(intgVV, multVV);
// center of mass ir.COM = intgV/mMassR;
const Vec4V comV = V4ScaleInv(intgV, intg);
// we rewrite the mass, but then we set it back
V4StoreU(comV, &ir.COM.x);
FStore(intg, &mMassR);
ir.mass = PxF64(mMassR); // = intg;
PxVec3 intg2;
V3StoreU(Vec3V_From_Vec4V(intgV2), intg2);
PxVec3 intVV;
V3StoreU(Vec3V_From_Vec4V(intgVV), intVV);
// inertia tensor relative to the provided origin parameter
ir.inertiaTensor[0][0] = PxF64(intg2.y + intg2.z);
ir.inertiaTensor[1][1] = PxF64(intg2.x + intg2.z);
ir.inertiaTensor[2][2] = PxF64(intg2.x + intg2.y);
ir.inertiaTensor[0][1] = ir.inertiaTensor[1][0] = PxF64(-intVV.x);
ir.inertiaTensor[1][2] = ir.inertiaTensor[2][1] = PxF64(-intVV.y);
ir.inertiaTensor[0][2] = ir.inertiaTensor[2][0] = PxF64(-intVV.z);
// inertia tensor relative to center of mass
ir.COMInertiaTensor[0][0] = ir.inertiaTensor[0][0] -PxF64(mMassR*(ir.COM.y*ir.COM.y+ir.COM.z*ir.COM.z));
ir.COMInertiaTensor[1][1] = ir.inertiaTensor[1][1] -PxF64(mMassR*(ir.COM.z*ir.COM.z+ir.COM.x*ir.COM.x));
ir.COMInertiaTensor[2][2] = ir.inertiaTensor[2][2] -PxF64(mMassR*(ir.COM.x*ir.COM.x+ir.COM.y*ir.COM.y));
ir.COMInertiaTensor[0][1] = ir.COMInertiaTensor[1][0] = (ir.inertiaTensor[0][1] +PxF64(mMassR*ir.COM.x*ir.COM.y));
ir.COMInertiaTensor[1][2] = ir.COMInertiaTensor[2][1] = (ir.inertiaTensor[1][2] +PxF64(mMassR*ir.COM.y*ir.COM.z));
ir.COMInertiaTensor[0][2] = ir.COMInertiaTensor[2][0] = (ir.inertiaTensor[0][2] +PxF64(mMassR*ir.COM.z*ir.COM.x));
// inertia tensor relative to (0,0,0)
if (!origin.isZero())
{
PxVec3 sum = ir.COM + origin;
ir.inertiaTensor[0][0] -= PxF64(mMassR*((ir.COM.y*ir.COM.y+ir.COM.z*ir.COM.z) - (sum.y*sum.y+sum.z*sum.z)));
ir.inertiaTensor[1][1] -= PxF64(mMassR*((ir.COM.z*ir.COM.z+ir.COM.x*ir.COM.x) - (sum.z*sum.z+sum.x*sum.x)));
ir.inertiaTensor[2][2] -= PxF64(mMassR*((ir.COM.x*ir.COM.x+ir.COM.y*ir.COM.y) - (sum.x*sum.x+sum.y*sum.y)));
ir.inertiaTensor[0][1] = ir.inertiaTensor[1][0] = ir.inertiaTensor[0][1] + PxF64(mMassR*((ir.COM.x*ir.COM.y) - (sum.x*sum.y)));
ir.inertiaTensor[1][2] = ir.inertiaTensor[2][1] = ir.inertiaTensor[1][2] + PxF64(mMassR*((ir.COM.y*ir.COM.z) - (sum.y*sum.z)));
ir.inertiaTensor[0][2] = ir.inertiaTensor[2][0] = ir.inertiaTensor[0][2] + PxF64(mMassR*((ir.COM.z*ir.COM.x) - (sum.z*sum.x)));
ir.COM = sum;
}
return true;
}
/**
* Computes volume integrals for a polyhedron by summing surface integrals over its faces.
* \param ir [out] a result structure.
* \param origin [in] the origin of the mesh vertices. All vertices will be shifted accordingly prior to computing the volume integrals.
Can improve accuracy, for example, if the centroid is used in the case of a convex mesh. Note: the returned inertia will not be relative to this origin but relative to (0,0,0).
* \return true if success
*/
bool VolumeIntegratorEberly::computeVolumeIntegrals(PxIntegrals& ir, const PxVec3& origin)
{
const PxF64 mult[10] = {1.0/6.0,1.0/24.0,1.0/24.0,1.0/24.0,1.0/60.0,1.0/60.0,1.0/60.0,1.0/120.0,1.0/120.0,1.0/120.0};
PxF64 intg[10] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; // order: 1, x, y, z, x^2, y^2, z^2, xy, yz, zx
const PxVec3* hullVerts = static_cast<const PxVec3*> (mDesc.points.data);
for (PxU32 i = 0; i < mDesc.polygons.count; i++)
{
const Gu::HullPolygonData& polygon = (static_cast<const Gu::HullPolygonData*> (mDesc.polygons.data))[i];
const PxU8* Data = static_cast<const PxU8*>(mDesc.indices.data) + polygon.mVRef8;
const PxU32 NbVerts = polygon.mNbVerts;
for (PxU32 j = 0; j < NbVerts - 2; j++)
{
const PxVec3 p0 = hullVerts[Data[0]] - origin;
PxVec3 p1 = hullVerts[Data[(j + 1) % NbVerts]] - origin;
PxVec3 p2 = hullVerts[Data[(j + 2) % NbVerts]] - origin;
PxVec3 cp = (p1 - p0).cross(p2 - p0);
if(cp.dot(polygon.mPlane.n) < 0)
{
cp = -cp;
PxSwap(p1,p2);
}
PxF64 x0 = PxF64(p0.x); PxF64 y0 = PxF64(p0.y); PxF64 z0 = PxF64(p0.z);
PxF64 x1 = PxF64(p1.x); PxF64 y1 = PxF64(p1.y); PxF64 z1 = PxF64(p1.z);
PxF64 x2 = PxF64(p2.x); PxF64 y2 = PxF64(p2.y); PxF64 z2 = PxF64(p2.z);
// get edges and cross product of edges
PxF64 d0 = PxF64(cp.x); PxF64 d1 = PxF64(cp.y); PxF64 d2 = PxF64(cp.z);
// compute integral terms
PxF64 f1x; PxF64 f2x; PxF64 f3x; PxF64 g0x; PxF64 g1x; PxF64 g2x;
PxF64 f1y; PxF64 f2y; PxF64 f3y; PxF64 g0y; PxF64 g1y; PxF64 g2y;
PxF64 f1z; PxF64 f2z; PxF64 f3z; PxF64 g0z; PxF64 g1z; PxF64 g2z;
subexpressions(x0, x1, x2, f1x, f2x, f3x, g0x, g1x, g2x);
subexpressions(y0, y1, y2, f1y, f2y, f3y, g0y, g1y, g2y);
subexpressions(z0, z1, z2, f1z, f2z, f3z, g0z, g1z, g2z);
// update integrals
intg[0] += d0*f1x;
intg[1] += d0*f2x; intg[2] += d1*f2y; intg[3] += d2*f2z;
intg[4] += d0*f3x; intg[5] += d1*f3y; intg[6] += d2*f3z;
intg[7] += d0*(y0*g0x + y1*g1x + y2*g2x);
intg[8] += d1*(z0*g0y + z1*g1y + z2*g2y);
intg[9] += d2*(x0*g0z + x1*g1z + x2*g2z);
}
}
for (PxU32 i = 0; i < 10; i++)
{
intg[i] *= mult[i];
}
ir.mass = mMass = intg[0];
// center of mass
ir.COM.x = PxReal(intg[1]/mMass);
ir.COM.y = PxReal(intg[2]/mMass);
ir.COM.z = PxReal(intg[3]/mMass);
// inertia tensor relative to the provided origin parameter
ir.inertiaTensor[0][0] = intg[5]+intg[6];
ir.inertiaTensor[1][1] = intg[4]+intg[6];
ir.inertiaTensor[2][2] = intg[4]+intg[5];
ir.inertiaTensor[0][1] = ir.inertiaTensor[1][0] = -intg[7];
ir.inertiaTensor[1][2] = ir.inertiaTensor[2][1] = -intg[8];
ir.inertiaTensor[0][2] = ir.inertiaTensor[2][0] = -intg[9];
// inertia tensor relative to center of mass
ir.COMInertiaTensor[0][0] = ir.inertiaTensor[0][0] -mMass*PxF64((ir.COM.y*ir.COM.y+ir.COM.z*ir.COM.z));
ir.COMInertiaTensor[1][1] = ir.inertiaTensor[1][1] -mMass*PxF64((ir.COM.z*ir.COM.z+ir.COM.x*ir.COM.x));
ir.COMInertiaTensor[2][2] = ir.inertiaTensor[2][2] -mMass*PxF64((ir.COM.x*ir.COM.x+ir.COM.y*ir.COM.y));
ir.COMInertiaTensor[0][1] = ir.COMInertiaTensor[1][0] = (ir.inertiaTensor[0][1] +mMass*PxF64(ir.COM.x*ir.COM.y));
ir.COMInertiaTensor[1][2] = ir.COMInertiaTensor[2][1] = (ir.inertiaTensor[1][2] +mMass*PxF64(ir.COM.y*ir.COM.z));
ir.COMInertiaTensor[0][2] = ir.COMInertiaTensor[2][0] = (ir.inertiaTensor[0][2] +mMass*PxF64(ir.COM.z*ir.COM.x));
// inertia tensor relative to (0,0,0)
if (!origin.isZero())
{
PxVec3 sum = ir.COM + origin;
ir.inertiaTensor[0][0] -= mMass*PxF64((ir.COM.y*ir.COM.y+ir.COM.z*ir.COM.z) - (sum.y*sum.y+sum.z*sum.z));
ir.inertiaTensor[1][1] -= mMass*PxF64((ir.COM.z*ir.COM.z+ir.COM.x*ir.COM.x) - (sum.z*sum.z+sum.x*sum.x));
ir.inertiaTensor[2][2] -= mMass*PxF64((ir.COM.x*ir.COM.x+ir.COM.y*ir.COM.y) - (sum.x*sum.x+sum.y*sum.y));
ir.inertiaTensor[0][1] = ir.inertiaTensor[1][0] = ir.inertiaTensor[0][1] + mMass*PxF64((ir.COM.x*ir.COM.y) - (sum.x*sum.y));
ir.inertiaTensor[1][2] = ir.inertiaTensor[2][1] = ir.inertiaTensor[1][2] + mMass*PxF64((ir.COM.y*ir.COM.z) - (sum.y*sum.z));
ir.inertiaTensor[0][2] = ir.inertiaTensor[2][0] = ir.inertiaTensor[0][2] + mMass*PxF64((ir.COM.z*ir.COM.x) - (sum.z*sum.x));
ir.COM = sum;
}
return true;
}
} // namespace
// Wrapper
bool computeVolumeIntegrals(const PxSimpleTriangleMesh& mesh, PxReal density, PxIntegrals& integrals)
{
VolumeIntegrator v(mesh, PxF64(density));
return v.computeVolumeIntegrals(integrals);
}
// Wrapper
bool computeVolumeIntegralsEberly(const PxConvexMeshDesc& mesh, PxReal density, PxIntegrals& integrals, const PxVec3& origin, bool useSimd)
{
VolumeIntegratorEberly v(mesh, PxF64(density));
if(useSimd)
return v.computeVolumeIntegralsSIMD(integrals, origin);
else
return v.computeVolumeIntegrals(integrals, origin);
}
}
| 25,885 | C++ | 34.26703 | 181 | 0.627584 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullUtils.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_COOKING_CONVEX_HULL_UTILS_H
#define GU_COOKING_CONVEX_HULL_UTILS_H
#include "foundation/PxMemory.h"
#include "foundation/PxPlane.h"
#include "cooking/PxConvexMeshDesc.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxArray.h"
namespace physx
{
//////////////////////////////////////////////////////////////////////////
// helper class for hull construction, holds the vertices and planes together
// while cropping the hull with planes
class ConvexHull : public PxUserAllocated
{
public:
// Helper class for halfedge representation
class HalfEdge
{
public:
PxI16 ea; // the other half of the edge (index into edges list)
PxU8 v; // the vertex at the start of this edge (index into vertices list)
PxU8 p; // the facet on which this edge lies (index into facets list)
HalfEdge(){}
HalfEdge(PxI16 _ea, PxU8 _v, PxU8 _p) :ea(_ea), v(_v), p(_p){}
};
ConvexHull& operator = (const ConvexHull&);
// construct the base cube hull from given max/min AABB
ConvexHull(const PxVec3& bmin, const PxVec3& bmax, const PxArray<PxPlane>& inPlanes);
// construct the base cube hull from given OBB
ConvexHull(const PxVec3& extent, const PxTransform& transform, const PxArray<PxPlane>& inPlanes);
// copy constructor
ConvexHull(const ConvexHull& srcHull)
: mInputPlanes(srcHull.getInputPlanes())
{
copyHull(srcHull);
}
// construct plain hull
ConvexHull(const PxArray<PxPlane>& inPlanes)
: mInputPlanes(inPlanes)
{
}
// finds the candidate plane, returns -1 otherwise
PxI32 findCandidatePlane(float planetestepsilon, float epsilon) const;
// internal check of the hull integrity
bool assertIntact(float epsilon) const;
// return vertices
const PxArray<PxVec3>& getVertices() const
{
return mVertices;
}
// return edges
const PxArray<HalfEdge>& getEdges() const
{
return mEdges;
}
// return faces
const PxArray<PxPlane>& getFacets() const
{
return mFacets;
}
// return input planes
const PxArray<PxPlane>& getInputPlanes() const
{
return mInputPlanes;
}
// return vertices
PxArray<PxVec3>& getVertices()
{
return mVertices;
}
// return edges
PxArray<HalfEdge>& getEdges()
{
return mEdges;
}
// return faces
PxArray<PxPlane>& getFacets()
{
return mFacets;
}
// returns the maximum number of vertices on a face
PxU32 maxNumVertsPerFace() const;
// copy the hull from source
void copyHull(const ConvexHull& src)
{
mVertices.resize(src.getVertices().size());
mEdges.resize(src.getEdges().size());
mFacets.resize(src.getFacets().size());
PxMemCopy(mVertices.begin(), src.getVertices().begin(), src.getVertices().size()*sizeof(PxVec3));
PxMemCopy(mEdges.begin(), src.getEdges().begin(), src.getEdges().size()*sizeof(HalfEdge));
PxMemCopy(mFacets.begin(), src.getFacets().begin(), src.getFacets().size()*sizeof(PxPlane));
}
private:
PxArray<PxVec3> mVertices;
PxArray<HalfEdge> mEdges;
PxArray<PxPlane> mFacets;
const PxArray<PxPlane>& mInputPlanes;
};
//////////////////////////////////////////////////////////////////////////|
// Crops the hull with a provided plane and with given epsilon
// returns new hull if succeeded
ConvexHull* convexHullCrop(const ConvexHull& convex, const PxPlane& slice, float planetestepsilon);
//////////////////////////////////////////////////////////////////////////|
// three planes intersection
PX_FORCE_INLINE PxVec3 threePlaneIntersection(const PxPlane& p0, const PxPlane& p1, const PxPlane& p2)
{
PxMat33 mp = (PxMat33(p0.n, p1.n, p2.n)).getTranspose();
PxMat33 mi = (mp).getInverse();
PxVec3 b(p0.d, p1.d, p2.d);
return -mi.transform(b);
}
//////////////////////////////////////////////////////////////////////////
// Compute OBB around given convex hull
bool computeOBBFromConvex(const PxConvexMeshDesc& desc, PxVec3& sides, PxTransform& matrix);
}
#endif
| 5,641 | C | 31.802325 | 103 | 0.685871 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexMeshBuilder.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 "GuConvexMesh.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxAlloca.h"
#include "GuCooking.h"
#include "GuBigConvexData2.h"
#include "GuBounds.h"
#include "GuCookingVolumeIntegration.h"
#include "GuCookingConvexMeshBuilder.h"
#include "GuCookingBigConvexDataBuilder.h"
#include "CmUtils.h"
#include "foundation/PxVecMath.h"
#include "GuCookingSDF.h"
using namespace physx;
using namespace Gu;
using namespace aos;
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
ConvexMeshBuilder::ConvexMeshBuilder(const bool buildGRBData) : hullBuilder(&mHullData, buildGRBData), mSdfData(NULL), mBigConvexData(NULL), mMass(0.0f), mInertia(PxIdentity)
{
}
ConvexMeshBuilder::~ConvexMeshBuilder()
{
PX_DELETE(mSdfData);
PX_DELETE(mBigConvexData);
}
// load the mesh data from given polygons
bool ConvexMeshBuilder::build(const PxConvexMeshDesc& desc, PxU32 gaussMapVertexLimit, bool validateOnly, ConvexHullLib* hullLib)
{
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Gu::ConvexMesh::loadFromDesc: desc.isValid() failed!");
if(!loadConvexHull(desc, hullLib))
return false;
// Compute local bounds (*after* hull has been created)
PxBounds3 minMaxBounds;
computeBoundsAroundVertices(minMaxBounds, mHullData.mNbHullVertices, hullBuilder.mHullDataHullVertices);
mHullData.mAABB = CenterExtents(minMaxBounds);
if(mHullData.mNbHullVertices > gaussMapVertexLimit)
{
if(!computeGaussMaps())
{
return false;
}
}
if(validateOnly)
return true;
// TEST_INTERNAL_OBJECTS
computeInternalObjects();
//~TEST_INTERNAL_OBJECTS
if (desc.sdfDesc)
{
computeSDF(desc);
}
return true;
}
PX_COMPILE_TIME_ASSERT(sizeof(PxMaterialTableIndex)==sizeof(PxU16));
bool ConvexMeshBuilder::save(PxOutputStream& stream, bool platformMismatch) const
{
// Export header
if(!writeHeader('C', 'V', 'X', 'M', PX_CONVEX_VERSION, platformMismatch, stream))
return false;
// Export serialization flags
PxU32 serialFlags = 0;
writeDword(serialFlags, platformMismatch, stream);
if(!hullBuilder.save(stream, platformMismatch))
return false;
// Export local bounds
// writeFloat(geomEpsilon, platformMismatch, stream);
writeFloat(0.0f, platformMismatch, stream);
writeFloat(mHullData.mAABB.getMin(0), platformMismatch, stream);
writeFloat(mHullData.mAABB.getMin(1), platformMismatch, stream);
writeFloat(mHullData.mAABB.getMin(2), platformMismatch, stream);
writeFloat(mHullData.mAABB.getMax(0), platformMismatch, stream);
writeFloat(mHullData.mAABB.getMax(1), platformMismatch, stream);
writeFloat(mHullData.mAABB.getMax(2), platformMismatch, stream);
// Export mass info
writeFloat(mMass, platformMismatch, stream);
writeFloatBuffer(reinterpret_cast<const PxF32*>(&mInertia), 9, platformMismatch, stream);
writeFloatBuffer(&mHullData.mCenterOfMass.x, 3, platformMismatch, stream);
// Export gaussmaps
if(mBigConvexData)
{
writeFloat(1.0f, platformMismatch, stream); //gauss map flag true
BigConvexDataBuilder SVMB(&mHullData, mBigConvexData, hullBuilder.mHullDataHullVertices);
SVMB.save(stream, platformMismatch);
}
else
writeFloat(-1.0f, platformMismatch, stream); //gauss map flag false
if (mSdfData)
{
writeFloat(1.0f, platformMismatch, stream); //sdf flag true
// Export sdf values
writeFloat(mSdfData->mMeshLower.x, platformMismatch, stream);
writeFloat(mSdfData->mMeshLower.y, platformMismatch, stream);
writeFloat(mSdfData->mMeshLower.z, platformMismatch, stream);
writeFloat(mSdfData->mSpacing, platformMismatch, stream);
writeDword(mSdfData->mDims.x, platformMismatch, stream);
writeDword(mSdfData->mDims.y, platformMismatch, stream);
writeDword(mSdfData->mDims.z, platformMismatch, stream);
writeDword(mSdfData->mNumSdfs, platformMismatch, stream);
writeDword(mSdfData->mNumSubgridSdfs, platformMismatch, stream);
writeDword(mSdfData->mNumStartSlots, platformMismatch, stream);
writeDword(mSdfData->mSubgridSize, platformMismatch, stream);
writeDword(mSdfData->mSdfSubgrids3DTexBlockDim.x, platformMismatch, stream);
writeDword(mSdfData->mSdfSubgrids3DTexBlockDim.y, platformMismatch, stream);
writeDword(mSdfData->mSdfSubgrids3DTexBlockDim.z, platformMismatch, stream);
writeFloat(mSdfData->mSubgridsMinSdfValue, platformMismatch, stream);
writeFloat(mSdfData->mSubgridsMaxSdfValue, platformMismatch, stream);
writeDword(mSdfData->mBytesPerSparsePixel, platformMismatch, stream);
writeFloatBuffer(mSdfData->mSdf, mSdfData->mNumSdfs, platformMismatch, stream);
writeByteBuffer(mSdfData->mSubgridSdf, mSdfData->mNumSubgridSdfs, stream);
writeIntBuffer(mSdfData->mSubgridStartSlots, mSdfData->mNumStartSlots, platformMismatch, stream);
}
else
writeFloat(-1.0f, platformMismatch, stream); //sdf flag false
// TEST_INTERNAL_OBJECTS
writeFloat(mHullData.mInternal.mRadius, platformMismatch, stream);
writeFloat(mHullData.mInternal.mExtents[0], platformMismatch, stream);
writeFloat(mHullData.mInternal.mExtents[1], platformMismatch, stream);
writeFloat(mHullData.mInternal.mExtents[2], platformMismatch, stream);
//~TEST_INTERNAL_OBJECTS
return true;
}
//////////////////////////////////////////////////////////////////////////
// instead of saving the data into stream, we copy the mesh data
// into internal Gu::ConvexMesh.
bool ConvexMeshBuilder::copy(Gu::ConvexHullInitData& hullData)
{
// hull builder data copy
PxU32 nb = 0;
hullBuilder.copy(hullData.mHullData, nb);
hullData.mNb = nb;
hullData.mInertia = mInertia;
hullData.mMass = mMass;
// mass props
hullData.mHullData.mAABB = mHullData.mAABB;
hullData.mHullData.mCenterOfMass = mHullData.mCenterOfMass;
// big convex data
if(mBigConvexData)
{
hullData.mHullData.mBigConvexRawData = &mBigConvexData->mData;
hullData.mBigConvexData = mBigConvexData;
mBigConvexData = NULL;
}
else
{
hullData.mHullData.mBigConvexRawData = NULL;
hullData.mBigConvexData = NULL;
}
if (mSdfData)
{
hullData.mHullData.mSdfData = mSdfData;
hullData.mSdfData = mSdfData;
mSdfData = NULL;
}
else
{
hullData.mHullData.mSdfData = NULL;
hullData.mSdfData = NULL;
}
// internal data
hullData.mHullData.mInternal.mRadius = mHullData.mInternal.mRadius;
hullData.mHullData.mInternal.mExtents[0] = mHullData.mInternal.mExtents[0];
hullData.mHullData.mInternal.mExtents[1] = mHullData.mInternal.mExtents[1];
hullData.mHullData.mInternal.mExtents[2] = mHullData.mInternal.mExtents[2];
return true;
}
// compute mass and inertia of the convex mesh
void ConvexMeshBuilder::computeMassInfo(bool lowerPrecision)
{
if(mMass <= 0.0f) //not yet computed.
{
PxIntegrals integrals;
PxConvexMeshDesc meshDesc;
meshDesc.points.count = mHullData.mNbHullVertices;
meshDesc.points.data = hullBuilder.mHullDataHullVertices;
meshDesc.points.stride = sizeof(PxVec3);
meshDesc.polygons.data = hullBuilder.mHullDataPolygons;
meshDesc.polygons.stride = sizeof(Gu::HullPolygonData);
meshDesc.polygons.count = hullBuilder.mHull->mNbPolygons;
meshDesc.indices.data = hullBuilder.mHullDataVertexData8;
// using the centroid of the convex for the volume integration solved accuracy issues in cases where the inertia tensor
// ended up close to not being positive definite and after a few further transforms the diagonalized inertia tensor ended
// up with negative values.
PxVec3 mean(0.0f);
for(PxU32 i=0; i < mHullData.mNbHullVertices; i++)
mean += hullBuilder.mHullDataHullVertices[i];
mean *= (1.0f / mHullData.mNbHullVertices);
if(computeVolumeIntegralsEberly(meshDesc, 1.0f, integrals, mean, lowerPrecision))
{
integrals.getOriginInertia(mInertia);
mHullData.mCenterOfMass = integrals.COM;
//note: the mass will be negative for an inside-out mesh!
if(mInertia.column0.isFinite() && mInertia.column1.isFinite() && mInertia.column2.isFinite()
&& mHullData.mCenterOfMass.isFinite() && PxIsFinite(PxReal(integrals.mass)))
{
if (integrals.mass < 0)
{
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Gu::ConvexMesh: Mesh has a negative volume! Is it open or do (some) faces have reversed winding? (Taking absolute value.)");
integrals.mass = -integrals.mass;
mInertia = -mInertia;
}
mMass = PxReal(integrals.mass); //set mass to valid value.
return;
}
}
outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Gu::ConvexMesh: Error computing mesh mass properties!\n");
}
}
#if PX_VC
#pragma warning(push)
#pragma warning(disable:4996) // permitting use of gatherStrided until we have a replacement.
#endif
bool ConvexMeshBuilder::loadConvexHull(const PxConvexMeshDesc& desc, ConvexHullLib* hullLib)
{
// gather points
PxVec3* geometry = reinterpret_cast<PxVec3*>(PxAlloca(sizeof(PxVec3)*desc.points.count));
immediateCooking::gatherStrided(desc.points.data, geometry, desc.points.count, sizeof(PxVec3), desc.points.stride);
PxU32* topology = NULL;
// gather indices
// store the indices into topology if we have the polygon data
if(desc.indices.data)
{
topology = reinterpret_cast<PxU32*>(PxAlloca(sizeof(PxU32)*desc.indices.count));
if (desc.flags & PxConvexFlag::e16_BIT_INDICES)
{
// conversion; 16 bit index -> 32 bit index & stride
PxU32* dest = topology;
const PxU32* pastLastDest = topology + desc.indices.count;
const PxU8* source = reinterpret_cast<const PxU8*>(desc.indices.data);
while (dest < pastLastDest)
{
const PxU16 * trig16 = reinterpret_cast<const PxU16*>(source);
*dest++ = *trig16;
source += desc.indices.stride;
}
}
else
{
immediateCooking::gatherStrided(desc.indices.data, topology, desc.indices.count, sizeof(PxU32), desc.indices.stride);
}
}
// gather polygons
PxHullPolygon* hullPolygons = NULL;
if(desc.polygons.data)
{
hullPolygons = reinterpret_cast<PxHullPolygon*>(PxAlloca(sizeof(PxHullPolygon)*desc.polygons.count));
immediateCooking::gatherStrided(desc.polygons.data,hullPolygons,desc.polygons.count,sizeof(PxHullPolygon),desc.polygons.stride);
// if user polygons, make sure the largest one is the first one
if (!hullLib)
{
PxU32 largestPolygon = 0;
for (PxU32 i = 1; i < desc.polygons.count; i++)
{
if(hullPolygons[i].mNbVerts > hullPolygons[largestPolygon].mNbVerts)
largestPolygon = i;
}
if(largestPolygon != 0)
{
PxHullPolygon movedPolygon = hullPolygons[0];
hullPolygons[0] = hullPolygons[largestPolygon];
hullPolygons[largestPolygon] = movedPolygon;
}
}
}
const bool doValidation = desc.flags & PxConvexFlag::eDISABLE_MESH_VALIDATION ? false : true;
if(!hullBuilder.init(desc.points.count, geometry, topology, desc.indices.count, desc.polygons.count, hullPolygons, doValidation, hullLib))
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Gu::ConvexMesh::loadConvexHull: convex hull init failed!");
computeMassInfo(desc.flags & PxConvexFlag::eFAST_INERTIA_COMPUTATION);
return true;
}
#if PX_VC
#pragma warning(pop)
#endif
// compute polygons from given triangles. This is support function used in extensions. We do not accept triangles as an input for convex mesh desc.
bool ConvexMeshBuilder::computeHullPolygons(const PxU32& nbVerts,const PxVec3* verts, const PxU32& nbTriangles, const PxU32* triangles, PxAllocatorCallback& inAllocator,
PxU32& outNbVerts, PxVec3*& outVertices , PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& polygons)
{
if(!hullBuilder.computeHullPolygons(nbVerts,verts,nbTriangles,triangles))
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "ConvexMeshBuilder::computeHullPolygons: compute convex hull polygons failed. Provided triangles dont form a convex hull.");
outNbVerts = hullBuilder.mHull->mNbHullVertices;
nbPolygons = hullBuilder.mHull->mNbPolygons;
outVertices = reinterpret_cast<PxVec3*>(inAllocator.allocate(outNbVerts*sizeof(PxVec3),"PxVec3",__FILE__,__LINE__));
PxMemCopy(outVertices,hullBuilder.mHullDataHullVertices,outNbVerts*sizeof(PxVec3));
nbIndices = 0;
for (PxU32 i = 0; i < nbPolygons; i++)
{
nbIndices += hullBuilder.mHullDataPolygons[i].mNbVerts;
}
indices = reinterpret_cast<PxU32*>(inAllocator.allocate(nbIndices*sizeof(PxU32),"PxU32",__FILE__,__LINE__));
for (PxU32 i = 0; i < nbIndices; i++)
{
indices[i] = hullBuilder.mHullDataVertexData8[i];
}
polygons = reinterpret_cast<PxHullPolygon*>(inAllocator.allocate(nbPolygons*sizeof(PxHullPolygon),"PxHullPolygon",__FILE__,__LINE__));
for (PxU32 i = 0; i < nbPolygons; i++)
{
const Gu::HullPolygonData& polygonData = hullBuilder.mHullDataPolygons[i];
PxHullPolygon& outPolygon = polygons[i];
outPolygon.mPlane[0] = polygonData.mPlane.n.x;
outPolygon.mPlane[1] = polygonData.mPlane.n.y;
outPolygon.mPlane[2] = polygonData.mPlane.n.z;
outPolygon.mPlane[3] = polygonData.mPlane.d;
outPolygon.mNbVerts = polygonData.mNbVerts;
outPolygon.mIndexBase = polygonData.mVRef8;
for (PxU32 j = 0; j < polygonData.mNbVerts; j++)
{
PX_ASSERT(indices[outPolygon.mIndexBase + j] == hullBuilder.mHullDataVertexData8[polygonData.mVRef8+j]);
}
}
return true;
}
// compute big convex data
bool ConvexMeshBuilder::computeGaussMaps()
{
// The number of polygons is limited to 256 because the gaussmap encode 256 polys maximum
PxU32 density = 16;
// density = 64;
// density = 8;
// density = 2;
PX_DELETE(mBigConvexData);
PX_NEW_SERIALIZED(mBigConvexData,BigConvexData);
BigConvexDataBuilder SVMB(&mHullData, mBigConvexData, hullBuilder.mHullDataHullVertices);
// valencies we need to compute first, they are needed for min/max precompute
SVMB.computeValencies(hullBuilder);
SVMB.precompute(density);
return true;
}
// TEST_INTERNAL_OBJECTS
static void ComputeInternalExtent(Gu::ConvexHullData& data, const Gu::HullPolygonData* hullPolys)
{
const PxVec3 e = data.mAABB.getMax() - data.mAABB.getMin();
// PT: For that formula, see %SDKRoot%\InternalDocumentation\Cooking\InternalExtents.png
const float r = data.mInternal.mRadius / sqrtf(3.0f);
const float epsilon = 1E-7f;
const PxU32 largestExtent = PxLargestAxis(e);
PxU32 e0 = PxGetNextIndex3(largestExtent);
PxU32 e1 = PxGetNextIndex3(e0);
if(e[e0] < e[e1])
PxSwap<PxU32>(e0,e1);
data.mInternal.mExtents[0] = FLT_MAX;
data.mInternal.mExtents[1] = FLT_MAX;
data.mInternal.mExtents[2] = FLT_MAX;
// PT: the following code does ray-vs-plane raycasts.
// find the largest box along the largest extent, with given internal radius
for(PxU32 i = 0; i < data.mNbPolygons; i++)
{
// concurrent with search direction
const float d = hullPolys[i].mPlane.n[largestExtent];
if((-epsilon < d && d < epsilon))
continue;
const float numBase = -hullPolys[i].mPlane.d - hullPolys[i].mPlane.n.dot(data.mCenterOfMass);
const float denBase = 1.0f/hullPolys[i].mPlane.n[largestExtent];
const float numn0 = r * hullPolys[i].mPlane.n[e0];
const float numn1 = r * hullPolys[i].mPlane.n[e1];
float num = numBase - numn0 - numn1;
float ext = PxMax(fabsf(num*denBase), r);
if(ext < data.mInternal.mExtents[largestExtent])
data.mInternal.mExtents[largestExtent] = ext;
num = numBase - numn0 + numn1;
ext = PxMax(fabsf(num *denBase), r);
if(ext < data.mInternal.mExtents[largestExtent])
data.mInternal.mExtents[largestExtent] = ext;
num = numBase + numn0 + numn1;
ext = PxMax(fabsf(num *denBase), r);
if(ext < data.mInternal.mExtents[largestExtent])
data.mInternal.mExtents[largestExtent] = ext;
num = numBase + numn0 - numn1;
ext = PxMax(fabsf(num *denBase), r);
if(ext < data.mInternal.mExtents[largestExtent])
data.mInternal.mExtents[largestExtent] = ext;
}
// Refine the box along e0,e1
for(PxU32 i = 0; i < data.mNbPolygons; i++)
{
const float denumAdd = hullPolys[i].mPlane.n[e0] + hullPolys[i].mPlane.n[e1];
const float denumSub = hullPolys[i].mPlane.n[e0] - hullPolys[i].mPlane.n[e1];
const float numBase = -hullPolys[i].mPlane.d - hullPolys[i].mPlane.n.dot(data.mCenterOfMass);
const float numn0 = data.mInternal.mExtents[largestExtent] * hullPolys[i].mPlane.n[largestExtent];
if(!(-epsilon < denumAdd && denumAdd < epsilon))
{
float num = numBase - numn0;
float ext = PxMax(fabsf(num/ denumAdd), r);
if(ext < data.mInternal.mExtents[e0])
data.mInternal.mExtents[e0] = ext;
num = numBase + numn0;
ext = PxMax(fabsf(num / denumAdd), r);
if(ext < data.mInternal.mExtents[e0])
data.mInternal.mExtents[e0] = ext;
}
if(!(-epsilon < denumSub && denumSub < epsilon))
{
float num = numBase - numn0;
float ext = PxMax(fabsf(num / denumSub), r);
if(ext < data.mInternal.mExtents[e0])
data.mInternal.mExtents[e0] = ext;
num = numBase + numn0;
ext = PxMax(fabsf(num / denumSub), r);
if(ext < data.mInternal.mExtents[e0])
data.mInternal.mExtents[e0] = ext;
}
}
data.mInternal.mExtents[e1] = data.mInternal.mExtents[e0];
}
//////////////////////////////////////////////////////////////////////////
// compute internal objects, get the internal extent and radius
void ConvexMeshBuilder::computeInternalObjects()
{
const Gu::HullPolygonData* hullPolys = hullBuilder.mHullDataPolygons;
Gu::ConvexHullData& data = mHullData;
// compute the internal radius
data.mInternal.mRadius = FLT_MAX;
for(PxU32 i=0;i<data.mNbPolygons;i++)
{
const float dist = fabsf(hullPolys[i].mPlane.distance(data.mCenterOfMass));
if(dist<data.mInternal.mRadius)
data.mInternal.mRadius = dist;
}
ComputeInternalExtent(data, hullPolys);
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);
}
bool ConvexMeshBuilder::checkExtentRadiusRatio()
{
return mHullData.checkExtentRadiusRatio();
}
void ConvexMeshBuilder::computeSDF(const PxConvexMeshDesc& desc)
{
PX_DELETE(mSdfData);
PX_NEW_SERIALIZED(mSdfData, SDF);
//create triangle mesh from polygons
const PxU32 nbPolygons = mHullData.mNbPolygons;
PxU32 nbVerts = mHullData.mNbHullVertices;
const Gu::HullPolygonData* hullPolys = hullBuilder.mHullDataPolygons;
const PxU8* polygons = hullBuilder.mHullDataVertexData8;
const PxVec3* verts = hullBuilder.mHullDataHullVertices;
//compute total number of triangles
PxU32 numTotalTriangles = 0;
for (PxU32 i = 0; i < nbPolygons; ++i)
{
const Gu::HullPolygonData& polyData = hullPolys[i];
const PxU32 nbTriangles = polyData.mNbVerts - 2;
numTotalTriangles += nbTriangles;
}
PxArray<PxU32> triangleIndice(numTotalTriangles * 3);
PxU32 startIndex = 0;
for (PxU32 i = 0; i < nbPolygons; ++i)
{
const Gu::HullPolygonData& polyData = hullPolys[i];
const PxU32 nbTriangles = polyData.mNbVerts - 2;
const PxU8 vref0 = polygons[polyData.mVRef8];
for (PxU32 j = 0; j < nbTriangles; ++j)
{
const PxU32 index = startIndex + j * 3;
const PxU32 vref1 = polygons[polyData.mVRef8 + 0 + j + 1];
const PxU32 vref2 = polygons[polyData.mVRef8 + 0 + j + 2];
triangleIndice[index + 0] = vref0;
triangleIndice[index + 1] = vref1;
triangleIndice[index + 2] = vref2;
}
startIndex += nbTriangles * 3;
}
PxArray<PxReal> sdfData;
PxArray<PxU8> sdfDataSubgrids;
PxArray<PxU32> sdfSubgridsStartSlots;
PxTriangleMeshDesc triDesc;
triDesc.points.count = nbVerts;
triDesc.points.stride = sizeof(PxVec3);
triDesc.points.data = verts;
triDesc.triangles.count = numTotalTriangles;
triDesc.triangles.stride = sizeof(PxU32) * 3;
triDesc.triangles.data = triangleIndice.begin();
triDesc.flags &= (~PxMeshFlag::e16_BIT_INDICES);
triDesc.sdfDesc = desc.sdfDesc;
buildSDF(triDesc, sdfData, sdfDataSubgrids, sdfSubgridsStartSlots);
PxSDFDesc& sdfDesc = *desc.sdfDesc;
PxReal* sdf = mSdfData->allocateSdfs(sdfDesc.meshLower, sdfDesc.spacing, sdfDesc.dims.x, sdfDesc.dims.y, sdfDesc.dims.z,
sdfDesc.subgridSize, sdfDesc.sdfSubgrids3DTexBlockDim.x, sdfDesc.sdfSubgrids3DTexBlockDim.y, sdfDesc.sdfSubgrids3DTexBlockDim.z,
sdfDesc.subgridsMinSdfValue, sdfDesc.subgridsMaxSdfValue, sdfDesc.bitsPerSubgridPixel);
if (sdfDesc.subgridSize > 0)
{
//Sparse sdf
immediateCooking::gatherStrided(sdfDesc.sdf.data, sdf, sdfDesc.sdf.count, sizeof(PxReal), sdfDesc.sdf.stride);
immediateCooking::gatherStrided(sdfDesc.sdfSubgrids.data, mSdfData->mSubgridSdf,
sdfDesc.sdfSubgrids.count,
sizeof(PxU8), sdfDesc.sdfSubgrids.stride);
immediateCooking::gatherStrided(sdfDesc.sdfStartSlots.data, mSdfData->mSubgridStartSlots, sdfDesc.sdfStartSlots.count, sizeof(PxU32), sdfDesc.sdfStartSlots.stride);
}
else
{
//copy, and compact to get rid of strides:
immediateCooking::gatherStrided(sdfDesc.sdf.data, sdf, sdfDesc.dims.x * sdfDesc.dims.y * sdfDesc.dims.z, sizeof(PxReal), sdfDesc.sdf.stride);
}
}
//~TEST_INTERNAL_OBJECTS
| 22,642 | C++ | 34.94127 | 185 | 0.736596 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexPolygonsBuilder.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 "foundation/PxBasicTemplates.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxUserAllocated.h"
#include "GuAdjacencies.h"
#include "GuMeshCleaner.h"
#include "GuVertexReducer.h"
#include "foundation/PxArray.h"
#include "GuCookingConvexPolygonsBuilder.h"
using namespace physx;
using namespace Gu;
#define USE_PRECOMPUTED_HULL_PROJECTION
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Computes the center of the hull. It should be inside it !
* \param center [out] hull center
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool computeGeomCenter(PxVec3& center, PxU32 numFaces, const IndexedTriangle32* PX_RESTRICT faces, const PxVec3* PX_RESTRICT hullVerts, PxU32 nbHullVertices)
{
if (!nbHullVertices || !hullVerts)
return false;
// Use the topological method
float totalArea = 0.0f;
center = PxVec3(0);
for (PxU32 i = 0; i < numFaces; i++)
{
IndexedTriangle32 curTri(faces[i].mRef[0], faces[i].mRef[1], faces[i].mRef[2]);
const float area = curTri.area(hullVerts);
PxVec3 curCenter; curTri.center(hullVerts, curCenter);
center += area * curCenter;
totalArea += area;
}
center /= totalArea;
return true;
}
//////////////////////////////////////////////////////////////////////////
//! A generic couple structure
class Pair : public PxUserAllocated
{
public:
PX_FORCE_INLINE Pair() {}
PX_FORCE_INLINE Pair(PxU32 i0, PxU32 i1) : id0(i0), id1(i1) {}
PX_FORCE_INLINE ~Pair() {}
//! Operator for "if(Pair==Pair)"
PX_FORCE_INLINE bool operator==(const Pair& p) const { return (id0==p.id0) && (id1==p.id1); }
//! Operator for "if(Pair!=Pair)"
PX_FORCE_INLINE bool operator!=(const Pair& p) const { return (id0!=p.id0) || (id1!=p.id1); }
PxU32 id0; //!< First index of the pair
PxU32 id1; //!< Second index of the pair
};
PX_COMPILE_TIME_ASSERT(sizeof(Pair)==8);
//////////////////////////////////////////////////////////////////////////
// construct a plane
template <class T>
PX_INLINE PxPlane PlaneEquation(const T& t, const PxVec3* verts)
{
const PxVec3& p0 = verts[t.mRef[0]];
const PxVec3& p1 = verts[t.mRef[1]];
const PxVec3& p2 = verts[t.mRef[2]];
return PxPlane(p0, p1, p2);
}
//////////////////////////////////////////////////////////////////////////
// negate plane
static PX_FORCE_INLINE void negatePlane(HullPolygonData& data)
{
data.mPlane.n = -data.mPlane.n;
data.mPlane.d = -data.mPlane.d;
}
//////////////////////////////////////////////////////////////////////////
// Inverse a buffer in-place
static bool inverseBuffer(PxU32 nbEntries, PxU8* entries)
{
if(!nbEntries || !entries) return false;
for(PxU32 i=0; i < (nbEntries>>1); i++)
PxSwap(entries[i], entries[nbEntries-1-i]);
return true;
}
//////////////////////////////////////////////////////////////////////////
// Extracts a line-strip from a list of non-sorted line-segments (slow)
static bool findLineStrip(PxArray<PxU32>& lineStrip, const PxArray<Pair>& lineSegments)
{
// Ex:
//
// 4-2
// 0-1
// 2-3
// 4-0
// 7-3
// 7-1
//
// => 0-1-7-3-2-4-0
// 0-0-1-1-2-2-3-3-4-4-7-7
// 0-1
// 0-4
// 1-7
// 2-3
// 2-4
// 3-7
// Naive implementation below
PxArray<Pair> Copy(lineSegments);
RunAgain:
{
PxU32 nbSegments = Copy.size();
for(PxU32 j=0;j<nbSegments;j++)
{
PxU32 ID0 = Copy[j].id0;
PxU32 ID1 = Copy[j].id1;
for(PxU32 i=j+1;i<nbSegments;i++)
{
if(
(Copy[i].id0==ID0 && Copy[i].id1==ID1)
|| (Copy[i].id1==ID0 && Copy[i].id0==ID1)
)
{
// Duplicate segment found => remove both
PX_ASSERT(Copy.size()>=2);
Copy.remove(i);
Copy.remove(j);
goto RunAgain;
}
}
}
// Goes through when everything's fine
}
PxU32 ref0 = 0xffffffff;
PxU32 ref1 = 0xffffffff;
if(Copy.size()>=1)
{
Pair* Segments = Copy.begin();
if(Segments)
{
ref0 = Segments->id0;
ref1 = Segments->id1;
lineStrip.pushBack(ref0);
lineStrip.pushBack(ref1);
PX_ASSERT(Copy.size()>=1);
Copy.remove(0);
}
}
Wrap:
// Look for same vertex ref in remaining segments
PxU32 nb = Copy.size();
if(!nb)
{
// ### check the line is actually closed?
return true;
}
for(PxU32 i=0;i<nb;i++)
{
PxU32 newRef0 = Copy[i].id0;
PxU32 newRef1 = Copy[i].id1;
// We look for Ref1 only
if(newRef0==ref1)
{
// r0 - r1
// r1 - x
lineStrip.pushBack(newRef1); // Output the other reference
ref0 = newRef0;
ref1 = newRef1;
Copy.remove(i);
goto Wrap;
}
else if(newRef1==ref1)
{
// r0 - r1
// x - r1 => r1 - x
lineStrip.pushBack(newRef0); // Output the other reference
ref0 = newRef1;
ref1 = newRef0;
Copy.remove(i);
goto Wrap;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
// Test for duplicate triangles
PX_COMPILE_TIME_ASSERT(sizeof(IndexedTriangle32)==sizeof(PxVec3)); // ...
static bool TestDuplicateTriangles(PxU32& nbFaces, IndexedTriangle32* faces, bool repair)
{
if(!nbFaces || !faces)
return true;
IndexedTriangle32* indices32 = reinterpret_cast<IndexedTriangle32*>(PxAlloca(nbFaces*sizeof(IndexedTriangle32)));
for(PxU32 i=0;i<nbFaces;i++)
{
indices32[i].mRef[0] = faces[i].mRef[0];
indices32[i].mRef[1] = faces[i].mRef[1];
indices32[i].mRef[2] = faces[i].mRef[2];
}
// Radix-sort power...
ReducedVertexCloud reducer(reinterpret_cast<PxVec3*>(indices32), nbFaces);
REDUCEDCLOUD rc;
reducer.reduce(&rc);
if(rc.NbRVerts<nbFaces)
{
if(repair)
{
nbFaces = rc.NbRVerts;
for(PxU32 i=0;i<nbFaces;i++)
{
const IndexedTriangle32* curTri = reinterpret_cast<const IndexedTriangle32*>(&rc.RVerts[i]);
faces[i].mRef[0] = curTri->mRef[0];
faces[i].mRef[1] = curTri->mRef[1];
faces[i].mRef[2] = curTri->mRef[2];
}
}
return false; // Test failed
}
return true; // Test succeeded
}
//////////////////////////////////////////////////////////////////////////
// plane culling test
static PX_FORCE_INLINE bool testCulling(const IndexedTriangle32& triangle, const PxVec3* verts, const PxVec3& center)
{
const PxPlane plane(verts[triangle.mRef[0]], verts[triangle.mRef[1]], verts[triangle.mRef[2]]);
return plane.distance(center)>0.0f;
}
//////////////////////////////////////////////////////////////////////////
// face normals test
static bool TestUnifiedNormals(PxU32 nbVerts, const PxVec3* verts, PxU32 nbFaces, IndexedTriangle32* faces, bool repair)
{
if(!nbVerts || !verts || !nbFaces || !faces)
return false;
// Unify normals so that all hull faces are well oriented
// Compute geometric center - we need a vertex inside the hull
const float coeff = 1.0f / float(nbVerts);
PxVec3 geomCenter(0.0f, 0.0f, 0.0f);
for(PxU32 i=0;i<nbVerts;i++)
{
geomCenter.x += verts[i].x * coeff;
geomCenter.y += verts[i].y * coeff;
geomCenter.z += verts[i].z * coeff;
}
// We know the hull is (hopefully) convex so we can easily test whether a point is inside the hull or not.
// The previous geometric center must be invisible from any hull face: that's our test to decide whether a normal
// must be flipped or not.
bool status = true;
for(PxU32 i=0;i<nbFaces;i++)
{
// Test face visibility from the geometric center (supposed to be inside the hull).
// All faces must be invisible from this point to ensure a strict CCW order.
if(testCulling(faces[i], verts, geomCenter))
{
if(repair) faces[i].flip();
status = false;
}
}
return status;
}
//////////////////////////////////////////////////////////////////////////
// clean the mesh
static bool CleanFaces(PxU32& nbFaces, IndexedTriangle32* faces, PxU32& nbVerts, PxVec3* verts)
{
// Brute force mesh cleaning.
// PT: I added this back on Feb-18-05 because it fixes bugs with hulls from QHull.
MeshCleaner cleaner(nbVerts, verts, nbFaces, faces->mRef, 0.0f, 0.0f);
if (!cleaner.mNbTris)
return false;
nbVerts = cleaner.mNbVerts;
nbFaces = cleaner.mNbTris;
PxMemCopy(verts, cleaner.mVerts, cleaner.mNbVerts*sizeof(PxVec3));
for (PxU32 i = 0; i < cleaner.mNbTris; i++)
{
faces[i].mRef[0] = cleaner.mIndices[i * 3 + 0];
faces[i].mRef[1] = cleaner.mIndices[i * 3 + 1];
faces[i].mRef[2] = cleaner.mIndices[i * 3 + 2];
}
// Get rid of duplicates
TestDuplicateTriangles(nbFaces, faces, true);
// Unify normals
TestUnifiedNormals(nbVerts, verts, nbFaces, faces, true);
// Remove zero-area triangles
// TestZeroAreaTriangles(nbFaces, faces, verts, true);
// Unify normals again
TestUnifiedNormals(nbVerts, verts, nbFaces, faces, true);
// Get rid of duplicates again
TestDuplicateTriangles(nbFaces, faces, true);
return true;
}
//////////////////////////////////////////////////////////////////////////
// check the newly constructed faces
static bool CheckFaces(PxU32 nbFaces, const IndexedTriangle32* faces, PxU32 nbVerts, const PxVec3* verts)
{
// Remove const since we use functions that can do both testing & repairing. But we won't change the data.
IndexedTriangle32* f = const_cast<IndexedTriangle32*>(faces);
// Test duplicate faces
if(!TestDuplicateTriangles(nbFaces, f, false))
return false;
// Test unified normals
if(!TestUnifiedNormals(nbVerts, verts, nbFaces, f, false))
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
// compute the newell plane from the face verts
static bool computeNewellPlane(PxPlane& plane, PxU32 nbVerts, const PxU8* indices, const PxVec3* verts)
{
if(!nbVerts || !indices || !verts)
return false;
PxVec3 centroid(0,0,0), normal(0,0,0);
for(PxU32 i=nbVerts-1, j=0; j<nbVerts; i=j, j++)
{
normal.x += (verts[indices[i]].y - verts[indices[j]].y) * (verts[indices[i]].z + verts[indices[j]].z);
normal.y += (verts[indices[i]].z - verts[indices[j]].z) * (verts[indices[i]].x + verts[indices[j]].x);
normal.z += (verts[indices[i]].x - verts[indices[j]].x) * (verts[indices[i]].y + verts[indices[j]].y);
centroid += verts[indices[j]];
}
plane.n = normal;
plane.n.normalize();
plane.d = -(centroid.dot(plane.n))/float(nbVerts);
return true;
}
/**
* Analyses a redundant vertices and splits the polygons if necessary.
* \relates ConvexHull
* \fn extractHullPolygons(Container& polygon_data, const ConvexHull& hull)
* \param nb_polygons [out] number of extracted polygons
* \param polygon_data [out] polygon data: (Nb indices, index 0, index 1... index N)(Nb indices, index 0, index 1... index N)(...)
* \param hull [in] convex hull
* \param redundantVertices [out] redundant vertices found inside the polygons - we want to remove them because of PCM
*/
static void checkRedundantVertices(PxU32& nb_polygons, PxArray<PxU32>& polygon_data, const ConvexPolygonsBuilder& hull, PxArray<PxU32>& triangle_data, PxArray<PxU32>& redundantVertices)
{
const PxU32* dFaces = reinterpret_cast<const PxU32*>(hull.getFaces());
bool needToSplitPolygons = false;
bool* polygonMarkers = reinterpret_cast<bool*>(PxAlloca(nb_polygons*sizeof(bool)));
PxMemZero(polygonMarkers, nb_polygons*sizeof(bool));
bool* redundancyMarkers = reinterpret_cast<bool*>(PxAlloca(redundantVertices.size()*sizeof(bool)));
PxMemZero(redundancyMarkers, redundantVertices.size()*sizeof(bool));
// parse through the redundant vertices and if we cannot remove them split just the actual polygon if possible
PxArray<PxU32> polygonsContainer;
PxU32 numEntries = 0;
for (PxU32 i = redundantVertices.size(); i--;)
{
numEntries = 0;
polygonsContainer.clear();
// go through polygons, if polygons does have only 3 verts we cannot remove any vertex from it, try to decompose the second one
PxU32* Data = polygon_data.begin();
for(PxU32 t=0;t<nb_polygons;t++)
{
PxU32 nbVerts = *Data++;
PX_ASSERT(nbVerts>=3); // Else something very wrong happened...
for(PxU32 j=0;j<nbVerts;j++)
{
if(redundantVertices[i] == Data[j])
{
polygonsContainer.pushBack(t);
polygonsContainer.pushBack(nbVerts);
numEntries++;
break;
}
}
Data += nbVerts;
}
bool needToSplit = false;
for (PxU32 j = 0; j < numEntries; j++)
{
PxU32 numInternalVertices = polygonsContainer[j*2 + 1];
if(numInternalVertices == 3)
{
needToSplit = true;
}
}
// now lets mark the polygons for split
if(needToSplit)
{
// mark the redundant vertex, it is solved by spliting, dont report it
needToSplitPolygons = true;
redundancyMarkers[i] = true;
for (PxU32 j = 0; j < numEntries; j++)
{
PxU32 polygonNumber = polygonsContainer[j*2];
PxU32 numInternalPolygons = polygonsContainer[j*2 + 1];
if(numInternalPolygons != 3)
{
polygonMarkers[polygonNumber] = true;
}
}
}
}
if(needToSplitPolygons)
{
// parse from the end so we can remove it and not change the order
for (PxU32 i = redundantVertices.size(); i--;)
{
// remove it
if(redundancyMarkers[i])
{
redundantVertices.remove(i);
}
}
PxArray<PxU32> newPolygon_data;
PxArray<PxU32> newTriangle_data;
PxU32 newNb_polygons = 0;
PxU32* data = polygon_data.begin();
PxU32* triData = triangle_data.begin();
for(PxU32 i=0;i<nb_polygons;i++)
{
PxU32 nbVerts = *data++;
PxU32 nbTris = *triData++;
if(polygonMarkers[i])
{
// split the polygon into triangles
for(PxU32 k=0;k< nbTris; k++)
{
newNb_polygons++;
const PxU32 faceIndex = triData[k];
newPolygon_data.pushBack(PxU32(3));
newPolygon_data.pushBack(dFaces[3*faceIndex]);
newPolygon_data.pushBack(dFaces[3*faceIndex + 1]);
newPolygon_data.pushBack(dFaces[3*faceIndex + 2]);
newTriangle_data.pushBack(PxU32(1));
newTriangle_data.pushBack(faceIndex);
}
}
else
{
newNb_polygons++;
// copy the original polygon
newPolygon_data.pushBack(nbVerts);
for(PxU32 j=0;j<nbVerts;j++)
newPolygon_data.pushBack(data[j]);
// copy the original polygon triangles
newTriangle_data.pushBack(nbTris);
for(PxU32 k=0;k< nbTris; k++)
{
newTriangle_data.pushBack(triData[k]);
}
}
data += nbVerts;
triData += nbTris;
}
// now put the data to output
polygon_data.clear();
triangle_data.clear();
// the copy does copy even the data
polygon_data = newPolygon_data;
triangle_data = newTriangle_data;
nb_polygons = newNb_polygons;
}
}
/**
* Analyses a convex hull made of triangles and extracts polygon data out of it.
* \relates ConvexHull
* \fn extractHullPolygons(PxArray<PxU32>& polygon_data, const ConvexHull& hull)
* \param nb_polygons [out] number of extracted polygons
* \param polygon_data [out] polygon data: (Nb indices, index 0, index 1... index N)(Nb indices, index 0, index 1... index N)(...)
* \param hull [in] convex hull
* \param triangle_data [out] triangle data
* \param rendundantVertices [out] redundant vertices found inside the polygons - we want to remove them because of PCM
* \return true if success
*/
static bool extractHullPolygons(PxU32& nb_polygons, PxArray<PxU32>& polygon_data, const ConvexPolygonsBuilder& hull, PxArray<PxU32>* triangle_data, PxArray<PxU32>& rendundantVertices)
{
PxU32 nbFaces = hull.getNbFaces();
const PxVec3* hullVerts = hull.mHullDataHullVertices;
const PxU32 nbVertices = hull.mHull->mNbHullVertices;
const PxU16* wFaces = NULL;
const PxU32* dFaces = reinterpret_cast<const PxU32*>(hull.getFaces());
PX_ASSERT(wFaces || dFaces);
ADJACENCIESCREATE create;
create.NbFaces = nbFaces;
create.DFaces = dFaces;
create.WFaces = wFaces;
create.Verts = hullVerts;
//Create.Epsilon = 0.01f; // PT: trying to fix Rob Elam bug. Also fixes TTP 2467
// Create.Epsilon = 0.001f; // PT: for "Bruno's bug"
create.Epsilon = 0.005f; // PT: middle-ground seems to fix both. Expose this param?
AdjacenciesBuilder adj;
if(!adj.Init(create)) return false;
PxU32 nbBoundaryEdges = adj.ComputeNbBoundaryEdges();
if(nbBoundaryEdges) return false; // A valid hull shouldn't have open edges!!
bool* markers = reinterpret_cast<bool*>(PxAlloca(nbFaces*sizeof(bool)));
PxMemZero(markers, nbFaces*sizeof(bool));
PxU8* vertexMarkers = reinterpret_cast<PxU8*>(PxAlloca(nbVertices*sizeof(PxU8)));
PxMemZero(vertexMarkers, nbVertices*sizeof(PxU8));
PxU32 currentFace = 0; // Start with first triangle
nb_polygons = 0;
do
{
currentFace = 0;
while(currentFace<nbFaces && markers[currentFace]) currentFace++;
// Start from "closest" face and floodfill through inactive edges
struct Local
{
static void FloodFill(PxArray<PxU32>& indices, const AdjTriangle* faces, PxU32 current, bool* inMarkers)
{
if(inMarkers[current]) return;
inMarkers[current] = true;
indices.pushBack(current);
const AdjTriangle& AT = faces[current];
// We can floodfill through inactive edges since the mesh is convex (inactive==planar)
if(!AT.HasActiveEdge01()) FloodFill(indices, faces, AT.GetAdjTri(EDGE01), inMarkers);
if(!AT.HasActiveEdge20()) FloodFill(indices, faces, AT.GetAdjTri(EDGE02), inMarkers);
if(!AT.HasActiveEdge12()) FloodFill(indices, faces, AT.GetAdjTri(EDGE12), inMarkers);
}
static bool GetNeighborFace(PxU32 index,PxU32 triangleIndex,const AdjTriangle* faces, const PxU32* dfaces, PxU32& neighbor, PxU32& current)
{
PxU32 currentIndex = index;
PxU32 previousIndex = index;
bool firstFace = true;
bool next = true;
while (next)
{
const AdjTriangle& currentAT = faces[currentIndex];
PxU32 refTr0 = dfaces[currentIndex*3 + 0];
PxU32 refTr1 = dfaces[currentIndex*3 + 1];
PxU32 edge[2];
edge[0] = 1;
edge[1] = 2;
if(triangleIndex == refTr0)
{
edge[0] = 0;
edge[1] = 1;
}
else
{
if(triangleIndex == refTr1)
{
edge[0] = 0;
edge[1] = 2;
}
}
if(currentAT.HasActiveEdge(edge[0]) && currentAT.HasActiveEdge(edge[1]))
{
return false;
}
if(!currentAT.HasActiveEdge(edge[0]) && !currentAT.HasActiveEdge(edge[1]))
{
// not interested in testing transition vertices
if(currentIndex == index)
{
return false;
}
// transition one
for (PxU32 i = 0; i < 2; i++)
{
PxU32 testIndex = currentAT.GetAdjTri(SharedEdgeIndex(edge[i]));
// exit if we circle around the vertex back to beginning
if(testIndex == index && previousIndex != index)
{
return false;
}
if(testIndex != previousIndex)
{
// move to next
previousIndex = currentIndex;
currentIndex = testIndex;
break;
}
}
}
else
{
if(!currentAT.HasActiveEdge(edge[0]))
{
PxU32 t = edge[0];
edge[0] = edge[1];
edge[1] = t;
}
if(currentAT.HasActiveEdge(edge[0]))
{
PxU32 testIndex = currentAT.GetAdjTri(SharedEdgeIndex(edge[0]));
if(firstFace)
{
firstFace = false;
}
else
{
neighbor = testIndex;
current = currentIndex;
return true;
}
}
if(!currentAT.HasActiveEdge(edge[1]))
{
PxU32 testIndex = currentAT.GetAdjTri(SharedEdgeIndex(edge[1]));
if(testIndex != index)
{
previousIndex = currentIndex;
currentIndex = testIndex;
}
}
}
}
return false;
}
static bool CheckFloodFillFace(PxU32 index,const AdjTriangle* faces, const PxU32* dfaces)
{
if(!dfaces)
return true;
const AdjTriangle& checkedAT = faces[index];
PxU32 refTr0 = dfaces[index*3 + 0];
PxU32 refTr1 = dfaces[index*3 + 1];
PxU32 refTr2 = dfaces[index*3 + 2];
for (PxU32 i = 0; i < 3; i++)
{
if(!checkedAT.HasActiveEdge(i))
{
PxU32 testTr0 = refTr1;
PxU32 testTr1 = refTr2;
PxU32 testIndex0 = 0;
PxU32 testIndex1 = 1;
if(i == 0)
{
testTr0 = refTr0;
testTr1 = refTr1;
testIndex0 = 1;
testIndex1 = 2;
}
else
{
if(i == 1)
{
testTr0 = refTr0;
testTr1 = refTr2;
testIndex0 = 0;
testIndex1 = 2;
}
}
PxU32 adjFaceTested = checkedAT.GetAdjTri(SharedEdgeIndex(testIndex0));
PxU32 neighborIndex00;
PxU32 neighborIndex01;
bool found0 = GetNeighborFace(index,testTr0,faces,dfaces, neighborIndex00, neighborIndex01);
PxU32 neighborIndex10;
PxU32 neighborIndex11;
bool found1 = GetNeighborFace(adjFaceTested,testTr0,faces,dfaces, neighborIndex10, neighborIndex11);
if(found0 && found1 && neighborIndex00 == neighborIndex11 && neighborIndex01 == neighborIndex10)
{
return false;
}
adjFaceTested = checkedAT.GetAdjTri(SharedEdgeIndex(testIndex1));
found0 = GetNeighborFace(index,testTr1,faces,dfaces,neighborIndex00,neighborIndex01);
found1 = GetNeighborFace(adjFaceTested,testTr1,faces,dfaces,neighborIndex10,neighborIndex11);
if(found0 && found1 && neighborIndex00 == neighborIndex11 && neighborIndex01 == neighborIndex10)
{
return false;
}
}
}
return true;
}
static bool CheckFloodFill(PxArray<PxU32>& indices,AdjTriangle* faces,bool* inMarkers, const PxU32* dfaces)
{
bool valid = true;
for(PxU32 i=0;i<indices.size();i++)
{
//const AdjTriangle& AT = faces[indices.GetEntry(i)];
for(PxU32 j= i + 1;j<indices.size();j++)
{
const AdjTriangle& testAT = faces[indices[j]];
if(testAT.GetAdjTri(EDGE01) == indices[i])
{
if(testAT.HasActiveEdge01())
{
valid = false;
}
}
if(testAT.GetAdjTri(EDGE02) == indices[i])
{
if(testAT.HasActiveEdge20())
{
valid = false;
}
}
if(testAT.GetAdjTri(EDGE12) == indices[i])
{
if(testAT.HasActiveEdge12())
{
valid = false;
}
}
if(!valid)
break;
}
if(!CheckFloodFillFace(indices[i], faces, dfaces))
{
valid = false;
}
if(!valid)
break;
}
if(!valid)
{
for(PxU32 i=0;i<indices.size();i++)
{
AdjTriangle& AT = faces[indices[i]];
AT.mATri[0] |= 0x20000000;
AT.mATri[1] |= 0x20000000;
AT.mATri[2] |= 0x20000000;
inMarkers[indices[i]] = false;
}
indices.forceSize_Unsafe(0);
return true;
}
return false;
}
};
if(currentFace!=nbFaces)
{
PxArray<PxU32> indices; // Indices of triangles forming hull polygon
bool doFill = true;
while (doFill)
{
Local::FloodFill(indices, adj.mFaces, currentFace, markers);
doFill = Local::CheckFloodFill(indices,adj.mFaces,markers, dFaces);
}
// Now it would be nice to recreate a closed linestrip, similar to silhouette extraction. The line is composed of active edges, this time.
PxArray<Pair> activeSegments;
//Container ActiveSegments;
// Loop through triangles composing the polygon
for(PxU32 i=0;i<indices.size();i++)
{
const PxU32 currentTriIndex = indices[i]; // Catch current triangle
const PxU32 vRef0 = dFaces ? dFaces[currentTriIndex*3+0] : wFaces[currentTriIndex*3+0];
const PxU32 vRef1 = dFaces ? dFaces[currentTriIndex*3+1] : wFaces[currentTriIndex*3+1];
const PxU32 vRef2 = dFaces ? dFaces[currentTriIndex*3+2] : wFaces[currentTriIndex*3+2];
// Keep active edges
if(adj.mFaces[currentTriIndex].HasActiveEdge01()) { activeSegments.pushBack(Pair(vRef0,vRef1)); }
if(adj.mFaces[currentTriIndex].HasActiveEdge20()) { activeSegments.pushBack(Pair(vRef0,vRef2)); }
if(adj.mFaces[currentTriIndex].HasActiveEdge12()) { activeSegments.pushBack(Pair(vRef1,vRef2)); }
}
// We assume the polygon is convex. In that case it should always be possible to retriangulate it so that the triangles are
// implicit (in particular, it should always be possible to remove interior triangles)
PxArray<PxU32> lineStrip;
if(findLineStrip(lineStrip, activeSegments))
{
PxU32 nb = lineStrip.size();
if(nb)
{
const PxU32* entries = lineStrip.begin();
PX_ASSERT(entries[0] == entries[nb-1]); // findLineStrip() is designed that way. Might not be what we want!
// We get rid of the last (duplicated) index
polygon_data.pushBack(nb-1);
for (PxU32 i = 0; i < nb-1; i++)
{
vertexMarkers[entries[i]]++;
polygon_data.pushBack(entries[i]);
}
nb_polygons++;
// Loop through vertices composing the line strip polygon end mark the redundant vertices inside the polygon
for(PxU32 i=0;i<indices.size();i++)
{
const PxU32 CurrentTriIndex = indices[i]; // Catch current triangle
const PxU32 VRef0 = dFaces ? dFaces[CurrentTriIndex*3+0] : wFaces[CurrentTriIndex*3+0];
const PxU32 VRef1 = dFaces ? dFaces[CurrentTriIndex*3+1] : wFaces[CurrentTriIndex*3+1];
const PxU32 VRef2 = dFaces ? dFaces[CurrentTriIndex*3+2] : wFaces[CurrentTriIndex*3+2];
bool found0 = false;
bool found1 = false;
bool found2 = false;
for (PxU32 j=0;j < nb - 1; j++)
{
if(VRef0 == entries[j])
{
found0 = true;
}
if(VRef1 == entries[j])
{
found1 = true;
}
if(VRef2 == entries[j])
{
found2 = true;
}
if(found0 && found1 && found2)
break;
}
if(!found0)
{
if(rendundantVertices.find(VRef0) == rendundantVertices.end())
rendundantVertices.pushBack(VRef0);
}
if(!found1)
{
if(rendundantVertices.find(VRef1) == rendundantVertices.end())
rendundantVertices.pushBack(VRef1);
}
if(!found2)
{
if(rendundantVertices.find(VRef2) == rendundantVertices.end())
rendundantVertices.pushBack(VRef2);
}
}
// If needed, output triangle indices used to build this polygon
if(triangle_data)
{
triangle_data->pushBack(indices.size());
for (PxU32 j = 0; j < indices.size(); j++)
triangle_data->pushBack(indices[j]);
}
}
}
else
return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Meshmerizer::extractHullPolygons: line strip extraction failed");
}
}
while(currentFace!=nbFaces);
for (PxU32 i = 0; i < nbVertices; i++)
{
if(vertexMarkers[i] < 3)
{
if(rendundantVertices.find(i) == rendundantVertices.end())
rendundantVertices.pushBack(i);
}
}
if(rendundantVertices.size() > 0 && triangle_data)
checkRedundantVertices(nb_polygons,polygon_data,hull,*triangle_data,rendundantVertices);
return true;
}
//////////////////////////////////////////////////////////////////////////
ConvexPolygonsBuilder::ConvexPolygonsBuilder(ConvexHullData* hull, const bool buildGRBData)
: ConvexHullBuilder(hull, buildGRBData), mNbHullFaces(0), mFaces(NULL)
{
}
//////////////////////////////////////////////////////////////////////////
ConvexPolygonsBuilder::~ConvexPolygonsBuilder()
{
PX_FREE(mFaces);
}
//////////////////////////////////////////////////////////////////////////
// compute hull polygons from given hull triangles
bool ConvexPolygonsBuilder::computeHullPolygons(const PxU32& nbVerts,const PxVec3* verts, const PxU32& nbTriangles, const PxU32* triangles)
{
PX_ASSERT(triangles);
PX_ASSERT(verts);
mHullDataHullVertices = NULL;
mHullDataPolygons = NULL;
mHullDataVertexData8 = NULL;
mHullDataFacesByEdges8 = NULL;
mHullDataFacesByVertices8 = NULL;
mNbHullFaces = nbTriangles;
mHull->mNbHullVertices = PxTo8(nbVerts);
// allocate additional vec3 for V4 safe load in VolumeInteration
mHullDataHullVertices = PX_ALLOCATE(PxVec3, (mHull->mNbHullVertices + 1), "PxVec3");
PxMemCopy(mHullDataHullVertices, verts, mHull->mNbHullVertices*sizeof(PxVec3));
mFaces = PX_ALLOCATE(IndexedTriangle32, mNbHullFaces, "mFaces");
for(PxU32 i=0;i<mNbHullFaces;i++)
{
PX_ASSERT(triangles[i*3+0]<=0xffff);
PX_ASSERT(triangles[i*3+1]<=0xffff);
PX_ASSERT(triangles[i*3+2]<=0xffff);
mFaces[i].mRef[0] = triangles[i*3+0];
mFaces[i].mRef[1] = triangles[i*3+1];
mFaces[i].mRef[2] = triangles[i*3+2];
}
IndexedTriangle32* hullAsIndexedTriangle = mFaces;
// We don't trust the user at all... So, clean the hull.
PxU32 nbHullVerts = mHull->mNbHullVertices;
CleanFaces(mNbHullFaces, hullAsIndexedTriangle, nbHullVerts, mHullDataHullVertices);
PX_ASSERT(nbHullVerts<256);
mHull->mNbHullVertices = PxTo8(nbHullVerts);
// ...and then run the full tests again.
if(!CheckFaces(mNbHullFaces, hullAsIndexedTriangle, mHull->mNbHullVertices, mHullDataHullVertices))
return false;
// Transform triangles-to-polygons
if(!createPolygonData())
return false;
return checkHullPolygons();
}
/**
* Computes polygon data.
* \return true if success
*/
bool ConvexPolygonsBuilder::createPolygonData()
{
// Cleanup
mHull->mNbPolygons = 0;
PX_FREE(mHullDataVertexData8);
PX_FREE(mHullDataFacesByVertices8);
PX_FREE(mHullDataPolygons);
// Extract polygon data from triangle data
PxArray<PxU32> temp;
PxArray<PxU32> temp2;
PxArray<PxU32> rendundantVertices;
PxU32 nbPolygons;
if(!extractHullPolygons(nbPolygons, temp, *this, &temp2,rendundantVertices))
return false;
PxVec3* reducedHullDataHullVertices = mHullDataHullVertices;
PxU8 numReducedHullDataVertices = mHull->mNbHullVertices;
if(rendundantVertices.size() > 0)
{
numReducedHullDataVertices = PxTo8(mHull->mNbHullVertices - rendundantVertices.size());
reducedHullDataHullVertices = PX_ALLOCATE(PxVec3, numReducedHullDataVertices, "Reduced vertices hull data");
PxU8* remapTable = PX_ALLOCATE(PxU8, mHull->mNbHullVertices, "remapTable");
PxU8 currentIndex = 0;
for (PxU8 i = 0; i < mHull->mNbHullVertices; i++)
{
if(rendundantVertices.find(i) == rendundantVertices.end())
{
PX_ASSERT(currentIndex < numReducedHullDataVertices);
reducedHullDataHullVertices[currentIndex] = mHullDataHullVertices[i];
remapTable[i] = currentIndex;
currentIndex++;
}
else
{
remapTable[i] = 0xFF;
}
}
PxU32* data = temp.begin();
for(PxU32 i=0;i<nbPolygons;i++)
{
PxU32 nbVerts = *data++;
PX_ASSERT(nbVerts>=3); // Else something very wrong happened...
for(PxU32 j=0;j<nbVerts;j++)
{
PX_ASSERT(data[j] < mHull->mNbHullVertices);
data[j] = remapTable[data[j]];
}
data += nbVerts;
}
PX_FREE(remapTable);
}
if(nbPolygons>255)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "ConvexHullBuilder: convex hull has more than 255 polygons!");
// Precompute hull polygon structures
mHull->mNbPolygons = PxTo8(nbPolygons);
mHullDataPolygons = PX_ALLOCATE(HullPolygonData, mHull->mNbPolygons, "Gu::HullPolygonData");
PxMemZero(mHullDataPolygons, sizeof(HullPolygonData)*mHull->mNbPolygons);
// The winding hasn't been preserved so we need to handle this. Basically we need to "unify normals"
// exactly as we did at hull creation time - except this time we work on polygons
PxVec3 geomCenter;
computeGeomCenter(geomCenter, mNbHullFaces, mFaces, mHullDataHullVertices, mHull->mNbHullVertices);
// Loop through polygons
// We have N polygons => remove N entries for number of vertices
PxU32 tmp = temp.size() - nbPolygons;
mHullDataVertexData8 = PX_ALLOCATE(PxU8, tmp, "mHullDataVertexData8");
PxU8* dest = mHullDataVertexData8;
const PxU32* data = temp.begin();
const PxU32* triData = temp2.begin();
for(PxU32 i=0;i<nbPolygons;i++)
{
mHullDataPolygons[i].mVRef8 = PxU16(dest - mHullDataVertexData8); // Setup link for current polygon
PxU32 nbVerts = *data++;
PX_ASSERT(nbVerts>=3); // Else something very wrong happened...
mHullDataPolygons[i].mNbVerts = PxTo8(nbVerts);
PxU32 index = 0;
for(PxU32 j=0;j<nbVerts;j++)
{
if(data[j] != 0xFF)
{
dest[index] = PxTo8(data[j]);
index++;
}
else
{
mHullDataPolygons[i].mNbVerts--;
}
}
// Compute plane equation
{
computeNewellPlane(mHullDataPolygons[i].mPlane, mHullDataPolygons[i].mNbVerts, dest, reducedHullDataHullVertices);
PxU32 nbTris = *triData++; // #tris in current poly
bool flip = false;
for(PxU32 k=0;k< nbTris; k++)
{
PxU32 triIndex = *triData++; // Index of one triangle composing polygon
PX_ASSERT(triIndex<mNbHullFaces);
const IndexedTriangle32& T = reinterpret_cast<const IndexedTriangle32&>(mFaces[triIndex]);
const PxPlane PL = PlaneEquation(T, mHullDataHullVertices);
if(k==0 && PL.n.dot(mHullDataPolygons[i].mPlane.n) < 0.0f)
{
flip = true;
}
}
if(flip)
{
negatePlane(mHullDataPolygons[i]);
inverseBuffer(mHullDataPolygons[i].mNbVerts, dest);
}
for(PxU32 j=0;j<mHull->mNbHullVertices;j++)
{
float d = - (mHullDataPolygons[i].mPlane.n).dot(mHullDataHullVertices[j]);
if(d<mHullDataPolygons[i].mPlane.d) mHullDataPolygons[i].mPlane.d=d;
}
}
// "Unify normal"
if(mHullDataPolygons[i].mPlane.distance(geomCenter)>0.0f)
{
inverseBuffer(mHullDataPolygons[i].mNbVerts, dest);
negatePlane(mHullDataPolygons[i]);
PX_ASSERT(mHullDataPolygons[i].mPlane.distance(geomCenter)<=0.0f);
}
// Next one
data += nbVerts; // Skip vertex indices
dest += mHullDataPolygons[i].mNbVerts;
}
if(reducedHullDataHullVertices != mHullDataHullVertices)
{
PxMemCopy(mHullDataHullVertices,reducedHullDataHullVertices,sizeof(PxVec3)*numReducedHullDataVertices);
PX_FREE(reducedHullDataHullVertices);
mHull->mNbHullVertices = numReducedHullDataVertices;
}
//calculate the vertex map table
if(!calculateVertexMapTable(nbPolygons))
return false;
#ifdef USE_PRECOMPUTED_HULL_PROJECTION
// Loop through polygons
for(PxU32 j=0;j<nbPolygons;j++)
{
// Precompute hull projection along local polygon normal
PxU32 nbVerts = mHull->mNbHullVertices;
const PxVec3* verts = mHullDataHullVertices;
HullPolygonData& polygon = mHullDataPolygons[j];
PxReal min = PX_MAX_F32;
PxU8 minIndex = 0xff;
for (PxU8 i = 0; i < nbVerts; i++)
{
float dp = (*verts++).dot(polygon.mPlane.n);
if(dp < min)
{
min = dp;
minIndex = i;
}
}
polygon.mMinIndex = minIndex;
}
#endif
// Triangulate newly created polygons to recreate a clean vertex cloud.
return createTrianglesFromPolygons();
}
//////////////////////////////////////////////////////////////////////////
// create back triangles from polygons
bool ConvexPolygonsBuilder::createTrianglesFromPolygons()
{
if (!mHull->mNbPolygons || !mHullDataPolygons) return false;
PxU32 maxNbTriangles = 0;
for (PxU32 i = 0; i < mHull->mNbPolygons; i++)
{
if (mHullDataPolygons[i].mNbVerts < 3)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "ConvexHullBuilder::CreateTrianglesFromPolygons: convex hull has a polygon with less than 3 vertices!");
maxNbTriangles += mHullDataPolygons[i].mNbVerts - 2;
}
IndexedTriangle32* tmpFaces = PX_ALLOCATE(IndexedTriangle32, maxNbTriangles, "tmpFaces");
IndexedTriangle32* currFace = tmpFaces;
PxU32 nbTriangles = 0;
const PxU8* vertexData = mHullDataVertexData8;
const PxVec3* hullVerts = mHullDataHullVertices;
for (PxU32 i = 0; i < mHull->mNbPolygons; i++)
{
const PxU8* data = vertexData + mHullDataPolygons[i].mVRef8;
PxU32 nbVerts = mHullDataPolygons[i].mNbVerts;
// Triangulate the polygon such that all all generated triangles have one and the same vertex
// in common.
//
// Make sure to avoid creating zero area triangles. Imagine the following polygon:
//
// 4 3
// *------------------*
// | |
// *---*----*----*----*
// 5 6 0 1 2
//
// Choosing vertex 0 as the shared vertex, the following zero area triangles will be created:
// [0 1 2], [0 5 6]
//
// Check for these triangles and discard them
// Note: Such polygons should only occur if the user defines the convex hull, i.e., the triangles
// of the convex shape, himself. If the convex hull is built from the vertices only, the
// hull algorithm removes the useless vertices.
//
for (PxU32 j = 0; j < nbVerts - 2; j++)
{
currFace->mRef[0] = data[0];
currFace->mRef[1] = data[(j + 1) % nbVerts];
currFace->mRef[2] = data[(j + 2) % nbVerts];
const PxVec3& p0 = hullVerts[currFace->mRef[0]];
const PxVec3& p1 = hullVerts[currFace->mRef[1]];
const PxVec3& p2 = hullVerts[currFace->mRef[2]];
const float area = ((p1 - p0).cross(p2 - p0)).magnitudeSquared();
if (area != 0.0f) // Else discard the triangle
{
nbTriangles++;
currFace++;
}
}
}
PX_FREE(mFaces);
IndexedTriangle32* faces;
PX_ASSERT(nbTriangles <= maxNbTriangles);
if (maxNbTriangles == nbTriangles)
{
// No zero area triangles, hence the face buffer has correct size and can be used directly.
faces = tmpFaces;
}
else
{
// Resize face buffer because some triangles were discarded.
faces = PX_ALLOCATE(IndexedTriangle32, nbTriangles, "mFaces");
if (!faces) // PT: TODO: is there a reason why we test the alloc result here and nowhere else?
{
PX_FREE(tmpFaces);
return false;
}
PxMemCopy(faces, tmpFaces, sizeof(IndexedTriangle32)*nbTriangles);
PX_FREE(tmpFaces);
}
mFaces = faces;
mNbHullFaces = nbTriangles;
// TODO: at this point useless vertices should be removed from the hull. The current fix is to initialize
// support vertices to known valid vertices, but it's not really convincing.
// Re-unify normals
PxVec3 geomCenter;
computeGeomCenter(geomCenter, mNbHullFaces, mFaces, mHullDataHullVertices, mHull->mNbHullVertices);
for (PxU32 i = 0; i < mNbHullFaces; i++)
{
const PxPlane P(hullVerts[mFaces[i].mRef[0]],
hullVerts[mFaces[i].mRef[1]],
hullVerts[mFaces[i].mRef[2]]);
if (P.distance(geomCenter) > 0.0f)
{
mFaces[i].flip();
}
}
return true;
}
| 39,872 | C++ | 28.934685 | 199 | 0.644036 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuRTreeCooking.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 "foundation/PxMemory.h"
#include "common/PxTolerancesScale.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxSort.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxInlineArray.h"
#include "GuRTree.h"
#include "GuRTreeCooking.h"
#define PRINT_RTREE_COOKING_STATS 0 // AP: keeping this frequently used macro for diagnostics/benchmarking
#if PRINT_RTREE_COOKING_STATS
#include <stdio.h>
#endif
using namespace physx::Gu;
using namespace physx::aos;
namespace physx
{
// Google "wikipedia QuickSelect" for algorithm explanation
namespace quickSelect {
#define SWAP32(x, y) { PxU32 tmp = y; y = x; x = tmp; }
// left is the index of the leftmost element of the subarray
// right is the index of the rightmost element of the subarray (inclusive)
// number of elements in subarray = right-left+1
template<typename LtEq>
PxU32 partition(PxU32* PX_RESTRICT a, PxU32 left, PxU32 right, PxU32 pivotIndex, const LtEq& cmpLtEq)
{
PX_ASSERT(pivotIndex >= left && pivotIndex <= right);
PxU32 pivotValue = a[pivotIndex];
SWAP32(a[pivotIndex], a[right]) // Move pivot to end
PxU32 storeIndex = left;
for (PxU32 i = left; i < right; i++) // left <= i < right
if (cmpLtEq(a[i], pivotValue))
{
SWAP32(a[i], a[storeIndex]);
storeIndex++;
}
SWAP32(a[storeIndex], a[right]); // Move pivot to its final place
for (PxU32 i = left; i < storeIndex; i++)
PX_ASSERT(cmpLtEq(a[i], a[storeIndex]));
for (PxU32 i = storeIndex+1; i <= right; i++)
PX_ASSERT(cmpLtEq(a[storeIndex], a[i]));
return storeIndex;
}
// left is the index of the leftmost element of the subarray
// right is the index of the rightmost element of the subarray (inclusive)
// number of elements in subarray = right-left+1
// recursive version
template<typename LtEq>
void quickFindFirstK(PxU32* PX_RESTRICT a, PxU32 left, PxU32 right, PxU32 k, const LtEq& cmpLtEq)
{
PX_ASSERT(k <= right-left+1);
if (right > left)
{
// select pivotIndex between left and right
PxU32 pivotIndex = (left + right) >> 1;
PxU32 pivotNewIndex = partition(a, left, right, pivotIndex, cmpLtEq);
// now all elements to the left of pivotNewIndex are < old value of a[pivotIndex] (bottom half values)
if (pivotNewIndex > left + k) // new condition
quickFindFirstK(a, left, pivotNewIndex-1, k, cmpLtEq);
if (pivotNewIndex < left + k)
quickFindFirstK(a, pivotNewIndex+1, right, k+left-pivotNewIndex-1, cmpLtEq);
}
}
// non-recursive version
template<typename LtEq>
void quickSelectFirstK(PxU32* PX_RESTRICT a, PxU32 left, PxU32 right, PxU32 k, const LtEq& cmpLtEq)
{
PX_ASSERT(k <= right-left+1);
for (;;)
{
PxU32 pivotIndex = (left+right) >> 1;
PxU32 pivotNewIndex = partition(a, left, right, pivotIndex, cmpLtEq);
PxU32 pivotDist = pivotNewIndex - left + 1;
if (pivotDist == k)
return;
else if (k < pivotDist)
{
PX_ASSERT(pivotNewIndex > 0);
right = pivotNewIndex - 1;
}
else
{
k = k - pivotDist;
left = pivotNewIndex+1;
}
}
}
} // namespace quickSelect
// Intermediate non-quantized representation for RTree node in a page (final format is SIMD transposed page)
struct RTreeNodeNQ
{
PxBounds3 bounds;
PxI32 childPageFirstNodeIndex; // relative to the beginning of all build tree nodes array
PxI32 leafCount; // -1 for empty nodes, 0 for non-terminal nodes, number of enclosed tris if non-zero (LeafTriangles), also means a terminal node
struct U {}; // selector struct for uninitialized constructor
RTreeNodeNQ(U) {} // uninitialized constructor
RTreeNodeNQ() : bounds(PxBounds3::empty()), childPageFirstNodeIndex(-1), leafCount(0) {}
};
// SIMD version of bounds class
struct PxBounds3V
{
struct U {}; // selector struct for uninitialized constructor
Vec3V mn, mx;
PxBounds3V(Vec3VArg mn_, Vec3VArg mx_) : mn(mn_), mx(mx_) {}
PxBounds3V(U) {} // uninitialized constructor
PX_FORCE_INLINE Vec3V getExtents() const { return V3Sub(mx, mn); }
PX_FORCE_INLINE void include(const PxBounds3V& other) { mn = V3Min(mn, other.mn); mx = V3Max(mx, other.mx); }
// convert vector extents to PxVec3
PX_FORCE_INLINE const PxVec3 getMinVec3() const { PxVec3 ret; V3StoreU(mn, ret); return ret; }
PX_FORCE_INLINE const PxVec3 getMaxVec3() const { PxVec3 ret; V3StoreU(mx, ret); return ret; }
};
static void buildFromBounds(
Gu::RTree& resultTree, const PxBounds3V* allBounds, PxU32 numBounds,
PxArray<PxU32>& resultPermute, RTreeCooker::RemapCallback* rc, Vec3VArg allMn, Vec3VArg allMx,
PxReal sizePerfTradeOff, PxMeshCookingHint::Enum hint);
/////////////////////////////////////////////////////////////////////////
void RTreeCooker::buildFromTriangles(
Gu::RTree& result, const PxVec3* verts, PxU32 numVerts, const PxU16* tris16, const PxU32* tris32, PxU32 numTris,
PxArray<PxU32>& resultPermute, RTreeCooker::RemapCallback* rc, PxReal sizePerfTradeOff01, PxMeshCookingHint::Enum hint)
{
PX_UNUSED(numVerts);
PxArray<PxBounds3V> allBounds;
allBounds.reserve(numTris);
Vec3V allMn = Vec3V_From_FloatV(FMax()), allMx = Vec3V_From_FloatV(FNegMax());
Vec3V eps = V3Splat(FLoad(5e-4f)); // AP scaffold: use PxTolerancesScale here?
// build RTree AABB bounds from triangles, conservative bound inflation is also performed here
for(PxU32 i = 0; i < numTris; i ++)
{
PxU32 i0, i1, i2;
PxU32 i3 = i*3;
if(tris16)
{
i0 = tris16[i3]; i1 = tris16[i3+1]; i2 = tris16[i3+2];
} else
{
i0 = tris32[i3]; i1 = tris32[i3+1]; i2 = tris32[i3+2];
}
PX_ASSERT_WITH_MESSAGE(i0 < numVerts && i1 < numVerts && i2 < numVerts ,"Input mesh triangle's vertex index exceeds specified numVerts.");
Vec3V v0 = V3LoadU(verts[i0]), v1 = V3LoadU(verts[i1]), v2 = V3LoadU(verts[i2]);
Vec3V mn = V3Sub(V3Min(V3Min(v0, v1), v2), eps); // min over 3 verts, subtract eps to inflate
Vec3V mx = V3Add(V3Max(V3Max(v0, v1), v2), eps); // max over 3 verts, add eps to inflate
allMn = V3Min(allMn, mn); allMx = V3Max(allMx, mx);
allBounds.pushBack(PxBounds3V(mn, mx));
}
buildFromBounds(result, allBounds.begin(), numTris, resultPermute, rc, allMn, allMx, sizePerfTradeOff01, hint);
}
/////////////////////////////////////////////////////////////////////////
// Fast but lower quality 4-way split sorting using repeated application of quickselect
// comparator template struct for sortin gbounds centers given a coordinate index (x,y,z=0,1,2)
struct BoundsLTE
{
PxU32 coordIndex;
const PxVec3* PX_RESTRICT boundCenters; // AP: precomputed centers are faster than recomputing the centers
BoundsLTE(PxU32 coordIndex_, const PxVec3* boundCenters_)
: coordIndex(coordIndex_), boundCenters(boundCenters_)
{}
PX_FORCE_INLINE bool operator()(const PxU32 & idx1, const PxU32 & idx2) const
{
PxF32 center1 = boundCenters[idx1][coordIndex];
PxF32 center2 = boundCenters[idx2][coordIndex];
return (center1 <= center2);
}
};
// ======================================================================
// Quick sorting method
// recursive sorting procedure:
// 1. find min and max extent along each axis for the current cluster
// 2. split input cluster into two 3 times using quickselect, splitting off a quarter of the initial cluster size each time
// 3. the axis is potentialy different for each split using the following
// approximate splitting heuristic - reduce max length by some estimated factor to encourage split along other axis
// since we cut off between a quarter to a half of elements in this direction per split
// the reduction for first split should be *0.75f but we use 0.8
// to account for some node overlap. This is somewhat of an arbitrary choice and there's room for improvement.
// 4. recurse on new clusters (goto step 1)
//
struct SubSortQuick
{
static const PxReal reductionFactors[RTREE_N-1];
enum { NTRADEOFF = 9 };
static const PxU32 stopAtTrisPerLeaf1[NTRADEOFF]; // presets for PxCookingParams::meshSizePerformanceTradeoff implementation
const PxU32* permuteEnd;
const PxU32* permuteStart;
const PxBounds3V* allBounds;
PxArray<PxVec3> boundCenters;
PxU32 maxBoundsPerLeafPage;
// initialize the context for the sorting routine
SubSortQuick(PxU32* permute, const PxBounds3V* allBounds_, PxU32 allBoundsSize, PxReal sizePerfTradeOff01)
: allBounds(allBounds_)
{
permuteEnd = permute + allBoundsSize;
permuteStart = permute;
PxU32 boundsCount = allBoundsSize;
boundCenters.reserve(boundsCount); // AP - measured that precomputing centers helps with perf significantly (~20% on 1k verts)
for(PxU32 i = 0; i < boundsCount; i++)
boundCenters.pushBack( allBounds[i].getMinVec3() + allBounds[i].getMaxVec3() );
PxU32 iTradeOff = PxMin<PxU32>( PxU32(PxMax<PxReal>(0.0f, sizePerfTradeOff01)*NTRADEOFF), NTRADEOFF-1 );
maxBoundsPerLeafPage = stopAtTrisPerLeaf1[iTradeOff];
}
// implements the sorting/splitting procedure
void sort4(
PxU32* PX_RESTRICT permute, const PxU32 clusterSize, // beginning and size of current recursively processed cluster
PxArray<RTreeNodeNQ>& resultTree, PxU32& maxLevels,
PxBounds3V& subTreeBound, PxU32 level = 0)
{
if(level == 0)
maxLevels = 1;
else
maxLevels = PxMax(maxLevels, level+1);
PX_ASSERT(permute + clusterSize <= permuteEnd);
PX_ASSERT(maxBoundsPerLeafPage >= RTREE_N-1);
const PxU32 cluster4 = PxMax<PxU32>(clusterSize/RTREE_N, 1);
PX_ASSERT(clusterSize > 0);
// find min and max world bound for current cluster
Vec3V mx = allBounds[permute[0]].mx, mn = allBounds[permute[0]].mn; PX_ASSERT(permute[0] < boundCenters.size());
for(PxU32 i = 1; i < clusterSize; i ++)
{
PX_ASSERT(permute[i] < boundCenters.size());
mx = V3Max(mx, allBounds[permute[i]].mx);
mn = V3Min(mn, allBounds[permute[i]].mn);
}
PX_ALIGN_PREFIX(16) PxReal maxElem[4] PX_ALIGN_SUFFIX(16);
V3StoreA(V3Sub(mx, mn), *reinterpret_cast<PxVec3*>(maxElem)); // compute the dimensions and store into a scalar maxElem array
// split along the longest axis
const PxU32 maxDiagElement = PxU32(maxElem[0] > maxElem[1] && maxElem[0] > maxElem[2] ? 0 : (maxElem[1] > maxElem[2] ? 1 : 2));
BoundsLTE cmpLte(maxDiagElement, boundCenters.begin());
const PxU32 startNodeIndex = resultTree.size();
resultTree.resizeUninitialized(startNodeIndex+RTREE_N); // at each recursion level we add 4 nodes to the tree
PxBounds3V childBound( (PxBounds3V::U()) ); // start off uninitialized for performance
const PxI32 leftover = PxMax<PxI32>(PxI32(clusterSize - cluster4*(RTREE_N-1)), 0);
PxU32 totalCount = 0;
for(PxU32 i = 0; i < RTREE_N; i++)
{
// split off cluster4 count nodes out of the entire cluster for each i
const PxU32 clusterOffset = cluster4*i;
PxU32 count1; // cluster4 or leftover depending on whether it's the last cluster
if(i < RTREE_N-1)
{
// only need to so quickSelect for the first pagesize-1 clusters
if(clusterOffset <= clusterSize-1)
{
quickSelect::quickSelectFirstK(permute, clusterOffset, clusterSize-1, cluster4, cmpLte);
// approximate heuristic - reduce max length by some estimated factor to encourage split along other axis
// since we cut off a quarter of elements in this direction the reduction should be *0.75f but we use 0.8
// to account for some node overlap. This is somewhat of an arbitrary choice though
maxElem[cmpLte.coordIndex] *= reductionFactors[i];
// recompute cmpLte.coordIndex from updated maxElements
cmpLte.coordIndex = PxU32(maxElem[0] > maxElem[1] && maxElem[0] > maxElem[2] ? 0 : (maxElem[1] > maxElem[2] ? 1 : 2));
}
count1 = cluster4;
} else
{
count1 = PxU32(leftover);
// verify that leftover + sum of previous clusters adds up to clusterSize or leftover is 0
// leftover can be 0 if clusterSize<RTREE_N, this is generally rare, can happen for meshes with < RTREE_N tris
PX_ASSERT(leftover == 0 || cluster4*i + count1 == clusterSize);
}
RTreeNodeNQ& curNode = resultTree[startNodeIndex+i];
totalCount += count1; // accumulate total node count
if(count1 <= maxBoundsPerLeafPage) // terminal page according to specified maxBoundsPerLeafPage
{
if(count1 && totalCount <= clusterSize)
{
// this will be true most of the time except when the total number of triangles in the mesh is < PAGESIZE
curNode.leafCount = PxI32(count1);
curNode.childPageFirstNodeIndex = PxI32(clusterOffset + PxU32(permute-permuteStart));
childBound = allBounds[permute[clusterOffset+0]];
for(PxU32 i1 = 1; i1 < count1; i1++)
{
const PxBounds3V& bnd = allBounds[permute[clusterOffset+i1]];
childBound.include(bnd);
}
} else
{
// since we are required to have PAGESIZE nodes per page for simd, we fill any leftover with empty nodes
// we should only hit this if the total number of triangles in the mesh is < PAGESIZE
childBound.mn = childBound.mx = V3Zero(); // shouldn't be necessary but setting just in case
curNode.bounds.setEmpty();
curNode.leafCount = -1;
curNode.childPageFirstNodeIndex = -1; // using -1 for empty node
}
} else // not a terminal page, recurse on count1 nodes cluster
{
curNode.childPageFirstNodeIndex = PxI32(resultTree.size());
curNode.leafCount = 0;
sort4(permute+cluster4*i, count1, resultTree, maxLevels, childBound, level+1);
}
if(i == 0)
subTreeBound = childBound; // initialize subTreeBound with first childBound
else
subTreeBound.include(childBound); // expand subTreeBound with current childBound
// can use curNode since the reference change due to resizing in recursive call, need to recompute the pointer
RTreeNodeNQ& curNode1 = resultTree[startNodeIndex+i];
curNode1.bounds.minimum = childBound.getMinVec3(); // update node bounds using recursively computed childBound
curNode1.bounds.maximum = childBound.getMaxVec3();
}
}
};
// heuristic size reduction factors for splitting heuristic (see how it's used above)
const PxReal SubSortQuick::reductionFactors[RTREE_N-1] = {0.8f, 0.7f, 0.6f};
// sizePerf trade-off presets for sorting routines
const PxU32 SubSortQuick::stopAtTrisPerLeaf1[SubSortQuick::NTRADEOFF] = {16, 14, 12, 10, 8, 7, 6, 5, 4};
/////////////////////////////////////////////////////////////////////////
// SAH sorting method
//
// Preset table: lower index=better size -> higher index = better perf
static const PxU32 NTRADEOFF = 15;
// % -24 -23 -17 -15 -10 -8 -5 -3 0 +3 +3 +5 +7 +8 +9 - % raycast MeshSurface*Random benchmark perf
// K 717 734 752 777 793 811 824 866 903 939 971 1030 1087 1139 1266 - testzone size in K
// # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 - preset number
static const PxU32 stopAtTrisPerPage[NTRADEOFF] = { 64, 60, 56, 48, 46, 44, 40, 36, 32, 28, 24, 20, 16, 12, 12};
static const PxU32 stopAtTrisPerLeaf[NTRADEOFF] = { 16, 14, 12, 10, 9, 8, 8, 6, 5, 5, 5, 4, 4, 4, 2}; // capped at 2 anyway
/////////////////////////////////////////////////////////////////////////
// comparator struct for sorting the bounds along a specified coordIndex (coordIndex=0,1,2 for X,Y,Z)
struct SortBoundsPredicate
{
PxU32 coordIndex;
const PxBounds3V* allBounds;
SortBoundsPredicate(PxU32 coordIndex_, const PxBounds3V* allBounds_) : coordIndex(coordIndex_), allBounds(allBounds_)
{}
bool operator()(const PxU32 & idx1, const PxU32 & idx2) const
{
// using the bounds center for comparison
PxF32 center1 = V3ReadXYZ(allBounds[idx1].mn)[coordIndex] + V3ReadXYZ(allBounds[idx1].mx)[coordIndex];
PxF32 center2 = V3ReadXYZ(allBounds[idx2].mn)[coordIndex] + V3ReadXYZ(allBounds[idx2].mx)[coordIndex];
return (center1 < center2);
}
};
/////////////////////////////////////////////////////////////////////////
// auxiliary class for SAH build (SAH = surface area heuristic)
struct Interval
{
PxU32 start, count;
Interval(PxU32 s, PxU32 c) : start(s), count(c) {}
};
// SAH function - returns surface area for given AABB extents
static PX_FORCE_INLINE void PxSAH(const Vec3VArg v, PxF32& sah)
{
FStore(V3Dot(v, V3PermZXY(v)), &sah); // v.x*v.y + v.y*v.z + v.x*v.z;
}
struct SubSortSAH
{
PxU32* PX_RESTRICT permuteStart, *PX_RESTRICT tempPermute;
const PxBounds3V* PX_RESTRICT allBounds;
PxF32* PX_RESTRICT metricL;
PxF32* PX_RESTRICT metricR;
const PxU32* PX_RESTRICT xOrder, *PX_RESTRICT yOrder, *PX_RESTRICT zOrder;
const PxU32* PX_RESTRICT xRanks, *PX_RESTRICT yRanks, *PX_RESTRICT zRanks;
PxU32* PX_RESTRICT tempRanks;
PxU32 nbTotalBounds;
PxU32 iTradeOff;
// precompute various values used during sort
SubSortSAH(
PxU32* permute, const PxBounds3V* allBounds_, PxU32 numBounds,
const PxU32* xOrder_, const PxU32* yOrder_, const PxU32* zOrder_,
const PxU32* xRanks_, const PxU32* yRanks_, const PxU32* zRanks_, PxReal sizePerfTradeOff01)
: permuteStart(permute), allBounds(allBounds_),
xOrder(xOrder_), yOrder(yOrder_), zOrder(zOrder_),
xRanks(xRanks_), yRanks(yRanks_), zRanks(zRanks_), nbTotalBounds(numBounds)
{
metricL = PX_ALLOCATE(PxF32, numBounds, "metricL");
metricR = PX_ALLOCATE(PxF32, numBounds, "metricR");
tempPermute = PX_ALLOCATE(PxU32, (numBounds*2+1), "tempPermute");
tempRanks = PX_ALLOCATE(PxU32, numBounds, "tempRanks");
iTradeOff = PxMin<PxU32>( PxU32(PxMax<PxReal>(0.0f, sizePerfTradeOff01)*NTRADEOFF), NTRADEOFF-1 );
}
~SubSortSAH() // release temporarily used memory
{
PX_FREE(metricL);
PX_FREE(metricR);
PX_FREE(tempPermute);
PX_FREE(tempRanks);
}
////////////////////////////////////////////////////////////////////
// returns split position for second array start relative to permute ptr
PxU32 split(PxU32* permute, PxU32 clusterSize)
{
if(clusterSize <= 1)
return 0;
if(clusterSize == 2)
return 1;
PxI32 minCount = clusterSize >= 4 ? 2 : 1;
PxI32 splitStartL = minCount; // range=[startL->endL)
PxI32 splitEndL = PxI32(clusterSize-minCount);
PxI32 splitStartR = PxI32(clusterSize-splitStartL); // range=(endR<-startR], startR > endR
PxI32 splitEndR = PxI32(clusterSize-splitEndL);
PX_ASSERT(splitEndL-splitStartL == splitStartR-splitEndR);
PX_ASSERT(splitStartL <= splitEndL);
PX_ASSERT(splitStartR >= splitEndR);
PX_ASSERT(splitEndR >= 1);
PX_ASSERT(splitEndL < PxI32(clusterSize));
// pick the best axis with some splitting metric
// axis index is X=0, Y=1, Z=2
PxF32 minMetric[3];
PxU32 minMetricSplit[3];
const PxU32* ranks3[3] = { xRanks, yRanks, zRanks };
const PxU32* orders3[3] = { xOrder, yOrder, zOrder };
for(PxU32 coordIndex = 0; coordIndex <= 2; coordIndex++)
{
SortBoundsPredicate sortPredicateLR(coordIndex, allBounds);
const PxU32* rank = ranks3[coordIndex];
const PxU32* order = orders3[coordIndex];
// build ranks in tempPermute
if(clusterSize == nbTotalBounds) // AP: about 4% perf gain from this optimization
{
// if this is a full cluster sort, we already have it done
for(PxU32 i = 0; i < clusterSize; i ++)
tempPermute[i] = order[i];
} else
{
// sort the tempRanks
for(PxU32 i = 0; i < clusterSize; i ++)
tempRanks[i] = rank[permute[i]];
PxSort(tempRanks, clusterSize);
for(PxU32 i = 0; i < clusterSize; i ++) // convert back from ranks to indices
tempPermute[i] = order[tempRanks[i]];
}
// we consider overlapping intervals for minimum sum of metrics
// left interval is from splitStartL up to splitEndL
// right interval is from splitStartR down to splitEndR
// first compute the array metricL
Vec3V boundsLmn = allBounds[tempPermute[0]].mn; // init with 0th bound
Vec3V boundsLmx = allBounds[tempPermute[0]].mx; // init with 0th bound
PxI32 ii;
for(ii = 1; ii < splitStartL; ii++) // sweep right to include all bounds up to splitStartL-1
{
boundsLmn = V3Min(boundsLmn, allBounds[tempPermute[ii]].mn);
boundsLmx = V3Max(boundsLmx, allBounds[tempPermute[ii]].mx);
}
PxU32 countL0 = 0;
for(ii = splitStartL; ii <= splitEndL; ii++) // compute metric for inclusive bounds from splitStartL to splitEndL
{
boundsLmn = V3Min(boundsLmn, allBounds[tempPermute[ii]].mn);
boundsLmx = V3Max(boundsLmx, allBounds[tempPermute[ii]].mx);
PxSAH(V3Sub(boundsLmx, boundsLmn), metricL[countL0++]);
}
// now we have metricL
// now compute the array metricR
Vec3V boundsRmn = allBounds[tempPermute[clusterSize-1]].mn; // init with last bound
Vec3V boundsRmx = allBounds[tempPermute[clusterSize-1]].mx; // init with last bound
for(ii = PxI32(clusterSize-2); ii > splitStartR; ii--) // include bounds to the left of splitEndR down to splitStartR
{
boundsRmn = V3Min(boundsRmn, allBounds[tempPermute[ii]].mn);
boundsRmx = V3Max(boundsRmx, allBounds[tempPermute[ii]].mx);
}
PxU32 countR0 = 0;
for(ii = splitStartR; ii >= splitEndR; ii--) // continue sweeping left, including bounds and recomputing the metric
{
boundsRmn = V3Min(boundsRmn, allBounds[tempPermute[ii]].mn);
boundsRmx = V3Max(boundsRmx, allBounds[tempPermute[ii]].mx);
PxSAH(V3Sub(boundsRmx, boundsRmn), metricR[countR0++]);
}
PX_ASSERT((countL0 == countR0) && (countL0 == PxU32(splitEndL-splitStartL+1)));
// now iterate over splitRange and compute the minimum sum of SAHLeft*countLeft + SAHRight*countRight
PxU32 minMetricSplitPosition = 0;
PxF32 minMetricLocal = PX_MAX_REAL;
const PxI32 hsI32 = PxI32(clusterSize/2);
const PxI32 splitRange = (splitEndL-splitStartL+1);
for(ii = 0; ii < splitRange; ii++)
{
PxF32 countL = PxF32(ii+minCount); // need to add minCount since ii iterates over splitRange
PxF32 countR = PxF32(splitRange-ii-1+minCount);
PX_ASSERT(PxU32(countL + countR) == clusterSize);
const PxF32 metric = (countL*metricL[ii] + countR*metricR[splitRange-ii-1]);
const PxU32 splitPos = PxU32(ii+splitStartL);
if(metric < minMetricLocal ||
(metric <= minMetricLocal && // same metric but more even split
PxAbs(PxI32(splitPos)-hsI32) < PxAbs(PxI32(minMetricSplitPosition)-hsI32)))
{
minMetricLocal = metric;
minMetricSplitPosition = splitPos;
}
}
minMetric[coordIndex] = minMetricLocal;
minMetricSplit[coordIndex] = minMetricSplitPosition;
// sum of axis lengths for both left and right AABBs
}
PxU32 winIndex = 2;
if(minMetric[0] <= minMetric[1] && minMetric[0] <= minMetric[2])
winIndex = 0;
else if(minMetric[1] <= minMetric[2])
winIndex = 1;
const PxU32* rank = ranks3[winIndex];
const PxU32* order = orders3[winIndex];
if(clusterSize == nbTotalBounds) // AP: about 4% gain from this special case optimization
{
// if this is a full cluster sort, we already have it done
for(PxU32 i = 0; i < clusterSize; i ++)
permute[i] = order[i];
} else
{
// sort the tempRanks
for(PxU32 i = 0; i < clusterSize; i ++)
tempRanks[i] = rank[permute[i]];
PxSort(tempRanks, clusterSize);
for(PxU32 i = 0; i < clusterSize; i ++)
permute[i] = order[tempRanks[i]];
}
PxU32 splitPoint = minMetricSplit[winIndex];
if(clusterSize == 3 && splitPoint == 0)
splitPoint = 1; // special case due to rounding
return splitPoint;
}
// compute surface area for a given split
PxF32 computeSA(const PxU32* permute, const Interval& split) // both permute and i are relative
{
PX_ASSERT(split.count >= 1);
Vec3V bmn = allBounds[permute[split.start]].mn;
Vec3V bmx = allBounds[permute[split.start]].mx;
for(PxU32 i = 1; i < split.count; i++)
{
const PxBounds3V& b1 = allBounds[permute[split.start+i]];
bmn = V3Min(bmn, b1.mn); bmx = V3Max(bmx, b1.mx);
}
PxF32 ret; PxSAH(V3Sub(bmx, bmn), ret);
return ret;
}
////////////////////////////////////////////////////////////////////
// main SAH sort routine
void sort4(PxU32* permute, PxU32 clusterSize,
PxArray<RTreeNodeNQ>& resultTree, PxU32& maxLevels, PxU32 level = 0, RTreeNodeNQ* parentNode = NULL)
{
PX_UNUSED(parentNode);
if(level == 0)
maxLevels = 1;
else
maxLevels = PxMax(maxLevels, level+1);
PxU32 splitPos[RTREE_N];
for(PxU32 j = 0; j < RTREE_N; j++)
splitPos[j] = j+1;
if(clusterSize >= RTREE_N)
{
// split into RTREE_N number of regions via RTREE_N-1 subsequent splits
// each split is represented as a current interval
// we iterate over currently active intervals and compute it's surface area
// then we split the interval with maximum surface area
// AP scaffold: possible optimization - seems like computeSA can be cached for unchanged intervals
PxInlineArray<Interval, 1024> splits;
splits.pushBack(Interval(0, clusterSize));
for(PxU32 iSplit = 0; iSplit < RTREE_N-1; iSplit++)
{
PxF32 maxSAH = -FLT_MAX;
PxU32 maxSplit = 0xFFFFffff;
for(PxU32 i = 0; i < splits.size(); i++)
{
if(splits[i].count == 1)
continue;
PxF32 SAH = computeSA(permute, splits[i])*splits[i].count;
if(SAH > maxSAH)
{
maxSAH = SAH;
maxSplit = i;
}
}
PX_ASSERT(maxSplit != 0xFFFFffff);
// maxSplit is now the index of the interval in splits array with maximum surface area
// we now split it into 2 using the split() function
Interval old = splits[maxSplit];
PX_ASSERT(old.count > 1);
PxU32 splitLocal = split(permute+old.start, old.count); // relative split pos
PX_ASSERT(splitLocal >= 1);
PX_ASSERT(old.count-splitLocal >= 1);
splits.pushBack(Interval(old.start, splitLocal));
splits.pushBack(Interval(old.start+splitLocal, old.count-splitLocal));
splits.replaceWithLast(maxSplit);
splitPos[iSplit] = old.start+splitLocal;
}
// verification code, make sure split counts add up to clusterSize
PX_ASSERT(splits.size() == RTREE_N);
PxU32 sum = 0;
PX_UNUSED(sum);
for(PxU32 j = 0; j < RTREE_N; j++)
sum += splits[j].count;
PX_ASSERT(sum == clusterSize);
}
else // clusterSize < RTREE_N
{
// make it so splitCounts based on splitPos add up correctly for small cluster sizes
for(PxU32 i = clusterSize; i < RTREE_N-1; i++)
splitPos[i] = clusterSize;
}
// sort splitPos index array using quicksort (just a few values)
PxSort(splitPos, RTREE_N-1);
splitPos[RTREE_N-1] = clusterSize; // splitCount[n] is computed as splitPos[n+1]-splitPos[n], so we need to add this last value
// now compute splitStarts and splitCounts from splitPos[] array. Also perform a bunch of correctness verification
PxU32 splitStarts[RTREE_N];
PxU32 splitCounts[RTREE_N];
splitStarts[0] = 0;
splitCounts[0] = splitPos[0];
PxU32 sumCounts = splitCounts[0];
PX_UNUSED(sumCounts);
for(PxU32 j = 1; j < RTREE_N; j++)
{
splitStarts[j] = splitPos[j-1];
PX_ASSERT(splitStarts[j-1]<=splitStarts[j]);
splitCounts[j] = splitPos[j]-splitPos[j-1];
PX_ASSERT(splitCounts[j] > 0 || clusterSize < RTREE_N);
sumCounts += splitCounts[j];
PX_ASSERT(splitStarts[j-1]+splitCounts[j-1]<=splitStarts[j]);
}
PX_ASSERT(sumCounts == clusterSize);
PX_ASSERT(splitStarts[RTREE_N-1]+splitCounts[RTREE_N-1]<=clusterSize);
// mark this cluster as terminal based on clusterSize <= stopAtTrisPerPage parameter for current iTradeOff user specified preset
bool terminalClusterByTotalCount = (clusterSize <= stopAtTrisPerPage[iTradeOff]);
// iterate over splitCounts for the current cluster, if any of counts exceed 16 (which is the maximum supported by LeafTriangles
// we cannot mark this cluster as terminal (has to be split more)
for(PxU32 s = 0; s < RTREE_N; s++)
if(splitCounts[s] > 16) // LeafTriangles doesn't support > 16 tris
terminalClusterByTotalCount = false;
// iterate over all the splits
for(PxU32 s = 0; s < RTREE_N; s++)
{
RTreeNodeNQ rtn;
PxU32 splitCount = splitCounts[s];
if(splitCount > 0) // splits shouldn't be empty generally
{
// sweep left to right and compute min and max SAH for each individual bound in current split
PxBounds3V b = allBounds[permute[splitStarts[s]]];
PxF32 sahMin; PxSAH(b.getExtents(), sahMin);
PxF32 sahMax = sahMin;
// AP scaffold - looks like this could be optimized (we are recomputing bounds top down)
for(PxU32 i = 1; i < splitCount; i++)
{
PxU32 localIndex = i + splitStarts[s];
const PxBounds3V& b1 = allBounds[permute[localIndex]];
PxF32 sah1; PxSAH(b1.getExtents(), sah1);
sahMin = PxMin(sahMin, sah1);
sahMax = PxMax(sahMax, sah1);
b.include(b1);
}
rtn.bounds.minimum = V3ReadXYZ(b.mn);
rtn.bounds.maximum = V3ReadXYZ(b.mx);
// if bounds differ widely (according to some heuristic preset), we continue splitting
// this is important for a mixed cluster with large and small triangles
bool okSAH = (sahMax/sahMin < 40.0f);
if(!okSAH)
terminalClusterByTotalCount = false; // force splitting this cluster
bool stopSplitting = // compute the final splitting criterion
splitCount <= 2 || (okSAH && splitCount <= 3) // stop splitting at 2 nodes or if SAH ratio is OK and splitCount <= 3
|| terminalClusterByTotalCount || splitCount <= stopAtTrisPerLeaf[iTradeOff];
if(stopSplitting)
{
// this is a terminal page then, mark as such
// first node index is relative to the top level input array beginning
rtn.childPageFirstNodeIndex = PxI32(splitStarts[s]+(permute-permuteStart));
rtn.leafCount = PxI32(splitCount);
PX_ASSERT(splitCount <= 16); // LeafTriangles doesn't support more
}
else
{
// this is not a terminal page, we will recompute this later, after we recurse on subpages (label ZZZ)
rtn.childPageFirstNodeIndex = -1;
rtn.leafCount = 0;
}
}
else // splitCount == 0 at this point, this is an empty paddding node (with current presets it's very rare)
{
PX_ASSERT(splitCount == 0);
rtn.bounds.setEmpty();
rtn.childPageFirstNodeIndex = -1;
rtn.leafCount = -1;
}
resultTree.pushBack(rtn); // push the new node into the resultTree array
}
if(terminalClusterByTotalCount) // abort recursion if terminal cluster
return;
// recurse on subpages
PxU32 parentIndex = resultTree.size() - RTREE_N; // save the parentIndex as specified (array can be resized during recursion)
for(PxU32 s = 0; s<RTREE_N; s++)
{
RTreeNodeNQ* sParent = &resultTree[parentIndex+s]; // array can be resized and relocated during recursion
if(sParent->leafCount == 0) // only split pages that were marked as non-terminal during splitting (see "label ZZZ" above)
{
// all child nodes will be pushed inside of this recursive call,
// so we set the child pointer for parent node to resultTree.size()
sParent->childPageFirstNodeIndex = PxI32(resultTree.size());
sort4(permute+splitStarts[s], splitCounts[s], resultTree, maxLevels, level+1, sParent);
}
}
}
};
/////////////////////////////////////////////////////////////////////////
// initializes the input permute array with identity permutation
// and shuffles it so that new sorted index, newIndex = resultPermute[oldIndex]
static void buildFromBounds(
Gu::RTree& result, const PxBounds3V* allBounds, PxU32 numBounds,
PxArray<PxU32>& permute, RTreeCooker::RemapCallback* rc, Vec3VArg allMn, Vec3VArg allMx,
PxReal sizePerfTradeOff01, PxMeshCookingHint::Enum hint)
{
PX_UNUSED(sizePerfTradeOff01);
PxBounds3V treeBounds(allMn, allMx);
// start off with an identity permutation
permute.resize(0);
permute.reserve(numBounds+1);
for(PxU32 j = 0; j < numBounds; j ++)
permute.pushBack(j);
const PxU32 sentinel = 0xABCDEF01;
permute.pushBack(sentinel);
// load sorted nodes into an RTreeNodeNQ tree representation
// build the tree structure from sorted nodes
const PxU32 pageSize = RTREE_N;
PxArray<RTreeNodeNQ> resultTree;
resultTree.reserve(numBounds*2);
PxU32 maxLevels = 0;
if(hint == PxMeshCookingHint::eSIM_PERFORMANCE) // use high quality SAH build
{
PxArray<PxU32> xRanks(numBounds), yRanks(numBounds), zRanks(numBounds), xOrder(numBounds), yOrder(numBounds), zOrder(numBounds);
PxMemCopy(xOrder.begin(), permute.begin(), sizeof(xOrder[0])*numBounds);
PxMemCopy(yOrder.begin(), permute.begin(), sizeof(yOrder[0])*numBounds);
PxMemCopy(zOrder.begin(), permute.begin(), sizeof(zOrder[0])*numBounds);
// sort by shuffling the permutation, precompute sorted ranks for x,y,z-orders
PxSort(xOrder.begin(), xOrder.size(), SortBoundsPredicate(0, allBounds));
for(PxU32 i = 0; i < numBounds; i++) xRanks[xOrder[i]] = i;
PxSort(yOrder.begin(), yOrder.size(), SortBoundsPredicate(1, allBounds));
for(PxU32 i = 0; i < numBounds; i++) yRanks[yOrder[i]] = i;
PxSort(zOrder.begin(), zOrder.size(), SortBoundsPredicate(2, allBounds));
for(PxU32 i = 0; i < numBounds; i++) zRanks[zOrder[i]] = i;
SubSortSAH ss(permute.begin(), allBounds, numBounds,
xOrder.begin(), yOrder.begin(), zOrder.begin(), xRanks.begin(), yRanks.begin(), zRanks.begin(), sizePerfTradeOff01);
ss.sort4(permute.begin(), numBounds, resultTree, maxLevels);
} else
{ // use fast cooking path
PX_ASSERT(hint == PxMeshCookingHint::eCOOKING_PERFORMANCE);
SubSortQuick ss(permute.begin(), allBounds, numBounds, sizePerfTradeOff01);
PxBounds3V discard((PxBounds3V::U()));
ss.sort4(permute.begin(), permute.size()-1, resultTree, maxLevels, discard); // AP scaffold: need to implement build speed/runtime perf slider
}
PX_ASSERT(permute[numBounds] == sentinel); // verify we didn't write past the array
permute.popBack(); // discard the sentinel value
#if PRINT_RTREE_COOKING_STATS // stats code
PxU32 totalLeafTris = 0;
PxU32 numLeaves = 0;
PxI32 maxLeafTris = 0;
PxU32 numEmpty = 0;
for(PxU32 i = 0; i < resultTree.size(); i++)
{
PxI32 leafCount = resultTree[i].leafCount;
numEmpty += (resultTree[i].bounds.isEmpty());
if(leafCount > 0)
{
numLeaves++;
totalLeafTris += leafCount;
if(leafCount > maxLeafTris)
maxLeafTris = leafCount;
}
}
printf("AABBs total/empty=%d/%d\n", resultTree.size(), numEmpty);
printf("numTris=%d, numLeafAABBs=%d, avgTrisPerLeaf=%.2f, maxTrisPerLeaf = %d\n",
numBounds, numLeaves, PxF32(totalLeafTris)/numLeaves, maxLeafTris);
#endif
PX_ASSERT(RTREE_N*sizeof(RTreeNodeQ) == sizeof(RTreePage)); // needed for nodePtrMultiplier computation to be correct
const int nodePtrMultiplier = sizeof(RTreeNodeQ); // convert offset as count in qnodes to page ptr
// Quantize the tree. AP scaffold - might be possible to merge this phase with the page pass below this loop
PxArray<RTreeNodeQ> qtreeNodes;
PxU32 firstEmptyIndex = PxU32(-1);
PxU32 resultCount = resultTree.size();
qtreeNodes.reserve(resultCount);
for(PxU32 i = 0; i < resultCount; i++) // AP scaffold - eliminate this pass
{
RTreeNodeNQ & u = resultTree[i];
RTreeNodeQ q;
q.setLeaf(u.leafCount > 0); // set the leaf flag
if(u.childPageFirstNodeIndex == -1) // empty node?
{
if(firstEmptyIndex == PxU32(-1))
firstEmptyIndex = qtreeNodes.size();
q.minx = q.miny = q.minz = FLT_MAX; // AP scaffold improvement - use empty 1e30 bounds instead and reference a valid leaf
q.maxx = q.maxy = q.maxz = -FLT_MAX; // that will allow to remove the empty node test from the runtime
q.ptr = firstEmptyIndex*nodePtrMultiplier; PX_ASSERT((q.ptr & 1) == 0);
q.setLeaf(true); // label empty node as leaf node
} else
{
// non-leaf node
q.minx = u.bounds.minimum.x;
q.miny = u.bounds.minimum.y;
q.minz = u.bounds.minimum.z;
q.maxx = u.bounds.maximum.x;
q.maxy = u.bounds.maximum.y;
q.maxz = u.bounds.maximum.z;
if(u.leafCount > 0)
{
q.ptr = PxU32(u.childPageFirstNodeIndex);
rc->remap(&q.ptr, q.ptr, PxU32(u.leafCount));
PX_ASSERT(q.isLeaf()); // remap is expected to set the isLeaf bit
}
else
{
// verify that all children bounds are included in the parent bounds
for(PxU32 s = 0; s < RTREE_N; s++)
{
const RTreeNodeNQ& child = resultTree[u.childPageFirstNodeIndex+s];
PX_UNUSED(child);
// is a sentinel node or is inside parent's bounds
PX_ASSERT(child.leafCount == -1 || child.bounds.isInside(u.bounds));
}
q.ptr = PxU32(u.childPageFirstNodeIndex * nodePtrMultiplier);
PX_ASSERT(q.ptr % RTREE_N == 0);
q.setLeaf(false);
}
}
qtreeNodes.pushBack(q);
}
// build the final rtree image
result.mInvDiagonal = PxVec4(1.0f);
PX_ASSERT(qtreeNodes.size() % RTREE_N == 0);
result.mTotalNodes = qtreeNodes.size();
result.mTotalPages = result.mTotalNodes / pageSize;
result.mPages = static_cast<RTreePage*>(
PxAlignedAllocator<128>().allocate(sizeof(RTreePage)*result.mTotalPages, PX_FL));
result.mBoundsMin = PxVec4(V3ReadXYZ(treeBounds.mn), 0.0f);
result.mBoundsMax = PxVec4(V3ReadXYZ(treeBounds.mx), 0.0f);
result.mDiagonalScaler = (result.mBoundsMax - result.mBoundsMin) / 65535.0f;
result.mPageSize = pageSize;
result.mNumLevels = maxLevels;
PX_ASSERT(result.mTotalNodes % pageSize == 0);
result.mNumRootPages = 1;
for(PxU32 j = 0; j < result.mTotalPages; j++)
{
RTreePage& page = result.mPages[j];
for(PxU32 k = 0; k < RTREE_N; k ++)
{
const RTreeNodeQ& n = qtreeNodes[j*RTREE_N+k];
page.maxx[k] = n.maxx;
page.maxy[k] = n.maxy;
page.maxz[k] = n.maxz;
page.minx[k] = n.minx;
page.miny[k] = n.miny;
page.minz[k] = n.minz;
page.ptrs[k] = n.ptr;
}
}
//printf("Tree size=%d\n", result.mTotalPages*sizeof(RTreePage));
#if PX_DEBUG
result.validate(); // make sure the child bounds are included in the parent and other validation
#endif
}
} // namespace physx
| 39,140 | C++ | 39.30999 | 147 | 0.689474 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingBigConvexDataBuilder.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 "cooking/PxCooking.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVecMath.h"
#include "GuConvexMeshData.h"
#include "GuBigConvexData2.h"
#include "GuIntersectionRayPlane.h"
#include "GuCookingBigConvexDataBuilder.h"
#include "GuCookingConvexHullBuilder.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace physx;
using namespace Gu;
using namespace aos;
static const PxU32 gSupportVersion = 0;
static const PxU32 gVersion = 0;
BigConvexDataBuilder::BigConvexDataBuilder(const Gu::ConvexHullData* hull, BigConvexData* gm, const PxVec3* hullVerts) : mHullVerts(hullVerts)
{
mSVM = gm;
mHull = hull;
}
BigConvexDataBuilder::~BigConvexDataBuilder()
{
}
bool BigConvexDataBuilder::initialize()
{
mSVM->mData.mSamples = PX_ALLOCATE(PxU8, mSVM->mData.mNbSamples*2u, "mData.mSamples");
#if PX_DEBUG
// printf("SVM: %d bytes\n", mNbSamples*sizeof(PxU8)*2);
#endif
return true;
}
bool BigConvexDataBuilder::save(PxOutputStream& stream, bool platformMismatch) const
{
// Export header
if(!Cm::WriteHeader('S', 'U', 'P', 'M', gSupportVersion, platformMismatch, stream))
return false;
// Save base gaussmap
// if(!GaussMapBuilder::Save(stream, platformMismatch)) return false;
// Export header
if(!Cm::WriteHeader('G', 'A', 'U', 'S', gVersion, platformMismatch, stream))
return false;
// Export basic info
// stream.StoreDword(mSubdiv);
writeDword(mSVM->mData.mSubdiv, platformMismatch, stream); // PT: could now write Word here
// stream.StoreDword(mNbSamples);
writeDword(mSVM->mData.mNbSamples, platformMismatch, stream); // PT: could now write Word here
// Save map data
// It's an array of bytes so we don't care about 'PlatformMismatch'
stream.write(mSVM->mData.mSamples, sizeof(PxU8)*mSVM->mData.mNbSamples*2);
if(!saveValencies(stream, platformMismatch))
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
// compute valencies for each vertex
// we dont compute the edges again here, we have them temporary stored in mHullDataFacesByAllEdges8 structure
bool BigConvexDataBuilder::computeValencies(const ConvexHullBuilder& meshBuilder)
{
// Create valencies
const PxU32 numVertices = meshBuilder.mHull->mNbHullVertices;
mSVM->mData.mNbVerts = numVertices;
// Get ram for valencies and adjacent verts
const PxU32 numAlignedVerts = (numVertices+3)&~3;
const PxU32 TotalSize = sizeof(Gu::Valency)*numAlignedVerts + sizeof(PxU8)*meshBuilder.mHull->mNbEdges*2u;
mSVM->mVBuffer = PX_ALLOC(TotalSize, "BigConvexData data");
mSVM->mData.mValencies = reinterpret_cast<Gu::Valency*>(mSVM->mVBuffer);
mSVM->mData.mAdjacentVerts = (reinterpret_cast<PxU8*>(mSVM->mVBuffer)) + sizeof(Gu::Valency)*numAlignedVerts;
PxMemZero(mSVM->mData.mValencies, numVertices*sizeof(Gu::Valency));
PxU8 vertexMarker[256];
PxMemZero(vertexMarker,numVertices);
// Compute valencies
for (PxU32 i = 0; i < meshBuilder.mHull->mNbPolygons; i++)
{
const PxU32 numVerts = meshBuilder.mHullDataPolygons[i].mNbVerts;
const PxU8* Data = meshBuilder.mHullDataVertexData8 + meshBuilder.mHullDataPolygons[i].mVRef8;
for (PxU32 j = 0; j < numVerts; j++)
{
mSVM->mData.mValencies[Data[j]].mCount++;
PX_ASSERT(mSVM->mData.mValencies[Data[j]].mCount != 0xffff);
}
}
// Create offsets
mSVM->CreateOffsets();
// mNbAdjVerts = mOffsets[mNbVerts-1] + mValencies[mNbVerts-1];
mSVM->mData.mNbAdjVerts = PxU32(mSVM->mData.mValencies[mSVM->mData.mNbVerts - 1].mOffset + mSVM->mData.mValencies[mSVM->mData.mNbVerts - 1].mCount);
PX_ASSERT(mSVM->mData.mNbAdjVerts == PxU32(meshBuilder.mHull->mNbEdges * 2));
// Create adjacent vertices
// parse the polygons and its vertices
for (PxU32 i = 0; i < meshBuilder.mHull->mNbPolygons; i++)
{
PxU32 numVerts = meshBuilder.mHullDataPolygons[i].mNbVerts;
const PxU8* Data = meshBuilder.mHullDataVertexData8 + meshBuilder.mHullDataPolygons[i].mVRef8;
for (PxU32 j = 0; j < numVerts; j++)
{
const PxU8 vertexIndex = Data[j];
PxU8 numAdj = 0;
// if we did not parsed this vertex, traverse to the adjacent face and then
// again to next till we hit back the original polygon
if(vertexMarker[vertexIndex] == 0)
{
PxU8 prevIndex = Data[(j+1)%numVerts];
mSVM->mData.mAdjacentVerts[mSVM->mData.mValencies[vertexIndex].mOffset++] = prevIndex;
numAdj++;
// now traverse the neighbors
const PxU16 edgeIndex = PxU16(meshBuilder.mEdgeData16[meshBuilder.mHullDataPolygons[i].mVRef8 + j]*2);
PxU8 n0 = meshBuilder.mHullDataFacesByEdges8[edgeIndex];
PxU8 n1 = meshBuilder.mHullDataFacesByEdges8[edgeIndex + 1];
PxU32 neighborPolygon = n0 == i ? n1 : n0;
while (neighborPolygon != i)
{
PxU32 numNeighborVerts = meshBuilder.mHullDataPolygons[neighborPolygon].mNbVerts;
const PxU8* neighborData = meshBuilder.mHullDataVertexData8 + meshBuilder.mHullDataPolygons[neighborPolygon].mVRef8;
PxU32 nextEdgeIndex = 0;
// search in the neighbor face for the tested vertex
for (PxU32 k = 0; k < numNeighborVerts; k++)
{
// search the vertexIndex
if(neighborData[k] == vertexIndex)
{
const PxU8 nextIndex = neighborData[(k+1)%numNeighborVerts];
// next index already there, pick the previous
if(nextIndex == prevIndex)
{
prevIndex = k == 0 ? neighborData[numNeighborVerts - 1] : neighborData[k-1];
nextEdgeIndex = k == 0 ? numNeighborVerts - 1 : k-1;
}
else
{
prevIndex = nextIndex;
nextEdgeIndex = k;
}
mSVM->mData.mAdjacentVerts[mSVM->mData.mValencies[vertexIndex].mOffset++] = prevIndex;
numAdj++;
break;
}
}
// now move to next neighbor
const PxU16 edgeIndex2 = PxU16(meshBuilder.mEdgeData16[(meshBuilder.mHullDataPolygons[neighborPolygon].mVRef8 + nextEdgeIndex)]*2);
n0 = meshBuilder.mHullDataFacesByEdges8[edgeIndex2];
n1 = meshBuilder.mHullDataFacesByEdges8[edgeIndex2 + 1];
neighborPolygon = n0 == neighborPolygon ? n1 : n0;
}
vertexMarker[vertexIndex] = numAdj;
}
}
}
// Recreate offsets
mSVM->CreateOffsets();
return true;
}
//////////////////////////////////////////////////////////////////////////
// compute the min dot product from the verts for given dir
void BigConvexDataBuilder::precomputeSample(const PxVec3& dir, PxU8& startIndex_, float negativeDir)
{
PxU8 startIndex = startIndex_;
const PxVec3* verts = mHullVerts;
const Valency* valency = mSVM->mData.mValencies;
const PxU8* adjacentVerts = mSVM->mData.mAdjacentVerts;
// we have only 256 verts
PxU32 smallBitMap[8] = {0,0,0,0,0,0,0,0};
float minimum = negativeDir * verts[startIndex].dot(dir);
PxU32 initialIndex = startIndex;
do
{
initialIndex = startIndex;
const PxU32 numNeighbours = valency[startIndex].mCount;
const PxU32 offset = valency[startIndex].mOffset;
for (PxU32 a = 0; a < numNeighbours; ++a)
{
const PxU8 neighbourIndex = adjacentVerts[offset + a];
const float dist = negativeDir * verts[neighbourIndex].dot(dir);
if (dist < minimum)
{
const PxU32 ind = PxU32(neighbourIndex >> 5);
const PxU32 mask = PxU32(1 << (neighbourIndex & 31));
if ((smallBitMap[ind] & mask) == 0)
{
smallBitMap[ind] |= mask;
minimum = dist;
startIndex = neighbourIndex;
}
}
}
} while (startIndex != initialIndex);
startIndex_ = startIndex;
}
//////////////////////////////////////////////////////////////////////////
// Precompute the min/max vertices for cube directions.
bool BigConvexDataBuilder::precompute(PxU32 subdiv)
{
mSVM->mData.mSubdiv = PxTo16(subdiv);
mSVM->mData.mNbSamples = PxTo16(6 * subdiv*subdiv);
if (!initialize())
return false;
PxU8 startIndex[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
PxU8 startIndex2[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
const float halfSubdiv = float(subdiv - 1) * 0.5f;
for (PxU32 j = 0; j < subdiv; j++)
{
for (PxU32 i = j; i < subdiv; i++)
{
const float iSubDiv = 1.0f - i / halfSubdiv;
const float jSubDiv = 1.0f - j / halfSubdiv;
PxVec3 tempDir(1.0f, iSubDiv, jSubDiv);
// we need to normalize only once, then we permute the components
// as before for each i,j and j,i face direction
tempDir.normalize();
const PxVec3 dirs[12] = {
PxVec3(-tempDir.x, tempDir.y, tempDir.z),
PxVec3(tempDir.x, tempDir.y, tempDir.z),
PxVec3(tempDir.z, -tempDir.x, tempDir.y),
PxVec3(tempDir.z, tempDir.x, tempDir.y),
PxVec3(tempDir.y, tempDir.z, -tempDir.x),
PxVec3(tempDir.y, tempDir.z, tempDir.x),
PxVec3(-tempDir.x, tempDir.z, tempDir.y),
PxVec3(tempDir.x, tempDir.z, tempDir.y),
PxVec3(tempDir.y, -tempDir.x, tempDir.z),
PxVec3(tempDir.y, tempDir.x, tempDir.z),
PxVec3(tempDir.z, tempDir.y, -tempDir.x),
PxVec3(tempDir.z, tempDir.y, tempDir.x)
};
// compute in each direction + negative/positive dot, we have
// then two start indexes, which are used then for hill climbing
for (PxU32 dStep = 0; dStep < 12; dStep++)
{
precomputeSample(dirs[dStep], startIndex[dStep], 1.0f);
precomputeSample(dirs[dStep], startIndex2[dStep], -1.0f);
}
// decompose the vector results into face directions
for (PxU32 k = 0; k < 6; k++)
{
const PxU32 ksub = k*subdiv*subdiv;
const PxU32 offset = j + i*subdiv + ksub;
const PxU32 offset2 = i + j*subdiv + ksub;
PX_ASSERT(offset < mSVM->mData.mNbSamples);
PX_ASSERT(offset2 < mSVM->mData.mNbSamples);
mSVM->mData.mSamples[offset] = startIndex[k];
mSVM->mData.mSamples[offset + mSVM->mData.mNbSamples] = startIndex2[k];
mSVM->mData.mSamples[offset2] = startIndex[k + 6];
mSVM->mData.mSamples[offset2 + mSVM->mData.mNbSamples] = startIndex2[k + 6];
}
}
}
return true;
}
static const PxU32 gValencyVersion = 2;
//////////////////////////////////////////////////////////////////////////
bool BigConvexDataBuilder::saveValencies(PxOutputStream& stream, bool platformMismatch) const
{
// Export header
if(!Cm::WriteHeader('V', 'A', 'L', 'E', gValencyVersion, platformMismatch, stream))
return false;
writeDword(mSVM->mData.mNbVerts, platformMismatch, stream);
writeDword(mSVM->mData.mNbAdjVerts, platformMismatch, stream);
{
PxU16* temp = PX_ALLOCATE(PxU16, mSVM->mData.mNbVerts, "tmp");
for(PxU32 i=0;i<mSVM->mData.mNbVerts;i++)
temp[i] = mSVM->mData.mValencies[i].mCount;
const PxU32 maxIndex = computeMaxIndex(temp, mSVM->mData.mNbVerts);
writeDword(maxIndex, platformMismatch, stream);
Cm::StoreIndices(PxTo16(maxIndex), mSVM->mData.mNbVerts, temp, stream, platformMismatch);
PX_FREE(temp);
}
stream.write(mSVM->mData.mAdjacentVerts, mSVM->mData.mNbAdjVerts);
return true;
}
| 12,637 | C++ | 34.6 | 199 | 0.6788 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingQuickHullConvexHullLib.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 "GuCookingQuickHullConvexHullLib.h"
#include "GuCookingConvexHullUtils.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxSort.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxMath.h"
#include "foundation/PxPlane.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxMemory.h"
using namespace physx;
namespace local
{
//////////////////////////////////////////////////////////////////////////
static const float MIN_ADJACENT_ANGLE = 3.0f; // in degrees - result wont have two adjacent facets within this angle of each other.
static const float PLANE_THICKNES = 3.0f * PX_EPS_F32; // points within this distance are considered on a plane
static const float MAXDOT_MINANG = cosf(PxDegToRad(MIN_ADJACENT_ANGLE)); // adjacent angle for dot product tests
//////////////////////////////////////////////////////////////////////////
struct QuickHullFace;
class ConvexHull;
class HullPlanes;
//////////////////////////////////////////////////////////////////////////
template<typename T, bool useIndexing>
class MemBlock
{
public:
MemBlock(PxU32 preallocateSize)
: mPreallocateSize(preallocateSize), mCurrentBlock(0), mCurrentIndex(0)
{
PX_ASSERT(preallocateSize);
T* block = PX_ALLOCATE(T, preallocateSize, "Quickhull MemBlock");
mBlocks.pushBack(block);
}
MemBlock()
: mPreallocateSize(0), mCurrentBlock(0), mCurrentIndex(0)
{
}
void init(PxU32 preallocateSize)
{
PX_ASSERT(preallocateSize);
mPreallocateSize = preallocateSize;
T* block = PX_ALLOCATE(T, preallocateSize, "Quickhull MemBlock");
if(useIndexing)
{
for (PxU32 i = 0; i < mPreallocateSize; i++)
{
// placement new to index data
PX_PLACEMENT_NEW(&block[i], T)(i);
}
}
mBlocks.pushBack(block);
}
~MemBlock()
{
for (PxU32 i = 0; i < mBlocks.size(); i++)
{
PX_FREE(mBlocks[i]);
}
mBlocks.clear();
}
void reset()
{
for (PxU32 i = 0; i < mBlocks.size(); i++)
{
PX_FREE(mBlocks[i]);
}
mBlocks.clear();
mCurrentBlock = 0;
mCurrentIndex = 0;
init(mPreallocateSize);
}
T* getItem(PxU32 index)
{
const PxU32 block = index/mPreallocateSize;
const PxU32 itemIndex = index % mPreallocateSize;
PX_ASSERT(block <= mCurrentBlock);
PX_ASSERT(itemIndex < mPreallocateSize);
return &(mBlocks[block])[itemIndex];
}
T* getFreeItem()
{
PX_ASSERT(mPreallocateSize);
// check if we have enough space in block, otherwise allocate new block
if(mCurrentIndex < mPreallocateSize)
{
return &(mBlocks[mCurrentBlock])[mCurrentIndex++];
}
else
{
T* block = PX_ALLOCATE(T, mPreallocateSize, "Quickhull MemBlock");
mCurrentBlock++;
if (useIndexing)
{
for (PxU32 i = 0; i < mPreallocateSize; i++)
{
// placement new to index data
PX_PLACEMENT_NEW(&block[i], T)(mCurrentBlock*mPreallocateSize + i);
}
}
mBlocks.pushBack(block);
mCurrentIndex = 0;
return &(mBlocks[mCurrentBlock])[mCurrentIndex++];
}
}
private:
PxU32 mPreallocateSize;
PxU32 mCurrentBlock;
PxU32 mCurrentIndex;
PxArray<T*> mBlocks;
};
//////////////////////////////////////////////////////////////////////////
// representation of quick hull vertex
struct QuickHullVertex
{
PxVec3 point; // point vector
PxU32 index; // point index for compare
float dist; // distance from plane if necessary
QuickHullVertex* next; // link to next vertex, linked list used for conflict list
PX_FORCE_INLINE bool operator==(const QuickHullVertex& vertex) const
{
return index == vertex.index ? true : false;
}
PX_FORCE_INLINE bool operator <(const QuickHullVertex& vertex) const
{
return dist < vertex.dist ? true : false;
}
};
//////////////////////////////////////////////////////////////////////////
// representation of quick hull half edge
struct QuickHullHalfEdge
{
QuickHullHalfEdge() : prev(NULL), next(NULL), twin(NULL), face(NULL), edgeIndex(0xFFFFFFFF)
{
}
QuickHullHalfEdge(PxU32 )
: prev(NULL), next(NULL), twin(NULL), face(NULL), edgeIndex(0xFFFFFFFF)
{
}
QuickHullVertex tail; // tail vertex, head vertex is the tail of the twin
QuickHullHalfEdge* prev; // previous edge
QuickHullHalfEdge* next; // next edge
QuickHullHalfEdge* twin; // twin/opposite edge
QuickHullFace* face; // face where the edge belong
PxU32 edgeIndex; // edge index used for edge creation
PX_FORCE_INLINE const QuickHullVertex& getTail() const
{
return tail;
}
PX_FORCE_INLINE const QuickHullVertex& getHead() const
{
PX_ASSERT(twin);
return twin->tail;
}
PX_FORCE_INLINE void setTwin(QuickHullHalfEdge* edge)
{
twin = edge;
edge->twin = this;
}
PX_FORCE_INLINE QuickHullFace* getOppositeFace() const
{
return twin->face;
}
float getOppositeFaceDistance() const;
};
//////////////////////////////////////////////////////////////////////////
typedef PxArray<QuickHullVertex*> QuickHullVertexArray;
typedef PxArray<QuickHullHalfEdge*> QuickHullHalfEdgeArray;
typedef PxArray<QuickHullFace*> QuickHullFaceArray;
//////////////////////////////////////////////////////////////////////////
// representation of quick hull face
struct QuickHullFace
{
enum FaceState
{
eVISIBLE,
eDELETED,
eNON_CONVEX
};
QuickHullHalfEdge* edge; // starting edge
PxU16 numEdges; // num edges on the face
QuickHullVertex* conflictList; // conflict list, used to determine unclaimed vertices
PxVec3 normal; // Newell plane normal
float area; // face area
PxVec3 centroid; // face centroid
float planeOffset; // Newell plane offset
float expandOffset; // used for plane expansion if vertex limit reached
FaceState state; // face validity state
QuickHullFace* nextFace; // used to indicate next free face in faceList
PxU32 index; // face index for compare identification
PxU8 outIndex; // face index used for output descriptor
public:
QuickHullFace()
: edge(NULL), numEdges(0), conflictList(NULL), area(0.0f), planeOffset(0.0f), expandOffset(-FLT_MAX),
state(eVISIBLE), nextFace(NULL), outIndex(0)
{
}
QuickHullFace(PxU32 ind)
: edge(NULL), numEdges(0), conflictList(NULL), area(0.0f), planeOffset(0.0f), expandOffset(-FLT_MAX),
state(eVISIBLE), nextFace(NULL), index(ind), outIndex(0)
{
}
~QuickHullFace()
{
}
// get edge on index
PX_FORCE_INLINE QuickHullHalfEdge* getEdge(PxU32 i) const
{
QuickHullHalfEdge* he = edge;
while (i > 0)
{
he = he->next;
i--;
}
return he;
}
// distance from a plane to provided point
PX_FORCE_INLINE float distanceToPlane(const PxVec3 p) const
{
return normal.dot(p) - planeOffset;
}
// compute face normal and centroid
PX_FORCE_INLINE void computeNormalAndCentroid()
{
PX_ASSERT(edge);
normal = PxVec3(PxZero);
numEdges = 1;
QuickHullHalfEdge* testEdge = edge;
QuickHullHalfEdge* startEdge = NULL;
float maxDist = -1.0f;
for (PxU32 i = 0; i < 3; i++)
{
const float d = (testEdge->tail.point - testEdge->next->tail.point).magnitudeSquared();
if (d > maxDist)
{
maxDist = d;
startEdge = testEdge;
}
testEdge = testEdge->next;
}
PX_ASSERT(startEdge);
QuickHullHalfEdge* he = startEdge->next;
const PxVec3& p0 = startEdge->tail.point;
const PxVec3 d = he->tail.point - p0;
centroid = startEdge->tail.point;
do
{
numEdges++;
centroid += he->tail.point;
normal += d.cross(he->next->tail.point - p0);
he = he->next;
} while (he != startEdge);
area = normal.normalize();
centroid *= (1.0f / float(numEdges));
planeOffset = normal.dot(centroid);
}
// merge adjacent face
bool mergeAdjacentFace(QuickHullHalfEdge* halfEdge, QuickHullFaceArray& discardedFaces);
// check face consistency
bool checkFaceConsistency();
private:
// connect halfedges
QuickHullFace* connectHalfEdges(QuickHullHalfEdge* hedgePrev, QuickHullHalfEdge* hedge);
// check if the face does have only 3 vertices
PX_FORCE_INLINE bool isTriangle() const
{
return numEdges == 3 ? true : false;
}
};
//////////////////////////////////////////////////////////////////////////
struct QuickHullResult
{
enum Enum
{
eSUCCESS, // ok
eZERO_AREA_TEST_FAILED, // area test failed for simplex
eVERTEX_LIMIT_REACHED, // vertex limit reached need to expand hull
ePOLYGONS_LIMIT_REACHED, // polygons hard limit reached
eFAILURE // general failure
};
};
//////////////////////////////////////////////////////////////////////////
// Quickhull base class holding the hull during construction
class QuickHull : public PxUserAllocated
{
PX_NOCOPY(QuickHull)
public:
QuickHull(const PxCookingParams& params, const PxConvexMeshDesc& desc);
~QuickHull();
// preallocate the edges, faces, vertices
void preallocate(PxU32 numVertices);
// parse the input verts, store them into internal format
void parseInputVertices(const PxVec3* verts, PxU32 numVerts);
// release the hull and data
void releaseHull();
// sets the precomputed min/max data
void setPrecomputedMinMax(const QuickHullVertex* minVertex,const QuickHullVertex* maxVertex, const float tolerance,const float planeTolerance);
// main entry function to build the hull from provided points
QuickHullResult::Enum buildHull();
PxU32 maxNumVertsPerFace() const;
protected:
// compute min max verts
void computeMinMaxVerts();
// find the initial simplex
bool findSimplex();
// add the initial simplex
// returns true if the operation was successful, false otherwise
bool addSimplex(QuickHullVertex* simplex, bool flipTriangle);
// finds next point to add
QuickHullVertex* nextPointToAdd(QuickHullFace*& eyeFace);
// adds point to the hull
bool addPointToHull(const QuickHullVertex* vertex, QuickHullFace& face, bool& addFailed);
// creates new face from given triangles
QuickHullFace* createTriangle(const QuickHullVertex& v0, const QuickHullVertex& v1, const QuickHullVertex& v2);
// adds point to the face conflict list
void addPointToFace(QuickHullFace& face, QuickHullVertex* vertex, float dist);
// removes eye point from the face conflict list
void removeEyePointFromFace(QuickHullFace& face, const QuickHullVertex* vertex);
// calculate the horizon fro the eyePoint against a given face
void calculateHorizon(const PxVec3& eyePoint, QuickHullHalfEdge* edge, QuickHullFace& face, QuickHullHalfEdgeArray& horizon, QuickHullFaceArray& removedFaces);
// adds new faces from given horizon and eyePoint
void addNewFacesFromHorizon(const QuickHullVertex* eyePoint, const QuickHullHalfEdgeArray& horizon, QuickHullFaceArray& newFaces);
// merge adjacent face
bool doAdjacentMerge(QuickHullFace& face, bool mergeWrtLargeFace, bool& mergeFailed);
// merge adjacent face doing normal test
bool doPostAdjacentMerge(QuickHullFace& face, const float minAngle);
// delete face points
void deleteFacePoints(QuickHullFace& faceToDelete, QuickHullFace* absorbingFace);
// resolve unclaimed points
void resolveUnclaimedPoints(const QuickHullFaceArray& newFaces);
// merges polygons with similar normals
void postMergeHull();
// check if 2 faces can be merged
bool canMergeFaces(const QuickHullHalfEdge& he);
// get next free face
PX_FORCE_INLINE QuickHullFace* getFreeHullFace()
{
return mFreeFaces.getFreeItem();
}
// get next free half edge
PX_FORCE_INLINE QuickHullHalfEdge* getFreeHullHalfEdge()
{
return mFreeHalfEdges.getFreeItem();
}
PX_FORCE_INLINE PxU32 getNbHullVerts() { return mOutputNumVertices; }
protected:
friend class physx::QuickHullConvexHullLib;
const PxCookingParams& mCookingParams; // cooking params
const PxConvexMeshDesc& mConvexDesc; // convex desc
PxVec3 mInteriorPoint; // interior point for int/ext tests
PxU32 mMaxVertices; // maximum number of vertices (can be different as we may add vertices during the cleanup
PxU32 mNumVertices; // actual number of input vertices
PxU32 mOutputNumVertices; // num vertices of the computed hull
PxU32 mTerminalVertex; // in case we failed to generate hull in a regular run we set the terminal vertex and rerun
QuickHullVertex* mVerticesList; // vertices list preallocated
MemBlock<QuickHullHalfEdge, false> mFreeHalfEdges; // free half edges
MemBlock<QuickHullFace, true> mFreeFaces; // free faces
QuickHullFaceArray mHullFaces; // actual hull faces, contains also invalid and not used faces
PxU32 mNumHullFaces; // actual number of hull faces
bool mPrecomputedMinMax; // if we got the precomputed min/max values
QuickHullVertex mMinVertex[3]; // min vertex
QuickHullVertex mMaxVertex[3]; // max vertex
float mTolerance; // hull tolerance, used for plane thickness and merge strategy
float mPlaneTolerance; // used for post merge stage
QuickHullVertexArray mUnclaimedPoints; // holds temp unclaimed points
QuickHullHalfEdgeArray mHorizon; // array for horizon computation
QuickHullFaceArray mNewFaces; // new faces created during horizon computation
QuickHullFaceArray mRemovedFaces; // removd faces during horizon computation
QuickHullFaceArray mDiscardedFaces; // discarded faces during face merging
};
//////////////////////////////////////////////////////////////////////////
// return the distance from opposite face
float QuickHullHalfEdge::getOppositeFaceDistance() const
{
PX_ASSERT(face);
PX_ASSERT(twin);
return face->distanceToPlane(twin->face->centroid);
}
//////////////////////////////////////////////////////////////////////////
// merge adjacent face from provided half edge.
// 1. set new half edges
// 2. connect the new half edges - check we did not produced redundant triangles, discard them
// 3. recompute the plane and check consistency
// Returns false if merge failed
bool QuickHullFace::mergeAdjacentFace(QuickHullHalfEdge* hedgeAdj, QuickHullFaceArray& discardedFaces)
{
QuickHullFace* oppFace = hedgeAdj->getOppositeFace();
discardedFaces.pushBack(oppFace);
oppFace->state = QuickHullFace::eDELETED;
QuickHullHalfEdge* hedgeOpp = hedgeAdj->twin;
QuickHullHalfEdge* hedgeAdjPrev = hedgeAdj->prev;
QuickHullHalfEdge* hedgeAdjNext = hedgeAdj->next;
QuickHullHalfEdge* hedgeOppPrev = hedgeOpp->prev;
QuickHullHalfEdge* hedgeOppNext = hedgeOpp->next;
// check if we are lining up with the face in adjPrev dir
QuickHullHalfEdge* breakEdge = hedgeAdjPrev;
while (hedgeAdjPrev->getOppositeFace() == oppFace)
{
hedgeAdjPrev = hedgeAdjPrev->prev;
hedgeOppNext = hedgeOppNext->next;
// Edge case merge face is degenerated and we need to abort merging
if (hedgeAdjPrev == breakEdge)
{
return false;
}
}
// check if we are lining up with the face in adjNext dir
breakEdge = hedgeAdjNext;
while (hedgeAdjNext->getOppositeFace() == oppFace)
{
hedgeOppPrev = hedgeOppPrev->prev;
hedgeAdjNext = hedgeAdjNext->next;
// Edge case merge face is degenerated and we need to abort merging
if (hedgeAdjNext == breakEdge)
{
return false;
}
}
QuickHullHalfEdge* hedge;
// set new face owner for the line up edges
for (hedge = hedgeOppNext; hedge != hedgeOppPrev->next; hedge = hedge->next)
{
hedge->face = this;
}
// if we are about to delete the shared edge, check if its not the starting edge of the face
if (hedgeAdj == edge)
{
edge = hedgeAdjNext;
}
// handle the half edges at the head
QuickHullFace* discardedFace;
discardedFace = connectHalfEdges(hedgeOppPrev, hedgeAdjNext);
if (discardedFace != NULL)
{
discardedFaces.pushBack(discardedFace);
}
// handle the half edges at the tail
discardedFace = connectHalfEdges(hedgeAdjPrev, hedgeOppNext);
if (discardedFace != NULL)
{
discardedFaces.pushBack(discardedFace);
}
computeNormalAndCentroid();
PX_ASSERT(checkFaceConsistency());
return true;
}
//////////////////////////////////////////////////////////////////////////
// connect half edges of 2 adjacent faces
// if we find redundancy - edges are in a line, we drop the addional face if it is just a skinny triangle
QuickHullFace* QuickHullFace::connectHalfEdges(QuickHullHalfEdge* hedgePrev, QuickHullHalfEdge* hedge)
{
QuickHullFace* discardedFace = NULL;
// redundant edge - can be in a line
if (hedgePrev->getOppositeFace() == hedge->getOppositeFace())
{
// then there is a redundant edge that we can get rid off
QuickHullFace* oppFace = hedge->getOppositeFace();
QuickHullHalfEdge* hedgeOpp;
if (hedgePrev == edge)
{
edge = hedge;
}
// check if its not a skinny face with just 3 vertices - 3 edges
if (oppFace->isTriangle())
{
// then we can get rid of the opposite face altogether
hedgeOpp = hedge->twin->prev->twin;
oppFace->state = QuickHullFace::eDELETED;
discardedFace = oppFace;
}
else
{
// if not triangle, merge the 2 opposite halfedges into one
hedgeOpp = hedge->twin->next;
if (oppFace->edge == hedgeOpp->prev)
{
oppFace->edge = hedgeOpp;
}
hedgeOpp->prev = hedgeOpp->prev->prev;
hedgeOpp->prev->next = hedgeOpp;
}
hedge->prev = hedgePrev->prev;
hedge->prev->next = hedge;
hedge->twin = hedgeOpp;
hedgeOpp->twin = hedge;
// oppFace was modified, so need to recompute
oppFace->computeNormalAndCentroid();
}
else
{
// just merge the halfedges
hedgePrev->next = hedge;
hedge->prev = hedgePrev;
}
return discardedFace;
}
//////////////////////////////////////////////////////////////////////////
// check face consistency
bool QuickHullFace::checkFaceConsistency()
{
// do a sanity check on the face
QuickHullHalfEdge* hedge = edge;
PxU32 numv = 0;
// check degenerate face
do
{
numv++;
hedge = hedge->next;
} while (hedge != edge);
// degenerate face found
PX_ASSERT(numv > 2);
numv = 0;
hedge = edge;
do
{
QuickHullHalfEdge* hedgeOpp = hedge->twin;
// check if we have twin set
PX_ASSERT(hedgeOpp != NULL);
// twin for the twin must be the original edge
PX_ASSERT(hedgeOpp->twin == hedge);
QuickHullFace* oppFace = hedgeOpp->face;
PX_UNUSED(oppFace);
// opposite edge face must be set and valid
PX_ASSERT(oppFace != NULL);
PX_ASSERT(oppFace->state != QuickHullFace::eDELETED);
// edges face must be this one
PX_ASSERT(hedge->face == this);
hedge = hedge->next;
} while (hedge != edge);
return true;
}
//////////////////////////////////////////////////////////////////////////
QuickHull::QuickHull(const PxCookingParams& params, const PxConvexMeshDesc& desc)
: mCookingParams(params), mConvexDesc(desc), mOutputNumVertices(0), mTerminalVertex(0xFFFFFFFF), mVerticesList(NULL), mNumHullFaces(0), mPrecomputedMinMax(false),
mTolerance(-1.0f), mPlaneTolerance(-1.0f)
{
}
//////////////////////////////////////////////////////////////////////////
QuickHull::~QuickHull()
{
}
//////////////////////////////////////////////////////////////////////////
// sets the precomputed min/max values
void QuickHull::setPrecomputedMinMax(const QuickHullVertex* minVertex,const QuickHullVertex* maxVertex, const float tolerance,const float planeTolerance)
{
for (PxU32 i = 0; i < 3; i++)
{
mMinVertex[i] = minVertex[i];
mMaxVertex[i] = maxVertex[i];
}
mTolerance = tolerance;
mPlaneTolerance = planeTolerance;
mPrecomputedMinMax = true;
}
//////////////////////////////////////////////////////////////////////////
// preallocate internal buffers
void QuickHull::preallocate(PxU32 numVertices)
{
PX_ASSERT(numVertices > 0);
// max num vertices = numVertices
mMaxVertices = PxMax(PxU32(8), numVertices); // 8 is min, since we can expand to AABB during the clean vertices phase
mVerticesList = PX_ALLOCATE(QuickHullVertex, mMaxVertices, "QuickHullVertex");
// estimate the max half edges
PxU32 maxHalfEdges = (3 * mMaxVertices - 6) * 3;
mFreeHalfEdges.init(maxHalfEdges);
// estimate the max faces
PxU32 maxFaces = (2 * mMaxVertices - 4);
mFreeFaces.init(maxFaces*2);
mHullFaces.reserve(maxFaces);
mUnclaimedPoints.reserve(numVertices);
mNewFaces.reserve(32);
mRemovedFaces.reserve(32);
mDiscardedFaces.reserve(32);
mHorizon.reserve(PxMin(numVertices,PxU32(128)));
}
//////////////////////////////////////////////////////////////////////////
// release internal buffers
void QuickHull::releaseHull()
{
PX_FREE(mVerticesList);
mHullFaces.clear();
}
//////////////////////////////////////////////////////////////////////////
// returns the maximum number of vertices on a face
PxU32 QuickHull::maxNumVertsPerFace() const
{
PxU32 numFaces = mHullFaces.size();
PxU32 maxVerts = 0;
for (PxU32 i = 0; i < numFaces; i++)
{
const local::QuickHullFace& face = *mHullFaces[i];
if (face.state == local::QuickHullFace::eVISIBLE)
{
if (face.numEdges > maxVerts)
maxVerts = face.numEdges;
}
}
return maxVerts;
}
//////////////////////////////////////////////////////////////////////////
// parse the input vertices and store them in the hull
void QuickHull::parseInputVertices(const PxVec3* verts, PxU32 numVerts)
{
PX_ASSERT(verts);
PX_ASSERT(numVerts <= mMaxVertices);
mNumVertices = numVerts;
for (PxU32 i = 0; i < numVerts; i++)
{
mVerticesList[i].point = verts[i];
mVerticesList[i].index = i;
}
}
//////////////////////////////////////////////////////////////////////////
// compute min max verts
void QuickHull::computeMinMaxVerts()
{
for (PxU32 i = 0; i < 3; i++)
{
mMinVertex[i] = mVerticesList[0];
mMaxVertex[i] = mVerticesList[0];
}
PxVec3 max = mVerticesList[0].point;
PxVec3 min = mVerticesList[0].point;
// get the max min vertices along the x,y,z
for (PxU32 i = 1; i < mNumVertices; i++)
{
const QuickHullVertex& testVertex = mVerticesList[i];
const PxVec3& testPoint = testVertex.point;
if (testPoint.x > max.x)
{
max.x = testPoint.x;
mMaxVertex[0] = testVertex;
}
else if (testPoint.x < min.x)
{
min.x = testPoint.x;
mMinVertex[0] = testVertex;
}
if (testPoint.y > max.y)
{
max.y = testPoint.y;
mMaxVertex[1] = testVertex;
}
else if (testPoint.y < min.y)
{
min.y = testPoint.y;
mMinVertex[1] = testVertex;
}
if (testPoint.z > max.z)
{
max.z = testPoint.z;
mMaxVertex[2] = testVertex;
}
else if (testPoint.z < min.z)
{
min.z = testPoint.z;
mMinVertex[2] = testVertex;
}
}
const float sizeTol = (max.x-min.x + max.y - min.y + max.z - min.z)*0.5f;
mTolerance = PxMax(local::PLANE_THICKNES * sizeTol, local::PLANE_THICKNES);
mPlaneTolerance = PxMax(mCookingParams.planeTolerance * sizeTol, mCookingParams.planeTolerance);
}
//////////////////////////////////////////////////////////////////////////
// find the initial simplex
// 1. search in max axis from compute min,max
// 2. 3rd point is the furthest vertex from the initial line
// 3. 4th vertex is along the line, 3rd vertex normal
bool QuickHull::findSimplex()
{
float max = 0;
PxU32 imax = 0;
for (PxU32 i = 0; i < 3; i++)
{
float diff = mMaxVertex[i].point[i] - mMinVertex[i].point[i];
if (diff > max)
{
max = diff;
imax = i;
}
}
if (max <= mTolerance)
// should not happen as we clear the vertices before and expand them if they are really close to each other
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "QuickHullConvexHullLib::findSimplex: Simplex input points appers to be almost at the same place");
QuickHullVertex simplex[4];
// set first two vertices to be those with the greatest
// one dimensional separation
simplex[0] = mMaxVertex[imax];
simplex[1] = mMinVertex[imax];
// set third vertex to be the vertex farthest from
// the line between simplex[0] and simplex[1]
PxVec3 normal;
float maxDist = 0;
PxVec3 u01 = (simplex[1].point - simplex[0].point);
u01.normalize();
for (PxU32 i = 0; i < mNumVertices; i++)
{
const QuickHullVertex& testVert = mVerticesList[i];
const PxVec3& testPoint = testVert.point;
const PxVec3 diff = testPoint - simplex[0].point;
const PxVec3 xprod = u01.cross(diff);
const float lenSqr = xprod.magnitudeSquared();
if (lenSqr > maxDist && testVert.index != simplex[0].index && testVert.index != simplex[1].index)
{
maxDist = lenSqr;
simplex[2] = testVert;
normal = xprod;
}
}
if (PxSqrt(maxDist) <= mTolerance)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "QuickHullConvexHullLib::findSimplex: Simplex input points appers to be colinear.");
normal.normalize();
// set the forth vertex in the normal direction
const float d0 = simplex[2].point.dot(normal);
maxDist = 0.0f;
for (PxU32 i = 0; i < mNumVertices; i++)
{
const QuickHullVertex& testVert = mVerticesList[i];
const PxVec3& testPoint = testVert.point;
const float dist = PxAbs(testPoint.dot(normal) - d0);
if (dist > maxDist && testVert.index != simplex[0].index &&
testVert.index != simplex[1].index && testVert.index != simplex[2].index)
{
maxDist = dist;
simplex[3] = testVert;
}
}
if (PxAbs(maxDist) <= mTolerance)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "QuickHullConvexHullLib::findSimplex: Simplex input points appers to be coplanar.");
// now create faces from those triangles
if (!addSimplex(&simplex[0], simplex[3].point.dot(normal) - d0 < 0))
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
// create triangle from given vertices, produce new face and connect the half edges
QuickHullFace* QuickHull::createTriangle(const QuickHullVertex& v0, const QuickHullVertex& v1, const QuickHullVertex& v2)
{
QuickHullFace* face = getFreeHullFace();
if (!face)
return NULL;
QuickHullHalfEdge* he0 = getFreeHullHalfEdge();
if (!he0)
return NULL;
he0->face = face;
he0->tail = v0;
QuickHullHalfEdge* he1 = getFreeHullHalfEdge();
if (!he1)
return NULL;
he1->face = face;
he1->tail = v1;
QuickHullHalfEdge* he2 = getFreeHullHalfEdge();
if (!he2)
return NULL;
he2->face = face;
he2->tail = v2;
he0->prev = he2;
he0->next = he1;
he1->prev = he0;
he1->next = he2;
he2->prev = he1;
he2->next = he0;
face->edge = he0;
face->nextFace = NULL;
// compute the normal and offset
face->computeNormalAndCentroid();
return face;
}
//////////////////////////////////////////////////////////////////////////
// add initial simplex to the quickhull
// construct triangles from the simplex points and connect them with half edges
bool QuickHull::addSimplex(QuickHullVertex* simplex, bool flipTriangle)
{
PX_ASSERT(simplex);
// get interior point
PxVec3 vectorSum = simplex[0].point;
for (PxU32 i = 1; i < 4; i++)
{
vectorSum += simplex[i].point;
}
mInteriorPoint = vectorSum / 4.0f;
QuickHullFace* tris[4];
// create the triangles from the initial simplex
if (flipTriangle)
{
tris[0] = createTriangle(simplex[0], simplex[1], simplex[2]);
if (tris[0] == NULL)
return false;
tris[1] = createTriangle(simplex[3], simplex[1], simplex[0]);
if (tris[1] == NULL)
return false;
tris[2] = createTriangle(simplex[3], simplex[2], simplex[1]);
if (tris[2] == NULL)
return false;
tris[3] = createTriangle(simplex[3], simplex[0], simplex[2]);
if (tris[3] == NULL)
return false;
for (PxU32 i = 0; i < 3; i++)
{
PxU32 k = (i + 1) % 3;
tris[i + 1]->getEdge(1)->setTwin(tris[k + 1]->getEdge(0));
tris[i + 1]->getEdge(2)->setTwin(tris[0]->getEdge(k));
}
}
else
{
tris[0] = createTriangle(simplex[0], simplex[2], simplex[1]);
if (tris[0] == NULL)
return false;
tris[1] = createTriangle(simplex[3], simplex[0], simplex[1]);
if (tris[1] == NULL)
return false;
tris[2] = createTriangle(simplex[3], simplex[1], simplex[2]);
if (tris[2] == NULL)
return false;
tris[3] = createTriangle(simplex[3], simplex[2], simplex[0]);
if (tris[3] == NULL)
return false;
for (PxU32 i = 0; i < 3; i++)
{
PxU32 k = (i + 1) % 3;
tris[i + 1]->getEdge(0)->setTwin(tris[k + 1]->getEdge(1));
tris[i + 1]->getEdge(2)->setTwin(tris[0]->getEdge((3 - i) % 3));
}
}
// push back the first 4 faces created from the simplex
for (PxU32 i = 0; i < 4; i++)
{
mHullFaces.pushBack(tris[i]);
}
mNumHullFaces = 4;
// go through points and add point to faces if they are on the plane
for (PxU32 i = 0; i < mNumVertices; i++)
{
const QuickHullVertex& v = mVerticesList[i];
if (v == simplex[0] || v == simplex[1] || v == simplex[2] || v == simplex[3])
{
continue;
}
float maxDist = mTolerance;
QuickHullFace* maxFace = NULL;
for (PxU32 k = 0; k < 4; k++)
{
const float dist = tris[k]->distanceToPlane(v.point);
if (dist > maxDist)
{
maxFace = tris[k];
maxDist = dist;
}
}
if (maxFace != NULL)
{
addPointToFace(*maxFace, &mVerticesList[i], maxDist);
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// adds a point to the conflict list
// the trick here is to store the most furthest point as the last, thats the only one we care about
// the rest is not important, we just need to store them and claim to new faces later, if the
// faces most furthest point is the current global maximum
void QuickHull::addPointToFace(QuickHullFace& face, QuickHullVertex* vertex, float dist)
{
// if we dont have a conflict list, store the vertex as the first one in the conflict list
vertex->dist = dist;
if(!face.conflictList)
{
face.conflictList = vertex;
vertex->dist = dist;
vertex->next = NULL;
return;
}
PX_ASSERT(face.conflictList);
// this is not the furthest vertex, store it as next in the linked list
if (face.conflictList->dist > dist)
{
vertex->next = face.conflictList->next;
face.conflictList->next = vertex;
}
else
{
// this is the furthest vertex, store it as first in the linked list
vertex->next = face.conflictList;
face.conflictList = vertex;
}
}
//////////////////////////////////////////////////////////////////////////
// removes eye point from a conflict list
// we know that the vertex must the last, as we store it at the back, so just popback()
void QuickHull::removeEyePointFromFace(QuickHullFace& face, const QuickHullVertex* vertex)
{
PX_UNUSED(vertex);
// the picked vertex should always be the first in the linked list
PX_ASSERT(face.conflictList == vertex);
face.conflictList = face.conflictList->next;
}
//////////////////////////////////////////////////////////////////////////
// merge polygons with similar normals
void QuickHull::postMergeHull()
{
// merge faces with similar normals
for (PxU32 i = 0; i < mHullFaces.size(); i++)
{
QuickHullFace& face = *mHullFaces[i];
if (face.state == QuickHullFace::eVISIBLE)
{
PX_ASSERT(face.checkFaceConsistency());
while (doPostAdjacentMerge(face, local::MAXDOT_MINANG));
}
}
}
//////////////////////////////////////////////////////////////////////////
// builds the hull
// 1. find the initial simplex
// 2. check if simplex has a valid area
// 3. add vertices to the hull. We add vertex most furthest from the hull
// 4. terminate if hull limit reached or we have added all vertices
QuickHullResult::Enum QuickHull::buildHull()
{
QuickHullVertex* eyeVtx = NULL;
QuickHullFace* eyeFace;
// compute the vertex min max along x,y,z
if(!mPrecomputedMinMax)
computeMinMaxVerts();
// find the initial simplex of the hull
if (!findSimplex())
{
return QuickHullResult::eFAILURE;
}
// simplex area test
const bool useAreaTest = mConvexDesc.flags & PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES ? true : false;
const float areaEpsilon = mCookingParams.areaTestEpsilon * 2.0f;
if (useAreaTest)
{
for (PxU32 i = 0; i < mHullFaces.size(); i++)
{
if (mHullFaces[i]->area < areaEpsilon)
{
return QuickHullResult::eZERO_AREA_TEST_FAILED;
}
}
}
// add points to the hull
PxU32 numVerts = 4; // initial vertex count - simplex vertices
while ((eyeVtx = nextPointToAdd(eyeFace)) != NULL && eyeVtx->index != mTerminalVertex)
{
// if plane shifting vertex limit, we need the reduced hull
if((mConvexDesc.flags & PxConvexFlag::ePLANE_SHIFTING) && (numVerts >= mConvexDesc.vertexLimit))
break;
bool addFailed = false;
PX_ASSERT(eyeFace);
if (!addPointToHull(eyeVtx, *eyeFace, addFailed))
{
mOutputNumVertices = numVerts;
// we hit the polygons hard limit
return QuickHullResult::ePOLYGONS_LIMIT_REACHED;
}
// We failed to add the vertex, store the vertex as terminal vertex and re run the hull generator
if(addFailed)
{
// set the terminal vertex
mTerminalVertex = eyeVtx->index;
// reset the edges/faces memory
mFreeHalfEdges.reset();
mFreeFaces.reset();
// reset the hull state
mHullFaces.clear();
mNumHullFaces = 0;
mUnclaimedPoints.clear();
mHorizon.clear();
mNewFaces.clear();
mRemovedFaces.clear();
mDiscardedFaces.clear();
// rerun the hull generator
return buildHull();
}
numVerts++;
}
mOutputNumVertices = numVerts;
// vertex limit has been reached. We did not stopped the iteration, since we
// will use the produced hull to compute OBB from it and use the planes
// to slice the initial OBB
if (numVerts > mConvexDesc.vertexLimit)
{
return QuickHullResult::eVERTEX_LIMIT_REACHED;
}
return QuickHullResult::eSUCCESS;
}
//////////////////////////////////////////////////////////////////////////
// finds the best point to add to the hull
// go through the faces conflict list and pick the global maximum
QuickHullVertex* QuickHull::nextPointToAdd(QuickHullFace*& eyeFace)
{
QuickHullVertex* eyeVtx = NULL;
QuickHullFace* eyeF = NULL;
float maxDist = mPlaneTolerance;
for (PxU32 i = 0; i < mHullFaces.size(); i++)
{
if (mHullFaces[i]->state == QuickHullFace::eVISIBLE && mHullFaces[i]->conflictList)
{
const float dist = mHullFaces[i]->conflictList->dist;
if (maxDist < dist)
{
maxDist = dist;
eyeVtx = mHullFaces[i]->conflictList;
eyeF = mHullFaces[i];
}
}
}
eyeFace = eyeF;
return eyeVtx;
}
//////////////////////////////////////////////////////////////////////////
// adds vertex to the hull
// sets addFailed to true if we failed to add a point because the merging failed
// this can happen as the face plane equation changes and some faces might become concave
// returns false if the new faces count would hit the hull face hard limit (255 / 64 for GPU-compatible)
bool QuickHull::addPointToHull(const QuickHullVertex* eyeVtx, QuickHullFace& eyeFace, bool& addFailed)
{
addFailed = false;
// removes the eyePoint from the conflict list
removeEyePointFromFace(eyeFace, eyeVtx);
// calculates the horizon from the eyePoint
calculateHorizon(eyeVtx->point, NULL, eyeFace, mHorizon, mRemovedFaces);
// check if we dont hit the polygons hard limit
if (mNumHullFaces + mHorizon.size() > mConvexDesc.polygonLimit)
{
// make the faces visible again and quit
for (PxU32 i = 0; i < mRemovedFaces.size(); i++)
{
mRemovedFaces[i]->state = QuickHullFace::eVISIBLE;
}
mNumHullFaces += mRemovedFaces.size();
return false;
}
// adds new faces from given horizon and eyePoint
addNewFacesFromHorizon(eyeVtx, mHorizon, mNewFaces);
bool mergeFailed = false;
// first merge pass ... merge faces which are non-convex
// as determined by the larger face
for (PxU32 i = 0; i < mNewFaces.size(); i++)
{
QuickHullFace& face = *mNewFaces[i];
if (face.state == QuickHullFace::eVISIBLE)
{
PX_ASSERT(face.checkFaceConsistency());
while (doAdjacentMerge(face, true, mergeFailed));
}
}
if (mergeFailed)
{
addFailed = true;
return true;
}
// second merge pass ... merge faces which are non-convex
// wrt either face
for (PxU32 i = 0; i < mNewFaces.size(); i++)
{
QuickHullFace& face = *mNewFaces[i];
if (face.state == QuickHullFace::eNON_CONVEX)
{
face.state = QuickHullFace::eVISIBLE;
while (doAdjacentMerge(face, false, mergeFailed));
}
}
if (mergeFailed)
{
addFailed = true;
return true;
}
resolveUnclaimedPoints(mNewFaces);
mHorizon.clear();
mNewFaces.clear();
mRemovedFaces.clear();
return true;
}
//////////////////////////////////////////////////////////////////////////
// merge adjacent faces
// We merge 2 adjacent faces if they lie on the same thick plane defined by the mTolerance
// we do this in 2 steps to ensure we dont leave non-convex faces
bool QuickHull::doAdjacentMerge(QuickHullFace& face, bool mergeWrtLargeFace, bool& mergeFailed)
{
QuickHullHalfEdge* hedge = face.edge;
mergeFailed = false;
bool convex = true;
do
{
const QuickHullFace& oppFace = *hedge->getOppositeFace();
bool merge = false;
if (mergeWrtLargeFace)
{
// merge faces if they are parallel or non-convex
// wrt to the larger face; otherwise, just mark
// the face non-convex for the second pass.
if (face.area > oppFace.area)
{
if (hedge->getOppositeFaceDistance() > -mTolerance)
{
merge = true;
}
else if (hedge->twin->getOppositeFaceDistance() > -mTolerance)
{
convex = false;
}
}
else
{
if (hedge->twin->getOppositeFaceDistance() > -mTolerance)
{
merge = true;
}
else if (hedge->getOppositeFaceDistance() > -mTolerance)
{
convex = false;
}
}
}
else
{
// then merge faces if they are definitively non-convex
if (hedge->getOppositeFaceDistance() > -mTolerance ||
hedge->twin->getOppositeFaceDistance() > -mTolerance)
{
merge = true;
}
}
if (merge)
{
mDiscardedFaces.clear();
if (!face.mergeAdjacentFace(hedge, mDiscardedFaces))
{
mergeFailed = true;
return false;
}
mNumHullFaces -= mDiscardedFaces.size();
for (PxU32 i = 0; i < mDiscardedFaces.size(); i++)
{
deleteFacePoints(*mDiscardedFaces[i], &face);
}
PX_ASSERT(face.checkFaceConsistency());
return true;
}
hedge = hedge->next;
} while (hedge != face.edge);
if (!convex)
{
face.state = QuickHullFace::eNON_CONVEX;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
// merge adjacent faces doing normal test
// we try to merge more aggressively 2 faces with the same normal.
bool QuickHull::doPostAdjacentMerge(QuickHullFace& face, const float maxdot_minang)
{
QuickHullHalfEdge* hedge = face.edge;
do
{
const QuickHullFace& oppFace = *hedge->getOppositeFace();
bool merge = false;
const PxVec3& ni = face.normal;
const PxVec3& nj = oppFace.normal;
const float dotP = ni.dot(nj);
if (dotP > maxdot_minang)
{
if (face.area >= oppFace.area)
{
// check if we can merge the 2 faces
merge = canMergeFaces(*hedge);
}
}
if (merge)
{
QuickHullFaceArray discardedFaces;
face.mergeAdjacentFace(hedge, discardedFaces);
mNumHullFaces -= discardedFaces.size();
for (PxU32 i = 0; i < discardedFaces.size(); i++)
{
deleteFacePoints(*discardedFaces[i], &face);
}
PX_ASSERT(face.checkFaceConsistency());
return true;
}
hedge = hedge->next;
} while (hedge != face.edge);
return false;
}
//////////////////////////////////////////////////////////////////////////
// checks if 2 adjacent faces can be merged
// 1. creates a face with merged vertices
// 2. computes new normal and centroid
// 3. checks that all verts are not too far away from the plane
// 4. checks that the new polygon is still convex
// 5. checks if we are about to merge only 2 neighbor faces, we dont
// want to merge additional faces, that might corrupt the convexity
bool QuickHull::canMergeFaces(const QuickHullHalfEdge& he)
{
const QuickHullFace& face1 = *he.face;
const QuickHullFace& face2 = *he.twin->face;
// construct the merged face
PX_ALLOCA(edges, QuickHullHalfEdge, (face1.numEdges + face2.numEdges));
PxMemSet(edges, 0, (face1.numEdges + face2.numEdges)*sizeof(QuickHullHalfEdge));
QuickHullFace mergedFace;
mergedFace.edge = &edges[0];
// copy the first face edges
PxU32 currentEdge = 0;
const QuickHullHalfEdge* heTwin = NULL;
const QuickHullHalfEdge* heCopy = NULL;
const QuickHullHalfEdge* startEdge = (face1.edge != &he) ? face1.edge : face1.edge->next;
const QuickHullHalfEdge* copyHe = startEdge;
do
{
edges[currentEdge].face = &mergedFace;
edges[currentEdge].tail = copyHe->tail;
if(copyHe == &he)
{
heTwin = copyHe->twin;
heCopy = &edges[currentEdge];
}
const PxU32 nextIndex = (copyHe->next == startEdge) ? 0 : currentEdge + 1;
const PxU32 prevIndex = (currentEdge == 0) ? face1.numEdges - 1 : currentEdge - 1;
edges[currentEdge].next = &edges.mPointer[nextIndex];
edges[currentEdge].prev = &edges.mPointer[prevIndex];
currentEdge++;
copyHe = copyHe->next;
} while (copyHe != startEdge);
// copy the second face edges
copyHe = face2.edge;
do
{
edges[currentEdge].face = &mergedFace;
edges[currentEdge].tail = copyHe->tail;
if(heTwin == copyHe)
heTwin = &edges[currentEdge];
const PxU32 nextIndex = (copyHe->next == face2.edge) ? face1.numEdges : currentEdge + 1;
const PxU32 prevIndex = (currentEdge == face1.numEdges) ? face1.numEdges + face2.numEdges - 1 : currentEdge - 1;
edges[currentEdge].next = &edges.mPointer[nextIndex];
edges[currentEdge].prev = &edges.mPointer[prevIndex];
currentEdge++;
copyHe = copyHe->next;
} while (copyHe != face2.edge);
PX_ASSERT(heTwin);
PX_ASSERT(heCopy);
QuickHullHalfEdge* hedgeAdjPrev = heCopy->prev;
QuickHullHalfEdge* hedgeAdjNext = heCopy->next;
QuickHullHalfEdge* hedgeOppPrev = heTwin->prev;
QuickHullHalfEdge* hedgeOppNext = heTwin->next;
hedgeOppPrev->next = hedgeAdjNext;
hedgeAdjNext->prev = hedgeOppPrev;
hedgeAdjPrev->next = hedgeOppNext;
hedgeOppNext->prev = hedgeAdjPrev;
// compute normal and centroid
mergedFace.computeNormalAndCentroid();
// test the vertex distance
const float maxDist = mPlaneTolerance;
for(PxU32 iVerts=0; iVerts< mNumVertices; iVerts++)
{
const QuickHullVertex& vertex = mVerticesList[iVerts];
const float dist = mergedFace.distanceToPlane(vertex.point);
if (dist > maxDist)
{
return false;
}
}
// check the convexity
QuickHullHalfEdge* qhe = mergedFace.edge;
do
{
const QuickHullVertex& vertex = qhe->tail;
const QuickHullVertex& nextVertex = qhe->next->tail;
PxVec3 edgeVector = nextVertex.point - vertex.point;
edgeVector.normalize();
const PxVec3 outVector = -mergedFace.normal.cross(edgeVector);
QuickHullHalfEdge* testHe = qhe->next;
do
{
const QuickHullVertex& testVertex = testHe->tail;
const float dist = (testVertex.point - vertex.point).dot(outVector);
if (dist > mTolerance)
return false;
testHe = testHe->next;
} while (testHe != qhe->next);
qhe = qhe->next;
} while (qhe != mergedFace.edge);
const QuickHullFace* oppFace = he.getOppositeFace();
QuickHullHalfEdge* hedgeOpp = he.twin;
hedgeAdjPrev = he.prev;
hedgeAdjNext = he.next;
hedgeOppPrev = hedgeOpp->prev;
hedgeOppNext = hedgeOpp->next;
// check if we are lining up with the face in adjPrev dir
while (hedgeAdjPrev->getOppositeFace() == oppFace)
{
hedgeAdjPrev = hedgeAdjPrev->prev;
hedgeOppNext = hedgeOppNext->next;
}
// check if we are lining up with the face in adjNext dir
while (hedgeAdjNext->getOppositeFace() == oppFace)
{
hedgeOppPrev = hedgeOppPrev->prev;
hedgeAdjNext = hedgeAdjNext->next;
}
// no redundant merges, just clean merge of 2 neighbour faces
if (hedgeOppPrev->getOppositeFace() == hedgeAdjNext->getOppositeFace())
{
return false;
}
if (hedgeAdjPrev->getOppositeFace() == hedgeOppNext->getOppositeFace())
{
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// delete face points and store them as unclaimed, so we can add them back to new faces later
void QuickHull::deleteFacePoints(QuickHullFace& face, QuickHullFace* absorbingFace)
{
// no conflict list for this face
if(!face.conflictList)
return;
QuickHullVertex* unclaimedVertex = face.conflictList;
QuickHullVertex* vertexToClaim = NULL;
while (unclaimedVertex)
{
vertexToClaim = unclaimedVertex;
unclaimedVertex = unclaimedVertex->next;
vertexToClaim->next = NULL;
if (!absorbingFace)
{
mUnclaimedPoints.pushBack(vertexToClaim);
}
else
{
const float dist = absorbingFace->distanceToPlane(vertexToClaim->point);
if (dist > mTolerance)
{
addPointToFace(*absorbingFace, vertexToClaim, dist);
}
else
{
mUnclaimedPoints.pushBack(vertexToClaim);
}
}
}
face.conflictList = NULL;
}
//////////////////////////////////////////////////////////////////////////
// calculate the horizon from the eyePoint against a given face
void QuickHull::calculateHorizon(const PxVec3& eyePoint, QuickHullHalfEdge* edge0, QuickHullFace& face, QuickHullHalfEdgeArray& horizon, QuickHullFaceArray& removedFaces)
{
deleteFacePoints(face, NULL);
face.state = QuickHullFace::eDELETED;
removedFaces.pushBack(&face);
mNumHullFaces--;
QuickHullHalfEdge* edge;
if (edge0 == NULL)
{
edge0 = face.getEdge(0);
edge = edge0;
}
else
{
edge = edge0->next;
}
do
{
QuickHullFace* oppFace = edge->getOppositeFace();
if (oppFace->state == QuickHullFace::eVISIBLE)
{
const float dist = oppFace->distanceToPlane(eyePoint);
if (dist > mTolerance)
{
calculateHorizon(eyePoint, edge->twin, *oppFace, horizon, removedFaces);
}
else
{
horizon.pushBack(edge);
}
}
edge = edge->next;
} while (edge != edge0);
}
//////////////////////////////////////////////////////////////////////////
// adds new faces from given horizon and eyePoint
void QuickHull::addNewFacesFromHorizon(const QuickHullVertex* eyePoint, const QuickHullHalfEdgeArray& horizon, QuickHullFaceArray& newFaces)
{
QuickHullHalfEdge* hedgeSidePrev = NULL;
QuickHullHalfEdge* hedgeSideBegin = NULL;
for (PxU32 i = 0; i < horizon.size(); i++)
{
const QuickHullHalfEdge& horizonHe = *horizon[i];
QuickHullFace* face = createTriangle(*eyePoint, horizonHe.getHead(), horizonHe.getTail());
mHullFaces.pushBack(face);
mNumHullFaces++;
face->getEdge(2)->setTwin(horizonHe.twin);
QuickHullHalfEdge* hedgeSide = face->edge;
if (hedgeSidePrev != NULL)
{
hedgeSide->next->setTwin(hedgeSidePrev);
}
else
{
hedgeSideBegin = hedgeSide;
}
newFaces.pushBack(face);
hedgeSidePrev = hedgeSide;
}
if(hedgeSideBegin)
hedgeSideBegin->next->setTwin(hedgeSidePrev);
}
//////////////////////////////////////////////////////////////////////////
// resolve unclaimed points
void QuickHull::resolveUnclaimedPoints(const QuickHullFaceArray& newFaces)
{
for (PxU32 i = 0; i < mUnclaimedPoints.size(); i++)
{
QuickHullVertex* vtx = mUnclaimedPoints[i];
float maxDist = mTolerance;
QuickHullFace* maxFace = NULL;
for (PxU32 j = 0; j < newFaces.size(); j++)
{
const QuickHullFace& newFace = *newFaces[j];
if (newFace.state == QuickHullFace::eVISIBLE)
{
const float dist = newFace.distanceToPlane(vtx->point);
if (dist > maxDist)
{
maxDist = dist;
maxFace = newFaces[j];
}
}
}
if (maxFace != NULL)
{
addPointToFace(*maxFace, vtx, maxDist);
}
}
mUnclaimedPoints.clear();
}
//////////////////////////////////////////////////////////////////////////
// helper struct for hull expand point
struct ExpandPoint
{
PxPlane plane[3]; // the 3 planes that will give us the point
PxU32 planeIndex[3]; // index of the planes for identification
bool operator==(const ExpandPoint& expPoint) const
{
if (expPoint.planeIndex[0] == planeIndex[0] && expPoint.planeIndex[1] == planeIndex[1] &&
expPoint.planeIndex[2] == planeIndex[2])
return true;
else
return false;
}
};
//////////////////////////////////////////////////////////////////////////
// gets the half edge neighbors and form the expand point
void getExpandPoint(const QuickHullHalfEdge& he, ExpandPoint& expandPoint, const PxArray<PxU32>* translationTable = NULL)
{
// set the first 2 - the edge face and the twin face
expandPoint.planeIndex[0] = (translationTable) ? ((*translationTable)[he.face->index]) : (he.face->index);
PxU32 index = translationTable ? ((*translationTable)[he.twin->face->index]) : he.twin->face->index;
if (index < expandPoint.planeIndex[0])
{
expandPoint.planeIndex[1] = expandPoint.planeIndex[0];
expandPoint.planeIndex[0] = index;
}
else
{
expandPoint.planeIndex[1] = index;
}
// now the 3rd one is the next he twin index
index = translationTable ? (*translationTable)[he.next->twin->face->index] : he.next->twin->face->index;
if (index < expandPoint.planeIndex[0])
{
expandPoint.planeIndex[2] = expandPoint.planeIndex[1];
expandPoint.planeIndex[1] = expandPoint.planeIndex[0];
expandPoint.planeIndex[0] = index;
}
else
{
if (index < expandPoint.planeIndex[1])
{
expandPoint.planeIndex[2] = expandPoint.planeIndex[1];
expandPoint.planeIndex[1] = index;
}
else
{
expandPoint.planeIndex[2] = index;
}
}
}
//////////////////////////////////////////////////////////////////////////
// adds the expand point, don't add similar point
void addExpandPoint(const ExpandPoint& expandPoint, PxArray<ExpandPoint>& expandPoints)
{
for (PxU32 i = expandPoints.size(); i--;)
{
if (expandPoint == expandPoints[i])
{
return;
}
}
expandPoints.pushBack(expandPoint);
}
//////////////////////////////////////////////////////////////////////////
// helper for 3 planes intersection
static PxVec3 threePlaneIntersection(const PxPlane &p0, const PxPlane &p1, const PxPlane &p2)
{
PxMat33 mp = (PxMat33(p0.n, p1.n, p2.n)).getTranspose();
PxMat33 mi = (mp).getInverse();
PxVec3 b(p0.d, p1.d, p2.d);
return -mi.transform(b);
}
}
//////////////////////////////////////////////////////////////////////////
QuickHullConvexHullLib::QuickHullConvexHullLib(const PxConvexMeshDesc& desc, const PxCookingParams& params)
: ConvexHullLib(desc, params),mQuickHull(NULL), mCropedConvexHull(NULL), mOutMemoryBuffer(NULL), mFaceTranslateTable(NULL)
{
mQuickHull = PX_NEW(local::QuickHull)(params, desc);
mQuickHull->preallocate(desc.points.count);
}
//////////////////////////////////////////////////////////////////////////
QuickHullConvexHullLib::~QuickHullConvexHullLib()
{
mQuickHull->releaseHull();
PX_DELETE(mQuickHull);
PX_DELETE(mCropedConvexHull);
PX_FREE(mOutMemoryBuffer);
mFaceTranslateTable = NULL; // memory is a part of mOutMemoryBuffer
}
//////////////////////////////////////////////////////////////////////////
// create the hull
// 1. clean the input vertices
// 2. check we can construct the simplex, if not expand the input verts
// 3. prepare the quickhull - preallocate, parse input verts
// 4. construct the hull
// 5. post merge faces if limit not reached
// 6. if limit reached, expand the hull
PxConvexMeshCookingResult::Enum QuickHullConvexHullLib::createConvexHull()
{
PxConvexMeshCookingResult::Enum res = PxConvexMeshCookingResult::eFAILURE;
PxU32 vcount = mConvexMeshDesc.points.count;
if ( vcount < 8 )
vcount = 8;
PxVec3* outvsource = PX_ALLOCATE(PxVec3, vcount, "PxVec3");
PxU32 outvcount;
// cleanup the vertices first
if(mConvexMeshDesc.flags & PxConvexFlag::eSHIFT_VERTICES)
{
if(!shiftAndcleanupVertices(mConvexMeshDesc.points.count, reinterpret_cast<const PxVec3*> (mConvexMeshDesc.points.data), mConvexMeshDesc.points.stride,
outvcount, outvsource))
{
PX_FREE(outvsource);
return res;
}
}
else
{
if(!cleanupVertices(mConvexMeshDesc.points.count, reinterpret_cast<const PxVec3*> (mConvexMeshDesc.points.data), mConvexMeshDesc.points.stride,
outvcount, outvsource))
{
PX_FREE(outvsource);
return res;
}
}
local::QuickHullVertex minimumVertex[3];
local::QuickHullVertex maximumVertex[3];
float tolerance;
float planeTolerance;
bool canReuse = cleanupForSimplex(outvsource, outvcount, &minimumVertex[0], &maximumVertex[0], tolerance, planeTolerance);
mQuickHull->parseInputVertices(outvsource,outvcount);
if(canReuse)
{
mQuickHull->setPrecomputedMinMax(minimumVertex, maximumVertex, tolerance, planeTolerance);
}
local::QuickHullResult::Enum qhRes = mQuickHull->buildHull();
switch(qhRes)
{
case local::QuickHullResult::eZERO_AREA_TEST_FAILED:
res = PxConvexMeshCookingResult::eZERO_AREA_TEST_FAILED;
break;
case local::QuickHullResult::eSUCCESS:
mQuickHull->postMergeHull();
res = PxConvexMeshCookingResult::eSUCCESS;
break;
case local::QuickHullResult::ePOLYGONS_LIMIT_REACHED:
if(mQuickHull->getNbHullVerts() > mConvexMeshDesc.vertexLimit)
{
// expand the hull
if(mConvexMeshDesc.flags & PxConvexFlag::ePLANE_SHIFTING)
res = expandHull();
else
res = expandHullOBB();
}
else
{
mQuickHull->postMergeHull();
}
res = PxConvexMeshCookingResult::ePOLYGONS_LIMIT_REACHED;
break;
case local::QuickHullResult::eVERTEX_LIMIT_REACHED:
{
// expand the hull
if(mConvexMeshDesc.flags & PxConvexFlag::ePLANE_SHIFTING)
res = expandHull();
else
res = expandHullOBB();
}
break;
case local::QuickHullResult::eFAILURE:
break;
};
// check if we need to build GRB compatible mesh
// if hull was cropped we already have a compatible mesh, if not check
// the max verts per face
if(((mConvexMeshDesc.flags & PxConvexFlag::eGPU_COMPATIBLE) || mCookingParams.buildGPUData) && !mCropedConvexHull &&
(res == PxConvexMeshCookingResult::eSUCCESS || res == PxConvexMeshCookingResult::ePOLYGONS_LIMIT_REACHED))
{
PX_ASSERT(mQuickHull);
// if we hit the vertex per face limit, expand the hull by cropping OBB
if(mQuickHull->maxNumVertsPerFace() > gpuMaxVertsPerFace)
{
res = expandHullOBB();
}
}
PX_FREE(outvsource);
return res;
}
//////////////////////////////////////////////////////////////////////////
// fixup the input vertices to be not colinear or coplanar for the initial simplex find
bool QuickHullConvexHullLib::cleanupForSimplex(PxVec3* vertices, PxU32 vertexCount, local::QuickHullVertex* minimumVertex,
local::QuickHullVertex* maximumVertex, float& tolerance, float& planeTolerance)
{
bool retVal = true;
for (PxU32 i = 0; i < 3; i++)
{
minimumVertex[i].point = vertices[0];
minimumVertex[i].index = 0;
maximumVertex[i].point = vertices[0];
maximumVertex[i].index = 0;
}
PxVec3 max = vertices[0];
PxVec3 min = vertices[0];
// get the max min vertices along the x,y,z
for (PxU32 i = 1; i < vertexCount; i++)
{
const PxVec3& testPoint = vertices[i];
if (testPoint.x > max.x)
{
max.x = testPoint.x;
maximumVertex[0].point = testPoint;
maximumVertex[0].index = i;
}
else if (testPoint.x < min.x)
{
min.x = testPoint.x;
minimumVertex[0].point = testPoint;
minimumVertex[0].index = i;
}
if (testPoint.y > max.y)
{
max.y = testPoint.y;
maximumVertex[1].point = testPoint;
maximumVertex[1].index = i;
}
else if (testPoint.y < min.y)
{
min.y = testPoint.y;
minimumVertex[1].point = testPoint;
minimumVertex[1].index = i;
}
if (testPoint.z > max.z)
{
max.z = testPoint.z;
maximumVertex[2].point = testPoint;
maximumVertex[2].index = i;
}
else if (testPoint.z < min.z)
{
min.z = testPoint.z;
minimumVertex[2].point = testPoint;
minimumVertex[2].index = i;
}
}
const float sizeTol = (max.x-min.x + max.y - min.y + max.z - min.z)*0.5f;
tolerance = PxMax(local::PLANE_THICKNES * sizeTol, local::PLANE_THICKNES);
planeTolerance = PxMax(mCookingParams.planeTolerance *sizeTol, mCookingParams.planeTolerance);
float fmax = 0;
PxU32 imax = 0;
for (PxU32 i = 0; i < 3; i++)
{
float diff = (maximumVertex[i].point)[i] - (minimumVertex[i].point)[i];
if (diff > fmax)
{
fmax = diff;
imax = i;
}
}
PxVec3 simplex[4];
// set first two vertices to be those with the greatest
// one dimensional separation
simplex[0] = maximumVertex[imax].point;
simplex[1] = minimumVertex[imax].point;
simplex[2] = simplex[3] = PxVec3(0.0f); // PT: added to silence the static analyzer
// set third vertex to be the vertex farthest from
// the line between simplex[0] and simplex[1]
PxVec3 normal(0.0f);
float maxDist = 0;
imax = 0;
PxVec3 u01 = (simplex[1] - simplex[0]);
u01.normalize();
for (PxU32 i = 0; i < vertexCount; i++)
{
const PxVec3& testPoint = vertices[i];
const PxVec3 diff = testPoint - simplex[0];
const PxVec3 xprod = u01.cross(diff);
const float lenSqr = xprod.magnitudeSquared();
if (lenSqr > maxDist)
{
maxDist = lenSqr;
simplex[2] = testPoint;
normal = xprod;
imax = i;
}
}
if (PxSqrt(maxDist) < planeTolerance)
{
// points are collinear, we have to move the point further
PxVec3 u02 = simplex[2] - simplex[0];
float fT = u02.dot(u01);
const float sqrLen = u01.magnitudeSquared();
fT /= sqrLen;
PxVec3 n = u02 - fT*u01;
n.normalize();
const PxVec3 mP = simplex[2] + n * planeTolerance;
simplex[2] = mP;
vertices[imax] = mP;
retVal = false;
}
normal.normalize();
// set the forth vertex in the normal direction
float d0 = simplex[2].dot(normal);
maxDist = 0.0f;
imax = 0;
for (PxU32 i = 0; i < vertexCount; i++)
{
const PxVec3& testPoint = vertices[i];
float dist = PxAbs(testPoint.dot(normal) - d0);
if (dist > maxDist)
{
maxDist = dist;
// PT: simplex[3] is never used, is it?
simplex[3] = testPoint;
imax = i;
}
}
if (PxAbs(maxDist) < planeTolerance)
{
const float dist = (vertices[imax].dot(normal) - d0);
if (dist > 0)
vertices[imax] = vertices[imax] + normal * planeTolerance;
else
vertices[imax] = vertices[imax] - normal * planeTolerance;
retVal = false;
}
return retVal;
}
//////////////////////////////////////////////////////////////////////////
// expand the hull with the from the limited triangles set
// expand hull will do following steps:
// 1. get expand points from hull that form the best hull with given vertices
// 2. expand the planes to have all vertices inside the planes volume
// 3. compute new points by 3 adjacency planes intersections
// 4. take those points and create the hull from them
PxConvexMeshCookingResult::Enum QuickHullConvexHullLib::expandHull()
{
PxArray<local::ExpandPoint> expandPoints;
expandPoints.reserve(mQuickHull->mNumVertices);
// go over faces and gather expand points
for (PxU32 i = 0; i < mQuickHull->mHullFaces.size(); i++)
{
const local::QuickHullFace& face = *mQuickHull->mHullFaces[i];
if(face.state == local::QuickHullFace::eVISIBLE)
{
local::ExpandPoint expandPoint;
local::QuickHullHalfEdge* he = face.edge;
local::getExpandPoint(*he, expandPoint);
local::addExpandPoint(expandPoint, expandPoints);
he = he->next;
while (he != face.edge)
{
local::getExpandPoint(*he, expandPoint);
local::addExpandPoint(expandPoint, expandPoints);
he = he->next;
}
}
}
// go over the planes now and expand them
for(PxU32 iVerts=0;iVerts< mQuickHull->mNumVertices;iVerts++)
{
const local::QuickHullVertex& vertex = mQuickHull->mVerticesList[iVerts];
for (PxU32 i = 0; i < mQuickHull->mHullFaces.size(); i++)
{
local::QuickHullFace& face = *mQuickHull->mHullFaces[i];
if(face.state == local::QuickHullFace::eVISIBLE)
{
const float dist = face.distanceToPlane(vertex.point);
if(dist > 0 && dist > face.expandOffset)
{
face.expandOffset = dist;
}
}
}
}
// fill the expand points planes
for(PxU32 i=0;i<expandPoints.size();i++)
{
local::ExpandPoint& expandPoint = expandPoints[i];
for (PxU32 k = 0; k < 3; k++)
{
const local::QuickHullFace& face = *mQuickHull->mFreeFaces.getItem(expandPoint.planeIndex[k]);
PX_ASSERT(face.index == expandPoint.planeIndex[k]);
PxPlane plane;
plane.n = face.normal;
plane.d = -face.planeOffset;
if(face.expandOffset > 0.0f)
plane.d -= face.expandOffset;
expandPoint.plane[k] = plane;
}
}
// now find the plane intersection
PX_ALLOCA(vertices,PxVec3,expandPoints.size());
for(PxU32 i=0;i<expandPoints.size();i++)
{
local::ExpandPoint& expandPoint = expandPoints[i];
vertices[i] = local::threePlaneIntersection(expandPoint.plane[0],expandPoint.plane[1],expandPoint.plane[2]);
}
// construct again the hull from the new points
local::QuickHull* newHull = PX_NEW(local::QuickHull)(mQuickHull->mCookingParams, mQuickHull->mConvexDesc);
newHull->preallocate(expandPoints.size());
newHull->parseInputVertices(vertices,expandPoints.size());
local::QuickHullResult::Enum qhRes = newHull->buildHull();
switch(qhRes)
{
case local::QuickHullResult::eZERO_AREA_TEST_FAILED:
{
newHull->releaseHull();
PX_DELETE(newHull);
return PxConvexMeshCookingResult::eZERO_AREA_TEST_FAILED;
}
case local::QuickHullResult::eSUCCESS:
case local::QuickHullResult::eVERTEX_LIMIT_REACHED:
case local::QuickHullResult::ePOLYGONS_LIMIT_REACHED:
{
mQuickHull->releaseHull();
PX_DELETE(mQuickHull);
mQuickHull = newHull;
}
break;
case local::QuickHullResult::eFAILURE:
{
newHull->releaseHull();
PX_DELETE(newHull);
return PxConvexMeshCookingResult::eFAILURE;
}
};
return PxConvexMeshCookingResult::eSUCCESS;
}
//////////////////////////////////////////////////////////////////////////
// expand the hull from the limited triangles set
// 1. collect all planes
// 2. create OBB from the input verts
// 3. slice the OBB with the planes
// 5. iterate till vlimit is reached
PxConvexMeshCookingResult::Enum QuickHullConvexHullLib::expandHullOBB()
{
PxArray<PxPlane> expandPlanes;
expandPlanes.reserve(mQuickHull->mHullFaces.size());
// collect expand planes
for (PxU32 i = 0; i < mQuickHull->mHullFaces.size(); i++)
{
local::QuickHullFace& face = *mQuickHull->mHullFaces[i];
if (face.state == local::QuickHullFace::eVISIBLE)
{
PxPlane plane;
plane.n = face.normal;
plane.d = -face.planeOffset;
if (face.expandOffset > 0.0f)
plane.d -= face.expandOffset;
expandPlanes.pushBack(plane);
}
}
PxTransform obbTransform;
PxVec3 sides;
// compute the OBB
PxConvexMeshDesc convexDesc;
fillConvexMeshDescFromQuickHull(convexDesc);
convexDesc.flags = mConvexMeshDesc.flags;
computeOBBFromConvex(convexDesc, sides, obbTransform);
// free the memory used for the convex mesh desc
PX_FREE(mOutMemoryBuffer);
mFaceTranslateTable = NULL;
// crop the OBB
PxU32 maxplanes = PxMin(PxU32(256), expandPlanes.size());
ConvexHull* c = PX_NEW(ConvexHull)(sides*0.5f,obbTransform, expandPlanes);
const float planeTolerance = mQuickHull->mPlaneTolerance;
const float epsilon = mQuickHull->mTolerance;
PxI32 k;
while (maxplanes-- && (k = c->findCandidatePlane(planeTolerance, epsilon)) >= 0)
{
ConvexHull* tmp = c;
c = convexHullCrop(*tmp, expandPlanes[PxU32(k)], planeTolerance);
if (c == NULL)
{
c = tmp;
break;
} // might want to debug this case better!!!
if (!c->assertIntact(planeTolerance))
{
PX_DELETE(c);
c = tmp;
break;
} // might want to debug this case better too!!!
// check for vertex limit
if (c->getVertices().size() > mConvexMeshDesc.vertexLimit)
{
PX_DELETE(c);
c = tmp;
maxplanes = 0;
break;
}
// check for vertex limit per face if necessary, GRB supports max 32 verts per face
if (((mConvexMeshDesc.flags & PxConvexFlag::eGPU_COMPATIBLE) || mCookingParams.buildGPUData) && c->maxNumVertsPerFace() > gpuMaxVertsPerFace)
{
PX_DELETE(c);
c = tmp;
maxplanes = 0;
break;
}
PX_DELETE(tmp);
}
PX_ASSERT(c->assertIntact(planeTolerance));
mCropedConvexHull = c;
return PxConvexMeshCookingResult::eSUCCESS;
}
//////////////////////////////////////////////////////////////////////////
bool QuickHullConvexHullLib::createEdgeList(const PxU32 nbIndices, const PxU8* indices, PxU8** outHullDataFacesByEdges8, PxU16** outEdgeData16, PxU16** outEdges)
{
// if we croped hull, we dont have the edge information, early exit
if (mCropedConvexHull)
return false;
PX_ASSERT(mQuickHull);
// Make sure we did recieved empty buffers
PX_ASSERT(*outHullDataFacesByEdges8 == NULL);
PX_ASSERT(*outEdges == NULL);
PX_ASSERT(*outEdgeData16 == NULL);
// Allocated the out bufferts
PxU8* hullDataFacesByEdges8 = PX_ALLOCATE(PxU8, nbIndices, "hullDataFacesByEdges8");
PxU16* edges = PX_ALLOCATE(PxU16, nbIndices, "edges");
PxU16* edgeData16 = PX_ALLOCATE(PxU16, nbIndices, "edgeData16");
*outHullDataFacesByEdges8 = hullDataFacesByEdges8;
*outEdges = edges;
*outEdgeData16 = edgeData16;
PxU16 edgeIndex = 0;
PxU32 edgeOffset = 0;
for(PxU32 i = 0; i < mQuickHull->mNumHullFaces; i++)
{
const local::QuickHullFace& face = *mQuickHull->mHullFaces[mFaceTranslateTable[i]];
// Face must be visible
PX_ASSERT(face.state == local::QuickHullFace::eVISIBLE);
// parse the edges
const PxU32 startEdgeOffset = edgeOffset;
local::QuickHullHalfEdge* hedge = face.edge;
do
{
// check if hedge has been stored
if(hedge->edgeIndex == 0xFFFFFFFF)
{
edges[edgeIndex*2] = indices[edgeOffset];
edges[edgeIndex*2 + 1] = indices[(hedge->next != face.edge) ? edgeOffset + 1 : startEdgeOffset];
hullDataFacesByEdges8[edgeIndex*2] = hedge->face->outIndex;
hullDataFacesByEdges8[edgeIndex*2 + 1] = hedge->next->twin->face->outIndex;
edgeData16[edgeOffset] = edgeIndex;
hedge->edgeIndex = edgeIndex;
hedge->next->twin->prev->edgeIndex = edgeIndex;
edgeIndex++;
}
else
{
edgeData16[edgeOffset] = PxTo16(hedge->edgeIndex);
}
hedge = hedge->next;
edgeOffset++;
} while (hedge != face.edge);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// fill the descriptor with computed verts, indices and polygons
void QuickHullConvexHullLib::fillConvexMeshDesc(PxConvexMeshDesc& desc)
{
if (mCropedConvexHull)
fillConvexMeshDescFromCroppedHull(desc);
else
fillConvexMeshDescFromQuickHull(desc);
if(mConvexMeshDesc.flags & PxConvexFlag::eSHIFT_VERTICES)
shiftConvexMeshDesc(desc);
}
//////////////////////////////////////////////////////////////////////////
// fill the descriptor with computed verts, indices and polygons from quickhull convex
void QuickHullConvexHullLib::fillConvexMeshDescFromQuickHull(PxConvexMeshDesc& desc)
{
// get the number of indices needed
PxU32 numIndices = 0;
PxU32 numFaces = mQuickHull->mHullFaces.size();
PxU32 numFacesOut = 0;
PxU32 largestFace = 0; // remember the largest face, we store it as the first face, required for GRB test (max 32 vers per face supported)
for (PxU32 i = 0; i < numFaces; i++)
{
const local::QuickHullFace& face = *mQuickHull->mHullFaces[i];
if(face.state == local::QuickHullFace::eVISIBLE)
{
numFacesOut++;
numIndices += face.numEdges;
if(face.numEdges > mQuickHull->mHullFaces[largestFace]->numEdges)
largestFace = i;
}
}
// allocate out buffers
const PxU32 indicesBufferSize = sizeof(PxU32)*numIndices;
const PxU32 verticesBufferSize = sizeof(PxVec3)*(mQuickHull->mNumVertices + 1);
const PxU32 facesBufferSize = sizeof(PxHullPolygon)*numFacesOut;
const PxU32 faceTranslationTableSize = sizeof(PxU16)*numFacesOut;
const PxU32 translationTableSize = sizeof(PxU32)*mQuickHull->mNumVertices;
const PxU32 bufferMemorySize = indicesBufferSize + verticesBufferSize + facesBufferSize + faceTranslationTableSize + translationTableSize;
mOutMemoryBuffer = reinterpret_cast<PxU8*>(PX_ALLOC(bufferMemorySize, "ConvexMeshDesc"));
PxU32* indices = reinterpret_cast<PxU32*> (mOutMemoryBuffer);
PxVec3* vertices = reinterpret_cast<PxVec3*> (mOutMemoryBuffer + indicesBufferSize);
PxHullPolygon* polygons = reinterpret_cast<PxHullPolygon*> (mOutMemoryBuffer + indicesBufferSize + verticesBufferSize);
mFaceTranslateTable = reinterpret_cast<PxU16*> (mOutMemoryBuffer + indicesBufferSize + verticesBufferSize + facesBufferSize);
PxI32* translateTable = reinterpret_cast<PxI32*> (mOutMemoryBuffer + indicesBufferSize + verticesBufferSize + facesBufferSize + faceTranslationTableSize);
PxMemSet(translateTable,-1,mQuickHull->mNumVertices*sizeof(PxU32));
// go over the hullPolygons and mark valid vertices, create translateTable
PxU32 numVertices = 0;
for (PxU32 i = 0; i < numFaces; i++)
{
const local::QuickHullFace& face = *mQuickHull->mHullFaces[i];
if(face.state == local::QuickHullFace::eVISIBLE)
{
local::QuickHullHalfEdge* he = face.edge;
if(translateTable[he->tail.index] == -1)
{
vertices[numVertices] = he->tail.point;
translateTable[he->tail.index] = PxI32(numVertices);
numVertices++;
}
he = he->next;
while (he != face.edge)
{
if(translateTable[he->tail.index] == -1)
{
vertices[numVertices] = he->tail.point;
translateTable[he->tail.index] = PxI32(numVertices);
numVertices++;
}
he = he->next;
}
}
}
desc.points.count = numVertices;
desc.points.data = vertices;
desc.points.stride = sizeof(PxVec3);
desc.indices.count = numIndices;
desc.indices.data = indices;
desc.indices.stride = sizeof(PxU32);
desc.polygons.count = numFacesOut;
desc.polygons.data = polygons;
desc.polygons.stride = sizeof(PxHullPolygon);
PxU16 indexOffset = 0;
numFacesOut = 0;
for (PxU32 i = 0; i < numFaces; i++)
{
// faceIndex - store the largest face first then the rest
PxU32 faceIndex;
if(i == 0)
{
faceIndex = largestFace;
}
else
{
faceIndex = (i == largestFace) ? 0 : i;
}
local::QuickHullFace& face = *mQuickHull->mHullFaces[faceIndex];
if(face.state == local::QuickHullFace::eVISIBLE)
{
//create index data
local::QuickHullHalfEdge* he = face.edge;
PxU32 index = 0;
he->edgeIndex = 0xFFFFFFFF;
indices[index + indexOffset] = PxU32(translateTable[he->tail.index]);
index++;
he = he->next;
while (he != face.edge)
{
indices[index + indexOffset] = PxU32(translateTable[he->tail.index]);
index++;
he->edgeIndex = 0xFFFFFFFF;
he = he->next;
}
// create polygon
PxHullPolygon polygon;
polygon.mPlane[0] = face.normal[0];
polygon.mPlane[1] = face.normal[1];
polygon.mPlane[2] = face.normal[2];
polygon.mPlane[3] = -face.planeOffset;
polygon.mIndexBase = indexOffset;
polygon.mNbVerts = face.numEdges;
indexOffset += face.numEdges;
polygons[numFacesOut] = polygon;
mFaceTranslateTable[numFacesOut] = PxTo16(faceIndex);
face.outIndex = PxTo8(numFacesOut);
numFacesOut++;
}
}
PX_ASSERT(mQuickHull->mNumHullFaces == numFacesOut);
}
//////////////////////////////////////////////////////////////////////////
// fill the desc from cropped hull data
void QuickHullConvexHullLib::fillConvexMeshDescFromCroppedHull(PxConvexMeshDesc& outDesc)
{
PX_ASSERT(mCropedConvexHull);
// allocate the output buffers
const PxU32 numIndices = mCropedConvexHull->getEdges().size();
const PxU32 numPolygons = mCropedConvexHull->getFacets().size();
const PxU32 numVertices = mCropedConvexHull->getVertices().size();
const PxU32 indicesBufferSize = sizeof(PxU32)*numIndices;
const PxU32 facesBufferSize = sizeof(PxHullPolygon)*numPolygons;
const PxU32 verticesBufferSize = sizeof(PxVec3)*(numVertices + 1); // allocate additional vec3 for V4 safe load in VolumeInteration
const PxU32 bufferMemorySize = indicesBufferSize + verticesBufferSize + facesBufferSize;
mOutMemoryBuffer = reinterpret_cast<PxU8*>(PX_ALLOC(bufferMemorySize, "ConvexMeshDesc"));
// parse the hullOut and fill the result with vertices and polygons
PxU32* indicesOut = reinterpret_cast<PxU32*> (mOutMemoryBuffer);
PxHullPolygon* polygonsOut = reinterpret_cast<PxHullPolygon*> (mOutMemoryBuffer + indicesBufferSize);
PxVec3* vertsOut = reinterpret_cast<PxVec3*> (mOutMemoryBuffer + indicesBufferSize + facesBufferSize);
PxMemCopy(vertsOut, mCropedConvexHull->getVertices().begin(), sizeof(PxVec3)*numVertices);
PxU32 i = 0;
PxU32 k = 0;
PxU32 j = 1;
while (i < mCropedConvexHull->getEdges().size())
{
j = 1;
PxHullPolygon& polygon = polygonsOut[k];
// get num indices per polygon
while (j + i < mCropedConvexHull->getEdges().size() && mCropedConvexHull->getEdges()[i].p == mCropedConvexHull->getEdges()[i + j].p)
{
j++;
}
polygon.mNbVerts = PxTo16(j);
polygon.mIndexBase = PxTo16(i);
// get the plane
polygon.mPlane[0] = mCropedConvexHull->getFacets()[k].n[0];
polygon.mPlane[1] = mCropedConvexHull->getFacets()[k].n[1];
polygon.mPlane[2] = mCropedConvexHull->getFacets()[k].n[2];
polygon.mPlane[3] = mCropedConvexHull->getFacets()[k].d;
while (j--)
{
indicesOut[i] = mCropedConvexHull->getEdges()[i].v;
i++;
}
k++;
}
PX_ASSERT(k == mCropedConvexHull->getFacets().size());
outDesc.indices.count = numIndices;
outDesc.indices.stride = sizeof(PxU32);
outDesc.indices.data = indicesOut;
outDesc.points.count = numVertices;
outDesc.points.stride = sizeof(PxVec3);
outDesc.points.data = vertsOut;
outDesc.polygons.count = numPolygons;
outDesc.polygons.stride = sizeof(PxHullPolygon);
outDesc.polygons.data = polygonsOut;
swapLargestFace(outDesc);
}
| 75,802 | C++ | 28.256272 | 171 | 0.657173 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullBuilder.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 "cooking/PxCooking.h"
#include "GuEdgeList.h"
#include "GuTriangle.h"
#include "GuConvexMesh.h"
#include "GuMeshCleaner.h"
#include "GuCookingConvexHullBuilder.h"
#include "GuCookingConvexHullLib.h"
#include "foundation/PxArray.h"
#include "foundation/PxVecMath.h"
#include "CmRadixSort.h"
// PT: TODO: refactor/revisit this, looks like it comes from an old ICE file
// 7: added mHullDataFacesByVertices8
// 8: added mEdges
// 9: removed duplicite 'C', 'V', 'H', 'L' header
static const physx::PxU32 gVersion = 9;
using namespace physx;
using namespace Gu;
using namespace Cm;
using namespace aos;
#define USE_PRECOMPUTED_HULL_PROJECTION
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
// default constructor
ConvexHullBuilder::ConvexHullBuilder(ConvexHullData* hull, const bool buildGRBData) :
mHullDataHullVertices (NULL),
mHullDataPolygons (NULL),
mHullDataVertexData8 (NULL),
mHullDataFacesByEdges8 (NULL),
mHullDataFacesByVertices8 (NULL),
mEdgeData16 (NULL),
mEdges (NULL),
mHull (hull),
mBuildGRBData (buildGRBData)
{
}
//////////////////////////////////////////////////////////////////////////
// default destructor
ConvexHullBuilder::~ConvexHullBuilder()
{
PX_FREE(mEdgeData16);
PX_FREE(mEdges);
PX_FREE(mHullDataHullVertices);
PX_FREE(mHullDataPolygons);
PX_FREE(mHullDataVertexData8);
PX_FREE(mHullDataFacesByEdges8);
PX_FREE(mHullDataFacesByVertices8);
}
//////////////////////////////////////////////////////////////////////////
// initialize the convex hull
// \param nbVerts [in] number of vertices used
// \param verts [in] vertices array
// \param indices [in] indices array
// \param nbPolygons [in] number of polygons
// \param hullPolygons [in] polygons array
// \param doValidation [in] specifies whether we should run the validation code
// \param hullLib [in] if hullLib is provided, we can reuse the hull create data, hulllib is NULL in case of user provided polygons
bool ConvexHullBuilder::init(PxU32 nbVerts, const PxVec3* verts, const PxU32* indices, const PxU32 nbIndices,
const PxU32 nbPolygons, const PxHullPolygon* hullPolygons, bool doValidation, ConvexHullLib* hullLib)
{
PX_ASSERT(indices);
PX_ASSERT(verts);
PX_ASSERT(hullPolygons);
PX_ASSERT(nbVerts);
PX_ASSERT(nbPolygons);
mHullDataHullVertices = NULL;
mHullDataPolygons = NULL;
mHullDataVertexData8 = NULL;
mHullDataFacesByEdges8 = NULL;
mHullDataFacesByVertices8 = NULL;
mEdges = NULL;
mEdgeData16 = NULL;
mHull->mNbHullVertices = PxTo8(nbVerts);
// allocate additional vec3 for V4 safe load in VolumeInteration
mHullDataHullVertices = PX_ALLOCATE(PxVec3, (mHull->mNbHullVertices + 1), "PxVec3");
PxMemCopy(mHullDataHullVertices, verts, mHull->mNbHullVertices*sizeof(PxVec3));
// Cleanup
mHull->mNbPolygons = 0;
PX_FREE(mHullDataVertexData8);
PX_FREE(mHullDataPolygons);
if(nbPolygons>255)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "ConvexHullBuilder::init: convex hull has more than 255 polygons!");
// Precompute hull polygon structures
mHull->mNbPolygons = PxTo8(nbPolygons);
mHullDataPolygons = PX_ALLOCATE(HullPolygonData, mHull->mNbPolygons, "Gu::HullPolygonData");
mHullDataVertexData8 = PX_ALLOCATE(PxU8, nbIndices, "mHullDataVertexData8");
PxU8* dest = mHullDataVertexData8;
for(PxU32 i=0;i<nbPolygons;i++)
{
const PxHullPolygon& inPolygon = hullPolygons[i];
mHullDataPolygons[i].mVRef8 = PxU16(dest - mHullDataVertexData8); // Setup link for current polygon
PxU32 numVerts = inPolygon.mNbVerts;
PX_ASSERT(numVerts>=3); // Else something very wrong happened...
mHullDataPolygons[i].mNbVerts = PxTo8(numVerts);
for (PxU32 j = 0; j < numVerts; j++)
{
dest[j] = PxTo8(indices[inPolygon.mIndexBase + j]);
}
mHullDataPolygons[i].mPlane = PxPlane(inPolygon.mPlane[0],inPolygon.mPlane[1],inPolygon.mPlane[2],inPolygon.mPlane[3]);
// Next one
dest += numVerts;
}
if(!calculateVertexMapTable(nbPolygons, (hullLib != NULL) ? false : true))
return false;
// moved create edge list here from save, copy. This is a part of the validation process and
// we need to create the edge list anyway
if(!hullLib || !hullLib->createEdgeList(nbIndices, mHullDataVertexData8, &mHullDataFacesByEdges8, &mEdgeData16, &mEdges))
{
if (!createEdgeList(doValidation, nbIndices))
return false;
}
else
{
mHull->mNbEdges = PxU16(nbIndices/2);
}
#ifdef USE_PRECOMPUTED_HULL_PROJECTION
// Loop through polygons
for (PxU32 j = 0; j < nbPolygons; j++)
{
// Precompute hull projection along local polygon normal
PxU32 NbVerts = mHull->mNbHullVertices;
const PxVec3* Verts = mHullDataHullVertices;
HullPolygonData& polygon = mHullDataPolygons[j];
PxReal min = PX_MAX_F32;
PxU8 minIndex = 0xff;
for (PxU8 i = 0; i < NbVerts; i++)
{
float dp = (*Verts++).dot(polygon.mPlane.n);
if (dp < min)
{
min = dp;
minIndex = i;
}
}
polygon.mMinIndex = minIndex;
}
#endif
if(doValidation)
return checkHullPolygons();
else
return true;
}
//////////////////////////////////////////////////////////////////////////
// hull polygons check
bool ConvexHullBuilder::checkHullPolygons() const
{
const PxVec3* hullVerts = mHullDataHullVertices;
const PxU8* vertexData = mHullDataVertexData8;
HullPolygonData* hullPolygons = mHullDataPolygons;
// Check hull validity
if(!hullVerts || !hullPolygons)
return false;
if(mHull->mNbPolygons<4)
return false;
PxVec3 max(-FLT_MAX,-FLT_MAX,-FLT_MAX);
PxVec3 hullMax = hullVerts[0];
PxVec3 hullMin = hullVerts[0];
for(PxU32 j=0;j<mHull->mNbHullVertices;j++)
{
const PxVec3& hullVert = hullVerts[j];
if(fabsf(hullVert.x) > max.x)
max.x = fabsf(hullVert.x);
if(fabsf(hullVert.y) > max.y)
max.y = fabsf(hullVert.y);
if(fabsf(hullVert.z) > max.z)
max.z = fabsf(hullVert.z);
if (hullVert.x > hullMax.x)
{
hullMax.x = hullVert.x;
}
else if (hullVert.x < hullMin.x)
{
hullMin.x = hullVert.x;
}
if (hullVert.y > hullMax.y)
{
hullMax.y = hullVert.y;
}
else if (hullVert.y < hullMin.y)
{
hullMin.y = hullVert.y;
}
if (hullVert.z > hullMax.z)
{
hullMax.z = hullVert.z;
}
else if (hullVert.z < hullMin.z)
{
hullMin.z = hullVert.z;
}
}
// compute the test epsilon the same way we construct the hull, verts are considered coplanar within this epsilon
const float planeTolerance = 0.02f;
const float testEpsilon = PxMax(planeTolerance * (PxMax(PxAbs(hullMax.x), PxAbs(hullMin.x)) +
PxMax(PxAbs(hullMax.y), PxAbs(hullMin.y)) +
PxMax(PxAbs(hullMax.z), PxAbs(hullMin.z))), planeTolerance);
max += PxVec3(testEpsilon, testEpsilon, testEpsilon);
PxVec3 testVectors[8];
bool foundPlane[8];
for (PxU32 i = 0; i < 8; i++)
{
foundPlane[i] = false;
}
testVectors[0] = PxVec3(max.x,max.y,max.z);
testVectors[1] = PxVec3(max.x,-max.y,-max.z);
testVectors[2] = PxVec3(max.x,max.y,-max.z);
testVectors[3] = PxVec3(max.x,-max.y,max.z);
testVectors[4] = PxVec3(-max.x,max.y,max.z);
testVectors[5] = PxVec3(-max.x,-max.y,max.z);
testVectors[6] = PxVec3(-max.x,max.y,-max.z);
testVectors[7] = PxVec3(-max.x,-max.y,-max.z);
// Extra convex hull validity check. This is less aggressive than previous convex decomposer!
// Loop through polygons
for(PxU32 i=0;i<mHull->mNbPolygons;i++)
{
const PxPlane& P = hullPolygons[i].mPlane;
for (PxU32 k = 0; k < 8; k++)
{
if(!foundPlane[k])
{
const float d = P.distance(testVectors[k]);
if(d >= 0)
{
foundPlane[k] = true;
}
}
}
// Test hull vertices against polygon plane
for(PxU32 j=0;j<mHull->mNbHullVertices;j++)
{
// Don't test vertex if it belongs to plane (to prevent numerical issues)
PxU32 nb = hullPolygons[i].mNbVerts;
bool discard=false;
for(PxU32 k=0;k<nb;k++)
{
if(vertexData[hullPolygons[i].mVRef8+k]==PxU8(j))
{
discard = true;
break;
}
}
if(!discard)
{
const float d = P.distance(hullVerts[j]);
// if(d>0.0001f)
//if(d>0.02f)
if(d > testEpsilon)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Gu::ConvexMesh::checkHullPolygons: Some hull vertices seems to be too far from hull planes.");
}
}
}
for (PxU32 i = 0; i < 8; i++)
{
if(!foundPlane[i])
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Gu::ConvexMesh::checkHullPolygons: Hull seems to have opened volume or do (some) faces have reversed winding?");
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// hull data store
PX_COMPILE_TIME_ASSERT(sizeof(EdgeDescData)==8);
PX_COMPILE_TIME_ASSERT(sizeof(EdgeData)==8);
bool ConvexHullBuilder::save(PxOutputStream& stream, bool platformMismatch) const
{
// Export header
if(!WriteHeader('C', 'L', 'H', 'L', gVersion, platformMismatch, stream))
return false;
// Export figures
//embed grb flag into mNbEdges
PxU16 hasGRBData = PxU16(mBuildGRBData);
hasGRBData = PxU16(hasGRBData << 15);
PX_ASSERT(mHull->mNbEdges <( (1 << 15) - 1));
const PxU16 nbEdges = PxU16(mHull->mNbEdges | hasGRBData);
writeDword(mHull->mNbHullVertices, platformMismatch, stream);
writeDword(nbEdges, platformMismatch, stream);
writeDword(computeNbPolygons(), platformMismatch, stream); // Use accessor to lazy-build
PxU32 nb=0;
for(PxU32 i=0;i<mHull->mNbPolygons;i++)
nb += mHullDataPolygons[i].mNbVerts;
writeDword(nb, platformMismatch, stream);
// Export triangles
writeFloatBuffer(&mHullDataHullVertices->x, PxU32(mHull->mNbHullVertices*3), platformMismatch, stream);
// Export polygons
// TODO: allow lazy-evaluation
// We can't really store the buffer in one run anymore!
for(PxU32 i=0;i<mHull->mNbPolygons;i++)
{
HullPolygonData tmpCopy = mHullDataPolygons[i];
if(platformMismatch)
flipData(tmpCopy);
stream.write(&tmpCopy, sizeof(HullPolygonData));
}
// PT: why not storeBuffer here?
for(PxU32 i=0;i<nb;i++)
stream.write(&mHullDataVertexData8[i], sizeof(PxU8));
stream.write(mHullDataFacesByEdges8, PxU32(mHull->mNbEdges*2));
stream.write(mHullDataFacesByVertices8, PxU32(mHull->mNbHullVertices*3));
if (mBuildGRBData)
writeWordBuffer(mEdges, PxU32(mHull->mNbEdges * 2), platformMismatch, stream);
return true;
}
//////////////////////////////////////////////////////////////////////////
bool ConvexHullBuilder::copy(ConvexHullData& hullData, PxU32& mNb)
{
// set the numbers
hullData.mNbHullVertices = mHull->mNbHullVertices;
PxU16 hasGRBData = PxU16(mBuildGRBData);
hasGRBData = PxU16(hasGRBData << 15);
PX_ASSERT(mHull->mNbEdges <((1 << 15) - 1));
hullData.mNbEdges = PxU16(mHull->mNbEdges | hasGRBData);;
hullData.mNbPolygons = PxTo8(computeNbPolygons());
PxU32 nb = 0;
for (PxU32 i = 0; i < mHull->mNbPolygons; i++)
nb += mHullDataPolygons[i].mNbVerts;
mNb = nb;
PxU32 bytesNeeded = computeBufferSize(hullData, nb);
// allocate the memory first.
void* dataMemory = PX_ALLOC(bytesNeeded, "ConvexHullData data");
PxU8* address = reinterpret_cast<PxU8*>(dataMemory);
// set data pointers
hullData.mPolygons = reinterpret_cast<HullPolygonData*>(address); address += sizeof(HullPolygonData) * hullData.mNbPolygons;
PxVec3* dataHullVertices = reinterpret_cast<PxVec3*>(address); address += sizeof(PxVec3) * hullData.mNbHullVertices;
PxU8* dataFacesByEdges8 = reinterpret_cast<PxU8*>(address); address += sizeof(PxU8) * hullData.mNbEdges * 2;
PxU8* dataFacesByVertices8 = reinterpret_cast<PxU8*>(address); address += sizeof(PxU8) * hullData.mNbHullVertices * 3;
PxU16* dataEdges = reinterpret_cast<PxU16*>(address); address += hullData.mNbEdges.isBitSet() ? sizeof(PxU16) *hullData.mNbEdges * 2 : 0;
PxU8* dataVertexData8 = reinterpret_cast<PxU8*>(address); address += sizeof(PxU8) * nb; // PT: leave that one last, so that we don't need to serialize "Nb"
PX_ASSERT(!(size_t(dataHullVertices) % sizeof(PxReal)));
PX_ASSERT(!(size_t(hullData.mPolygons) % sizeof(PxReal)));
PX_ASSERT(size_t(address) <= size_t(dataMemory) + bytesNeeded);
PX_ASSERT(mHullDataHullVertices);
PX_ASSERT(mHullDataPolygons);
PX_ASSERT(mHullDataVertexData8);
PX_ASSERT(mHullDataFacesByEdges8);
PX_ASSERT(mHullDataFacesByVertices8);
// copy the data
PxMemCopy(dataHullVertices, &mHullDataHullVertices->x, PxU32(mHull->mNbHullVertices * 3)*sizeof(float));
PxMemCopy(hullData.mPolygons, mHullDataPolygons , hullData.mNbPolygons*sizeof(HullPolygonData));
PxMemCopy(dataVertexData8, mHullDataVertexData8, nb);
PxMemCopy(dataFacesByEdges8,mHullDataFacesByEdges8, PxU32(mHull->mNbEdges * 2));
if (mBuildGRBData)
PxMemCopy(dataEdges, mEdges, PxU32(mHull->mNbEdges * 2) * sizeof(PxU16));
PxMemCopy(dataFacesByVertices8, mHullDataFacesByVertices8, PxU32(mHull->mNbHullVertices * 3));
return true;
}
//////////////////////////////////////////////////////////////////////////
// calculate vertex map table
bool ConvexHullBuilder::calculateVertexMapTable(PxU32 nbPolygons, bool userPolygons)
{
mHullDataFacesByVertices8 = PX_ALLOCATE(PxU8, mHull->mNbHullVertices*3u, "mHullDataFacesByVertices8");
PxU8 vertexMarker[256];
PxMemSet(vertexMarker, 0, mHull->mNbHullVertices);
for (PxU32 i = 0; i < nbPolygons; i++)
{
const HullPolygonData& polygon = mHullDataPolygons[i];
for (PxU32 k = 0; k < polygon.mNbVerts; ++k)
{
const PxU8 index = mHullDataVertexData8[polygon.mVRef8 + k];
if (vertexMarker[index] < 3)
{
//Found a polygon
mHullDataFacesByVertices8[index*3 + vertexMarker[index]++] = PxTo8(i);
}
}
}
bool noPlaneShift = false;
for (PxU32 i = 0; i < mHull->mNbHullVertices; ++i)
{
if(vertexMarker[i] != 3)
noPlaneShift = true;
}
if (noPlaneShift)
{
//PCM will use the original shape, which means it will have a huge performance drop
if (!userPolygons)
outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "ConvexHullBuilder: convex hull does not have vertex-to-face info! Try to use different convex mesh cooking settings.");
else
outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "ConvexHullBuilder: convex hull does not have vertex-to-face info! Some of the vertices have less than 3 neighbor polygons. The vertex is most likely inside a polygon or on an edge between 2 polygons, please remove those vertices.");
for (PxU32 i = 0; i < mHull->mNbHullVertices; ++i)
{
mHullDataFacesByVertices8[i * 3 + 0] = 0xFF;
mHullDataFacesByVertices8[i * 3 + 1] = 0xFF;
mHullDataFacesByVertices8[i * 3 + 2] = 0xFF;
}
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// create edge list
bool ConvexHullBuilder::createEdgeList(bool doValidation, PxU32 nbEdges)
{
// Code below could be greatly simplified if we assume manifold meshes!
//feodorb: ok, let's assume manifold meshes, since the code before this change
//would fail on non-maniflold meshes anyways
// We need the adjacency graph for hull polygons, similar to what we have for triangles.
// - sort the polygon edges and walk them in order
// - each edge should appear exactly twice since a convex is a manifold mesh without boundary edges
// - the polygon index is implicit when we walk the sorted list => get the 2 polygons back and update adjacency graph
//
// Two possible structures:
// - polygon to edges: needed for local search (actually: polygon to polygons)
// - edge to polygons: needed to compute edge normals on-the-fly
// Below is largely copied from the edge-list code
// Polygon to edges:
//
// We're dealing with convex polygons made of N vertices, defining N edges. For each edge we want the edge in
// an edge array.
//
// Edges to polygon:
//
// For each edge in the array, we want two polygon indices - ie an edge.
// 0) Compute the total size needed for "polygon to edges"
const PxU32 nbPolygons = mHull->mNbPolygons;
PxU32 nbEdgesUnshared = nbEdges;
// in a manifold mesh, each edge is repeated exactly twice as it shares exactly 2 faces
if (nbEdgesUnshared % 2 != 0)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: non-manifold mesh cannot be used, invalid mesh!");
// 1) Get some bytes: I need one EdgesRefs for each face, and some temp buffers
// Face indices by edge indices. First face is the one where the edge is ordered from tail to head.
PX_FREE(mHullDataFacesByEdges8);
mHullDataFacesByEdges8 = PX_ALLOCATE(PxU8, nbEdgesUnshared, "mHullDataFacesByEdges8");
PxU32* tempBuffer = PX_ALLOCATE(PxU32, nbEdgesUnshared*8, "tmp"); // Temp storage
PxU32* bufferAdd = tempBuffer;
PxU32* PX_RESTRICT vRefs0 = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* PX_RESTRICT vRefs1 = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* polyIndex = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* vertexIndex = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* polyIndex2 = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* vertexIndex2 = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* edgeIndex = tempBuffer; tempBuffer += nbEdgesUnshared;
PxU32* edgeData = tempBuffer; tempBuffer += nbEdgesUnshared;
// TODO avoroshilov: use the same "tempBuffer"
bool* flippedVRefs = PX_ALLOCATE(bool, nbEdgesUnshared, "tmp"); // Temp storage
PxU32* run0 = vRefs0;
PxU32* run1 = vRefs1;
PxU32* run2 = polyIndex;
PxU32* run3 = vertexIndex;
bool* run4 = flippedVRefs;
// 2) Create a full redundant list of edges
PxU32 edgeCounter = 0;
for(PxU32 i=0;i<nbPolygons;i++)
{
PxU32 nbVerts = mHullDataPolygons[i].mNbVerts;
const PxU8* PX_RESTRICT Data = mHullDataVertexData8 + mHullDataPolygons[i].mVRef8;
// Loop through polygon vertices
for(PxU32 j=0;j<nbVerts;j++)
{
PxU32 vRef0 = Data[j];
PxU32 vRef1 = Data[(j+1)%nbVerts];
bool flipped = vRef0>vRef1;
if (flipped)
physx::PxSwap(vRef0, vRef1);
*run0++ = vRef0;
*run1++ = vRef1;
*run2++ = i;
*run3++ = j;
*run4++ = flipped;
edgeData[edgeCounter] = edgeCounter;
edgeCounter++;
}
}
PX_ASSERT(PxU32(run0-vRefs0)==nbEdgesUnshared);
PX_ASSERT(PxU32(run1-vRefs1)==nbEdgesUnshared);
// 3) Sort the list according to both keys (VRefs0 and VRefs1)
Cm::RadixSortBuffered sorter;
const PxU32* PX_RESTRICT sorted = sorter.Sort(vRefs1, nbEdgesUnshared,Cm::RADIX_UNSIGNED).Sort(vRefs0, nbEdgesUnshared,Cm::RADIX_UNSIGNED).GetRanks();
PX_FREE(mEdges);
// Edges by their tail and head VRefs. NbEdgesUnshared == nbEdges * 2
// mEdges[edgeIdx*2 + 0] = tailVref, mEdges[edgeIdx*2 + 1] = headVref
// Tails and heads should be consistent with face refs, so that the edge is given in the order of
// his first face and opposite to the order of his second face
mEdges = PX_ALLOCATE(PxU16, nbEdgesUnshared, "mEdges");
PX_FREE(mEdgeData16);
// Face to edge mapping
mEdgeData16 = PX_ALLOCATE(PxU16, nbEdgesUnshared, "mEdgeData16");
// TODO avoroshilov: remove this comment
//mHull->mNbEdges = PxTo16(nbEdgesUnshared / 2); // #non-redundant edges
mHull->mNbEdges = 0; // #non-redundant edges
// 4) Loop through all possible edges
// - clean edges list by removing redundant edges
// - create EdgesRef list
// mNbFaces = nbFaces;
// TODO avoroshilov:
PxU32 numFacesPerEdgeVerificationCounter = 0;
PxU16* edgeVertOutput = mEdges;
PxU32 previousRef0 = PX_INVALID_U32;
PxU32 previousRef1 = PX_INVALID_U32;
PxU32 previousPolyId = PX_INVALID_U32;
PxU16 nbHullEdges = 0;
for (PxU32 i = 0; i < nbEdgesUnshared; i++)
{
const PxU32 sortedIndex = sorted[i]; // Between 0 and Nb
const PxU32 polyID = polyIndex[sortedIndex]; // Poly index
const PxU32 vertexID = vertexIndex[sortedIndex]; // Poly index
PxU32 sortedRef0 = vRefs0[sortedIndex]; // (SortedRef0, SortedRef1) is the sorted edge
PxU32 sortedRef1 = vRefs1[sortedIndex];
bool flipped = flippedVRefs[sortedIndex];
if (sortedRef0 != previousRef0 || sortedRef1 != previousRef1)
{
// TODO avoroshilov: remove this?
if (i != 0 && numFacesPerEdgeVerificationCounter != 1)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: non-manifold mesh cannot be used, invalid mesh!");
numFacesPerEdgeVerificationCounter = 0;
// ### TODO: change this in edge list as well
previousRef0 = sortedRef0;
previousRef1 = sortedRef1;
previousPolyId = polyID;
//feodorb:restore the original order of VRefs (tail and head)
if (flipped)
physx::PxSwap(sortedRef0, sortedRef1);
*edgeVertOutput++ = PxTo16(sortedRef0);
*edgeVertOutput++ = PxTo16(sortedRef1);
nbHullEdges++;
}
else
{
mHullDataFacesByEdges8[(nbHullEdges - 1) * 2] = PxTo8(previousPolyId);
mHullDataFacesByEdges8[(nbHullEdges - 1) * 2 + 1] = PxTo8(polyID);
++numFacesPerEdgeVerificationCounter;
}
mEdgeData16[mHullDataPolygons[polyID].mVRef8 + vertexID] = PxTo16(i / 2);
// Create mEdgesRef on the fly
polyIndex2[i] = polyID;
vertexIndex2[i] = vertexID;
edgeIndex[i] = PxU32(nbHullEdges - 1);
}
mHull->mNbEdges = nbHullEdges;
//////////////////////
// 2) Get some bytes: one Pair structure / edge
// create this structure only for validation purpose
// 3) Create Counters, ie compute the #faces sharing each edge
if(doValidation)
{
//
sorted = sorter.Sort(vertexIndex2, nbEdgesUnshared, Cm::RADIX_UNSIGNED).Sort(polyIndex2, nbEdgesUnshared, Cm::RADIX_UNSIGNED).GetRanks();
for (PxU32 i = 0; i < nbEdgesUnshared; i++) edgeData[i] = edgeIndex[sorted[i]];
const PxU16 nbToGo = PxU16(mHull->mNbEdges);
EdgeDescData* edgeToTriangles = PX_ALLOCATE(EdgeDescData, nbToGo, "edgeToTriangles");
PxMemZero(edgeToTriangles, sizeof(EdgeDescData)*nbToGo);
PxU32* data = edgeData;
for(PxU32 i=0;i<nbEdgesUnshared;i++) // <= maybe not the same Nb
{
edgeToTriangles[*data++].Count++;
}
// if we don't have a manifold mesh, this can fail... but the runtime would assert in any case
for (PxU32 i = 0; i < nbToGo; i++)
{
if (edgeToTriangles[i].Count != 2)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Cooking::cookConvexMesh: non-manifold mesh cannot be used, invalid mesh!");
}
PX_FREE(edgeToTriangles);
}
// TODO avoroshilov: use the same "tempBuffer"
PX_FREE(flippedVRefs);
// ### free temp ram
PX_FREE(bufferAdd);
return true;
}
| 24,094 | C++ | 32.93662 | 288 | 0.695277 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuRTreeCooking.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_COOKING_RTREE_H
#define GU_COOKING_RTREE_H
#include "cooking/PxCooking.h"
#include "foundation/PxArray.h"
#include "GuMeshData.h"
#include "GuRTree.h"
namespace physx
{
struct RTreeCooker
{
struct RemapCallback // a callback to convert indices from triangle to LeafTriangles or other uses
{
virtual ~RemapCallback() {}
virtual void remap(PxU32* rtreePtr, PxU32 start, PxU32 leafCount) = 0;
};
// triangles will be remapped so that newIndex = resultPermute[oldIndex]
static void buildFromTriangles(
Gu::RTree& resultTree, const PxVec3* verts, PxU32 numVerts, const PxU16* tris16, const PxU32* tris32, PxU32 numTris,
PxArray<PxU32>& resultPermute, RemapCallback* rc, PxReal sizePerfTradeOff01, PxMeshCookingHint::Enum hint);
};
}
#endif
| 2,483 | C | 43.357142 | 119 | 0.757954 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingTriangleMesh.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 "GuCooking.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxSort.h"
#include "foundation/PxFPU.h"
#include "common/PxInsertionCallback.h"
#include "GuRTreeCooking.h"
#include "GuCookingTriangleMesh.h"
#include "GuEdgeList.h"
#include "GuMeshCleaner.h"
#include "GuConvexEdgeFlags.h"
#include "GuTriangle.h"
#include "GuBV4Build.h"
#include "GuBV32Build.h"
#include "GuBounds.h"
#include "CmSerialize.h"
#include "GuCookingGrbTriangleMesh.h"
#include "GuCookingVolumeIntegration.h"
#include "GuCookingSDF.h"
#include "GuMeshAnalysis.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
TriangleMeshBuilder::TriangleMeshBuilder(TriangleMeshData& m, const PxCookingParams& params) :
mEdgeList (NULL),
mParams (params),
mMeshData (m)
{
}
TriangleMeshBuilder::~TriangleMeshBuilder()
{
PX_DELETE(mEdgeList);
}
void TriangleMeshBuilder::remapTopology(const PxU32* order)
{
if(!mMeshData.mNbTriangles)
return;
GU_PROFILE_ZONE("remapTopology")
// Remap one array at a time to limit memory usage
IndexedTriangle32* newTopo = PX_ALLOCATE(IndexedTriangle32, mMeshData.mNbTriangles, "IndexedTriangle32");
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
newTopo[i] = reinterpret_cast<IndexedTriangle32*>(mMeshData.mTriangles)[order[i]];
PX_FREE(mMeshData.mTriangles);
mMeshData.mTriangles = newTopo;
if(mMeshData.mMaterialIndices)
{
PxMaterialTableIndex* newMat = PX_ALLOCATE(PxMaterialTableIndex, mMeshData.mNbTriangles, "mMaterialIndices");
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
newMat[i] = mMeshData.mMaterialIndices[order[i]];
PX_FREE(mMeshData.mMaterialIndices);
mMeshData.mMaterialIndices = newMat;
}
if(!mParams.suppressTriangleMeshRemapTable || mParams.buildGPUData)
{
PxU32* newMap = PX_ALLOCATE(PxU32, mMeshData.mNbTriangles, "mFaceRemap");
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
newMap[i] = mMeshData.mFaceRemap ? mMeshData.mFaceRemap[order[i]] : order[i];
PX_FREE(mMeshData.mFaceRemap);
mMeshData.mFaceRemap = newMap;
}
}
///////////////////////////////////////////////////////////////////////////////
bool TriangleMeshBuilder::cleanMesh(bool validate, PxTriangleMeshCookingResult::Enum* condition)
{
PX_ASSERT(mMeshData.mFaceRemap == NULL);
PxF32 meshWeldTolerance = 0.0f;
if(mParams.meshPreprocessParams & PxMeshPreprocessingFlag::eWELD_VERTICES)
{
if(mParams.meshWeldTolerance == 0.0f)
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "TriangleMeshBuilder::cleanMesh: mesh welding enabled with 0 weld tolerance!");
else
meshWeldTolerance = mParams.meshWeldTolerance;
}
MeshCleaner cleaner(mMeshData.mNbVertices, mMeshData.mVertices, mMeshData.mNbTriangles, reinterpret_cast<const PxU32*>(mMeshData.mTriangles), meshWeldTolerance, mParams.meshAreaMinLimit);
if(!cleaner.mNbTris)
{
if(condition)
*condition = PxTriangleMeshCookingResult::eEMPTY_MESH;
return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "TriangleMeshBuilder::cleanMesh: mesh cleaning removed all triangles!");
}
if(validate)
{
// if we do only validate, we check if cleaning did not remove any verts or triangles.
// such a mesh can be then directly used for cooking without clean flag
if((cleaner.mNbVerts != mMeshData.mNbVertices) || (cleaner.mNbTris != mMeshData.mNbTriangles))
return false;
}
// PT: deal with the remap table
{
// PT: TODO: optimize this
if(cleaner.mRemap)
{
const PxU32 newNbTris = cleaner.mNbTris;
// Remap material array
if(mMeshData.mMaterialIndices)
{
PxMaterialTableIndex* tmp = PX_ALLOCATE(PxMaterialTableIndex, newNbTris, "mMaterialIndices");
for(PxU32 i=0;i<newNbTris;i++)
tmp[i] = mMeshData.mMaterialIndices[cleaner.mRemap[i]];
PX_FREE(mMeshData.mMaterialIndices);
mMeshData.mMaterialIndices = tmp;
}
if (!mParams.suppressTriangleMeshRemapTable || mParams.buildGPUData)
{
mMeshData.mFaceRemap = PX_ALLOCATE(PxU32, newNbTris, "mFaceRemap");
PxMemCopy(mMeshData.mFaceRemap, cleaner.mRemap, newNbTris*sizeof(PxU32));
}
}
}
// PT: deal with geometry
{
if(mMeshData.mNbVertices!=cleaner.mNbVerts)
{
PX_FREE(mMeshData.mVertices);
mMeshData.allocateVertices(cleaner.mNbVerts);
}
PxMemCopy(mMeshData.mVertices, cleaner.mVerts, mMeshData.mNbVertices*sizeof(PxVec3));
}
// PT: deal with topology
{
PX_ASSERT(!(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
if(mMeshData.mNbTriangles!=cleaner.mNbTris)
{
PX_FREE(mMeshData.mTriangles);
mMeshData.allocateTriangles(cleaner.mNbTris, true);
}
const bool testEdgeLength = mParams.meshEdgeLengthMaxLimit!=0.0f;
const float testLengthSquared = mParams.meshEdgeLengthMaxLimit * mParams.meshEdgeLengthMaxLimit * mParams.scale.length * mParams.scale.length;
bool foundLargeTriangle = false;
const PxVec3* v = mMeshData.mVertices;
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
{
const PxU32 vref0 = cleaner.mIndices[i*3+0];
const PxU32 vref1 = cleaner.mIndices[i*3+1];
const PxU32 vref2 = cleaner.mIndices[i*3+2];
PX_ASSERT(vref0!=vref1 && vref0!=vref2 && vref1!=vref2);
reinterpret_cast<IndexedTriangle32*>(mMeshData.mTriangles)[i].mRef[0] = vref0;
reinterpret_cast<IndexedTriangle32*>(mMeshData.mTriangles)[i].mRef[1] = vref1;
reinterpret_cast<IndexedTriangle32*>(mMeshData.mTriangles)[i].mRef[2] = vref2;
if(testEdgeLength)
{
const PxVec3& v0 = v[vref0];
const PxVec3& v1 = v[vref1];
const PxVec3& v2 = v[vref2];
if( (v0 - v1).magnitudeSquared() >= testLengthSquared
|| (v1 - v2).magnitudeSquared() >= testLengthSquared
|| (v2 - v0).magnitudeSquared() >= testLengthSquared
)
foundLargeTriangle = true;
}
}
if(foundLargeTriangle)
{
if(condition)
*condition = PxTriangleMeshCookingResult::eLARGE_TRIANGLE;
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "TriangleMesh: triangles are too big, reduce their size to increase simulation stability!");
}
}
return true;
}
static EdgeList* createEdgeList(const TriangleMeshData& meshData)
{
EDGELISTCREATE create;
create.NbFaces = meshData.mNbTriangles;
if(meshData.has16BitIndices())
{
create.DFaces = NULL;
create.WFaces = reinterpret_cast<PxU16*>(meshData.mTriangles);
}
else
{
create.DFaces = reinterpret_cast<PxU32*>(meshData.mTriangles);
create.WFaces = NULL;
}
create.FacesToEdges = true;
create.EdgesToFaces = true;
create.Verts = meshData.mVertices;
//create.Epsilon = 0.1f;
// create.Epsilon = convexEdgeThreshold;
EdgeList* edgeList = PX_NEW(EdgeList);
if(!edgeList->init(create))
{
PX_DELETE(edgeList);
}
return edgeList;
}
void TriangleMeshBuilder::createSharedEdgeData(bool buildAdjacencies, bool buildActiveEdges)
{
GU_PROFILE_ZONE("createSharedEdgeData")
const bool savedFlag = buildActiveEdges;
if(buildAdjacencies) // building edges is required if buildAdjacencies is requested
buildActiveEdges = true;
PX_ASSERT(mMeshData.mExtraTrigData == NULL);
PX_ASSERT(mMeshData.mAdjacencies == NULL);
if(!buildActiveEdges)
return;
const PxU32 nTrigs = mMeshData.mNbTriangles;
if(0x40000000 <= nTrigs)
{
//mesh is too big for this algo, need to be able to express trig indices in 30 bits, and still have an index reserved for "unused":
outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "TriangleMesh: mesh is too big for this algo!");
return;
}
mMeshData.mExtraTrigData = PX_ALLOCATE(PxU8, nTrigs, "mExtraTrigData");
PxMemZero(mMeshData.mExtraTrigData, sizeof(PxU8)*nTrigs);
const IndexedTriangle32* trigs = reinterpret_cast<const IndexedTriangle32*>(mMeshData.mTriangles);
mEdgeList = createEdgeList(mMeshData);
if(mEdgeList)
{
PX_ASSERT(mEdgeList->getNbFaces()==mMeshData.mNbTriangles);
if(mEdgeList->getNbFaces()==mMeshData.mNbTriangles)
{
for(PxU32 i=0;i<mEdgeList->getNbFaces();i++)
{
const EdgeTriangleData& ET = mEdgeList->getEdgeTriangle(i);
// Replicate flags
if(EdgeTriangleAC::HasActiveEdge01(ET))
mMeshData.mExtraTrigData[i] |= ETD_CONVEX_EDGE_01;
if(EdgeTriangleAC::HasActiveEdge12(ET))
mMeshData.mExtraTrigData[i] |= ETD_CONVEX_EDGE_12;
if(EdgeTriangleAC::HasActiveEdge20(ET))
mMeshData.mExtraTrigData[i] |= ETD_CONVEX_EDGE_20;
}
}
}
// fill the adjacencies
if(buildAdjacencies)
{
mMeshData.mAdjacencies = PX_ALLOCATE(PxU32, nTrigs*3, "mAdjacencies");
memset(mMeshData.mAdjacencies, 0xFFFFffff, sizeof(PxU32)*nTrigs*3);
PxU32 NbEdges = mEdgeList->getNbEdges();
const EdgeDescData* ED = mEdgeList->getEdgeToTriangles();
const EdgeData* Edges = mEdgeList->getEdges();
const PxU32* FBE = mEdgeList->getFacesByEdges();
while(NbEdges--)
{
// Get number of triangles sharing current edge
const PxU32 Count = ED->Count;
if(Count > 1)
{
const PxU32 FaceIndex0 = FBE[ED->Offset+0];
const PxU32 FaceIndex1 = FBE[ED->Offset+1];
const EdgeData& edgeData = *Edges;
const IndexedTriangle32& T0 = trigs[FaceIndex0];
const IndexedTriangle32& T1 = trigs[FaceIndex1];
const PxU32 offset0 = T0.findEdgeCCW(edgeData.Ref0,edgeData.Ref1);
const PxU32 offset1 = T1.findEdgeCCW(edgeData.Ref0,edgeData.Ref1);
mMeshData.setTriangleAdjacency(FaceIndex0, FaceIndex1, offset0);
mMeshData.setTriangleAdjacency(FaceIndex1, FaceIndex0, offset1);
}
ED++;
Edges++;
}
}
#if PX_DEBUG
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
{
const IndexedTriangle32& T = trigs[i];
PX_UNUSED(T);
const EdgeTriangleData& ET = mEdgeList->getEdgeTriangle(i);
PX_ASSERT((EdgeTriangleAC::HasActiveEdge01(ET) && (mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_01)) || (!EdgeTriangleAC::HasActiveEdge01(ET) && !(mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_01)));
PX_ASSERT((EdgeTriangleAC::HasActiveEdge12(ET) && (mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_12)) || (!EdgeTriangleAC::HasActiveEdge12(ET) && !(mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_12)));
PX_ASSERT((EdgeTriangleAC::HasActiveEdge20(ET) && (mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_20)) || (!EdgeTriangleAC::HasActiveEdge20(ET) && !(mMeshData.mExtraTrigData[i] & ETD_CONVEX_EDGE_20)));
}
#endif
// PT: respect the PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE flag. This is important for
// deformable meshes - even if the edge data was needed on-the-fly to compute adjacencies.
if(!savedFlag)
PX_FREE(mMeshData.mExtraTrigData);
}
void TriangleMeshBuilder::createVertMapping()
{
GU_PROFILE_ZONE("createVertMapping")
const PxU32 nbVerts = mMeshData.mNbVertices;
mMeshData.mAccumulatedTrianglesRef = PX_ALLOCATE(PxU32, nbVerts, "accumulatedTrianglesRef");
PxU32* tempCounts = PX_ALLOCATE(PxU32, nbVerts, "tempCounts");
PxU32* triangleCounts = mMeshData.mAccumulatedTrianglesRef;
PxMemZero(triangleCounts, sizeof(PxU32) * nbVerts);
PxMemZero(tempCounts, sizeof(PxU32) * nbVerts);
const PxU32 nbTriangles = mMeshData.mNbTriangles;
IndexedTriangle32* triangles = reinterpret_cast<IndexedTriangle32*>(mMeshData.mGRB_primIndices);
for (PxU32 i = 0; i < nbTriangles; i++)
{
IndexedTriangle32& triangle = triangles[i];
triangleCounts[triangle.mRef[0]]++;
triangleCounts[triangle.mRef[1]]++;
triangleCounts[triangle.mRef[2]]++;
}
//compute runsum
PxU32 totalReference = 0;
for (PxU32 i = 0; i < nbVerts; ++i)
{
PxU32 originalReference = triangleCounts[i];
triangleCounts[i] = totalReference;
totalReference += originalReference;
}
PX_ASSERT(totalReference == nbTriangles * 3);
mMeshData.mTrianglesReferences = PX_ALLOCATE(PxU32, totalReference, "mTrianglesReferences");
mMeshData.mNbTrianglesReferences = totalReference;
PxU32* triangleRefs = mMeshData.mTrianglesReferences;
for (PxU32 i = 0; i < nbTriangles; i++)
{
IndexedTriangle32& triangle = triangles[i];
const PxU32 ind0 = triangle.mRef[0];
const PxU32 ind1 = triangle.mRef[1];
const PxU32 ind2 = triangle.mRef[2];
triangleRefs[triangleCounts[ind0] + tempCounts[ind0]] = i;
tempCounts[ind0]++;
triangleRefs[triangleCounts[ind1] + tempCounts[ind1]] = i;
tempCounts[ind1]++;
triangleRefs[triangleCounts[ind2] + tempCounts[ind2]] = i;
tempCounts[ind2]++;
}
PX_FREE(tempCounts);
}
void TriangleMeshBuilder::recordTriangleIndices()
{
if (mParams.buildGPUData)
{
PX_ASSERT(!(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
PX_ASSERT(mMeshData.mGRB_primIndices);
//copy the BV4 triangle indices to GPU triangle indices buffer
PxMemCopy(mMeshData.mGRB_primIndices, mMeshData.mTriangles, sizeof(IndTri32) *mMeshData.mNbTriangles);
}
}
void TriangleMeshBuilder::createGRBData()
{
GU_PROFILE_ZONE("buildAdjacencies")
const PxU32 numTris = mMeshData.mNbTriangles;
PX_ASSERT(!(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
// Core: Mesh data
///////////////////////////////////////////////////////////////////////////////////
// (by using adjacency info generated by physx cooker)
PxVec3* tempNormalsPerTri_prealloc = PX_ALLOCATE(PxVec3, numTris, "tempNormalsPerTri_prealloc");
mMeshData.mGRB_primAdjacencies = PX_ALLOCATE(uint4, numTris, "GRB_triAdjacencies");
buildAdjacencies(
reinterpret_cast<uint4*>(mMeshData.mGRB_primAdjacencies),
tempNormalsPerTri_prealloc,
mMeshData.mVertices,
reinterpret_cast<IndexedTriangle32*>(mMeshData.mGRB_primIndices),
numTris
);
PX_FREE(tempNormalsPerTri_prealloc);
}
bool TriangleMeshBuilder::createGRBMidPhaseAndData(const PxU32 originalTriangleCount)
{
PX_UNUSED(originalTriangleCount);
if (mParams.buildGPUData)
{
PX_ASSERT(!(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
BV32Tree* bv32Tree = PX_NEW(BV32Tree);
mMeshData.mGRB_BV32Tree = bv32Tree;
if(!BV32TriangleMeshBuilder::createMidPhaseStructure(mParams, mMeshData, *bv32Tree))
return false;
createGRBData();
if (mParams.meshPreprocessParams & PxMeshPreprocessingFlag::eENABLE_VERT_MAPPING || mParams.buildGPUData)
createVertMapping();
#if BV32_VALIDATE
IndTri32* grbTriIndices = reinterpret_cast<IndTri32*>(mMeshData.mGRB_primIndices);
IndTri32* cpuTriIndices = reinterpret_cast<IndTri32*>(mMeshData.mTriangles);
//map CPU remap triangle index to GPU remap triangle index
for (PxU32 i = 0; i < mMeshData.mNbTriangles; ++i)
{
PX_ASSERT(grbTriIndices[i].mRef[0] == cpuTriIndices[mMeshData.mGRB_faceRemap[i]].mRef[0]);
PX_ASSERT(grbTriIndices[i].mRef[1] == cpuTriIndices[mMeshData.mGRB_faceRemap[i]].mRef[1]);
PX_ASSERT(grbTriIndices[i].mRef[2] == cpuTriIndices[mMeshData.mGRB_faceRemap[i]].mRef[2]);
}
#endif
}
return true;
}
bool TriangleMeshBuilder::loadFromDescInternal(PxTriangleMeshDesc& desc, PxTriangleMeshCookingResult::Enum* condition, bool validateMesh)
{
#ifdef PROFILE_MESH_COOKING
printf("\n");
#endif
const PxU32 originalTriangleCount = desc.triangles.count;
if (!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "TriangleMesh::loadFromDesc: desc.isValid() failed!");
// verify the mesh params
if (!mParams.midphaseDesc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "TriangleMesh::loadFromDesc: mParams.midphaseDesc.isValid() failed!");
// Save simple params
{
// Handle implicit topology
PxU32* topology = NULL;
if (!desc.triangles.data)
{
// We'll create 32-bit indices
desc.flags &= ~PxMeshFlag::e16_BIT_INDICES;
desc.triangles.stride = sizeof(PxU32) * 3;
{
// Non-indexed mesh => create implicit topology
desc.triangles.count = desc.points.count / 3;
// Create default implicit topology
topology = PX_ALLOCATE(PxU32, desc.points.count, "topology");
for (PxU32 i = 0; i<desc.points.count; i++)
topology[i] = i;
desc.triangles.data = topology;
}
}
// Convert and clean the input mesh
if (!importMesh(desc, condition, validateMesh))
{
PX_FREE(topology);
return false;
}
// Cleanup if needed
PX_FREE(topology);
}
if(!createMidPhaseStructure())
return false;
//copy the BV4 triangle indices to grb triangle indices if buildGRBData is true
recordTriangleIndices();
// Compute local bounds
computeLocalBoundsAndGeomEpsilon(mMeshData.mVertices, mMeshData.mNbVertices, mMeshData.mAABB, mMeshData.mGeomEpsilon);
createSharedEdgeData(mParams.buildTriangleAdjacencies, !(mParams.meshPreprocessParams & PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE));
return createGRBMidPhaseAndData(originalTriangleCount);
}
void TriangleMeshBuilder::buildInertiaTensor(bool flipNormals)
{
PxTriangleMeshDesc simpleMesh;
simpleMesh.points.count = mMeshData.mNbVertices;
simpleMesh.points.stride = sizeof(PxVec3);
simpleMesh.points.data = mMeshData.mVertices;
simpleMesh.triangles.count = mMeshData.mNbTriangles;
simpleMesh.triangles.stride = sizeof(PxU32) * 3;
simpleMesh.triangles.data = mMeshData.mTriangles;
simpleMesh.flags &= (~PxMeshFlag::e16_BIT_INDICES);
if (flipNormals)
simpleMesh.flags.raise(PxMeshFlag::eFLIPNORMALS);
PxIntegrals integrals;
computeVolumeIntegrals(simpleMesh, 1, integrals);
integrals.getOriginInertia(mMeshData.mInertia);
mMeshData.mMass = PxReal(integrals.mass);
mMeshData.mLocalCenterOfMass = integrals.COM;
}
void TriangleMeshBuilder::buildInertiaTensorFromSDF()
{
if (MeshAnalyzer::checkMeshWatertightness(reinterpret_cast<const Gu::Triangle*>(mMeshData.mTriangles), mMeshData.mNbTriangles))
{
buildInertiaTensor();
if (mMeshData.mMass < 0.0f)
buildInertiaTensor(true); //The mesh can be watertight but all triangles might be oriented the wrong way round
return;
}
PxArray<PxVec3> points;
PxArray<PxU32> triangleIndices;
extractIsosurfaceFromSDF(mMeshData.mSdfData, points, triangleIndices);
PxTriangleMeshDesc simpleMesh;
simpleMesh.points.count = points.size();
simpleMesh.points.stride = sizeof(PxVec3);
simpleMesh.points.data = points.begin();
simpleMesh.triangles.count = triangleIndices.size() / 3;
simpleMesh.triangles.stride = sizeof(PxU32) * 3;
simpleMesh.triangles.data = triangleIndices.begin();
simpleMesh.flags &= (~PxMeshFlag::e16_BIT_INDICES);
PxIntegrals integrals;
computeVolumeIntegrals(simpleMesh, 1, integrals);
integrals.getOriginInertia(mMeshData.mInertia);
mMeshData.mMass = PxReal(integrals.mass);
mMeshData.mLocalCenterOfMass = integrals.COM;
}
//
// When suppressTriangleMeshRemapTable is true, the face remap table is not created. This saves a significant amount of memory,
// but the SDK will not be able to provide information about which mesh triangle is hit in collisions, sweeps or raycasts hits.
//
// The sequence is as follows:
bool TriangleMeshBuilder::loadFromDesc(const PxTriangleMeshDesc& _desc, PxTriangleMeshCookingResult::Enum* condition, bool validateMesh)
{
PxTriangleMeshDesc desc = _desc;
return loadFromDescInternal(desc, condition, validateMesh);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool TriangleMeshBuilder::save(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params) const
{
// Export header
if(!writeHeader('M', 'E', 'S', 'H', PX_MESH_VERSION, platformMismatch, stream))
return false;
// Export midphase ID
writeDword(getMidphaseID(), platformMismatch, stream);
// Export serialization flags
PxU32 serialFlags = 0;
if(mMeshData.mMaterialIndices) serialFlags |= IMSF_MATERIALS;
if(mMeshData.mFaceRemap) serialFlags |= IMSF_FACE_REMAP;
if(mMeshData.mAdjacencies) serialFlags |= IMSF_ADJACENCIES;
if (params.buildGPUData) serialFlags |= IMSF_GRB_DATA;
if (mMeshData.mGRB_faceRemapInverse) serialFlags |= IMSF_GRB_INV_REMAP;
// Compute serialization flags for indices
PxU32 maxIndex=0;
const IndexedTriangle32* tris = reinterpret_cast<const IndexedTriangle32*>(mMeshData.mTriangles);
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
{
if(tris[i].mRef[0]>maxIndex) maxIndex = tris[i].mRef[0];
if(tris[i].mRef[1]>maxIndex) maxIndex = tris[i].mRef[1];
if(tris[i].mRef[2]>maxIndex) maxIndex = tris[i].mRef[2];
}
bool enableSdf = mMeshData.mSdfData.mSdf ? true : false;
if(enableSdf) serialFlags |= IMSF_SDF;
bool enableInertia = (params.meshPreprocessParams & PxMeshPreprocessingFlag::eENABLE_INERTIA) || enableSdf;
if(enableInertia)
serialFlags |= IMSF_INERTIA;
bool force32 = (params.meshPreprocessParams & PxMeshPreprocessingFlag::eFORCE_32BIT_INDICES);
if (maxIndex <= 0xFFFF && !force32)
serialFlags |= (maxIndex <= 0xFF ? IMSF_8BIT_INDICES : IMSF_16BIT_INDICES);
bool enableVertexMapping = (params.buildGPUData || (params.meshPreprocessParams & PxMeshPreprocessingFlag::eENABLE_VERT_MAPPING));
if (enableVertexMapping)
serialFlags |= IMSF_VERT_MAPPING;
writeDword(serialFlags, platformMismatch, stream);
// Export mesh
writeDword(mMeshData.mNbVertices, platformMismatch, stream);
writeDword(mMeshData.mNbTriangles, platformMismatch, stream);
writeFloatBuffer(&mMeshData.mVertices->x, mMeshData.mNbVertices*3, platformMismatch, stream);
if(serialFlags & IMSF_8BIT_INDICES)
{
const PxU32* indices = tris->mRef;
for(PxU32 i=0;i<mMeshData.mNbTriangles*3;i++)
{
PxI8 data = PxI8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else if(serialFlags & IMSF_16BIT_INDICES)
{
const PxU32* indices = tris->mRef;
for(PxU32 i=0;i<mMeshData.mNbTriangles*3;i++)
writeWord(PxTo16(indices[i]), platformMismatch, stream);
}
else
writeIntBuffer(tris->mRef, mMeshData.mNbTriangles*3, platformMismatch, stream);
if(mMeshData.mMaterialIndices)
writeWordBuffer(mMeshData.mMaterialIndices, mMeshData.mNbTriangles, platformMismatch, stream);
if(mMeshData.mFaceRemap)
{
PxU32 maxId = computeMaxIndex(mMeshData.mFaceRemap, mMeshData.mNbTriangles);
writeDword(maxId, platformMismatch, stream);
storeIndices(maxId, mMeshData.mNbTriangles, mMeshData.mFaceRemap, stream, platformMismatch);
// writeIntBuffer(mMeshData.mFaceRemap, mMeshData.mNbTriangles, platformMismatch, stream);
}
if(mMeshData.mAdjacencies)
writeIntBuffer(mMeshData.mAdjacencies, mMeshData.mNbTriangles*3, platformMismatch, stream);
// Export midphase structure
saveMidPhaseStructure(stream, platformMismatch);
// Export local bounds
writeFloat(mMeshData.mGeomEpsilon, platformMismatch, stream);
writeFloat(mMeshData.mAABB.minimum.x, platformMismatch, stream);
writeFloat(mMeshData.mAABB.minimum.y, platformMismatch, stream);
writeFloat(mMeshData.mAABB.minimum.z, platformMismatch, stream);
writeFloat(mMeshData.mAABB.maximum.x, platformMismatch, stream);
writeFloat(mMeshData.mAABB.maximum.y, platformMismatch, stream);
writeFloat(mMeshData.mAABB.maximum.z, platformMismatch, stream);
if(mMeshData.mExtraTrigData)
{
writeDword(mMeshData.mNbTriangles, platformMismatch, stream);
// No need to convert those bytes
stream.write(mMeshData.mExtraTrigData, mMeshData.mNbTriangles*sizeof(PxU8));
}
else
writeDword(0, platformMismatch, stream);
// GRB write -----------------------------------------------------------------
if (params.buildGPUData)
{
const PxU32* indices = reinterpret_cast<PxU32*>(mMeshData.mGRB_primIndices);
if (serialFlags & IMSF_8BIT_INDICES)
{
for (PxU32 i = 0; i<mMeshData.mNbTriangles * 3; i++)
{
PxI8 data = PxI8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else if (serialFlags & IMSF_16BIT_INDICES)
{
for (PxU32 i = 0; i<mMeshData.mNbTriangles * 3; i++)
writeWord(PxTo16(indices[i]), platformMismatch, stream);
}
else
writeIntBuffer(indices, mMeshData.mNbTriangles * 3, platformMismatch, stream);
//writeIntBuffer(reinterpret_cast<PxU32*>(mMeshData.mGRB_triIndices), , mMeshData.mNbTriangles*3, platformMismatch, stream);
//writeIntBuffer(reinterpret_cast<PxU32 *>(mMeshData.mGRB_triIndices), mMeshData.mNbTriangles*4, platformMismatch, stream);
writeIntBuffer(reinterpret_cast<PxU32 *>(mMeshData.mGRB_primAdjacencies), mMeshData.mNbTriangles*4, platformMismatch, stream);
writeIntBuffer(mMeshData.mGRB_faceRemap, mMeshData.mNbTriangles, platformMismatch, stream);
if(mMeshData.mGRB_faceRemapInverse)
writeIntBuffer(mMeshData.mGRB_faceRemapInverse, mMeshData.mNbTriangles, platformMismatch, stream);
//Export GPU midphase structure
BV32Tree* bv32Tree = mMeshData.mGRB_BV32Tree;
BV32TriangleMeshBuilder::saveMidPhaseStructure(bv32Tree, stream, platformMismatch);
//Export vertex mapping
if (enableVertexMapping)
{
writeDword(mMeshData.mNbTrianglesReferences, platformMismatch, stream);
stream.write(mMeshData.mAccumulatedTrianglesRef, mMeshData.mNbVertices * sizeof(PxU32));
stream.write(mMeshData.mTrianglesReferences, mMeshData.mNbTrianglesReferences * sizeof(PxU32));
}
}
// End of GRB write ----------------------------------------------------------
// Export sdf values
if (enableSdf)
{
writeFloat(mMeshData.mSdfData.mMeshLower.x, platformMismatch, stream);
writeFloat(mMeshData.mSdfData.mMeshLower.y, platformMismatch, stream);
writeFloat(mMeshData.mSdfData.mMeshLower.z, platformMismatch, stream);
writeFloat(mMeshData.mSdfData.mSpacing, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mDims.x, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mDims.y, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mDims.z, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mNumSdfs, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mNumSubgridSdfs, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mNumStartSlots, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mSubgridSize, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mSdfSubgrids3DTexBlockDim.x, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mSdfSubgrids3DTexBlockDim.y, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mSdfSubgrids3DTexBlockDim.z, platformMismatch, stream);
writeFloat(mMeshData.mSdfData.mSubgridsMinSdfValue, platformMismatch, stream);
writeFloat(mMeshData.mSdfData.mSubgridsMaxSdfValue, platformMismatch, stream);
writeDword(mMeshData.mSdfData.mBytesPerSparsePixel, platformMismatch, stream);
writeFloatBuffer(mMeshData.mSdfData.mSdf, mMeshData.mSdfData.mNumSdfs, platformMismatch, stream);
writeByteBuffer(mMeshData.mSdfData.mSubgridSdf, mMeshData.mSdfData.mNumSubgridSdfs, stream);
writeIntBuffer(mMeshData.mSdfData.mSubgridStartSlots, mMeshData.mSdfData.mNumStartSlots, platformMismatch, stream);
}
//Export Inertia tensor
if(enableInertia)
{
writeFloat(mMeshData.mMass, platformMismatch, stream);
writeFloatBuffer(reinterpret_cast<const PxF32*>(&mMeshData.mInertia), 9, platformMismatch, stream);
writeFloatBuffer(&mMeshData.mLocalCenterOfMass.x, 3, platformMismatch, stream);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
#if PX_VC
#pragma warning(push)
#pragma warning(disable:4996) // permitting use of gatherStrided until we have a replacement.
#endif
#if PX_CHECKED
bool checkInputFloats(PxU32 nb, const float* values, const char* file, PxU32 line, const char* errorMsg)
{
while(nb--)
{
if(!PxIsFinite(*values++))
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, file, line, errorMsg);
}
return true;
}
#endif
bool TriangleMeshBuilder::importMesh(const PxTriangleMeshDesc& desc, PxTriangleMeshCookingResult::Enum* condition, bool validate)
{
//convert and clean the input mesh
//this is where the mesh data gets copied from user mem to our mem
PxVec3* verts = mMeshData.allocateVertices(desc.points.count);
IndexedTriangle32* tris = reinterpret_cast<IndexedTriangle32*>(mMeshData.allocateTriangles(desc.triangles.count, true, PxU32(mParams.buildGPUData)));
//copy, and compact to get rid of strides:
immediateCooking::gatherStrided(desc.points.data, verts, mMeshData.mNbVertices, sizeof(PxVec3), desc.points.stride);
#if PX_CHECKED
// PT: check all input vertices are valid
if(!checkInputFloats(desc.points.count*3, &verts->x, PX_FL, "input mesh contains corrupted vertex data"))
return false;
#endif
//for trigs index stride conversion and eventual reordering is also needed, I don't think flexicopy can do that for us.
IndexedTriangle32* dest = tris;
const IndexedTriangle32* pastLastDest = tris + mMeshData.mNbTriangles;
const PxU8* source = reinterpret_cast<const PxU8*>(desc.triangles.data);
//4 combos of 16 vs 32 and flip vs no flip
PxU32 c = (desc.flags & PxMeshFlag::eFLIPNORMALS)?PxU32(1):0;
if (desc.flags & PxMeshFlag::e16_BIT_INDICES)
{
//index stride conversion is also needed, I don't think flexicopy can do that for us.
while (dest < pastLastDest)
{
const PxU16 * trig16 = reinterpret_cast<const PxU16*>(source);
dest->mRef[0] = trig16[0];
dest->mRef[1] = trig16[1+c];
dest->mRef[2] = trig16[2-c];
dest ++;
source += desc.triangles.stride;
}
}
else
{
while (dest < pastLastDest)
{
const PxU32 * trig32 = reinterpret_cast<const PxU32*>(source);
dest->mRef[0] = trig32[0];
dest->mRef[1] = trig32[1+c];
dest->mRef[2] = trig32[2-c];
dest ++;
source += desc.triangles.stride;
}
}
//copy the material index list if any:
if(desc.materialIndices.data)
{
PxMaterialTableIndex* materials = mMeshData.allocateMaterials();
immediateCooking::gatherStrided(desc.materialIndices.data, materials, mMeshData.mNbTriangles, sizeof(PxMaterialTableIndex), desc.materialIndices.stride);
// Check material indices
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
PX_ASSERT(materials[i]!=0xffff);
}
// Clean the mesh using ICE's MeshBuilder
// This fixes the bug in ConvexTest06 where the inertia tensor computation fails for a mesh => it works with a clean mesh
if (!(mParams.meshPreprocessParams & PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH) || validate)
{
if(!cleanMesh(validate, condition))
return false;
}
else
{
// we need to fill the remap table if no cleaning was done
if(mParams.suppressTriangleMeshRemapTable == false)
{
PX_ASSERT(mMeshData.mFaceRemap == NULL);
mMeshData.mFaceRemap = PX_ALLOCATE(PxU32, mMeshData.mNbTriangles, "mFaceRemap");
for (PxU32 i = 0; i < mMeshData.mNbTriangles; i++)
mMeshData.mFaceRemap[i] = i;
}
}
if (mParams.meshPreprocessParams & PxMeshPreprocessingFlag::eENABLE_INERTIA)
{
buildInertiaTensor();
}
// Copy sdf data if enabled
if (desc.sdfDesc)
{
PxArray<PxReal> sdfData;
PxArray<PxU8> sdfDataSubgrids;
PxArray<PxU32> sdfSubgridsStartSlots;
PxTriangleMeshDesc newDesc;
newDesc.points.count = mMeshData.mNbVertices;
newDesc.points.stride = sizeof(PxVec3);
newDesc.points.data = mMeshData.mVertices;
newDesc.triangles.count = mMeshData.mNbTriangles;
newDesc.triangles.stride = sizeof(PxU32) * 3;
newDesc.triangles.data = mMeshData.mTriangles;
newDesc.flags &= (~PxMeshFlag::e16_BIT_INDICES);
newDesc.sdfDesc = desc.sdfDesc;
buildSDF(newDesc, sdfData, sdfDataSubgrids, sdfSubgridsStartSlots);
PxSDFDesc& sdfDesc = *desc.sdfDesc;
PxReal* sdf = mMeshData.mSdfData.allocateSdfs(sdfDesc.meshLower, sdfDesc.spacing, sdfDesc.dims.x, sdfDesc.dims.y, sdfDesc.dims.z,
sdfDesc.subgridSize, sdfDesc.sdfSubgrids3DTexBlockDim.x, sdfDesc.sdfSubgrids3DTexBlockDim.y, sdfDesc.sdfSubgrids3DTexBlockDim.z,
sdfDesc.subgridsMinSdfValue, sdfDesc.subgridsMaxSdfValue, sdfDesc.bitsPerSubgridPixel);
if (sdfDesc.subgridSize > 0)
{
//Sparse sdf
immediateCooking::gatherStrided(sdfDesc.sdf.data, sdf, sdfDesc.sdf.count, sizeof(PxReal), sdfDesc.sdf.stride);
immediateCooking::gatherStrided(sdfDesc.sdfSubgrids.data, mMeshData.mSdfData.mSubgridSdf,
sdfDesc.sdfSubgrids.count,
sizeof(PxU8), sdfDesc.sdfSubgrids.stride);
immediateCooking::gatherStrided(sdfDesc.sdfStartSlots.data, mMeshData.mSdfData.mSubgridStartSlots, sdfDesc.sdfStartSlots.count, sizeof(PxU32), sdfDesc.sdfStartSlots.stride);
}
else
{
//copy, and compact to get rid of strides:
immediateCooking::gatherStrided(sdfDesc.sdf.data, sdf, sdfDesc.dims.x*sdfDesc.dims.y*sdfDesc.dims.z, sizeof(PxReal), sdfDesc.sdf.stride);
}
//Make sure there is always a valid inertia tensor for meshes with an SDF
buildInertiaTensorFromSDF();
#if PX_CHECKED
// SN: check all input sdf values are valid
if(!checkInputFloats(sdfDesc.sdf.count, sdf, PX_FL, "input sdf contains corrupted data"))
return false;
#endif
}
return true;
}
#if PX_VC
#pragma warning(pop)
#endif
///////////////////////////////////////////////////////////////////////////////
void TriangleMeshBuilder::checkMeshIndicesSize()
{
TriangleMeshData& m = mMeshData;
// check if we can change indices from 32bits to 16bits
if(m.mNbVertices <= 0xffff && !m.has16BitIndices())
{
const PxU32 numTriangles = m.mNbTriangles;
PxU32* PX_RESTRICT indices32 = reinterpret_cast<PxU32*> (m.mTriangles);
PxU32* PX_RESTRICT grbIndices32 = reinterpret_cast<PxU32*>(m.mGRB_primIndices);
m.mTriangles = 0; // force a realloc
m.allocateTriangles(numTriangles, false, grbIndices32 != NULL ? 1u : 0u);
PX_ASSERT(m.has16BitIndices()); // realloc'ing without the force32bit flag changed it.
PxU16* PX_RESTRICT indices16 = reinterpret_cast<PxU16*> (m.mTriangles);
for (PxU32 i = 0; i < numTriangles * 3; i++)
indices16[i] = PxTo16(indices32[i]);
PX_FREE(indices32);
if (grbIndices32)
{
PxU16* PX_RESTRICT grbIndices16 = reinterpret_cast<PxU16*> (m.mGRB_primIndices);
for (PxU32 i = 0; i < numTriangles * 3; i++)
grbIndices16[i] = PxTo16(grbIndices32[i]);
}
PX_FREE(grbIndices32);
onMeshIndexFormatChange();
}
}
///////////////////////////////////////////////////////////////////////////////
BV4TriangleMeshBuilder::BV4TriangleMeshBuilder(const PxCookingParams& params) : TriangleMeshBuilder(mData, params)
{
}
BV4TriangleMeshBuilder::~BV4TriangleMeshBuilder()
{
}
void BV4TriangleMeshBuilder::onMeshIndexFormatChange()
{
IndTri32* triangles32 = NULL;
IndTri16* triangles16 = NULL;
if(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES)
triangles16 = reinterpret_cast<IndTri16*>(mMeshData.mTriangles);
else
triangles32 = reinterpret_cast<IndTri32*>(mMeshData.mTriangles);
mData.mMeshInterface.setPointers(triangles32, triangles16, mMeshData.mVertices);
}
bool BV4TriangleMeshBuilder::createMidPhaseStructure()
{
GU_PROFILE_ZONE("createMidPhaseStructure_BV4")
const float gBoxEpsilon = 2e-4f;
// const float gBoxEpsilon = 0.1f;
mData.mMeshInterface.initRemap();
mData.mMeshInterface.setNbVertices(mMeshData.mNbVertices);
mData.mMeshInterface.setNbTriangles(mMeshData.mNbTriangles);
IndTri32* triangles32 = NULL;
IndTri16* triangles16 = NULL;
if (mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES)
triangles16 = reinterpret_cast<IndTri16*>(mMeshData.mTriangles);
else
triangles32 = reinterpret_cast<IndTri32*>(mMeshData.mTriangles);
mData.mMeshInterface.setPointers(triangles32, triangles16, mMeshData.mVertices);
PX_ASSERT(mParams.midphaseDesc.getType() == PxMeshMidPhase::eBVH34);
const PxU32 nbTrisPerLeaf = mParams.midphaseDesc.mBVH34Desc.numPrimsPerLeaf;
const bool quantized = mParams.midphaseDesc.mBVH34Desc.quantized;
const PxBVH34BuildStrategy::Enum strategy = mParams.midphaseDesc.mBVH34Desc.buildStrategy;
BV4_BuildStrategy gubs = BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER; // Default
if(strategy==PxBVH34BuildStrategy::eSAH)
gubs = BV4_SAH;
else if(strategy==PxBVH34BuildStrategy::eFAST)
gubs = BV4_SPLATTER_POINTS;
if(!BuildBV4Ex(mData.mBV4Tree, mData.mMeshInterface, gBoxEpsilon, nbTrisPerLeaf, quantized, gubs))
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "BV4 tree failed to build.");
{
GU_PROFILE_ZONE("..BV4 remap")
// remapTopology(mData.mMeshInterface);
const PxU32* order = mData.mMeshInterface.getRemap();
if(mMeshData.mMaterialIndices)
{
PxMaterialTableIndex* newMat = PX_ALLOCATE(PxMaterialTableIndex, mMeshData.mNbTriangles, "mMaterialIndices");
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
newMat[i] = mMeshData.mMaterialIndices[order[i]];
PX_FREE(mMeshData.mMaterialIndices);
mMeshData.mMaterialIndices = newMat;
}
if (!mParams.suppressTriangleMeshRemapTable || mParams.buildGPUData)
{
PxU32* newMap = PX_ALLOCATE(PxU32, mMeshData.mNbTriangles, "mFaceRemap");
for(PxU32 i=0;i<mMeshData.mNbTriangles;i++)
newMap[i] = mMeshData.mFaceRemap ? mMeshData.mFaceRemap[order[i]] : order[i];
PX_FREE(mMeshData.mFaceRemap);
mMeshData.mFaceRemap = newMap;
}
mData.mMeshInterface.releaseRemap();
}
return true;
}
void BV4TriangleMeshBuilder::saveMidPhaseStructure(PxOutputStream& stream, bool mismatch) const
{
// PT: in version 1 we defined "mismatch" as:
// const bool mismatch = (littleEndian() == 1);
// i.e. the data was *always* saved to file in big-endian format no matter what.
// In version>1 we now do the same as for other structures in the SDK: the data is
// exported either as little or big-endian depending on the passed parameter.
const PxU32 bv4StructureVersion = 3;
writeChunk('B', 'V', '4', ' ', stream);
writeDword(bv4StructureVersion, mismatch, stream);
writeFloat(mData.mBV4Tree.mLocalBounds.mCenter.x, mismatch, stream);
writeFloat(mData.mBV4Tree.mLocalBounds.mCenter.y, mismatch, stream);
writeFloat(mData.mBV4Tree.mLocalBounds.mCenter.z, mismatch, stream);
writeFloat(mData.mBV4Tree.mLocalBounds.mExtentsMagnitude, mismatch, stream);
writeDword(mData.mBV4Tree.mInitData, mismatch, stream);
writeFloat(mData.mBV4Tree.mCenterOrMinCoeff.x, mismatch, stream);
writeFloat(mData.mBV4Tree.mCenterOrMinCoeff.y, mismatch, stream);
writeFloat(mData.mBV4Tree.mCenterOrMinCoeff.z, mismatch, stream);
writeFloat(mData.mBV4Tree.mExtentsOrMaxCoeff.x, mismatch, stream);
writeFloat(mData.mBV4Tree.mExtentsOrMaxCoeff.y, mismatch, stream);
writeFloat(mData.mBV4Tree.mExtentsOrMaxCoeff.z, mismatch, stream);
// PT: version 3
writeDword(PxU32(mData.mBV4Tree.mQuantized), mismatch, stream);
writeDword(mData.mBV4Tree.mNbNodes, mismatch, stream);
#ifdef GU_BV4_USE_SLABS
// PT: we use BVDataPacked to get the size computation right, but we're dealing with BVDataSwizzled here!
const PxU32 NodeSize = mData.mBV4Tree.mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
stream.write(mData.mBV4Tree.mNodes, NodeSize*mData.mBV4Tree.mNbNodes);
PX_ASSERT(!mismatch);
#else
#error Not implemented
#endif
}
///////////////////////////////////////////////////////////////////////////////
bool BV32TriangleMeshBuilder::createMidPhaseStructure(const PxCookingParams& params, TriangleMeshData& meshData, BV32Tree& bv32Tree)
{
GU_PROFILE_ZONE("createMidPhaseStructure_BV32")
const float gBoxEpsilon = 2e-4f;
SourceMesh meshInterface;
// const float gBoxEpsilon = 0.1f;
meshInterface.initRemap();
meshInterface.setNbVertices(meshData.mNbVertices);
meshInterface.setNbTriangles(meshData.mNbTriangles);
PX_ASSERT(!(meshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
IndTri32* triangles32 = reinterpret_cast<IndTri32*>(meshData.mGRB_primIndices);
meshInterface.setPointers(triangles32, NULL, meshData.mVertices);
const PxU32 nbTrisPerLeaf = 32;
if (!BuildBV32Ex(bv32Tree, meshInterface, gBoxEpsilon, nbTrisPerLeaf))
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "BV32 tree failed to build.");
{
GU_PROFILE_ZONE("..BV32 remap")
const PxU32* order = meshInterface.getRemap();
if (!params.suppressTriangleMeshRemapTable || params.buildGPUData)
{
PxU32* newMap = PX_ALLOCATE(PxU32, meshData.mNbTriangles, "mGRB_faceRemap");
for (PxU32 i = 0; i<meshData.mNbTriangles; i++)
newMap[i] = meshData.mGRB_faceRemap ? meshData.mGRB_faceRemap[order[i]] : order[i];
PX_FREE(meshData.mGRB_faceRemap);
meshData.mGRB_faceRemap = newMap;
if (!params.suppressTriangleMeshRemapTable)
{
PxU32* newMapInverse = PX_ALLOCATE(PxU32, meshData.mNbTriangles, "mGRB_faceRemapInverse");
for (PxU32 i = 0; i < meshData.mNbTriangles; ++i)
newMapInverse[meshData.mGRB_faceRemap[i]] = i;
PX_FREE(meshData.mGRB_faceRemapInverse);
meshData.mGRB_faceRemapInverse = newMapInverse;
}
}
meshInterface.releaseRemap();
}
return true;
}
void BV32TriangleMeshBuilder::saveMidPhaseStructure(BV32Tree* bv32Tree, PxOutputStream& stream, bool mismatch)
{
// PT: in version 1 we defined "mismatch" as:
// const bool mismatch = (littleEndian() == 1);
// i.e. the data was *always* saved to file in big-endian format no matter what.
// In version>1 we now do the same as for other structures in the SDK: the data is
// exported either as little or big-endian depending on the passed parameter.
const PxU32 bv32StructureVersion = 2;
writeChunk('B', 'V', '3', '2', stream);
writeDword(bv32StructureVersion, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.x, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.y, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.z, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mExtentsMagnitude, mismatch, stream);
writeDword(bv32Tree->mInitData, mismatch, stream);
writeDword(bv32Tree->mNbPackedNodes, mismatch, stream);
PX_ASSERT(bv32Tree->mNbPackedNodes > 0);
for (PxU32 i = 0; i < bv32Tree->mNbPackedNodes; ++i)
{
BV32DataPacked& node = bv32Tree->mPackedNodes[i];
const PxU32 nbElements = node.mNbNodes * 4;
writeDword(node.mNbNodes, mismatch, stream);
writeDword(node.mDepth, mismatch, stream);
WriteDwordBuffer(node.mData, node.mNbNodes, mismatch, stream);
writeFloatBuffer(&node.mMin[0].x, nbElements, mismatch, stream);
writeFloatBuffer(&node.mMax[0].x, nbElements, mismatch, stream);
}
writeDword(bv32Tree->mMaxTreeDepth, mismatch, stream);
PX_ASSERT(bv32Tree->mMaxTreeDepth > 0);
for (PxU32 i = 0; i < bv32Tree->mMaxTreeDepth; ++i)
{
BV32DataDepthInfo& info = bv32Tree->mTreeDepthInfo[i];
writeDword(info.offset, mismatch, stream);
writeDword(info.count, mismatch, stream);
}
WriteDwordBuffer(bv32Tree->mRemapPackedNodeIndexWithDepth, bv32Tree->mNbPackedNodes, mismatch, stream);
}
///////////////////////////////////////////////////////////////////////////////
RTreeTriangleMeshBuilder::RTreeTriangleMeshBuilder(const PxCookingParams& params) : TriangleMeshBuilder(mData, params)
{
}
RTreeTriangleMeshBuilder::~RTreeTriangleMeshBuilder()
{
}
struct RTreeCookerRemap : RTreeCooker::RemapCallback
{
PxU32 mNbTris;
RTreeCookerRemap(PxU32 numTris) : mNbTris(numTris)
{
}
virtual void remap(PxU32* val, PxU32 start, PxU32 leafCount)
{
PX_ASSERT(leafCount > 0);
PX_ASSERT(leafCount <= 16); // sanity check
PX_ASSERT(start < mNbTris);
PX_ASSERT(start+leafCount <= mNbTris);
PX_ASSERT(val);
LeafTriangles lt;
// here we remap from ordered leaf index in the rtree to index in post-remap in triangles
// this post-remap will happen later
lt.SetData(leafCount, start);
*val = lt.Data;
}
};
bool RTreeTriangleMeshBuilder::createMidPhaseStructure()
{
GU_PROFILE_ZONE("createMidPhaseStructure_RTREE")
const PxReal meshSizePerformanceTradeOff = mParams.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff;
const PxMeshCookingHint::Enum meshCookingHint = mParams.midphaseDesc.mBVH33Desc.meshCookingHint;
PxArray<PxU32> resultPermute;
RTreeCookerRemap rc(mMeshData.mNbTriangles);
RTreeCooker::buildFromTriangles(
mData.mRTree,
mMeshData.mVertices, mMeshData.mNbVertices,
(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) ? reinterpret_cast<PxU16*>(mMeshData.mTriangles) : NULL,
!(mMeshData.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES) ? reinterpret_cast<PxU32*>(mMeshData.mTriangles) : NULL,
mMeshData.mNbTriangles, resultPermute, &rc, meshSizePerformanceTradeOff, meshCookingHint);
PX_ASSERT(resultPermute.size() == mMeshData.mNbTriangles);
remapTopology(resultPermute.begin());
return true;
}
void RTreeTriangleMeshBuilder::saveMidPhaseStructure(PxOutputStream& stream, bool mismatch) const
{
// PT: in version 1 we defined "mismatch" as:
// const bool mismatch = (littleEndian() == 1);
// i.e. the data was *always* saved to file in big-endian format no matter what.
// In version>1 we now do the same as for other structures in the SDK: the data is
// exported either as little or big-endian depending on the passed parameter.
const PxU32 rtreeStructureVersion = 2;
// save the RTree root structure followed immediately by RTreePage pages to an output stream
writeChunk('R', 'T', 'R', 'E', stream);
writeDword(rtreeStructureVersion, mismatch, stream);
const RTree& d = mData.mRTree;
writeFloatBuffer(&d.mBoundsMin.x, 4, mismatch, stream);
writeFloatBuffer(&d.mBoundsMax.x, 4, mismatch, stream);
writeFloatBuffer(&d.mInvDiagonal.x, 4, mismatch, stream);
writeFloatBuffer(&d.mDiagonalScaler.x, 4, mismatch, stream);
writeDword(d.mPageSize, mismatch, stream);
writeDword(d.mNumRootPages, mismatch, stream);
writeDword(d.mNumLevels, mismatch, stream);
writeDword(d.mTotalNodes, mismatch, stream);
writeDword(d.mTotalPages, mismatch, stream);
PxU32 unused = 0; writeDword(unused, mismatch, stream); // backwards compatibility
for (PxU32 j = 0; j < d.mTotalPages; j++)
{
writeFloatBuffer(d.mPages[j].minx, RTREE_N, mismatch, stream);
writeFloatBuffer(d.mPages[j].miny, RTREE_N, mismatch, stream);
writeFloatBuffer(d.mPages[j].minz, RTREE_N, mismatch, stream);
writeFloatBuffer(d.mPages[j].maxx, RTREE_N, mismatch, stream);
writeFloatBuffer(d.mPages[j].maxy, RTREE_N, mismatch, stream);
writeFloatBuffer(d.mPages[j].maxz, RTREE_N, mismatch, stream);
WriteDwordBuffer(d.mPages[j].ptrs, RTREE_N, mismatch, stream);
}
}
///////////////////////////////////////////////////////////////////////////////
bool immediateCooking::validateTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc)
{
// cooking code does lots of float bitwise reinterpretation that generates exceptions
PX_FPU_GUARD;
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Cooking::validateTriangleMesh: user-provided triangle mesh descriptor is invalid!");
// PT: validation code doesn't look at midphase data, so ideally we wouldn't build the midphase structure at all here.
if(params.midphaseDesc.getType() == PxMeshMidPhase::eBVH33)
{
RTreeTriangleMeshBuilder builder(params);
return builder.loadFromDesc(desc, NULL, true /*doValidate*/);
}
else if(params.midphaseDesc.getType() == PxMeshMidPhase::eBVH34)
{
BV4TriangleMeshBuilder builder(params);
return builder.loadFromDesc(desc, NULL, true /*doValidate*/);
}
else
return false;
}
///////////////////////////////////////////////////////////////////////////////
PxTriangleMesh* immediateCooking::createTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxInsertionCallback& insertionCallback, PxTriangleMeshCookingResult::Enum* condition)
{
struct Local
{
static PxTriangleMesh* createTriangleMesh(const PxCookingParams& cookingParams_, TriangleMeshBuilder& builder, const PxTriangleMeshDesc& desc_, PxInsertionCallback& insertionCallback_, PxTriangleMeshCookingResult::Enum* condition_)
{
// cooking code does lots of float bitwise reinterpretation that generates exceptions
PX_FPU_GUARD;
if(condition_)
*condition_ = PxTriangleMeshCookingResult::eSUCCESS;
if(!builder.loadFromDesc(desc_, condition_, false))
return NULL;
// check if the indices can be moved from 32bits to 16bits
if(!(cookingParams_.meshPreprocessParams & PxMeshPreprocessingFlag::eFORCE_32BIT_INDICES))
builder.checkMeshIndicesSize();
PxConcreteType::Enum type;
if(builder.getMidphaseID()==PxMeshMidPhase::eBVH33)
type = PxConcreteType::eTRIANGLE_MESH_BVH33;
else
type = PxConcreteType::eTRIANGLE_MESH_BVH34;
return static_cast<PxTriangleMesh*>(insertionCallback_.buildObjectFromData(type, &builder.getMeshData()));
}
};
if(params.midphaseDesc.getType() == PxMeshMidPhase::eBVH33)
{
RTreeTriangleMeshBuilder builder(params);
return Local::createTriangleMesh(params, builder, desc, insertionCallback, condition);
}
else
{
BV4TriangleMeshBuilder builder(params);
return Local::createTriangleMesh(params, builder, desc, insertionCallback, condition);
}
}
///////////////////////////////////////////////////////////////////////////////
bool immediateCooking::cookTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxOutputStream& stream, PxTriangleMeshCookingResult::Enum* condition)
{
struct Local
{
static bool cookTriangleMesh(const PxCookingParams& cookingParams_, TriangleMeshBuilder& builder, const PxTriangleMeshDesc& desc_, PxOutputStream& stream_, PxTriangleMeshCookingResult::Enum* condition_)
{
// cooking code does lots of float bitwise reinterpretation that generates exceptions
PX_FPU_GUARD;
if(condition_)
*condition_ = PxTriangleMeshCookingResult::eSUCCESS;
if(!builder.loadFromDesc(desc_, condition_, false))
return false;
builder.save(stream_, immediateCooking::platformMismatch(), cookingParams_);
return true;
}
};
if(params.midphaseDesc.getType() == PxMeshMidPhase::eBVH33)
{
RTreeTriangleMeshBuilder builder(params);
return Local::cookTriangleMesh(params, builder, desc, stream, condition);
}
else
{
BV4TriangleMeshBuilder builder(params);
return Local::cookTriangleMesh(params, builder, desc, stream, condition);
}
}
///////////////////////////////////////////////////////////////////////////////
| 51,144 | C++ | 34.966948 | 233 | 0.736822 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullLib.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 "GuCookingConvexHullLib.h"
#include "GuQuantizer.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxMemory.h"
using namespace physx;
using namespace Gu;
namespace local
{
//////////////////////////////////////////////////////////////////////////
// constants
static const float DISTANCE_EPSILON = 0.000001f; // close enough to consider two floating point numbers to be 'the same'.
static const float RESIZE_VALUE = 0.01f; // if the provided points AABB is very thin resize it to this size
//////////////////////////////////////////////////////////////////////////
// checks if points form a valid AABB cube, if not construct a default CUBE
static bool checkPointsAABBValidity(PxU32 numPoints, const PxVec3* points, PxU32 stride , float distanceEpsilon,
float resizeValue, PxU32& vcount, PxVec3* vertices, bool fCheck = false)
{
const char* vtx = reinterpret_cast<const char *> (points);
PxBounds3 bounds;
bounds.setEmpty();
// get the bounding box
for (PxU32 i = 0; i < numPoints; i++)
{
const PxVec3& p = *reinterpret_cast<const PxVec3 *> (vtx);
vtx += stride;
bounds.include(p);
vertices[i] = p;
}
PxVec3 dim = bounds.getDimensions();
PxVec3 center = bounds.getCenter();
// special case, the AABB is very thin or user provided us with only input 2 points
// we construct an AABB cube and return it
if ( dim.x < distanceEpsilon || dim.y < distanceEpsilon || dim.z < distanceEpsilon || numPoints < 3 )
{
float len = FLT_MAX;
// pick the shortest size bigger than the distance epsilon
if ( dim.x > distanceEpsilon && dim.x < len )
len = dim.x;
if ( dim.y > distanceEpsilon && dim.y < len )
len = dim.y;
if ( dim.z > distanceEpsilon && dim.z < len )
len = dim.z;
// if the AABB is small in all dimensions, resize it
if ( len == FLT_MAX )
{
dim = PxVec3(resizeValue);
}
// if one edge is small, set to 1/5th the shortest non-zero edge.
else
{
if ( dim.x < distanceEpsilon )
dim.x = PxMin(len * 0.05f, resizeValue);
else
dim.x *= 0.5f;
if ( dim.y < distanceEpsilon )
dim.y = PxMin(len * 0.05f, resizeValue);
else
dim.y *= 0.5f;
if ( dim.z < distanceEpsilon )
dim.z = PxMin(len * 0.05f, resizeValue);
else
dim.z *= 0.5f;
}
// construct the AABB
const PxVec3 extPos = center + dim;
const PxVec3 extNeg = center - dim;
if(fCheck)
vcount = 0;
vertices[vcount++] = extNeg;
vertices[vcount++] = PxVec3(extPos.x,extNeg.y,extNeg.z);
vertices[vcount++] = PxVec3(extPos.x,extPos.y,extNeg.z);
vertices[vcount++] = PxVec3(extNeg.x,extPos.y,extNeg.z);
vertices[vcount++] = PxVec3(extNeg.x,extNeg.y,extPos.z);
vertices[vcount++] = PxVec3(extPos.x,extNeg.y,extPos.z);
vertices[vcount++] = extPos;
vertices[vcount++] = PxVec3(extNeg.x,extPos.y,extPos.z);
return true; // return cube
}
vcount = numPoints;
return false;
}
}
//////////////////////////////////////////////////////////////////////////
// shift vertices around origin and normalize point cloud, remove duplicates!
bool ConvexHullLib::shiftAndcleanupVertices(PxU32 svcount, const PxVec3* svertices, PxU32 stride,
PxU32& vcount, PxVec3* vertices)
{
mShiftedVerts = PX_ALLOCATE(PxVec3, svcount, "PxVec3");
const char* vtx = reinterpret_cast<const char *> (svertices);
PxBounds3 bounds;
bounds.setEmpty();
// get the bounding box
for (PxU32 i = 0; i < svcount; i++)
{
const PxVec3& p = *reinterpret_cast<const PxVec3 *> (vtx);
vtx += stride;
bounds.include(p);
}
mOriginShift = bounds.getCenter();
vtx = reinterpret_cast<const char *> (svertices);
for (PxU32 i = 0; i < svcount; i++)
{
const PxVec3& p = *reinterpret_cast<const PxVec3 *> (vtx);
vtx += stride;
mShiftedVerts[i] = p - mOriginShift;
}
return cleanupVertices(svcount, mShiftedVerts, sizeof(PxVec3), vcount, vertices);
}
//////////////////////////////////////////////////////////////////////////
// Shift verts/planes in the desc back
void ConvexHullLib::shiftConvexMeshDesc(PxConvexMeshDesc& desc)
{
PX_ASSERT(mConvexMeshDesc.flags & PxConvexFlag::eSHIFT_VERTICES);
PxVec3* points = reinterpret_cast<PxVec3*>(const_cast<void*>(desc.points.data));
for(PxU32 i = 0; i < desc.points.count; i++)
{
points[i] = points[i] + mOriginShift;
}
PxHullPolygon* polygons = reinterpret_cast<PxHullPolygon*>(const_cast<void*>(desc.polygons.data));
for(PxU32 i = 0; i < desc.polygons.count; i++)
{
polygons[i].mPlane[3] -= PxVec3(polygons[i].mPlane[0], polygons[i].mPlane[1], polygons[i].mPlane[2]).dot(mOriginShift);
}
}
//////////////////////////////////////////////////////////////////////////
// normalize point cloud, remove duplicates!
bool ConvexHullLib::cleanupVertices(PxU32 svcount, const PxVec3* svertices, PxU32 stride,
PxU32& vcount, PxVec3* vertices)
{
if (svcount == 0)
return false;
const PxVec3* verticesToClean = svertices;
PxU32 numVerticesToClean = svcount;
Quantizer* quantizer = NULL;
// if quantization is enabled, parse the input vertices and produce new qantized vertices,
// that will be then cleaned the same way
if (mConvexMeshDesc.flags & PxConvexFlag::eQUANTIZE_INPUT)
{
quantizer = createQuantizer();
PxU32 vertsOutCount;
const PxVec3* vertsOut = quantizer->kmeansQuantize3D(svcount, svertices, stride,true, mConvexMeshDesc.quantizedCount, vertsOutCount);
if (vertsOut)
{
numVerticesToClean = vertsOutCount;
verticesToClean = vertsOut;
}
}
const float distanceEpsilon = local::DISTANCE_EPSILON * mCookingParams.scale.length;
const float resizeValue = local::RESIZE_VALUE * mCookingParams.scale.length;
vcount = 0;
// check for the AABB from points, if its very tiny return a resized CUBE
if (local::checkPointsAABBValidity(numVerticesToClean, verticesToClean, stride, distanceEpsilon, resizeValue, vcount, vertices, false))
{
if (quantizer)
quantizer->release();
return true;
}
if(vcount < 4)
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "ConvexHullLib::cleanupVertices: Less than four valid vertices were found. Provide at least four valid (e.g. each at a different position) vertices.");
if (quantizer)
quantizer->release();
return true;
}
void ConvexHullLib::swapLargestFace(PxConvexMeshDesc& desc)
{
const PxHullPolygon* polygons = reinterpret_cast<const PxHullPolygon*>(desc.polygons.data);
PxHullPolygon* polygonsOut = const_cast<PxHullPolygon*>(polygons);
PxU32 largestFace = 0;
for (PxU32 i = 1; i < desc.polygons.count; i++)
{
if(polygons[largestFace].mNbVerts < polygons[i].mNbVerts)
largestFace = i;
}
// early exit if no swap needs to be done
if(largestFace == 0)
return;
const PxU32* indices = reinterpret_cast<const PxU32*>(desc.indices.data);
mSwappedIndices = PX_ALLOCATE(PxU32, desc.indices.count, "PxU32");
PxHullPolygon replacedPolygon = polygons[0];
PxHullPolygon largestPolygon = polygons[largestFace];
polygonsOut[0] = polygons[largestFace];
polygonsOut[largestFace] = replacedPolygon;
// relocate indices
PxU16 indexBase = 0;
for (PxU32 i = 0; i < desc.polygons.count; i++)
{
if(i == 0)
{
PxMemCopy(mSwappedIndices, &indices[largestPolygon.mIndexBase],sizeof(PxU32)*largestPolygon.mNbVerts);
polygonsOut[0].mIndexBase = indexBase;
indexBase += largestPolygon.mNbVerts;
}
else
{
if(i == largestFace)
{
PxMemCopy(&mSwappedIndices[indexBase], &indices[replacedPolygon.mIndexBase], sizeof(PxU32)*replacedPolygon.mNbVerts);
polygonsOut[i].mIndexBase = indexBase;
indexBase += replacedPolygon.mNbVerts;
}
else
{
PxMemCopy(&mSwappedIndices[indexBase], &indices[polygons[i].mIndexBase], sizeof(PxU32)*polygons[i].mNbVerts);
polygonsOut[i].mIndexBase = indexBase;
indexBase += polygons[i].mNbVerts;
}
}
}
PX_ASSERT(indexBase == desc.indices.count);
desc.indices.data = mSwappedIndices;
}
ConvexHullLib::~ConvexHullLib()
{
PX_FREE(mSwappedIndices);
PX_FREE(mShiftedVerts);
}
| 9,751 | C++ | 33.097902 | 221 | 0.682699 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexMeshBuilder.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_COOKING_CONVEX_MESH_BUILDER_H
#define GU_COOKING_CONVEX_MESH_BUILDER_H
#include "cooking/PxCooking.h"
#include "GuConvexMeshData.h"
#include "GuCookingConvexPolygonsBuilder.h"
#include "GuSDF.h"
namespace physx
{
class BigConvexData;
namespace Gu
{
struct ConvexHullInitData;
}
//////////////////////////////////////////////////////////////////////////
// Convex mesh builder, creates the convex mesh from given polygons and creates internal data
class ConvexMeshBuilder
{
public:
ConvexMeshBuilder(const bool buildGRBData);
~ConvexMeshBuilder();
// loads the computed or given convex hull from descriptor.
// the descriptor does contain polygons directly, triangles are not allowed
bool build(const PxConvexMeshDesc&, PxU32 gaussMapVertexLimit, bool validateOnly = false, ConvexHullLib* hullLib = NULL);
// save the convex mesh into stream
bool save(PxOutputStream& stream, bool platformMismatch) const;
// copy the convex mesh into internal convex mesh, which can be directly used then
bool copy(Gu::ConvexHullInitData& convexData);
// loads the convex mesh from given polygons
bool loadConvexHull(const PxConvexMeshDesc&, ConvexHullLib* hullLib);
// computed hull polygons from given triangles
bool computeHullPolygons(const PxU32& nbVerts,const PxVec3* verts, const PxU32& nbTriangles, const PxU32* triangles, PxAllocatorCallback& inAllocator,
PxU32& outNbVerts, PxVec3*& outVertices, PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& polygons);
// compute big convex data
bool computeGaussMaps();
// compute mass, inertia tensor
void computeMassInfo(bool lowerPrecision);
// TEST_INTERNAL_OBJECTS
// internal objects
void computeInternalObjects();
bool checkExtentRadiusRatio();
//~TEST_INTERNAL_OBJECTS
void computeSDF(const PxConvexMeshDesc& desc);
// set big convex data
void setBigConvexData(BigConvexData* data) { mBigConvexData = data; }
mutable ConvexPolygonsBuilder hullBuilder;
protected:
Gu::ConvexHullData mHullData;
Gu::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!
};
}
#endif
| 4,183 | C | 40.019607 | 157 | 0.729381 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullUtils.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 "foundation/PxMathUtils.h"
#include "foundation/PxSIMDHelpers.h"
#include "GuCookingConvexHullUtils.h"
#include "GuCookingVolumeIntegration.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVecMath.h"
#include "GuBox.h"
#include "GuConvexMeshData.h"
using namespace physx;
using namespace aos;
using namespace Gu;
namespace local
{
static const float MIN_ADJACENT_ANGLE = 3.0f; // in degrees - result wont have two adjacent facets within this angle of each other.
static const float MAXDOT_MINANG = cosf(PxDegToRad(MIN_ADJACENT_ANGLE)); // adjacent angle for dot product tests
//////////////////////////////////////////////////////////////////////////
// helper class for ConvexHullCrop
class VertFlag
{
public:
PxU8 planetest;
PxU8 undermap;
PxU8 overmap;
};
//////////////////////////////////////////////////////////////////////////|
// helper class for ConvexHullCrop
class EdgeFlag
{
public:
PxI16 undermap;
};
//////////////////////////////////////////////////////////////////////////|
// helper class for ConvexHullCrop
class Coplanar
{
public:
PxU16 ea;
PxU8 v0;
PxU8 v1;
};
//////////////////////////////////////////////////////////////////////////
// plane test
enum PlaneTestResult
{
eCOPLANAR = 0,
eUNDER = 1 << 0,
eOVER = 1 << 1
};
//////////////////////////////////////////////////////////////////////////
// test where vertex lies in respect to the plane
static PlaneTestResult planeTest(const PxPlane& p, const PxVec3& v, float epsilon)
{
const float a = v.dot(p.n) + p.d;
PlaneTestResult flag = (a > epsilon) ? eOVER : ((a < -epsilon) ? eUNDER : eCOPLANAR);
return flag;
}
// computes the OBB for this set of points relative to this transform matrix. SIMD version
void computeOBBSIMD(PxU32 vcount, const Vec4V* points, Vec4V& sides, const QuatV& rot, Vec4V& trans)
{
PX_ASSERT(vcount);
Vec4V minV = V4Load(PX_MAX_F32);
Vec4V maxV = V4Load(-PX_MAX_F32);
for (PxU32 i = 0; i < vcount; i++)
{
const Vec4V& vertexV = points[i];
const Vec4V t = V4Sub(vertexV, trans);
const Vec4V v = Vec4V_From_Vec3V(QuatRotateInv(rot, Vec3V_From_Vec4V(t)));
minV = V4Min(minV, v);
maxV = V4Max(maxV, v);
}
sides = V4Sub(maxV, minV);
Mat33V tmpMat;
QuatGetMat33V(rot, tmpMat.col0, tmpMat.col1, tmpMat.col2);
const FloatV coe = FLoad(0.5f);
const Vec4V deltaVec = V4Sub(maxV, V4Scale(sides, coe));
const Vec4V t0 = V4Scale(Vec4V_From_Vec3V(tmpMat.col0), V4GetX(deltaVec));
trans = V4Add(trans, t0);
const Vec4V t1 = V4Scale(Vec4V_From_Vec3V(tmpMat.col1), V4GetY(deltaVec));
trans = V4Add(trans, t1);
const Vec4V t2 = V4Scale(Vec4V_From_Vec3V(tmpMat.col2), V4GetZ(deltaVec));
trans = V4Add(trans, t2);
}
}
//////////////////////////////////////////////////////////////////////////
// construct the base cube from given min/max
ConvexHull::ConvexHull(const PxVec3& bmin, const PxVec3& bmax, const PxArray<PxPlane>& inPlanes)
: mInputPlanes(inPlanes)
{
// min max verts of the cube - 8 verts
mVertices.pushBack(PxVec3(bmin.x, bmin.y, bmin.z)); // ---
mVertices.pushBack(PxVec3(bmin.x, bmin.y, bmax.z)); // --+
mVertices.pushBack(PxVec3(bmin.x, bmax.y, bmin.z)); // -+-
mVertices.pushBack(PxVec3(bmin.x, bmax.y, bmax.z)); // -++
mVertices.pushBack(PxVec3(bmax.x, bmin.y, bmin.z)); // +--
mVertices.pushBack(PxVec3(bmax.x, bmin.y, bmax.z)); // +-+
mVertices.pushBack(PxVec3(bmax.x, bmax.y, bmin.z)); // ++-
mVertices.pushBack(PxVec3(bmax.x, bmax.y, bmax.z)); // +++
// cube planes - 6 planes
mFacets.pushBack(PxPlane(PxVec3(-1.f, 0, 0), bmin.x)); // 0,1,3,2
mFacets.pushBack(PxPlane(PxVec3(1.f, 0, 0), -bmax.x)); // 6,7,5,4
mFacets.pushBack(PxPlane(PxVec3(0, -1.f, 0), bmin.y)); // 0,4,5,1
mFacets.pushBack(PxPlane(PxVec3(0, 1.f, 0), -bmax.y)); // 3,7,6,2
mFacets.pushBack(PxPlane(PxVec3(0, 0, -1.f), bmin.z)); // 0,2,6,4
mFacets.pushBack(PxPlane(PxVec3(0, 0, 1.f), -bmax.z)); // 1,5,7,3
// cube edges - 24 edges
mEdges.pushBack(HalfEdge(11, 0, 0));
mEdges.pushBack(HalfEdge(23, 1, 0));
mEdges.pushBack(HalfEdge(15, 3, 0));
mEdges.pushBack(HalfEdge(16, 2, 0));
mEdges.pushBack(HalfEdge(13, 6, 1));
mEdges.pushBack(HalfEdge(21, 7, 1));
mEdges.pushBack(HalfEdge(9, 5, 1));
mEdges.pushBack(HalfEdge(18, 4, 1));
mEdges.pushBack(HalfEdge(19, 0, 2));
mEdges.pushBack(HalfEdge(6, 4, 2));
mEdges.pushBack(HalfEdge(20, 5, 2));
mEdges.pushBack(HalfEdge(0, 1, 2));
mEdges.pushBack(HalfEdge(22, 3, 3));
mEdges.pushBack(HalfEdge(4, 7, 3));
mEdges.pushBack(HalfEdge(17, 6, 3));
mEdges.pushBack(HalfEdge(2, 2, 3));
mEdges.pushBack(HalfEdge(3, 0, 4));
mEdges.pushBack(HalfEdge(14, 2, 4));
mEdges.pushBack(HalfEdge(7, 6, 4));
mEdges.pushBack(HalfEdge(8, 4, 4));
mEdges.pushBack(HalfEdge(10, 1, 5));
mEdges.pushBack(HalfEdge(5, 5, 5));
mEdges.pushBack(HalfEdge(12, 7, 5));
mEdges.pushBack(HalfEdge(1, 3, 5));
}
//////////////////////////////////////////////////////////////////////////
// create the initial convex hull from given OBB
ConvexHull::ConvexHull(const PxVec3& extent, const PxTransform& transform, const PxArray<PxPlane>& inPlanes)
: mInputPlanes(inPlanes)
{
// get the OBB corner points
PxVec3 extentPoints[8];
const PxMat33Padded rot(transform.q);
Gu::computeOBBPoints(extentPoints, transform.p, extent, rot.column0, rot.column1, rot.column2);
mVertices.pushBack(PxVec3(extentPoints[0].x, extentPoints[0].y, extentPoints[0].z)); // ---
mVertices.pushBack(PxVec3(extentPoints[4].x, extentPoints[4].y, extentPoints[4].z)); // --+
mVertices.pushBack(PxVec3(extentPoints[3].x, extentPoints[3].y, extentPoints[3].z)); // -+-
mVertices.pushBack(PxVec3(extentPoints[7].x, extentPoints[7].y, extentPoints[7].z)); // -++
mVertices.pushBack(PxVec3(extentPoints[1].x, extentPoints[1].y, extentPoints[1].z)); // +--
mVertices.pushBack(PxVec3(extentPoints[5].x, extentPoints[5].y, extentPoints[5].z)); // +-+
mVertices.pushBack(PxVec3(extentPoints[2].x, extentPoints[2].y, extentPoints[2].z)); // ++-
mVertices.pushBack(PxVec3(extentPoints[6].x, extentPoints[6].y, extentPoints[6].z)); // +++
// cube planes - 6 planes
PxPlane plane0(extentPoints[0], extentPoints[4], extentPoints[7]); // 0,1,3,2
mFacets.pushBack(PxPlane(plane0.n, plane0.d));
PxPlane plane1(extentPoints[2], extentPoints[6], extentPoints[5]); // 6,7,5,4
mFacets.pushBack(PxPlane(plane1.n, plane1.d));
PxPlane plane2(extentPoints[0], extentPoints[1], extentPoints[5]); // 0,4,5,1
mFacets.pushBack(PxPlane(plane2.n, plane2.d));
PxPlane plane3(extentPoints[7], extentPoints[6], extentPoints[2]); // 3,7,6,2
mFacets.pushBack(PxPlane(plane3.n, plane3.d));
PxPlane plane4(extentPoints[0], extentPoints[3], extentPoints[2]); // 0,2,6,4
mFacets.pushBack(PxPlane(plane4.n, plane4.d));
PxPlane plane5(extentPoints[4], extentPoints[5], extentPoints[6]); // 1,5,7,3
mFacets.pushBack(PxPlane(plane5.n, plane5.d));
// cube edges - 24 edges
mEdges.pushBack(HalfEdge(11, 0, 0));
mEdges.pushBack(HalfEdge(23, 1, 0));
mEdges.pushBack(HalfEdge(15, 3, 0));
mEdges.pushBack(HalfEdge(16, 2, 0));
mEdges.pushBack(HalfEdge(13, 6, 1));
mEdges.pushBack(HalfEdge(21, 7, 1));
mEdges.pushBack(HalfEdge(9, 5, 1));
mEdges.pushBack(HalfEdge(18, 4, 1));
mEdges.pushBack(HalfEdge(19, 0, 2));
mEdges.pushBack(HalfEdge(6, 4, 2));
mEdges.pushBack(HalfEdge(20, 5, 2));
mEdges.pushBack(HalfEdge(0, 1, 2));
mEdges.pushBack(HalfEdge(22, 3, 3));
mEdges.pushBack(HalfEdge(4, 7, 3));
mEdges.pushBack(HalfEdge(17, 6, 3));
mEdges.pushBack(HalfEdge(2, 2, 3));
mEdges.pushBack(HalfEdge(3, 0, 4));
mEdges.pushBack(HalfEdge(14, 2, 4));
mEdges.pushBack(HalfEdge(7, 6, 4));
mEdges.pushBack(HalfEdge(8, 4, 4));
mEdges.pushBack(HalfEdge(10, 1, 5));
mEdges.pushBack(HalfEdge(5, 5, 5));
mEdges.pushBack(HalfEdge(12, 7, 5));
mEdges.pushBack(HalfEdge(1, 3, 5));
}
//////////////////////////////////////////////////////////////////////////
// finds the candidate plane, returns -1 otherwise
PxI32 ConvexHull::findCandidatePlane(float planeTestEpsilon, float epsilon) const
{
PxI32 p = -1;
float md = 0.0f;
PxU32 i, j;
for (i = 0; i < mInputPlanes.size(); i++)
{
float d = 0.0f;
float dmax = 0.0f;
float dmin = 0.0f;
for (j = 0; j < mVertices.size(); j++)
{
dmax = PxMax(dmax, mVertices[j].dot(mInputPlanes[i].n) + mInputPlanes[i].d);
dmin = PxMin(dmin, mVertices[j].dot(mInputPlanes[i].n) + mInputPlanes[i].d);
}
float dr = dmax - dmin;
if (dr < planeTestEpsilon)
dr = 1.0f; // shouldn't happen.
d = dmax / dr;
// we have a better candidate try another one
if (d <= md)
continue;
// check if we dont have already that plane or if the normals are nearly the same
for (j = 0; j<mFacets.size(); j++)
{
if (mInputPlanes[i] == mFacets[j])
{
d = 0.0f;
continue;
}
if (mInputPlanes[i].n.dot(mFacets[j].n)> local::MAXDOT_MINANG)
{
for (PxU32 k = 0; k < mEdges.size(); k++)
{
if (mEdges[k].p != j)
continue;
if (mVertices[mEdges[k].v].dot(mInputPlanes[i].n) + mInputPlanes[i].d < 0)
{
d = 0; // so this plane wont get selected.
break;
}
}
}
}
if (d>md)
{
p = PxI32(i);
md = d;
}
}
return (md > epsilon) ? p : -1;
}
//////////////////////////////////////////////////////////////////////////
// internal hull check
bool ConvexHull::assertIntact(float epsilon) const
{
PxU32 i;
PxU32 estart = 0;
for (i = 0; i < mEdges.size(); i++)
{
if (mEdges[estart].p != mEdges[i].p)
{
estart = i;
}
PxU32 inext = i + 1;
if (inext >= mEdges.size() || mEdges[inext].p != mEdges[i].p)
{
inext = estart;
}
PX_ASSERT(mEdges[inext].p == mEdges[i].p);
PxI16 nb = mEdges[i].ea;
if (nb == 255 || nb == -1)
return false;
PX_ASSERT(nb != -1);
PX_ASSERT(i == PxU32(mEdges[PxU32(nb)].ea));
// Check that the vertex of the next edge is the vertex of the adjacent half edge.
// Otherwise the two half edges are not really adjacent and we have a hole.
PX_ASSERT(mEdges[PxU32(nb)].v == mEdges[inext].v);
if (!(mEdges[PxU32(nb)].v == mEdges[inext].v))
return false;
}
for (i = 0; i < mEdges.size(); i++)
{
PX_ASSERT(local::eCOPLANAR == local::planeTest(mFacets[mEdges[i].p], mVertices[mEdges[i].v], epsilon));
if (local::eCOPLANAR != local::planeTest(mFacets[mEdges[i].p], mVertices[mEdges[i].v], epsilon))
return false;
if (mEdges[estart].p != mEdges[i].p)
{
estart = i;
}
PxU32 i1 = i + 1;
if (i1 >= mEdges.size() || mEdges[i1].p != mEdges[i].p) {
i1 = estart;
}
PxU32 i2 = i1 + 1;
if (i2 >= mEdges.size() || mEdges[i2].p != mEdges[i].p) {
i2 = estart;
}
if (i == i2)
continue; // i sliced tangent to an edge and created 2 meaningless edges
// check the face normal against the triangle from edges
PxVec3 localNormal = (mVertices[mEdges[i1].v] - mVertices[mEdges[i].v]).cross(mVertices[mEdges[i2].v] - mVertices[mEdges[i1].v]);
const float m = localNormal.magnitude();
if (m == 0.0f)
localNormal = PxVec3(1.f, 0.0f, 0.0f);
localNormal *= (1.0f / m);
if (localNormal.dot(mFacets[mEdges[i].p].n) <= 0.0f)
return false;
}
return true;
}
// returns the maximum number of vertices on a face
PxU32 ConvexHull::maxNumVertsPerFace() const
{
PxU32 maxVerts = 0;
PxU32 currentVerts = 0;
PxU32 estart = 0;
for (PxU32 i = 0; i < mEdges.size(); i++)
{
if (mEdges[estart].p != mEdges[i].p)
{
if(currentVerts > maxVerts)
{
maxVerts = currentVerts + 1;
}
currentVerts = 0;
estart = i;
}
else
{
currentVerts++;
}
}
return maxVerts;
}
//////////////////////////////////////////////////////////////////////////
// slice the input convexHull with the slice plane
ConvexHull* physx::convexHullCrop(const ConvexHull& convex, const PxPlane& slice, float planeTestEpsilon)
{
static const PxU8 invalidIndex = PxU8(-1);
PxU32 i;
PxU32 vertCountUnder = 0; // Running count of the vertices UNDER the slicing plane.
PX_ASSERT(convex.getEdges().size() < 480);
// Arrays of mapping information associated with features in the input convex.
// edgeflag[i].undermap - output index of input edge convex->edges[i]
// vertflag[i].undermap - output index of input vertex convex->vertices[i]
// vertflag[i].planetest - the side-of-plane classification of convex->vertices[i]
// (There are other members but they are unused.)
local::EdgeFlag edgeFlag[512];
local::VertFlag vertFlag[256];
// Lists of output features. Populated during clipping.
// Coplanar edges have one sibling in tmpunderedges and one in coplanaredges.
// coplanaredges holds the sibling that belong to the new polygon created from slicing.
ConvexHull::HalfEdge tmpUnderEdges[512]; // The output edge list.
PxPlane tmpUnderPlanes[128]; // The output plane list.
local::Coplanar coplanarEdges[512]; // The coplanar edge list.
PxU32 coplanarEdgesNum = 0; // Running count of coplanar edges.
// Created vertices on the slicing plane (stored for output after clipping).
PxArray<PxVec3> createdVerts;
// Logical OR of individual vertex flags.
PxU32 convexClipFlags = 0;
// Classify each vertex against the slicing plane as OVER | COPLANAR | UNDER.
// OVER - Vertex is over (outside) the slicing plane. Will not be output.
// COPLANAR - Vertex is on the slicing plane. A copy will be output.
// UNDER - Vertex is under (inside) the slicing plane. Will be output.
// We keep an array of information structures for each vertex in the input convex.
// vertflag[i].undermap - The (computed) index of convex->vertices[i] in the output.
// invalidIndex for OVER vertices - they are not output.
// initially invalidIndex for COPLANAR vertices - set later.
// vertflag[i].overmap - Unused - we don't care about the over part.
// vertflag[i].planetest - The classification (clip flag) of convex->vertices[i].
for (i = 0; i < convex.getVertices().size(); i++)
{
local::PlaneTestResult vertexClipFlag = local::planeTest(slice, convex.getVertices()[i], planeTestEpsilon);
switch (vertexClipFlag)
{
case local::eOVER:
case local::eCOPLANAR:
vertFlag[i].undermap = invalidIndex; // Initially invalid for COPLANAR
vertFlag[i].overmap = invalidIndex;
break;
case local::eUNDER:
vertFlag[i].undermap = PxTo8(vertCountUnder++);
vertFlag[i].overmap = invalidIndex;
break;
}
vertFlag[i].planetest = PxU8(vertexClipFlag);
convexClipFlags |= vertexClipFlag;
}
// Check special case: everything UNDER or COPLANAR.
// This way we know we wont end up with silly faces / edges later on.
if ((convexClipFlags & local::eOVER) == 0)
{
// Just return a copy of the same convex.
ConvexHull* dst = PX_NEW(ConvexHull)(convex);
return dst;
}
PxU16 underEdgeCount = 0; // Running count of output edges.
PxU16 underPlanesCount = 0; // Running count of output planes.
// Clipping Loop
// =============
//
// for each plane
//
// for each edge
//
// if first UNDER & second !UNDER
// output current edge -> tmpunderedges
// if we have done the sibling
// connect current edge to its sibling
// set vout = first vertex of sibling
// else if second is COPLANAR
// if we havent already copied it
// copy second -> createdverts
// set vout = index of created vertex
// else
// generate a new vertex -> createdverts
// set vout = index of created vertex
// if vin is already set and vin != vout (non-trivial edge)
// output coplanar edge -> tmpunderedges (one sibling)
// set coplanaredge to new edge index (for connecting the other sibling)
//
// else if first !UNDER & second UNDER
// if we have done the sibling
// connect current edge to its sibling
// set vin = second vertex of sibling (this is a bit of a pain)
// else if first is COPLANAR
// if we havent already copied it
// copy first -> createdverts
// set vin = index of created vertex
// else
// generate a new vertex -> createdverts
// set vin = index of created vertex
// if vout is already set and vin != vout (non-trivial edge)
// output coplanar edge -> tmpunderedges (one sibling)
// set coplanaredge to new edge index (for connecting the other sibling)
// output current edge -> tmpunderedges
//
// else if first UNDER & second UNDER
// output current edge -> tmpunderedges
//
// next edge
//
// if part of current plane was UNDER
// output current plane -> tmpunderplanes
//
// if coplanaredge is set
// output coplanar edge -> coplanaredges
//
// next plane
//
// Indexing is a bit tricky here:
//
// e0 - index of the current edge
// e1 - index of the next edge
// estart - index of the first edge in the current plane
// currentplane - index of the current plane
// enextface - first edge of next plane
PxU32 e0 = 0;
for (PxU32 currentplane = 0; currentplane < convex.getFacets().size(); currentplane++)
{
PxU32 eStart = e0;
PxU32 eNextFace = 0xffffffff;
PxU32 e1 = e0 + 1;
PxU8 vout = invalidIndex;
PxU8 vin = invalidIndex;
PxU32 coplanarEdge = invalidIndex;
// Logical OR of individual vertex flags in the current plane.
PxU32 planeSide = 0;
do{
// Next edge modulo logic
if (e1 >= convex.getEdges().size() || convex.getEdges()[e1].p != currentplane)
{
eNextFace = e1;
e1 = eStart;
}
const ConvexHull::HalfEdge& edge0 = convex.getEdges()[e0];
const ConvexHull::HalfEdge& edge1 = convex.getEdges()[e1];
const ConvexHull::HalfEdge& edgea = convex.getEdges()[PxU32(edge0.ea)];
planeSide |= vertFlag[edge0.v].planetest;
if (vertFlag[edge0.v].planetest == local::eUNDER && vertFlag[edge1.v].planetest != local::eUNDER)
{
// first is UNDER, second is COPLANAR or OVER
// Output current edge.
edgeFlag[e0].undermap = short(underEdgeCount);
tmpUnderEdges[underEdgeCount].v = vertFlag[edge0.v].undermap;
tmpUnderEdges[underEdgeCount].p = PxU8(underPlanesCount);
PX_ASSERT(tmpUnderEdges[underEdgeCount].v != invalidIndex);
if (PxU32(edge0.ea) < e0)
{
// We have already done the sibling.
// Connect current edge to its sibling.
PX_ASSERT(edgeFlag[edge0.ea].undermap != invalidIndex);
tmpUnderEdges[underEdgeCount].ea = edgeFlag[edge0.ea].undermap;
tmpUnderEdges[edgeFlag[edge0.ea].undermap].ea = short(underEdgeCount);
// Set vout = first vertex of (output, clipped) sibling.
vout = tmpUnderEdges[edgeFlag[edge0.ea].undermap].v;
}
else if (vertFlag[edge1.v].planetest == local::eCOPLANAR)
{
// Boundary case.
// We output coplanar vertices once.
if (vertFlag[edge1.v].undermap == invalidIndex)
{
createdVerts.pushBack(convex.getVertices()[edge1.v]);
// Remember the index so we don't output it again.
vertFlag[edge1.v].undermap = PxTo8(vertCountUnder++);
}
vout = vertFlag[edge1.v].undermap;
}
else
{
// Add new vertex.
const PxPlane& p0 = convex.getFacets()[edge0.p];
const PxPlane& pa = convex.getFacets()[edgea.p];
createdVerts.pushBack(threePlaneIntersection(p0, pa, slice));
vout = PxTo8(vertCountUnder++);
}
// We added an edge, increment the counter
underEdgeCount++;
if (vin != invalidIndex && vin != vout)
{
// We already have vin and a non-trivial edge
// Output coplanar edge
PX_ASSERT(vout != invalidIndex);
coplanarEdge = underEdgeCount;
tmpUnderEdges[underEdgeCount].v = vout;
tmpUnderEdges[underEdgeCount].p = PxU8(underPlanesCount);
tmpUnderEdges[underEdgeCount].ea = invalidIndex;
underEdgeCount++;
}
}
else if (vertFlag[edge0.v].planetest != local::eUNDER && vertFlag[edge1.v].planetest == local::eUNDER)
{
// First is OVER or COPLANAR, second is UNDER.
if (PxU32(edge0.ea) < e0)
{
// We have already done the sibling.
// We need the second vertex of the sibling.
// Which is the vertex of the next edge in the adjacent poly.
int nea = edgeFlag[edge0.ea].undermap + 1;
int p = tmpUnderEdges[edgeFlag[edge0.ea].undermap].p;
if (nea >= underEdgeCount || tmpUnderEdges[nea].p != p)
{
// End of polygon, next edge is first edge
nea -= 2;
while (nea > 0 && tmpUnderEdges[nea - 1].p == p)
nea--;
}
vin = tmpUnderEdges[nea].v;
PX_ASSERT(vin < vertCountUnder);
}
else if (vertFlag[edge0.v].planetest == local::eCOPLANAR)
{
// Boundary case.
// We output coplanar vertices once.
if (vertFlag[edge0.v].undermap == invalidIndex)
{
createdVerts.pushBack(convex.getVertices()[edge0.v]);
// Remember the index so we don't output it again.
vertFlag[edge0.v].undermap = PxTo8(vertCountUnder++);
}
vin = vertFlag[edge0.v].undermap;
}
else
{
// Add new vertex.
const PxPlane& p0 = convex.getFacets()[edge0.p];
const PxPlane& pa = convex.getFacets()[edgea.p];
createdVerts.pushBack(threePlaneIntersection(p0, pa, slice));
vin = PxTo8(vertCountUnder++);
}
if (vout != invalidIndex && vin != vout)
{
// We have been in and out, Add the coplanar edge
coplanarEdge = underEdgeCount;
tmpUnderEdges[underEdgeCount].v = vout;
tmpUnderEdges[underEdgeCount].p = PxTo8(underPlanesCount);
tmpUnderEdges[underEdgeCount].ea = invalidIndex;
underEdgeCount++;
}
// Output current edge.
tmpUnderEdges[underEdgeCount].v = vin;
tmpUnderEdges[underEdgeCount].p = PxTo8(underPlanesCount);
edgeFlag[e0].undermap = short(underEdgeCount);
if (PxU32(edge0.ea) < e0)
{
// We have already done the sibling.
// Connect current edge to its sibling.
PX_ASSERT(edgeFlag[edge0.ea].undermap != invalidIndex);
tmpUnderEdges[underEdgeCount].ea = edgeFlag[edge0.ea].undermap;
tmpUnderEdges[edgeFlag[edge0.ea].undermap].ea = short(underEdgeCount);
}
PX_ASSERT(edgeFlag[e0].undermap == underEdgeCount);
underEdgeCount++;
}
else if (vertFlag[edge0.v].planetest == local::eUNDER && vertFlag[edge1.v].planetest == local::eUNDER)
{
// Both UNDER
// Output current edge.
edgeFlag[e0].undermap = short(underEdgeCount);
tmpUnderEdges[underEdgeCount].v = vertFlag[edge0.v].undermap;
tmpUnderEdges[underEdgeCount].p = PxTo8(underPlanesCount);
if (PxU32(edge0.ea) < e0)
{
// We have already done the sibling.
// Connect current edge to its sibling.
PX_ASSERT(edgeFlag[edge0.ea].undermap != invalidIndex);
tmpUnderEdges[underEdgeCount].ea = edgeFlag[edge0.ea].undermap;
tmpUnderEdges[edgeFlag[edge0.ea].undermap].ea = short(underEdgeCount);
}
underEdgeCount++;
}
e0 = e1;
e1++; // do the modulo at the beginning of the loop
} while (e0 != eStart);
e0 = eNextFace;
if (planeSide & local::eUNDER)
{
// At least part of current plane is UNDER.
// Output current plane.
tmpUnderPlanes[underPlanesCount] = convex.getFacets()[currentplane];
underPlanesCount++;
}
if (coplanarEdge != invalidIndex)
{
// We have a coplanar edge.
// Add to coplanaredges for later processing.
// (One sibling is in place but one is missing)
PX_ASSERT(vin != invalidIndex);
PX_ASSERT(vout != invalidIndex);
PX_ASSERT(coplanarEdge != 511);
coplanarEdges[coplanarEdgesNum].ea = PxU8(coplanarEdge);
coplanarEdges[coplanarEdgesNum].v0 = vin;
coplanarEdges[coplanarEdgesNum].v1 = vout;
coplanarEdgesNum++;
}
// Reset coplanar edge infos for next poly
vin = invalidIndex;
vout = invalidIndex;
coplanarEdge = invalidIndex;
}
// Add the new plane to the mix:
if (coplanarEdgesNum > 0)
{
tmpUnderPlanes[underPlanesCount++] = slice;
}
// Sort the coplanar edges in winding order.
for (i = 0; i < coplanarEdgesNum - 1; i++)
{
if (coplanarEdges[i].v1 != coplanarEdges[i + 1].v0)
{
PxU32 j = 0;
for (j = i + 2; j < coplanarEdgesNum; j++)
{
if (coplanarEdges[i].v1 == coplanarEdges[j].v0)
{
local::Coplanar tmp = coplanarEdges[i + 1];
coplanarEdges[i + 1] = coplanarEdges[j];
coplanarEdges[j] = tmp;
break;
}
}
if (j >= coplanarEdgesNum)
{
// PX_ASSERT(j<coplanaredges_num);
return NULL;
}
}
}
// PT: added this line to fix DE2904
if (!vertCountUnder)
return NULL;
// Create the output convex.
ConvexHull* punder = PX_NEW(ConvexHull)(convex.getInputPlanes());
ConvexHull& under = *punder;
// Copy UNDER vertices
PxU32 k = 0;
for (i = 0; i < convex.getVertices().size(); i++)
{
if (vertFlag[i].planetest == local::eUNDER)
{
under.getVertices().pushBack(convex.getVertices()[i]);
k++;
}
}
// Copy created vertices
i = 0;
while (k < vertCountUnder)
{
under.getVertices().pushBack(createdVerts[i++]);
k++;
}
PX_ASSERT(i == createdVerts.size());
// Copy the output edges and output planes.
under.getEdges().resize(underEdgeCount + coplanarEdgesNum);
under.getFacets().resize(underPlanesCount);
// Add the coplanar edge siblings that belong to the new polygon (coplanaredges).
for (i = 0; i < coplanarEdgesNum; i++)
{
under.getEdges()[underEdgeCount + i].p = PxU8(underPlanesCount - 1);
under.getEdges()[underEdgeCount + i].ea = short(coplanarEdges[i].ea);
tmpUnderEdges[coplanarEdges[i].ea].ea = PxI16(underEdgeCount + i);
under.getEdges()[underEdgeCount + i].v = coplanarEdges[i].v0;
}
PxMemCopy(under.getEdges().begin(), tmpUnderEdges, sizeof(ConvexHull::HalfEdge)*underEdgeCount);
PxMemCopy(under.getFacets().begin(), tmpUnderPlanes, sizeof(PxPlane)*underPlanesCount);
return punder;
}
bool physx::computeOBBFromConvex(const PxConvexMeshDesc& desc, PxVec3& sides, PxTransform& matrix)
{
PxIntegrals integrals;
// using the centroid of the convex for the volume integration solved accuracy issues in cases where the inertia tensor
// ended up close to not being positive definite and after a few further transforms the diagonalized inertia tensor ended
// up with negative values.
const PxVec3* verts = (reinterpret_cast<const PxVec3*>(desc.points.data));
const PxU32* ind = (reinterpret_cast<const PxU32*>(desc.indices.data));
const PxHullPolygon* polygons = (reinterpret_cast<const PxHullPolygon*>(desc.polygons.data));
PxVec3 mean(0.0f);
for (PxU32 i = 0; i < desc.points.count; i++)
mean += verts[i];
mean *= (1.0f / desc.points.count);
PxU8* indices = PX_ALLOCATE(PxU8, desc.indices.count, "PxU8");
for (PxU32 i = 0; i < desc.indices.count; i++)
{
indices[i] = PxTo8(ind[i]);
}
// we need to move the polygon data to internal format
Gu::HullPolygonData* polygonData = PX_ALLOCATE(Gu::HullPolygonData, desc.polygons.count, "Gu::HullPolygonData");
for (PxU32 i = 0; i < desc.polygons.count; i++)
{
polygonData[i].mPlane = PxPlane(polygons[i].mPlane[0], polygons[i].mPlane[1], polygons[i].mPlane[2], polygons[i].mPlane[3]);
polygonData[i].mNbVerts = PxTo8(polygons[i].mNbVerts);
polygonData[i].mVRef8 = polygons[i].mIndexBase;
}
PxConvexMeshDesc inDesc;
inDesc.points.data = desc.points.data;
inDesc.points.count = desc.points.count;
inDesc.polygons.data = polygonData;
inDesc.polygons.count = desc.polygons.count;
inDesc.indices.data = indices;
inDesc.indices.count = desc.indices.count;
// compute volume integrals to get basis axis
if(computeVolumeIntegralsEberly(inDesc, 1.0f, integrals, mean, desc.flags & PxConvexFlag::eFAST_INERTIA_COMPUTATION))
{
Vec4V* pointsV = PX_ALLOCATE(Vec4V, desc.points.count, "Vec4V");
for (PxU32 i = 0; i < desc.points.count; i++)
{
// safe to V4 load, same as volume integration - we allocate one more vector
pointsV[i] = V4LoadU(&verts[i].x);
}
PxMat33 inertia;
integrals.getOriginInertia(inertia);
PxQuat inertiaQuat;
PxDiagonalize(inertia, inertiaQuat);
const PxMat33Padded baseAxis(inertiaQuat);
Vec4V center = V4LoadU(&integrals.COM.x);
const PxU32 numSteps = 20;
const float subStep = PxDegToRad(float(360/numSteps));
float bestVolume = FLT_MAX;
for (PxU32 axis = 0; axis < 3; axis++)
{
for (PxU32 iStep = 0; iStep < numSteps; iStep++)
{
PxQuat quat(iStep*subStep, baseAxis[axis]);
Vec4V transV = center;
Vec4V psidesV;
const QuatV rotV = QuatVLoadU(&quat.x);
local::computeOBBSIMD(desc.points.count, pointsV, psidesV, rotV, transV);
PxVec3 psides;
V3StoreU(Vec3V_From_Vec4V(psidesV), psides);
const float volume = psides[0] * psides[1] * psides[2]; // the volume of the cube
if (volume <= bestVolume)
{
bestVolume = volume;
sides = psides;
V4StoreU(rotV, &matrix.q.x);
V3StoreU(Vec3V_From_Vec4V(transV), matrix.p);
}
}
}
PX_FREE(pointsV);
}
else
{
PX_FREE(indices);
PX_FREE(polygonData);
return false;
}
PX_FREE(indices);
PX_FREE(polygonData);
return true;
}
| 30,807 | C++ | 32.305946 | 134 | 0.650761 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullBuilder.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_COOKING_CONVEX_HULL_BUILDER_H
#define GU_COOKING_CONVEX_HULL_BUILDER_H
#include "cooking/PxCooking.h"
#include "GuConvexMeshData.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
struct PxHullPolygon;
class ConvexHullLib;
namespace Gu
{
struct EdgeDescData;
struct ConvexHullData;
} // namespace Gu
class ConvexHullBuilder : public PxUserAllocated
{
public:
ConvexHullBuilder(Gu::ConvexHullData* hull, const bool buildGRBData);
~ConvexHullBuilder();
bool init(PxU32 nbVerts, const PxVec3* verts, const PxU32* indices, const PxU32 nbIndices, const PxU32 nbPolygons,
const PxHullPolygon* hullPolygons, bool doValidation = true, ConvexHullLib* hullLib = NULL);
bool save(PxOutputStream& stream, bool platformMismatch) const;
bool copy(Gu::ConvexHullData& hullData, PxU32& nb);
bool createEdgeList(bool doValidation, PxU32 nbEdges);
bool checkHullPolygons() const;
bool calculateVertexMapTable(PxU32 nbPolygons, bool userPolygons = false);
PX_INLINE PxU32 computeNbPolygons() const
{
PX_ASSERT(mHull->mNbPolygons);
return mHull->mNbPolygons;
}
PxVec3* mHullDataHullVertices;
Gu::HullPolygonData* mHullDataPolygons;
PxU8* mHullDataVertexData8;
PxU8* mHullDataFacesByEdges8;
PxU8* mHullDataFacesByVertices8;
PxU16* mEdgeData16; //!< Edge indices indexed by hull polygons
PxU16* mEdges; //!< Edge to vertex mapping
Gu::ConvexHullData* mHull;
bool mBuildGRBData;
};
}
#endif
| 3,378 | C | 37.397727 | 125 | 0.715808 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingTriangleMesh.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_COOKING_TRIANGLE_MESH_H
#define GU_COOKING_TRIANGLE_MESH_H
#include "GuMeshData.h"
#include "cooking/PxCooking.h"
namespace physx
{
namespace Gu
{
class EdgeList;
}
class TriangleMeshBuilder
{
public:
TriangleMeshBuilder(Gu::TriangleMeshData& mesh, const PxCookingParams& params);
virtual ~TriangleMeshBuilder();
virtual PxMeshMidPhase::Enum getMidphaseID() const = 0;
// Called by base code when midphase structure should be built
virtual bool createMidPhaseStructure() = 0;
// Called by base code when midphase structure should be saved
virtual void saveMidPhaseStructure(PxOutputStream& stream, bool mismatch) const = 0;
// Called by base code when mesh index format has changed and the change should be reflected in midphase structure
virtual void onMeshIndexFormatChange() {}
bool cleanMesh(bool validate, PxTriangleMeshCookingResult::Enum* condition);
void remapTopology(const PxU32* order);
void createVertMapping();
void createSharedEdgeData(bool buildAdjacencies, bool buildActiveEdges);
void recordTriangleIndices();
bool createGRBMidPhaseAndData(const PxU32 originalTriangleCount);
void createGRBData();
bool loadFromDesc(const PxTriangleMeshDesc&, PxTriangleMeshCookingResult::Enum* condition, bool validate = false);
bool save(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params) const;
void checkMeshIndicesSize();
PX_FORCE_INLINE Gu::TriangleMeshData& getMeshData() { return mMeshData; }
protected:
bool importMesh(const PxTriangleMeshDesc& desc, PxTriangleMeshCookingResult::Enum* condition, bool validate = false);
bool loadFromDescInternal(PxTriangleMeshDesc&, PxTriangleMeshCookingResult::Enum* condition, bool validate = false);
void buildInertiaTensor(bool flipNormals = false);
void buildInertiaTensorFromSDF();
TriangleMeshBuilder& operator=(const TriangleMeshBuilder&);
Gu::EdgeList* mEdgeList;
const PxCookingParams& mParams;
Gu::TriangleMeshData& mMeshData;
};
class RTreeTriangleMeshBuilder : public TriangleMeshBuilder
{
public:
RTreeTriangleMeshBuilder(const PxCookingParams& params);
virtual ~RTreeTriangleMeshBuilder();
virtual PxMeshMidPhase::Enum getMidphaseID() const PX_OVERRIDE { return PxMeshMidPhase::eBVH33; }
virtual bool createMidPhaseStructure() PX_OVERRIDE;
virtual void saveMidPhaseStructure(PxOutputStream& stream, bool mismatch) const PX_OVERRIDE;
Gu::RTreeTriangleData mData;
};
class BV4TriangleMeshBuilder : public TriangleMeshBuilder
{
public:
BV4TriangleMeshBuilder(const PxCookingParams& params);
virtual ~BV4TriangleMeshBuilder();
virtual PxMeshMidPhase::Enum getMidphaseID() const PX_OVERRIDE { return PxMeshMidPhase::eBVH34; }
virtual bool createMidPhaseStructure() PX_OVERRIDE;
virtual void saveMidPhaseStructure(PxOutputStream& stream, bool mismatch) const PX_OVERRIDE;
virtual void onMeshIndexFormatChange();
Gu::BV4TriangleData mData;
};
class BV32TriangleMeshBuilder
{
public:
static bool createMidPhaseStructure(const PxCookingParams& params, Gu::TriangleMeshData& meshData, Gu::BV32Tree& bv32Tree);
static void saveMidPhaseStructure(Gu::BV32Tree* tree, PxOutputStream& stream, bool mismatch);
};
}
#endif
| 5,182 | C | 41.138211 | 130 | 0.743921 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingTetrahedronMesh.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.
#define USE_GJK_VIRTUAL
#include "GuCookingTetrahedronMesh.h"
#include "GuTetrahedron.h"
#include "GuInternal.h"
#include "foundation/PxHashMap.h"
#include "GuCookingTriangleMesh.h"
#include "GuBV4Build.h"
#include "GuBV32Build.h"
#include "GuDistancePointTetrahedron.h"
#ifdef USE_GJK_VIRTUAL
#include "GuGJKTest.h"
#else
#include "GuGJKUtil.h"
#include "GuGJK.h"
#endif
#include "GuVecTetrahedron.h"
#include "GuGJKType.h"
#include "GuCooking.h"
#include "GuBounds.h"
#include "CmSerialize.h"
#include "foundation/PxFPU.h"
#include "common/PxInsertionCallback.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*TetrahedronMeshBuilder::TetrahedronMeshBuilder(const PxCookingParams& params) : mParams(params)
{
}*/
void TetrahedronMeshBuilder::recordTetrahedronIndices(const TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, bool buildGPUData)
{
if (buildGPUData)
{
PX_ASSERT(!(collisionMesh.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
PX_ASSERT(collisionData.mGRB_primIndices);
//copy the BV4 tetrahedron indices to mGRB_primIndices
PxMemCopy(collisionData.mGRB_primIndices, collisionMesh.mTetrahedrons, sizeof(IndTetrahedron32) * collisionMesh.mNbTetrahedrons);
}
}
class SortedTriangleInds
{
public:
SortedTriangleInds() {}
SortedTriangleInds(const PxU32 ref0, const PxU32 ref1, const PxU32 ref2)
{
initialize(ref0, ref1, ref2);
}
SortedTriangleInds(const PxU16 ref0, const PxU16 ref1, const PxU16 ref2)
{
initialize(PxU32(ref0), PxU32(ref1), PxU32(ref2));
}
void initialize(const PxU32 ref0, const PxU32 ref1, const PxU32 ref2)
{
mOrigRef[0] = ref0;
mOrigRef[1] = ref1;
mOrigRef[2] = ref2;
if (ref0 < ref1 && ref0 < ref2)
{
mRef0 = ref0;
mRef1 = PxMin(ref1, ref2);
mRef2 = PxMax(ref1, ref2);
}
else if (ref1 < ref2)
{
mRef0 = ref1;
mRef1 = PxMin(ref0, ref2);
mRef2 = PxMax(ref0, ref2);
}
else
{
mRef0 = ref2;
mRef1 = PxMin(ref0, ref1);
mRef2 = PxMax(ref0, ref1);
}
}
bool operator == (const SortedTriangleInds& other) const
{
return other.mRef0 == mRef0 && other.mRef1 == mRef1 && other.mRef2 == mRef2;
}
static uint32_t hash(const SortedTriangleInds key)
{
uint64_t k0 = (key.mRef0 & 0xffff);
uint64_t k1 = (key.mRef1 & 0xffff);
uint64_t k2 = (key.mRef2 & 0xffff);
uint64_t k = (k2 << 32) | (k1 << 16) | k0;
k += ~(k << 32);
k ^= (k >> 22);
k += ~(k << 13);
k ^= (k >> 8);
k += (k << 3);
k ^= (k >> 15);
k += ~(k << 27);
k ^= (k >> 31);
return uint32_t(UINT32_MAX & k);
}
void setTetIndex(const PxU32 tetIndex)
{
mTetIndex = tetIndex;
}
PxU32 getTetIndex()
{
return mTetIndex;
}
PxU32 mOrigRef[3];
PxU32 mRef0;
PxU32 mRef1;
PxU32 mRef2;
PxU32 mTetIndex;
};
struct SortedTriangleIndsHash
{
uint32_t operator()(const SortedTriangleInds& k) const
{
return SortedTriangleInds::hash(k);
}
bool equal(const SortedTriangleInds& k0, const SortedTriangleInds& k1) const
{
return k0 == k1;
}
};
#if PX_CHECKED
bool checkInputFloats(PxU32 nb, const float* values, const char* file, PxU32 line, const char* errorMsg);
#endif
bool TetrahedronMeshBuilder::importMesh(const PxTetrahedronMeshDesc& collisionMeshDesc, const PxCookingParams& params,
TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, bool validateMesh)
{
PX_UNUSED(validateMesh);
//convert and clean the input mesh
//this is where the mesh data gets copied from user mem to our mem
PxVec3* verts = collisionMesh.allocateVertices(collisionMeshDesc.points.count);
collisionMesh.allocateTetrahedrons(collisionMeshDesc.tetrahedrons.count, 1);
if (params.buildGPUData)
collisionData.allocateCollisionData(collisionMeshDesc.tetrahedrons.count);
TetrahedronT<PxU32>* tets = reinterpret_cast<TetrahedronT<PxU32>*>(collisionMesh.mTetrahedrons);
//copy, and compact to get rid of strides:
immediateCooking::gatherStrided(collisionMeshDesc.points.data, verts, collisionMesh.mNbVertices, sizeof(PxVec3), collisionMeshDesc.points.stride);
#if PX_CHECKED
// PT: check all input vertices are valid
if(!checkInputFloats(collisionMeshDesc.points.count*3, &verts->x, PX_FL, "input mesh contains corrupted vertex data"))
return false;
#endif
TetrahedronT<PxU32>* dest = tets;
const TetrahedronT<PxU32>* pastLastDest = tets + collisionMesh.mNbTetrahedrons;
const PxU8* source = reinterpret_cast<const PxU8*>(collisionMeshDesc.tetrahedrons.data);
PX_ASSERT(source);
//4 combos of 16 vs 32, feed in collisionMesh.mTetrahedrons
if (collisionMeshDesc.flags & PxMeshFlag::e16_BIT_INDICES)
{
while (dest < pastLastDest)
{
const PxU16 *tet16 = reinterpret_cast<const PxU16*>(source);
dest->v[0] = tet16[0];
dest->v[1] = tet16[1];
dest->v[2] = tet16[2];
dest->v[3] = tet16[3];
dest++;
source += collisionMeshDesc.tetrahedrons.stride;
}
}
else
{
while (dest < pastLastDest)
{
const PxU32 * tet32 = reinterpret_cast<const PxU32*>(source);
dest->v[0] = tet32[0];
dest->v[1] = tet32[1];
dest->v[2] = tet32[2];
dest->v[3] = tet32[3];
dest++;
source += collisionMeshDesc.tetrahedrons.stride;
}
}
//copy the material index list if any:
if (collisionMeshDesc.materialIndices.data)
{
PxFEMMaterialTableIndex* materials = collisionMesh.allocateMaterials();
immediateCooking::gatherStrided(collisionMeshDesc.materialIndices.data, materials, collisionMesh.mNbTetrahedrons, sizeof(PxMaterialTableIndex), collisionMeshDesc.materialIndices.stride);
// Check material indices
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; i++) PX_ASSERT(materials[i] != 0xffff);
}
// we need to fill the remap table if no cleaning was done
if (params.suppressTriangleMeshRemapTable == false)
{
PX_ASSERT(collisionData.mFaceRemap == NULL);
collisionData.mFaceRemap = PX_ALLOCATE(PxU32, collisionMesh.mNbTetrahedrons, "mFaceRemap");
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; i++)
collisionData.mFaceRemap[i] = i;
}
return true;
}
bool TetrahedronMeshBuilder::createGRBMidPhaseAndData(const PxU32 originalTetrahedronCount, TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, const PxCookingParams& params)
{
PX_UNUSED(originalTetrahedronCount);
if (params.buildGPUData)
{
PX_ASSERT(!(collisionMesh.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
BV32Tree* bv32Tree = PX_NEW(BV32Tree);
collisionData.mGRB_BV32Tree = bv32Tree;
if(!BV32TetrahedronMeshBuilder::createMidPhaseStructure(params, collisionMesh, *bv32Tree, collisionData))
return false;
//create surface triangles, one tetrahedrons has 4 triangles
PxHashMap<SortedTriangleInds, PxU32, SortedTriangleIndsHash> triIndsMap;
//for trigs index stride conversion and eventual reordering is also needed, I don't think flexicopy can do that for us.
IndTetrahedron32* dest = reinterpret_cast<IndTetrahedron32*>(collisionData.mGRB_primIndices);
for(PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; ++i)
{
IndTetrahedron32& tetInd = dest[i];
SortedTriangleInds t0(tetInd.mRef[0], tetInd.mRef[1], tetInd.mRef[2]);
t0.setTetIndex(i);
triIndsMap[t0] += 1;
SortedTriangleInds t1(tetInd.mRef[1], tetInd.mRef[3], tetInd.mRef[2]);
t1.setTetIndex(i);
triIndsMap[t1] += 1;
SortedTriangleInds t2(tetInd.mRef[0], tetInd.mRef[3], tetInd.mRef[1]);
t2.setTetIndex(i);
triIndsMap[t2] += 1;
SortedTriangleInds t3(tetInd.mRef[0], tetInd.mRef[2], tetInd.mRef[3]);
t3.setTetIndex(i);
triIndsMap[t3] += 1;
}
PxMemZero(collisionData.mGRB_tetraSurfaceHint, collisionMesh.mNbTetrahedrons * sizeof(PxU8));
PxU8* tetHint = reinterpret_cast<PxU8*>(collisionData.mGRB_tetraSurfaceHint);
PxU32 triCount = 0;
//compute the surface triangles for the tetrahedron mesh
for (PxHashMap<SortedTriangleInds, PxU32, SortedTriangleIndsHash>::Iterator iter = triIndsMap.getIterator(); !iter.done(); ++iter)
{
SortedTriangleInds key = iter->first;
// only output faces that are referenced by one tet (open faces)
if (iter->second == 1)
{
PxU8 triHint = 0;
IndTetrahedron32& localTetra = dest[key.mTetIndex];
for (PxU32 i = 0; i < 3; ++i)
{
if (key.mOrigRef[i] == localTetra.mRef[0])
triHint |= 1;
else if (key.mOrigRef[i] == localTetra.mRef[1])
triHint |= (1 << 1);
else if (key.mOrigRef[i] == localTetra.mRef[2])
triHint |= (1 << 2);
else if (key.mOrigRef[i] == localTetra.mRef[3])
triHint |= (1 << 3);
}
//if this tetrahedron isn't surface tetrahedron, hint will be zero
//otherwise, the first 4 bits will indicate the indice of the
//surface triangle
PxU32 mask = 0;
if (triHint == 7) //0111
{
mask = 1 << 0;
}
else if (triHint == 11)//1011
{
mask = 1 << 1;
}
else if (triHint == 13)//1101
{
mask = 1 << 2;
}
else //1110
{
mask = 1 << 3;
}
tetHint[key.mTetIndex] |= mask;
triCount++;
}
}
#if BV32_VALIDATE
IndTetrahedron32* grbTriIndices = reinterpret_cast<IndTetrahedron32*>(collisionData.mGRB_primIndices);
IndTetrahedron32* cpuTriIndices = reinterpret_cast<IndTetrahedron32*>(collisionMesh.mTetrahedrons);
//map CPU remap triangle index to GPU remap triangle index
for (PxU32 i = 0; i < nbTetrahedrons; ++i)
{
PX_ASSERT(grbTriIndices[i].mRef[0] == cpuTriIndices[collisionData.mGRB_faceRemap[i]].mRef[0]);
PX_ASSERT(grbTriIndices[i].mRef[1] == cpuTriIndices[collisionData.mGRB_faceRemap[i]].mRef[1]);
PX_ASSERT(grbTriIndices[i].mRef[2] == cpuTriIndices[collisionData.mGRB_faceRemap[i]].mRef[2]);
PX_ASSERT(grbTriIndices[i].mRef[3] == cpuTriIndices[collisionData.mGRB_faceRemap[i]].mRef[3]);
}
#endif
}
return true;
}
void computeRestPoseAndPointMass(TetrahedronT<PxU32>* tetIndices, const PxU32 nbTets,
const PxVec3* verts, PxReal* invMasses, PxMat33* restPoses)
{
for (PxU32 i = 0; i < nbTets; ++i)
{
TetrahedronT<PxU32>& tetInd = tetIndices[i];
PxMat33 Q, QInv;
const PxReal volume = computeTetrahedronVolume(verts[tetInd.v[0]], verts[tetInd.v[1]], verts[tetInd.v[2]], verts[tetInd.v[3]], Q);
if (volume <= 1.e-9f)
{
//Neo-hookean model can deal with bad tets, so not issueing this error anymore
//PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeRestPoseAndPointMass(): tretrahedron is degenerate or inverted");
if (volume == 0)
QInv = PxMat33(PxZero);
else
QInv = Q.getInverse();
}
else
QInv = Q.getInverse();
// add volume fraction to particles
if (invMasses != NULL)
{
invMasses[tetInd.v[0]] += volume * 0.25f;
invMasses[tetInd.v[1]] += volume * 0.25f;
invMasses[tetInd.v[2]] += volume * 0.25f;
invMasses[tetInd.v[3]] += volume * 0.25f;
}
restPoses[i] = QInv;
}
}
#define MAX_NUM_PARTITIONS 32
PxU32 computeTetrahedronPartition(const TetrahedronT<PxU32>* tets, const PxU32 partitionStartIndex, PxU32* partitionProgresses,
const PxU32 numTetsPerElement)
{
PxU32 combinedMask = 0xFFFFFFFF;
for (PxU32 i = 0; i < numTetsPerElement; ++i)
{
PxU32 partitionA = partitionProgresses[tets[i].v[0]];
PxU32 partitionB = partitionProgresses[tets[i].v[1]];
PxU32 partitionC = partitionProgresses[tets[i].v[2]];
PxU32 partitionD = partitionProgresses[tets[i].v[3]];
combinedMask &= (~partitionA & ~partitionB & ~partitionC & ~partitionD);
}
PxU32 availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
return 0xFFFFFFFF;
const PxU32 partitionBit = (1u << availablePartition);
for (PxU32 i = 0; i < numTetsPerElement; ++i)
{
PxU32 partitionA = partitionProgresses[tets[i].v[0]];
PxU32 partitionB = partitionProgresses[tets[i].v[1]];
PxU32 partitionC = partitionProgresses[tets[i].v[2]];
PxU32 partitionD = partitionProgresses[tets[i].v[3]];
partitionA |= partitionBit;
partitionB |= partitionBit;
partitionC |= partitionBit;
partitionD |= partitionBit;
partitionProgresses[tets[i].v[0]] = partitionA;
partitionProgresses[tets[i].v[1]] = partitionB;
partitionProgresses[tets[i].v[2]] = partitionC;
partitionProgresses[tets[i].v[3]] = partitionD;
}
availablePartition += partitionStartIndex;
return availablePartition;
}
void classifyTetrahedrons(const TetrahedronT<PxU32>* tets, const PxU32 numTets, const PxU32 numVerts, const PxU32 numTetsPerElement,
PxU32* partitionProgresses, PxU32* tempTetrahedrons, PxArray<PxU32>& tetrahedronsPerPartition)
{
//initialize the partition progress counter to be zero
PxMemZero(partitionProgresses, sizeof(PxU32) * numVerts);
PxU32 numUnpartitionedTetrahedrons = 0;
//compute partitions for each tetrahedron in the grid model
for (PxU32 i = 0; i < numTets; i += numTetsPerElement)
{
const TetrahedronT<PxU32>* tet = &tets[i];
const PxU32 availablePartition = computeTetrahedronPartition(tet, 0, partitionProgresses, numTetsPerElement);
if (availablePartition == 0xFFFFFFFF)
{
tempTetrahedrons[numUnpartitionedTetrahedrons++] = i;
continue;
}
tetrahedronsPerPartition[availablePartition]++;
}
PxU32 partitionStartIndex = 0;
while (numUnpartitionedTetrahedrons > 0)
{
//initialize the partition progress counter to be zero
PxMemZero(partitionProgresses, sizeof(PxU32) * numVerts);
partitionStartIndex += MAX_NUM_PARTITIONS;
//Keep partitioning the un-partitioned constraints and blat the whole thing to 0!
tetrahedronsPerPartition.resize(MAX_NUM_PARTITIONS + tetrahedronsPerPartition.size());
PxMemZero(tetrahedronsPerPartition.begin() + partitionStartIndex, sizeof(PxU32) * MAX_NUM_PARTITIONS);
PxU32 newNumUnpartitionedConstraints = 0;
for (PxU32 i = 0; i < numUnpartitionedTetrahedrons; ++i)
{
const PxU32 tetInd = tempTetrahedrons[i];
const TetrahedronT<PxU32>* tet = &tets[tetInd];
const PxU32 availablePartition = computeTetrahedronPartition(tet, partitionStartIndex, partitionProgresses, numTetsPerElement);
if (availablePartition == 0xFFFFFFFF)
{
tempTetrahedrons[newNumUnpartitionedConstraints++] = tetInd;
continue;
}
tetrahedronsPerPartition[availablePartition]++;
}
numUnpartitionedTetrahedrons = newNumUnpartitionedConstraints;
}
}
void writeTetrahedrons(const TetrahedronT<PxU32>* tets, const PxU32 numTets, const PxU32 numVerts, const PxU32 numTetsPerElement,
PxU32* partitionProgresses, PxU32* tempTetrahedrons, PxU32* orderedTetrahedrons,
PxU32* accumulatedTetrahedronPerPartition)
{
//initialize the partition progress counter to be zero
PxMemZero(partitionProgresses, sizeof(PxU32) * numVerts);
PxU32 numUnpartitionedTetrahedrons = 0;
for (PxU32 i = 0; i < numTets; i += numTetsPerElement)
{
const TetrahedronT<PxU32>* tet = &tets[i];
const PxU32 availablePartition = computeTetrahedronPartition(tet, 0, partitionProgresses, numTetsPerElement);
if (availablePartition == 0xFFFFFFFF)
{
tempTetrahedrons[numUnpartitionedTetrahedrons++] = i;
continue;
}
//output tetrahedron
orderedTetrahedrons[accumulatedTetrahedronPerPartition[availablePartition]++] = i;
}
PxU32 partitionStartIndex = 0;
while (numUnpartitionedTetrahedrons > 0)
{
//initialize the partition progress counter to be zero
PxMemZero(partitionProgresses, sizeof(PxU32) * numVerts);
partitionStartIndex += MAX_NUM_PARTITIONS;
PxU32 newNumUnpartitionedConstraints = 0;
for (PxU32 i = 0; i < numUnpartitionedTetrahedrons; ++i)
{
const PxU32 tetInd = tempTetrahedrons[i];
const TetrahedronT<PxU32>* tet = &tets[tetInd];
const PxU32 availablePartition = computeTetrahedronPartition(tet, partitionStartIndex, partitionProgresses, numTetsPerElement);
if (availablePartition == 0xFFFFFFFF)
{
tempTetrahedrons[newNumUnpartitionedConstraints++] = tetInd;
continue;
}
//output tetrahedrons
orderedTetrahedrons[accumulatedTetrahedronPerPartition[availablePartition]++] = tetInd;
}
numUnpartitionedTetrahedrons = newNumUnpartitionedConstraints;
}
}
PxU32* computeGridModelTetrahedronPartitions(const TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData)
{
const PxU32 numTets = simulationMesh.mNbTetrahedrons;
const PxU32 numVerts = simulationMesh.mNbVertices;
//each grid model verts has a partition progress counter
PxU32* partitionProgresses = PX_ALLOCATE(PxU32, numVerts, "partitionProgress");
//this store the tetrahedron index for the unpartitioned tetrahedrons
PxU32* tempTetrahedrons = PX_ALLOCATE(PxU32, numTets, "tempTetrahedrons");
PxArray<PxU32> tetrahedronsPerPartition;
tetrahedronsPerPartition.reserve(MAX_NUM_PARTITIONS);
tetrahedronsPerPartition.forceSize_Unsafe(MAX_NUM_PARTITIONS);
PxMemZero(tetrahedronsPerPartition.begin(), sizeof(PxU32) * MAX_NUM_PARTITIONS);
const TetrahedronT<PxU32>* tetGM = reinterpret_cast<TetrahedronT<PxU32>*>(simulationMesh.mTetrahedrons);
classifyTetrahedrons(tetGM, numTets, numVerts, simulationData.mNumTetsPerElement, partitionProgresses,
tempTetrahedrons, tetrahedronsPerPartition);
//compute number of partitions
PxU32 maxPartition = 0;
for (PxU32 a = 0; a < tetrahedronsPerPartition.size(); ++a, maxPartition++)
{
if (tetrahedronsPerPartition[a] == 0)
break;
}
PxU32* accumulatedTetrahedronPerPartition = PX_ALLOCATE(PxU32, maxPartition, "accumulatedTetrahedronPerPartition");
//compute run sum
PxU32 accumulation = 0;
for (PxU32 a = 0; a < maxPartition; ++a)
{
PxU32 count = tetrahedronsPerPartition[a];
accumulatedTetrahedronPerPartition[a] = accumulation;
accumulation += count;
}
PX_ASSERT(accumulation*simulationData.mNumTetsPerElement == numTets);
simulationData.mGridModelOrderedTetrahedrons = PX_ALLOCATE(PxU32, numTets, "mGridModelPartitionTetrahedrons");
simulationData.mGridModelNbPartitions = maxPartition;
PxU32* orderedTetrahedrons = simulationData.mGridModelOrderedTetrahedrons;
writeTetrahedrons(tetGM, numTets, numVerts, simulationData.mNumTetsPerElement, partitionProgresses, tempTetrahedrons,
orderedTetrahedrons, accumulatedTetrahedronPerPartition);
PX_FREE(partitionProgresses);
PX_FREE(tempTetrahedrons);
return accumulatedTetrahedronPerPartition;
}
bool findSlot(const TetrahedronT<PxU32>* tetraIndices, bool* occupied, const PxU32 tetrahedronIdx,
const PxU32 offset, const PxU32 sVertInd, const PxU32 workIndex)
{
const TetrahedronT<PxU32>& tetraInd = tetraIndices[tetrahedronIdx];
for (PxU32 i = 0; i < 4; ++i)
{
const PxU32 dVertInd = i * offset + workIndex;
if (sVertInd == tetraInd.v[i] && (!occupied[dVertInd]))
{
occupied[dVertInd] = true;
return true;
}
}
return false;
}
//output to remapOutput
bool findSlot(const TetrahedronT<PxU32>* tetraIndices, bool* occupied, const PxU32 tetrahedronIdx,
const PxU32 offset, const PxU32 sVertInd, const PxU32 sVertIndOffset, PxU32* remapOutput,
PxU32* accumulatedWriteBackIndex, const PxU32 workIndex)
{
const TetrahedronT<PxU32>& tetraInd = tetraIndices[tetrahedronIdx];
for (PxU32 i = 0; i < 4; ++i)
{
const PxU32 dVertIndOffset = i * offset + workIndex;
if (sVertInd == tetraInd.v[i] && (!occupied[dVertIndOffset]))
{
remapOutput[sVertIndOffset] = dVertIndOffset;
accumulatedWriteBackIndex[dVertIndOffset] = sVertIndOffset;
occupied[dVertIndOffset] = true;
return true;
}
}
return false;
}
void computeNumberOfCopiesPerVerts(const PxU32 maximumPartitions, PxU32* combineAccumulatedTetraPerPartitions,
const TetrahedronT<PxU32>* tetraIndices, const PxU32* orderedTetrahedrons, const PxU32 offset, bool* occupied, PxU32* numCopiesEachVerts)
{
//compute numCopiesEachVerts
PxU32 startId = 0;
for (PxU32 i = 0; i < maximumPartitions; ++i)
{
PxU32 endId = combineAccumulatedTetraPerPartitions[i];
for (PxU32 j = startId; j < endId; ++j)
{
const PxU32 tetrahedronInd = orderedTetrahedrons[j];
const TetrahedronT<PxU32>& tetraInd = tetraIndices[tetrahedronInd];
for (PxU32 b = 0; b < 4; ++b)
{
const PxU32 vertInd = tetraInd.v[b];
bool found = false;
for (PxU32 k = i + 1; k < maximumPartitions; ++k)
{
const PxU32 tStartId = combineAccumulatedTetraPerPartitions[k - 1];
const PxU32 tEndId = combineAccumulatedTetraPerPartitions[k];
bool foundSlotInThisPartition = false;
for (PxU32 a = tStartId; a < tEndId; ++a)
{
const PxU32 otherTetrahedronInd = orderedTetrahedrons[a];
if (findSlot(tetraIndices, occupied, otherTetrahedronInd, offset, vertInd, a))
{
foundSlotInThisPartition = true;
break;
}
}
if (foundSlotInThisPartition)
{
found = true;
break;
}
}
if (!found)
{
numCopiesEachVerts[vertInd]++;
}
}
}
startId = endId;
}
}
//compute remapOutput
void computeRemapOutputForVertsAndAccumulatedBuffer(const PxU32 maximumPartitions, PxU32* combineAccumulatedTetraPerPartitions,
const TetrahedronT<PxU32>* tetraIndices, const PxU32* orderedTetrahedrons, const PxU32 offset, bool* occupied, PxU32* tempNumCopiesEachVerts, const PxU32* accumulatedCopies,
const PxU32 numVerts, PxU32* remapOutput,
PxU32* accumulatedWriteBackIndex, const PxU32 totalNumCopies)
{
PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * numVerts);
const PxU32 totalNumVerts = offset * 4;
PxMemZero(occupied, sizeof(bool) * totalNumVerts);
//initialize accumulatedWriteBackIndex to itself
for (PxU32 i = 0; i < totalNumVerts; ++i)
{
accumulatedWriteBackIndex[i] = i;
}
//compute remap output
PxU32 startId = 0;
for (PxU32 i = 0; i < maximumPartitions; ++i)
{
const PxU32 endId = combineAccumulatedTetraPerPartitions[i];
for (PxU32 j = startId; j < endId; ++j)
{
const PxU32 tetrahedronsIdx = orderedTetrahedrons[j];
const TetrahedronT<PxU32>& tetraInd = tetraIndices[tetrahedronsIdx];
for (PxU32 b = 0; b < 4; ++b)
{
const PxU32 vertInd = tetraInd.v[b];
const PxU32 vertOffset = j + offset * b;
bool found = false;
for (PxU32 k = i + 1; k < maximumPartitions; ++k)
{
const PxU32 tStartId = combineAccumulatedTetraPerPartitions[k-1];
const PxU32 tEndId = combineAccumulatedTetraPerPartitions[k];
bool foundSlotInThisPartition = false;
for (PxU32 a = tStartId; a < tEndId; ++a)
{
const PxU32 otherTetrahedronInd = orderedTetrahedrons[a];
if (findSlot(tetraIndices, occupied, otherTetrahedronInd, offset, vertInd,
vertOffset, remapOutput, accumulatedWriteBackIndex, a))
{
foundSlotInThisPartition = true;
break;
}
}
if (foundSlotInThisPartition)
{
found = true;
break;
}
}
if (!found)
{
const PxU32 abVertStartInd = vertInd == 0 ? 0 : accumulatedCopies[vertInd - 1];
const PxU32 index = totalNumVerts + abVertStartInd + tempNumCopiesEachVerts[vertInd];
//remapOutput for the current vert index
remapOutput[vertOffset] = index;
//const PxU32 writebackIndex = abVertStartInd + tempNumCopiesEachVerts[vertInd];
//accumulatedWriteBackIndex[writebackIndex] = vertOffset;
remapOutput[index] = vertOffset;
tempNumCopiesEachVerts[vertInd]++;
}
}
}
startId = endId;
}
//PxU32* writeBackBuffer = &accumulatedWriteBackIndex[totalNumVerts];
PxU32* accumulatedBufferRemap = &remapOutput[totalNumVerts];
for (PxU32 i = 0; i < totalNumCopies; ++i)
{
PxU32 originalIndex = accumulatedBufferRemap[i];
PxU32 wbIndex0, wbIndex1;
do
{
wbIndex0 = originalIndex;
wbIndex1 = accumulatedWriteBackIndex[wbIndex0];
originalIndex = wbIndex1;
} while (wbIndex0 != wbIndex1);
accumulatedBufferRemap[i] = wbIndex1;
}
}
//void combineGridModelPartitions(const TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData, PxU32** accumulatedTetrahedronPerPartitions)
//{
// const PxU32 numTets = simulationMesh.mNbTetrahedrons;
// const PxU32 numVerts = simulationMesh.mNbVertices;
// const PxU32 nbPartitions = simulationData.mGridModelNbPartitions;
// PxU32* accumulatedTetrahedronPerPartition = *accumulatedTetrahedronPerPartitions;
//
// const PxU32 maximumPartitions = 8;
// PxU32* combineAccumulatedTetraPerPartitions = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * maximumPartitions, "combineAccumulatedTetraPerPartitions"));
// simulationData.mGMAccumulatedPartitionsCP = combineAccumulatedTetraPerPartitions;
//
// PxMemZero(combineAccumulatedTetraPerPartitions, sizeof(PxU32) * maximumPartitions);
// const PxU32 maxAccumulatedPartitionsPerPartitions = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
// PxU32* orderedTetrahedrons = simulationData.mGridModelOrderedTetrahedrons;
// PxU32* tempOrderedTetrahedrons = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * numTets, "tempOrderedTetrahedrons"));
// const TetrahedronT<PxU32>* tetrahedrons = reinterpret_cast<TetrahedronT<PxU32>*>( simulationMesh.mTetrahedrons);
//
// const PxU32 maxAccumulatedCP = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
// const PxU32 partitionArraySize = maxAccumulatedCP * maximumPartitions;
// const PxU32 nbPartitionTables = partitionArraySize * numVerts;
// PxU32* tempPartitionTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempPartitionTablePerVert"));
// PxU32* tempRemapTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempRemapTablePerVert"));
// PxU32* pullIndices = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * numTets*4, "tempRemapTablePerVert"));
// PxU32* lastRef = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32)* maxAccumulatedCP*numVerts, "refCounts"));
// PxU32* accumulatedCopiesEachVerts = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * numVerts, "accumulatedCopiesEachVerts"));
// simulationData.mGMAccumulatedCopiesCP = accumulatedCopiesEachVerts;
// PxU32* tempNumCopiesEachVerts = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * numVerts, "numCopiesEachVerts"));
// PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * numVerts);
// PxMemSet(pullIndices, 0xffffffff, sizeof(PxU32)*numTets*4);
// PxMemSet(lastRef, 0xffffffff, sizeof(PxU32)*maxAccumulatedCP*numVerts);
// //initialize partitionTablePerVert
// for (PxU32 i = 0; i < nbPartitionTables; ++i)
// {
// tempPartitionTablePerVert[i] = 0xffffffff;
// tempRemapTablePerVert[i] = 0xffffffff;
//
// }
// PxU32 maxTetPerPartitions = 0;
// PxU32 count = 0;
// const PxU32 totalNumVerts = numTets * 4;
// PxU32 totalCopies = numVerts * maxAccumulatedCP;
// simulationData.mGridModelNbPartitions = maximumPartitions;
// simulationData.mGMRemapOutputSize = totalNumVerts + totalCopies;
// ////allocate enough memory for the verts and the accumulation buffer
// //PxVec4* orderedVertsInMassCP = reinterpret_cast<PxVec4*>(PX_ALLOC(sizeof(PxVec4) * totalNumVerts, "mGMOrderedVertInvMassCP"));
// //data.mGMOrderedVertInvMassCP = orderedVertsInMassCP;
// //compute remap table
// PxU32* remapOutput = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * simulationData.mGMRemapOutputSize, "remapOutput"));
// simulationData.mGMRemapOutputCP = remapOutput;
// for (PxU32 i = 0; i < maximumPartitions; ++i)
// {
// PxU32 totalTets = 0;
// for (PxU32 j = 0; j < maxAccumulatedPartitionsPerPartitions; ++j)
// {
// PxU32 partitionId = i + maximumPartitions * j;
// if (partitionId < nbPartitions)
// {
// const PxU32 startInd = partitionId == 0 ? 0 : accumulatedTetrahedronPerPartition[partitionId - 1];
// const PxU32 endInd = accumulatedTetrahedronPerPartition[partitionId];
// for (PxU32 k = startInd; k < endInd; ++k)
// {
// const PxU32 tetraInd = orderedTetrahedrons[k];
// tempOrderedTetrahedrons[count] = tetraInd;
// //tempCombinedTetraIndices[count] = tetGM[tetraInd];
// //tempTetRestPose[count] = tetRestPose[tetraInd];
// PxU32 index = i * maxAccumulatedCP + j;
// TetrahedronT<PxU32> tet = tetrahedrons[tetraInd];
// tempPartitionTablePerVert[tet.v[0] * partitionArraySize + index] = count;
// tempPartitionTablePerVert[tet.v[1] * partitionArraySize + index] = count + numTets;
// tempPartitionTablePerVert[tet.v[2] * partitionArraySize + index] = count + numTets * 2;
// tempPartitionTablePerVert[tet.v[3] * partitionArraySize + index] = count + numTets * 3;
// if (lastRef[tet.v[0] * maxAccumulatedCP + j] == 0xffffffff)
// {
// pullIndices[4 * count] = tet.v[0];
// tempNumCopiesEachVerts[tet.v[0]]++;
// }
// else
// {
// remapOutput[lastRef[tet.v[0] * maxAccumulatedCP + j]] = count;
// }
// lastRef[tet.v[0] * maxAccumulatedCP + j] = 4*count;
// if (lastRef[tet.v[1] * maxAccumulatedCP + j] == 0xffffffff)
// {
// pullIndices[4 * count + 1] = tet.v[1];
// tempNumCopiesEachVerts[tet.v[1]]++;
// }
// else
// {
// remapOutput[lastRef[tet.v[1] * maxAccumulatedCP + j]] = count + numTets;
// }
// lastRef[tet.v[1] * maxAccumulatedCP + j] = 4*count + 1;
// if (lastRef[tet.v[2] * maxAccumulatedCP + j] == 0xffffffff)
// {
// pullIndices[4 * count + 2] = tet.v[2];
// tempNumCopiesEachVerts[tet.v[2]]++;
//
// }
// else
// {
// remapOutput[lastRef[tet.v[2] * maxAccumulatedCP + j]] = count + 2*numTets;
// }
// lastRef[tet.v[2] * maxAccumulatedCP + j] = 4*count+2;
// if (lastRef[tet.v[3] * maxAccumulatedCP + j] == 0xffffffff)
// {
// pullIndices[4 * count + 3] = tet.v[3];
// tempNumCopiesEachVerts[tet.v[3]]++;
// }
// else
// {
// remapOutput[lastRef[tet.v[3] * maxAccumulatedCP + j]] = count + 3*numTets;
// }
// lastRef[tet.v[3] * maxAccumulatedCP + j] = 4*count+3;
// count++;
// }
// totalTets += (endInd - startInd);
// }
// }
// combineAccumulatedTetraPerPartitions[i] = count;
// maxTetPerPartitions = PxMax(maxTetPerPartitions, totalTets);
// }
// //Last bit - output accumulation buffer...
//
// PxU32 outIndex = 0;
// simulationData.mGridModelMaxTetsPerPartitions = maxTetPerPartitions;
// //If this commented out, we don't use combined partition anymore
// PxMemCopy(orderedTetrahedrons, tempOrderedTetrahedrons, sizeof(PxU32) * numTets);
// /*bool* tempOccupied = reinterpret_cast <bool*>( PX_ALLOC(sizeof(bool) * totalNumVerts, "tempOccupied"));
// PxMemZero(tempOccupied, sizeof(bool) * totalNumVerts);*/
//
// //data.mGridModelNbPartitions = maximumPartitions;
// //data.mGMRemapOutputSize = totalNumVerts + totalCopies;
// simulationData.mGridModelNbPartitions = maximumPartitions;
// simulationData.mGMRemapOutputSize = totalNumVerts + totalCopies;
// //data.mGMOrderedVertInvMassCP = orderedVertsInMassCP;
// //mGMOrderedVertInvMassCP = orderedVertsInMassCP;
// //Last bit - output accumulation buffer...
// outIndex = 0;
// for (PxU32 i = 0; i < numVerts; ++i)
// {
// for (PxU32 j = 0; j < maxAccumulatedCP; ++j)
// {
// if (lastRef[i * maxAccumulatedCP + j] != 0xffffffff)
// {
// remapOutput[lastRef[i * maxAccumulatedCP + j]] = totalNumVerts + outIndex++;
// }
// }
// accumulatedCopiesEachVerts[i] = outIndex;
// }
// PX_ASSERT(count == numTets);
// simulationData.mGridModelMaxTetsPerPartitions = maxTetPerPartitions;
// simulationData.mGMPullIndices = pullIndices;
// //If this commented out, we don't use combined partition anymore
// PxMemCopy(orderedTetrahedrons, tempOrderedTetrahedrons, sizeof(PxU32) * numTets);
// PX_FREE(tempNumCopiesEachVerts);
// PX_FREE(tempOrderedTetrahedrons);
// PX_FREE(tempPartitionTablePerVert);
// PX_FREE(tempRemapTablePerVert);
//
// PX_FREE(lastRef);
//}
PxU32 setBit(PxU32 value, PxU32 bitLocation, bool bitState)
{
if (bitState)
return value | (1 << bitLocation);
else
return value & (~(1 << bitLocation));
}
void combineGridModelPartitions(const TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData, PxU32** accumulatedTetrahedronPerPartitions)
{
const PxU32 numTets = simulationMesh.mNbTetrahedrons;
const PxU32 numVerts = simulationMesh.mNbVertices;
const PxU32 nbPartitions = simulationData.mGridModelNbPartitions;
PxU32* accumulatedTetrahedronPerPartition = *accumulatedTetrahedronPerPartitions;
const PxU32 maximumPartitions = 8;
PxU32* combineAccumulatedTetraPerPartitions = PX_ALLOCATE(PxU32, maximumPartitions, "combineAccumulatedTetraPerPartitions");
simulationData.mGMAccumulatedPartitionsCP = combineAccumulatedTetraPerPartitions;
PxMemZero(combineAccumulatedTetraPerPartitions, sizeof(PxU32) * maximumPartitions);
const PxU32 maxAccumulatedPartitionsPerPartitions = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
PxU32* orderedTetrahedrons = simulationData.mGridModelOrderedTetrahedrons;
PxU32* tempOrderedTetrahedrons = PX_ALLOCATE(PxU32, numTets, "tempOrderedTetrahedrons");
const TetrahedronT<PxU32>* tetrahedrons = reinterpret_cast<TetrahedronT<PxU32>*>(simulationMesh.mTetrahedrons);
const PxU32 maxAccumulatedCP = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
const PxU32 partitionArraySize = maxAccumulatedCP * maximumPartitions;
const PxU32 nbPartitionTables = partitionArraySize * numVerts;
PxU32* tempPartitionTablePerVert = PX_ALLOCATE(PxU32, nbPartitionTables, "tempPartitionTablePerVert");
PxU32* tempRemapTablePerVert = PX_ALLOCATE(PxU32, nbPartitionTables, "tempRemapTablePerVert");
PxU32* pullIndices = PX_ALLOCATE(PxU32, (numTets * 4), "tempRemapTablePerVert");
PxU32* lastRef = PX_ALLOCATE(PxU32, (maxAccumulatedCP*numVerts), "refCounts");
PxU32* accumulatedCopiesEachVerts = PX_ALLOCATE(PxU32, numVerts, "accumulatedCopiesEachVerts");
simulationData.mGMAccumulatedCopiesCP = accumulatedCopiesEachVerts;
PxU32* tempNumCopiesEachVerts = PX_ALLOCATE(PxU32, numVerts, "numCopiesEachVerts");
PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * numVerts);
PxMemSet(pullIndices, 0xffffffff, sizeof(PxU32)*numTets * 4);
PxMemSet(lastRef, 0xffffffff, sizeof(PxU32)*maxAccumulatedCP*numVerts);
//initialize partitionTablePerVert
for (PxU32 i = 0; i < nbPartitionTables; ++i)
{
tempPartitionTablePerVert[i] = 0xffffffff;
tempRemapTablePerVert[i] = 0xffffffff;
}
PxU32 maxTetPerPartitions = 0;
PxU32 count = 0;
const PxU32 totalNumVerts = numTets * 4;
PxU32 totalCopies = numVerts * maxAccumulatedCP;
simulationData.mGridModelNbPartitions = maximumPartitions;
simulationData.mGMRemapOutputSize = totalNumVerts + totalCopies;
////allocate enough memory for the verts and the accumulation buffer
//PxVec4* orderedVertsInMassCP = reinterpret_cast<PxVec4*>(PX_ALLOC(sizeof(PxVec4) * totalNumVerts, "mGMOrderedVertInvMassCP"));
//data.mGMOrderedVertInvMassCP = orderedVertsInMassCP;
//compute remap table
PxU32* remapOutput = PX_ALLOCATE(PxU32, simulationData.mGMRemapOutputSize, "remapOutput");
simulationData.mGMRemapOutputCP = remapOutput;
for (PxU32 i = 0; i < maximumPartitions; ++i)
{
PxU32 totalTets = 0;
for (PxU32 j = 0; j < maxAccumulatedPartitionsPerPartitions; ++j)
{
PxU32 partitionId = i + maximumPartitions * j;
if (partitionId < nbPartitions)
{
const PxU32 startInd = partitionId == 0 ? 0 : accumulatedTetrahedronPerPartition[partitionId - 1];
const PxU32 endInd = accumulatedTetrahedronPerPartition[partitionId];
for (PxU32 k = startInd; k < endInd; ++k)
{
const PxU32 tetraInd = orderedTetrahedrons[k];
tempOrderedTetrahedrons[count] = tetraInd;
//tempCombinedTetraIndices[count] = tetGM[tetraInd];
//tempTetRestPose[count] = tetRestPose[tetraInd];
PxU32 index = i * maxAccumulatedCP + j;
TetrahedronT<PxU32> tet = tetrahedrons[tetraInd];
tempPartitionTablePerVert[tet.v[0] * partitionArraySize + index] = count;
tempPartitionTablePerVert[tet.v[1] * partitionArraySize + index] = count + numTets;
tempPartitionTablePerVert[tet.v[2] * partitionArraySize + index] = count + numTets * 2;
tempPartitionTablePerVert[tet.v[3] * partitionArraySize + index] = count + numTets * 3;
if (lastRef[tet.v[0] * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * count] = tet.v[0];
tempNumCopiesEachVerts[tet.v[0]]++;
}
else
{
remapOutput[lastRef[tet.v[0] * maxAccumulatedCP + j]] = count;
}
lastRef[tet.v[0] * maxAccumulatedCP + j] = 4 * count;
if (lastRef[tet.v[1] * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * count + 1] = tet.v[1];
tempNumCopiesEachVerts[tet.v[1]]++;
}
else
{
remapOutput[lastRef[tet.v[1] * maxAccumulatedCP + j]] = count + numTets;
}
lastRef[tet.v[1] * maxAccumulatedCP + j] = 4 * count + 1;
if (lastRef[tet.v[2] * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * count + 2] = tet.v[2];
tempNumCopiesEachVerts[tet.v[2]]++;
}
else
{
remapOutput[lastRef[tet.v[2] * maxAccumulatedCP + j]] = count + 2 * numTets;
}
lastRef[tet.v[2] * maxAccumulatedCP + j] = 4 * count + 2;
if (lastRef[tet.v[3] * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * count + 3] = tet.v[3];
tempNumCopiesEachVerts[tet.v[3]]++;
}
else
{
remapOutput[lastRef[tet.v[3] * maxAccumulatedCP + j]] = count + 3 * numTets;
}
lastRef[tet.v[3] * maxAccumulatedCP + j] = 4 * count + 3;
count++;
}
totalTets += (endInd - startInd);
}
}
combineAccumulatedTetraPerPartitions[i] = count;
maxTetPerPartitions = PxMax(maxTetPerPartitions, totalTets);
}
//Last bit - output accumulation buffer...
PxU32 outIndex = 0;
for (PxU32 i = 0; i < numVerts; ++i)
{
for (PxU32 j = 0; j < maxAccumulatedCP; ++j)
{
if (lastRef[i * maxAccumulatedCP + j] != 0xffffffff)
{
remapOutput[lastRef[i * maxAccumulatedCP + j]] = totalNumVerts + outIndex++;
}
}
accumulatedCopiesEachVerts[i] = outIndex;
}
PX_ASSERT(count == numTets);
simulationData.mGridModelMaxTetsPerPartitions = maxTetPerPartitions;
simulationData.mGMPullIndices = pullIndices;
//If this commented out, we don't use combined partition anymore
PxMemCopy(orderedTetrahedrons, tempOrderedTetrahedrons, sizeof(PxU32) * numTets);
PX_FREE(tempNumCopiesEachVerts);
PX_FREE(tempOrderedTetrahedrons);
PX_FREE(tempPartitionTablePerVert);
PX_FREE(tempRemapTablePerVert);
PX_FREE(lastRef);
}
const PxI32 tetIndicesFromVoxels[8] = { 0, 1, 3, 14, 6, 11, 2, 18 };
//const PxI32 tets6PerVoxel[24] = { 0,1,6,2, 0,1,4,6, 1,4,6,5, 1,2,3,6, 1,3,7,6, 1,5,6,7 };
const PxI32 tetIndicesFromVoxelsA[8] = { 0, 5, 16, 2, 12, 3, 1, 9 };
const PxI32 tetIndicesFromVoxelsB[8] = { 5, 0, 3, 16, 2, 12, 9, 1 };
//const PxU32 tets5PerVoxel[] = {
// 0, 6, 3, 5, 0, 1, 5, 3, 6, 7, 3, 5, 4, 5, 6, 0, 2, 3, 0, 6,
// 1, 7, 4, 2, 1, 0, 2, 4, 7, 6, 4, 2, 5, 4, 1, 7, 3, 2, 7, 1 };
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void combineGridModelPartitionsHexMesh(const TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData,
PxU32** accumulatedTetrahedronPerPartitions, PxU32 numTetsPerElement)
{
//const PxU32 numTets = simulationMesh.mNbTetrahedrons;
const PxU32 numElements = simulationMesh.mNbTetrahedrons/simulationData.mNumTetsPerElement;
const PxU32 numVerts = simulationMesh.mNbVertices;
const PxU32 NumVertsPerElement = 8;
const PxU32 nbPartitions = simulationData.mGridModelNbPartitions;
PxU32* accumulatedTetrahedronPerPartition = *accumulatedTetrahedronPerPartitions;
const PxU32 maximumPartitions = 8;
PxU32* combineAccumulatedTetraPerPartitions = PX_ALLOCATE(PxU32, maximumPartitions, "combineAccumulatedTetraPerPartitions");
simulationData.mGMAccumulatedPartitionsCP = combineAccumulatedTetraPerPartitions;
PxMemZero(combineAccumulatedTetraPerPartitions, sizeof(PxU32) * maximumPartitions);
const PxU32 maxAccumulatedPartitionsPerPartitions = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
PxU32* orderedTetrahedrons = simulationData.mGridModelOrderedTetrahedrons;
PxU32* tempOrderedTetrahedrons = PX_ALLOCATE(PxU32, numElements, "tempOrderedTetrahedrons");
const TetrahedronT<PxU32>* tetrahedrons = reinterpret_cast<TetrahedronT<PxU32>*>(simulationMesh.mTetrahedrons);
const PxU32 maxAccumulatedCP = (nbPartitions + maximumPartitions - 1) / maximumPartitions;
const PxU32 partitionArraySize = maxAccumulatedCP * maximumPartitions;
const PxU32 nbPartitionTables = partitionArraySize * numVerts;
PxU32* tempPartitionTablePerVert = PX_ALLOCATE(PxU32, nbPartitionTables, "tempPartitionTablePerVert");
PxU32* tempRemapTablePerVert = PX_ALLOCATE(PxU32, nbPartitionTables, "tempRemapTablePerVert");
PxU32* pullIndices = PX_ALLOCATE(PxU32, (numElements * NumVertsPerElement), "tempRemapTablePerVert");
PxU32* lastRef = PX_ALLOCATE(PxU32, (maxAccumulatedCP*numVerts), "refCounts");
PxU32* accumulatedCopiesEachVerts = PX_ALLOCATE(PxU32, numVerts, "accumulatedCopiesEachVerts");
simulationData.mGMAccumulatedCopiesCP = accumulatedCopiesEachVerts;
PxU32* tempNumCopiesEachVerts = PX_ALLOCATE(PxU32, numVerts, "numCopiesEachVerts");
PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * numVerts);
PxMemSet(pullIndices, 0xffffffff, sizeof(PxU32)*numElements * NumVertsPerElement);
PxMemSet(lastRef, 0xffffffff, sizeof(PxU32)*maxAccumulatedCP*numVerts);
//initialize partitionTablePerVert
for (PxU32 i = 0; i < nbPartitionTables; ++i)
{
tempPartitionTablePerVert[i] = 0xffffffff;
tempRemapTablePerVert[i] = 0xffffffff;
}
PxU32 maxTetPerPartitions = 0;
PxU32 count = 0;
const PxU32 totalNumVerts = numElements* NumVertsPerElement;
PxU32 totalCopies = numVerts * maxAccumulatedCP;
simulationData.mGridModelNbPartitions = maximumPartitions;
simulationData.mGMRemapOutputSize = totalNumVerts + totalCopies;
////allocate enough memory for the verts and the accumulation buffer
//PxVec4* orderedVertsInMassCP = reinterpret_cast<PxVec4*>(PX_ALLOC(sizeof(PxVec4) * totalNumVerts, "mGMOrderedVertInvMassCP"));
//data.mGMOrderedVertInvMassCP = orderedVertsInMassCP;
//compute remap table
PxU32* remapOutput = PX_ALLOCATE(PxU32, simulationData.mGMRemapOutputSize, "remapOutput");
simulationData.mGMRemapOutputCP = remapOutput;
for (PxU32 i = 0; i < maximumPartitions; ++i)
{
PxU32 totalTets = 0;
for (PxU32 j = 0; j < maxAccumulatedPartitionsPerPartitions; ++j)
{
PxU32 partitionId = i + maximumPartitions * j;
if (partitionId < nbPartitions)
{
const PxU32 startInd = partitionId == 0 ? 0 : accumulatedTetrahedronPerPartition[partitionId - 1];
const PxU32 endInd = accumulatedTetrahedronPerPartition[partitionId];
for (PxU32 k = startInd; k < endInd; ++k)
{
const PxU32 tetraInd = orderedTetrahedrons[k];
tempOrderedTetrahedrons[count] = tetraInd;
PxU32 index = i * maxAccumulatedCP + j;
const PxI32* map = NULL;
const PxU32* tetInds = reinterpret_cast<const PxU32*>(&tetrahedrons[tetraInd]);
//If 5 tets are used per voxel, some voxels have a flipped tetrahedron configuration
//Tetmaker uses the following table to generate 5 tets per hex. The first row is the standard configuration, the second row the flipped config.
//To distinguish the two, a pattern must be found that is only present in one of the two configurations
//While 5 tets get created, this leads to 20 indices. The flipped configuration references the same vertex at indices[0] and indices[19] while
//the default config references different tets at indices[0] and indices[19]. This means that this comparsion can reliably detect flipped configurations.
//const PxU32 tets5PerVoxel[] = {
// 0, 6, 3, 5, 0, 1, 5, 3, 6, 7, 3, 5, 4, 5, 6, 0, 2, 3, 0, 6,
// 1, 7, 4, 2, 1, 0, 2, 4, 7, 6, 4, 2, 5, 4, 1, 7, 3, 2, 7, 1
bool flipped = tetInds[0] == tetInds[19];
if (numTetsPerElement == 6)
{
map = tetIndicesFromVoxels;
}
else
{
if (!flipped)
map = tetIndicesFromVoxelsA;
else
map = tetIndicesFromVoxelsB;
}
for (PxU32 v = 0; v < 4; ++v)
{
PxU32 vertInd = tetInds[map[v]];
tempPartitionTablePerVert[vertInd * partitionArraySize + index] = count + numElements * v;
if (lastRef[vertInd * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * count + v] = vertInd;
tempNumCopiesEachVerts[vertInd]++;
}
else
{
remapOutput[lastRef[vertInd * maxAccumulatedCP + j]] = count + v * numElements;
}
lastRef[vertInd * maxAccumulatedCP + j] = 4 * count + v;
}
for (PxU32 v = 0; v < 4; ++v)
{
//vertex index
PxU32 vertInd = tetInds[map[v+4]];
//Where the vertex data will be written to/read from
tempPartitionTablePerVert[vertInd * partitionArraySize + index] = count + numElements * (v+4);
if (lastRef[vertInd * maxAccumulatedCP + j] == 0xffffffff)
{
pullIndices[4 * (count + numElements) + v] = vertInd;
tempNumCopiesEachVerts[vertInd]++;
}
else
{
remapOutput[lastRef[vertInd * maxAccumulatedCP + j]] = count + (v+4) * numElements;
}
lastRef[vertInd * maxAccumulatedCP + j] = 4 * (numElements + count) + v;
}
if (numTetsPerElement == 5)
{
PxU32 ind = pullIndices[4 * count];
ind = setBit(ind, 31, flipped);
pullIndices[4 * count /*+ v*/] = ind;
}
count++;
}
totalTets += (endInd - startInd);
}
}
combineAccumulatedTetraPerPartitions[i] = count;
maxTetPerPartitions = PxMax(maxTetPerPartitions, totalTets);
}
//Last bit - output accumulation buffer...
PxU32 outIndex = 0;
for (PxU32 i = 0; i < numVerts; ++i)
{
for (PxU32 j = 0; j < maxAccumulatedCP; ++j)
{
if (lastRef[i * maxAccumulatedCP + j] != 0xffffffff)
{
remapOutput[lastRef[i * maxAccumulatedCP + j]] = totalNumVerts + outIndex++;
}
}
accumulatedCopiesEachVerts[i] = outIndex;
}
PX_ASSERT(count == numElements);
simulationData.mGridModelMaxTetsPerPartitions = maxTetPerPartitions;
simulationData.mGMPullIndices = pullIndices;
//If this commented out, we don't use combined partition anymore
PxMemCopy(orderedTetrahedrons, tempOrderedTetrahedrons, sizeof(PxU32) * numElements);
PX_FREE(tempNumCopiesEachVerts);
PX_FREE(tempOrderedTetrahedrons);
PX_FREE(tempPartitionTablePerVert);
PX_FREE(tempRemapTablePerVert);
PX_FREE(lastRef);
}
struct DistanceCheck
{
//input
PxVec3* mVerts;
IndTetrahedron32* mTetrahedron32;
PxVec3 mOriginalVert;
//output
PxU32 mTetInd;
PxReal mDistanceSq;
PxVec3 mClosestPoint;
//these data are for validation only
PxU32 mNbPrimsPerLeaf;
PxU32 mNbPrims;
};
static bool gDistanceNodeCheckCallback(const AABBTreeNode* current, void* userData)
{
DistanceCheck* Data = reinterpret_cast<DistanceCheck*>(userData);
const PxVec3& p = Data->mOriginalVert;
const AABBTreeNode* posNode = current->getPos();
const AABBTreeNode* negNode = current->getNeg();
PxReal distanceSqP = PX_MAX_F32;
if (posNode)
{
const PxBounds3& posAABB = posNode->getAABB();
const PxVec3 posClosest = posAABB.minimum.maximum(p.minimum(posAABB.maximum));
distanceSqP = (posClosest - p).magnitudeSquared();
}
PxReal distanceSqN = PX_MAX_F32;
if (negNode)
{
const PxBounds3& negAABB = negNode->getAABB();
const PxVec3 negClosest = negAABB.minimum.maximum(p.minimum(negAABB.maximum));
distanceSqN = (negClosest - p).magnitudeSquared();
}
return distanceSqP <= distanceSqN ? true : false;
}
static bool gDistanceCheckCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData)
{
DistanceCheck* Data = reinterpret_cast<DistanceCheck*>(userData);
const PxVec3& p = Data->mOriginalVert;
if (current->isLeaf())
{
const PxU32 n = current->getNbPrimitives();
PX_ASSERT(n <= Data->mNbPrimsPerLeaf);
PxU32* Prims = const_cast<PxU32*>(current->getPrimitives());
PX_UNUSED(Prims);
const PxVec3* verts = Data->mVerts;
for (PxU32 i = 0; i < n; i++)
{
PX_ASSERT(Prims[i] < Data->mNbPrims);
const PxU32 tetId = Prims[i];
const IndTetrahedron32& tetrahedron = Data->mTetrahedron32[tetId];
PX_UNUSED(tetrahedron);
const PxVec3 a = verts[tetrahedron.mRef[0]];
const PxVec3 b = verts[tetrahedron.mRef[1]];
const PxVec3 c = verts[tetrahedron.mRef[2]];
const PxVec3 d = verts[tetrahedron.mRef[3]];
//compute distance between the vert and the tetrahedron
const PxVec4 result = PointOutsideOfPlane4(p, a, b, c, d);
if (result.x >= 0.f && result.y >= 0.f && result.z >= 0.f && result.w >= 0.f)
{
//point is inside the tetrahedron
Data->mClosestPoint = closestPtPointTetrahedron(p, a, b, c, d);
Data->mDistanceSq = 0.f;
Data->mTetInd = tetId;
}
else
{
//point is outside the tetrahedron
const PxVec3 closestP = closestPtPointTetrahedron(p, a, b, c, d, result);
const PxReal distanceSq = (closestP - p).magnitudeSquared();
if (distanceSq < Data->mDistanceSq)
{
Data->mClosestPoint = closestP;
Data->mDistanceSq = distanceSq;
Data->mTetInd = tetId;
}
}
}
}
else
{
//compute distance
const PxBounds3& aabb = current->getAABB();
const PxVec3& min = aabb.minimum;
const PxVec3& max = aabb.maximum;
const PxVec3 closest = min.maximum(p.minimum(max));
PxReal distanceSq = (closest-p).magnitudeSquared();
if (distanceSq > Data->mDistanceSq)
return false;
}
return true;
}
struct OverlapCheck
{
//input
IndTetrahedron32 mColTetrahedron32;
PxVec3* mColMeshVerts;
PxBounds3 mColTetBound;
PxVec3* mSimMeshVerts;
IndTetrahedron32* mSimMeshTetra;
//output
PxArray<PxU32> mSimTetraIndices;
//these data are for validation only
PxU32 mNbPrimsPerLeaf;
PxU32 mNbPrims;
};
static bool gOverlapCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData)
{
OverlapCheck* Data = reinterpret_cast<OverlapCheck*>(userData);
const PxBounds3& bound = Data->mColTetBound;
if (current->isLeaf())
{
const PxU32 n = current->getNbPrimitives();
PX_ASSERT(n <= Data->mNbPrimsPerLeaf);
PxU32* Prims = const_cast<PxU32*>(current->getPrimitives());
PX_UNUSED(Prims);
const IndTetrahedron32& colTetInd = Data->mColTetrahedron32;
const PxVec3 a0 = Data->mColMeshVerts[colTetInd.mRef[0]];
const PxVec3 a1 = Data->mColMeshVerts[colTetInd.mRef[1]];
const PxVec3 a2 = Data->mColMeshVerts[colTetInd.mRef[2]];
const PxVec3 a3 = Data->mColMeshVerts[colTetInd.mRef[3]];
const PxVec3 center0 = (a0 + a1 + a2 + a3) * 0.25f;
TetrahedronV tetV(aos::V3LoadU(a0), aos::V3LoadU(a1), aos::V3LoadU(a2),
aos::V3LoadU(a3));
const LocalConvex<TetrahedronV> convexA(tetV);
aos::FloatV contactDist = aos::FLoad(1e-4f);
const PxVec3* verts = Data->mSimMeshVerts;
for (PxU32 i = 0; i < n; i++)
{
PX_ASSERT(Prims[i] < Data->mNbPrims);
const PxU32 tetId = Prims[i];
const IndTetrahedron32& tetrahedron = Data->mSimMeshTetra[tetId];
const PxVec3 b0 = verts[tetrahedron.mRef[0]];
const PxVec3 b1 = verts[tetrahedron.mRef[1]];
const PxVec3 b2 = verts[tetrahedron.mRef[2]];
const PxVec3 b3 = verts[tetrahedron.mRef[3]];
const PxVec3 center1 = (b0 + b1 + b2 + b3) * 0.25f;
const PxVec3 dir = center1 - center0;
TetrahedronV tetV2(aos::V3LoadU(b0), aos::V3LoadU(b1), aos::V3LoadU(b2),
aos::V3LoadU(b3));
tetV2.setMinMargin(aos::FEps());
const LocalConvex<TetrahedronV> convexB(tetV2);
GjkOutput output;
#ifdef USE_GJK_VIRTUAL
GjkStatus status = testGjk(convexA, convexB, aos::V3LoadU(dir), contactDist, output.closestA,
output.closestB, output.normal, output.penDep);
#else
GjkStatus status = gjk(convexA, convexB, aos::V3LoadU(dir), contactDist, output.closestA,
output.closestB, output.normal, output.penDep);
#endif
if (status == GjkStatus::GJK_CLOSE || status == GjkStatus::GJK_CONTACT)
{
Data->mSimTetraIndices.pushBack(tetId);
}
}
}
else
{
const PxBounds3& aabb = current->getAABB();
return bound.intersects(aabb);
}
return true;
}
void TetrahedronMeshBuilder::createCollisionModelMapping(const TetrahedronMeshData& collisionMesh, const SoftBodyCollisionData& collisionData, CollisionMeshMappingData& mappingData)
{
const PxU32 nbVerts = collisionMesh.mNbVertices;
mappingData.mCollisionAccumulatedTetrahedronsRef = PX_ALLOCATE(PxU32, nbVerts, "tetCounts");
PxU32* tempCounts = PX_ALLOCATE(PxU32, nbVerts, "tempCounts");
PxU32* tetCounts = mappingData.mCollisionAccumulatedTetrahedronsRef;
PxMemZero(tetCounts, sizeof(PxU32) * nbVerts);
PxMemZero(tempCounts, sizeof(PxU32) * nbVerts);
const PxU32 nbTetrahedrons = collisionMesh.mNbTetrahedrons;
IndTetrahedron32* tetra = reinterpret_cast<IndTetrahedron32*>(collisionData.mGRB_primIndices);
for (PxU32 i = 0; i < nbTetrahedrons; i++)
{
IndTetrahedron32& tet = tetra[i];
tetCounts[tet.mRef[0]]++;
tetCounts[tet.mRef[1]]++;
tetCounts[tet.mRef[2]]++;
tetCounts[tet.mRef[3]]++;
}
//compute runsum
PxU32 totalReference = 0;
for (PxU32 i = 0; i < nbVerts; ++i)
{
PxU32 originalReference = tetCounts[i];
tetCounts[i] = totalReference;
totalReference += originalReference;
}
mappingData.mCollisionTetrahedronsReferences = PX_ALLOCATE(PxU32, totalReference, "mGMMappedTetrahedrons");
mappingData.mCollisionNbTetrahedronsReferences = totalReference;
PxU32* tetrahedronRefs = mappingData.mCollisionTetrahedronsReferences;
for (PxU32 i = 0; i < nbTetrahedrons; i++)
{
IndTetrahedron32& tet = tetra[i];
const PxU32 ind0 = tet.mRef[0];
const PxU32 ind1 = tet.mRef[1];
const PxU32 ind2 = tet.mRef[2];
const PxU32 ind3 = tet.mRef[3];
tetrahedronRefs[tetCounts[ind0] + tempCounts[ind0]] = i;
tempCounts[ind0]++;
tetrahedronRefs[tetCounts[ind1] + tempCounts[ind1]] = i;
tempCounts[ind1]++;
tetrahedronRefs[tetCounts[ind2] + tempCounts[ind2]] = i;
tempCounts[ind2]++;
tetrahedronRefs[tetCounts[ind3] + tempCounts[ind3]] = i;
tempCounts[ind3]++;
}
PxVec3* verts = collisionMesh.mVertices;
PxU8* tetHint = reinterpret_cast<PxU8*>(collisionData.mGRB_tetraSurfaceHint);
IndTetrahedron32* surfaceTets = PX_ALLOCATE(IndTetrahedron32, nbTetrahedrons, "surfaceTets");
PxU8* surfaceVertsHint = PX_ALLOCATE(PxU8, nbVerts, "surfaceVertsHint");
PxU32* surfaceVertToTetRemap = PX_ALLOCATE(PxU32, nbVerts, "surfaceVertToTetRemap");
PxMemSet(surfaceVertsHint, 0, nbVerts);
PxU32 nbSurfaceTets = 0;
for (PxU32 i = 0; i < nbTetrahedrons; i++)
{
IndTetrahedron32& originalTet = tetra[i];
PxU8 hint = tetHint[i];
//This is a surface triangle
if (hint != 0)
{
IndTetrahedron32& tet = surfaceTets[nbSurfaceTets];
tet.mRef[0] = originalTet.mRef[0];
tet.mRef[1] = originalTet.mRef[1];
tet.mRef[2] = originalTet.mRef[2];
tet.mRef[3] = originalTet.mRef[3];
if (hint & 1) //0111
{
if (surfaceVertsHint[originalTet.mRef[0]] == 0)
{
surfaceVertsHint[originalTet.mRef[0]] = 1;
surfaceVertToTetRemap[originalTet.mRef[0]] = i;
}
if (surfaceVertsHint[originalTet.mRef[1]] == 0)
{
surfaceVertsHint[originalTet.mRef[1]] = 1;
surfaceVertToTetRemap[originalTet.mRef[1]] = i;
}
if (surfaceVertsHint[originalTet.mRef[2]] == 0)
{
surfaceVertsHint[originalTet.mRef[2]] = 1;
surfaceVertToTetRemap[originalTet.mRef[2]] = i;
}
}
if (hint & 2)//1011
{
if (surfaceVertsHint[originalTet.mRef[0]] == 0)
{
surfaceVertsHint[originalTet.mRef[0]] = 1;
surfaceVertToTetRemap[originalTet.mRef[0]] = i;
}
if (surfaceVertsHint[originalTet.mRef[1]] == 0)
{
surfaceVertsHint[originalTet.mRef[1]] = 1;
surfaceVertToTetRemap[originalTet.mRef[1]] = i;
}
if (surfaceVertsHint[originalTet.mRef[3]] == 0)
{
surfaceVertsHint[originalTet.mRef[3]] = 1;
surfaceVertToTetRemap[originalTet.mRef[3]] = i;
}
}
if (hint & 4) //1101
{
if (surfaceVertsHint[originalTet.mRef[0]] == 0)
{
surfaceVertsHint[originalTet.mRef[0]] = 1;
surfaceVertToTetRemap[originalTet.mRef[0]] = i;
}
if (surfaceVertsHint[originalTet.mRef[2]] == 0)
{
surfaceVertsHint[originalTet.mRef[2]] = 1;
surfaceVertToTetRemap[originalTet.mRef[2]] = i;
}
if (surfaceVertsHint[originalTet.mRef[3]] == 0)
{
surfaceVertsHint[originalTet.mRef[3]] = 1;
surfaceVertToTetRemap[originalTet.mRef[3]] = i;
}
}
if (hint & 8)//1110
{
if (surfaceVertsHint[originalTet.mRef[1]] == 0)
{
surfaceVertsHint[originalTet.mRef[1]] = 1;
surfaceVertToTetRemap[originalTet.mRef[1]] = i;
}
if (surfaceVertsHint[originalTet.mRef[2]] == 0)
{
surfaceVertsHint[originalTet.mRef[2]] = 1;
surfaceVertToTetRemap[originalTet.mRef[2]] = i;
}
if (surfaceVertsHint[originalTet.mRef[3]] == 0)
{
surfaceVertsHint[originalTet.mRef[3]] = 1;
surfaceVertToTetRemap[originalTet.mRef[3]] = i;
}
}
nbSurfaceTets++;
}
}
PxU32 numSurfaceVerts = 0;
for (PxU32 i = 0; i < nbVerts; ++i)
{
PxU32 hint = surfaceVertsHint[i];
if (hint)
numSurfaceVerts++;
}
mappingData.mCollisionSurfaceVertsHint = PX_ALLOCATE(PxU8, nbVerts, "mCollisionSurfaceVertsHint");
mappingData.mCollisionSurfaceVertToTetRemap = PX_ALLOCATE(PxU32, nbVerts, "mCollisionSurfaceVertToTetRemap");
PxMemCopy(mappingData.mCollisionSurfaceVertsHint, surfaceVertsHint, sizeof(PxU8)*nbVerts);
PxMemCopy(mappingData.mCollisionSurfaceVertToTetRemap, surfaceVertToTetRemap, sizeof(PxU32)*nbVerts);
//Build the tree based on surface tetra
TetrahedronSourceMesh meshInterface;
// const PxReal gBoxEpsilon = 0.1f;
meshInterface.initRemap();
meshInterface.setNbVertices(collisionMesh.mNbVertices);
meshInterface.setNbTetrahedrons(nbSurfaceTets);
meshInterface.setPointers(surfaceTets, NULL, verts);
const PxU32 nbPrimsPerLeaf = 4;
BV4_AABBTree aabbTree;
if (!aabbTree.buildFromMesh(meshInterface, nbPrimsPerLeaf))
{
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "BV4_AABBTree tree failed to build.");
return;
}
PX_FREE(tempCounts);
PX_FREE(surfaceTets);
PX_FREE(surfaceVertsHint);
PX_FREE(surfaceVertToTetRemap);
}
/*//Keep for debugging & verification
void writeTets(const char* path, const PxVec3* tetPoints, PxU32 numPoints, const IndTetrahedron32* tets, PxU32 numTets)
{
FILE *fp;
fp = fopen(path, "w+");
fprintf(fp, "# Tetrahedral mesh generated using\n\n");
fprintf(fp, "# %d vertices\n", numPoints);
for (PxU32 i = 0; i < numPoints; ++i)
{
fprintf(fp, "v %f %f %f\n", PxF64(tetPoints[i].x), PxF64(tetPoints[i].y), PxF64(tetPoints[i].z));
}
fprintf(fp, "\n");
fprintf(fp, "# %d tetrahedra\n", numTets);
for (PxU32 i = 0; i < numTets; ++i)
{
fprintf(fp, "t %d %d %d %d\n", tets[i].mRef[0], tets[i].mRef[1], tets[i].mRef[2], tets[i].mRef[3]);
}
fclose(fp);
}*/
void TetrahedronMeshBuilder::computeModelsMapping(TetrahedronMeshData& simulationMesh,
const TetrahedronMeshData& collisionMesh, const SoftBodyCollisionData& collisionData,
CollisionMeshMappingData& mappingData, bool buildGPUData, const PxBoundedData* vertexToTet)
{
createCollisionModelMapping(collisionMesh, collisionData, mappingData);
if (buildGPUData)
{
const PxU32 gridModelNbVerts = simulationMesh.mNbVertices;
PxVec3* gridModelVertices = PX_ALLOCATE(PxVec3, gridModelNbVerts, "gridModelVertices");
PxVec3* gridModelVerticesInvMass = simulationMesh.mVertices;
for (PxU32 i = 0; i < gridModelNbVerts; ++i)
{
gridModelVertices[i] = gridModelVerticesInvMass[i];
}
PX_ASSERT(!(collisionMesh.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
TetrahedronSourceMesh meshInterface;
// const PxReal gBoxEpsilon = 0.1f;
meshInterface.initRemap();
meshInterface.setNbVertices(simulationMesh.mNbVertices);
meshInterface.setNbTetrahedrons(simulationMesh.mNbTetrahedrons);
IndTetrahedron32* tetrahedron32 = reinterpret_cast<IndTetrahedron32*>(simulationMesh.mTetrahedrons);
meshInterface.setPointers(tetrahedron32, NULL, gridModelVertices);
//writeTets("C:\\tmp\\grid.tet", gridModelVertices, simulationMesh.mNbVertices, tetrahedron32, simulationMesh.mNbTetrahedrons);
//writeTets("C:\\tmp\\col.tet", mVertices, mNbVertices, reinterpret_cast<IndTetrahedron32*>(mTetrahedrons), mNbTetrahedrons);
const PxU32 nbPrimsPerLeaf = 2;
BV4_AABBTree aabbTree;
if (!aabbTree.buildFromMesh(meshInterface, nbPrimsPerLeaf))
{
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "BV32 tree failed to build.");
return;
}
const PxU32 nbTetModelVerts = collisionMesh.mNbVertices;
mappingData.mVertsBarycentricInGridModel = reinterpret_cast<PxReal*>(PX_ALLOC(nbTetModelVerts * sizeof(PxReal) * 4, "mVertsInfoMapOriginalGridModel"));
mappingData.mVertsRemapInGridModel = reinterpret_cast<PxU32*>(PX_ALLOC(nbTetModelVerts * sizeof(PxU32), "mVertsRemapInGridModel"));
PxReal* vertsBarycentricInGridModel = mappingData.mVertsBarycentricInGridModel;
PxU32* vertsRemapInGridModel = mappingData.mVertsRemapInGridModel;
if (vertexToTet && vertexToTet->count == nbTetModelVerts)
{
for (PxU32 i = 0; i < nbTetModelVerts; ++i)
{
vertsRemapInGridModel[i] = vertexToTet->at<PxU32>(i);
const PxVec3& p = collisionMesh.mVertices[i];
IndTetrahedron32& tetra = tetrahedron32[vertsRemapInGridModel[i]];
const PxVec3& a = gridModelVertices[tetra.mRef[0]];
const PxVec3& b = gridModelVertices[tetra.mRef[1]];
const PxVec3& c = gridModelVertices[tetra.mRef[2]];
const PxVec3& d = gridModelVertices[tetra.mRef[3]];
PxVec4 bary;
computeBarycentric(a, b, c, d, p, bary);
#if PX_DEBUG
const PxReal eps = 1e-4f;
PX_ASSERT((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) &&
(bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps));
PX_ASSERT(vertexToTet->at<PxI32>(i) >= 0);
#endif
const PxU32 index = i * 4;
vertsBarycentricInGridModel[index] = bary.x;
vertsBarycentricInGridModel[index + 1] = bary.y;
vertsBarycentricInGridModel[index + 2] = bary.z;
vertsBarycentricInGridModel[index + 3] = bary.w;
}
}
else
{
for (PxU32 i = 0; i < nbTetModelVerts; ++i)
{
DistanceCheck result;
result.mVerts = gridModelVertices;
result.mTetrahedron32 = tetrahedron32;
result.mOriginalVert = collisionMesh.mVertices[i];
result.mDistanceSq = PX_MAX_F32;
result.mNbPrimsPerLeaf = 2;
result.mNbPrims = simulationMesh.mNbTetrahedrons;
aabbTree.walkDistance(gDistanceCheckCallback, gDistanceNodeCheckCallback, &result);
IndTetrahedron32& tetra = tetrahedron32[result.mTetInd];
const PxVec3& a = gridModelVertices[tetra.mRef[0]];
const PxVec3& b = gridModelVertices[tetra.mRef[1]];
const PxVec3& c = gridModelVertices[tetra.mRef[2]];
const PxVec3& d = gridModelVertices[tetra.mRef[3]];
PxVec4 bary;
computeBarycentric(a, b, c, d, result.mOriginalVert, bary);
#if PX_DEBUG
const PxReal eps = 1e-4f;
PX_ASSERT((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) &&
(bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps));
#endif
const PxU32 index = i * 4;
vertsBarycentricInGridModel[index] = bary.x;
vertsBarycentricInGridModel[index + 1] = bary.y;
vertsBarycentricInGridModel[index + 2] = bary.z;
vertsBarycentricInGridModel[index + 3] = bary.w;
vertsRemapInGridModel[i] = result.mTetInd;
}
}
PxU16* colMaterials = collisionMesh.mMaterialIndices;
PxU16* simMaterials = NULL;
const PxU32 nbSimMeshTetra = simulationMesh.mNbTetrahedrons;
if (colMaterials)
{
simMaterials = simulationMesh.allocateMaterials();
for (PxU32 i = 0; i < nbSimMeshTetra; ++i)
{
simMaterials[i] = 0xffff;
}
}
const PxU32 nbColMeshTetra = collisionMesh.mNbTetrahedrons;
PxArray<PxU32> tetIndiceRunSum;
tetIndiceRunSum.reserve(nbColMeshTetra * 4);
mappingData.mTetsAccumulatedRemapColToSim = reinterpret_cast<PxU32*>( PX_ALLOC(sizeof(PxU32) * nbColMeshTetra, "mTetsAccumulatedRemapColToSim"));
PxU32* runSum = mappingData.mTetsAccumulatedRemapColToSim;
PxU32 offset = 0;
IndTetrahedron32* colTetra = reinterpret_cast<IndTetrahedron32*>(collisionData.mGRB_primIndices);
OverlapCheck result;
result.mSimTetraIndices.reserve(100);
//IndTetrahedron32* simTetra = reinterpret_cast<IndTetrahedron32*>(simulationMesh.mTetrahedrons);
for (PxU32 i = 0; i < nbColMeshTetra; ++i)
{
IndTetrahedron32& tetInd = colTetra[i];
const PxVec3 a = collisionMesh.mVertices[tetInd.mRef[0]];
const PxVec3 b = collisionMesh.mVertices[tetInd.mRef[1]];
const PxVec3 c = collisionMesh.mVertices[tetInd.mRef[2]];
const PxVec3 d = collisionMesh.mVertices[tetInd.mRef[3]];
const PxVec3 max = a.maximum(b.maximum(c.maximum(d)));
const PxVec3 min = a.minimum(b.minimum(c.minimum(d)));
PxBounds3 bound(min, max);
result.mSimTetraIndices.forceSize_Unsafe(0);
result.mColMeshVerts = collisionMesh.mVertices;
result.mColTetBound = bound;
result.mColTetrahedron32 = tetInd;
result.mSimMeshTetra = tetrahedron32;
result.mSimMeshVerts = gridModelVertices;
result.mNbPrimsPerLeaf = 2;
result.mNbPrims = simulationMesh.mNbTetrahedrons;
aabbTree.walk(gOverlapCallback, &result);
const PxU32 size = result.mSimTetraIndices.size();
PX_ASSERT(size > 0);
for (PxU32 j = 0; j < size; ++j)
{
const PxU32 simTetraInd = result.mSimTetraIndices[j];
if (simMaterials && simMaterials[simTetraInd] == 0xffff)
simMaterials[simTetraInd] = colMaterials[i];
tetIndiceRunSum.pushBack(simTetraInd);
}
offset += size;
runSum[i] = offset;
}
if (simMaterials)
{
//loop through all the simMaterials to make sure material indices has valid material index. If not,
//we will use the first material index for the tet materials
for (PxU32 i = 0; i < nbSimMeshTetra; ++i)
{
if (simMaterials[i] == 0xffff)
simMaterials[i] = 0;
}
}
mappingData.mTetsRemapSize = tetIndiceRunSum.size();
mappingData.mTetsRemapColToSim = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mappingData.mTetsRemapSize, "mTetsRemapInSimModel"));
PxMemCopy(mappingData.mTetsRemapColToSim, tetIndiceRunSum.begin(), sizeof(PxU32) * mappingData.mTetsRemapSize);
#if PX_DEBUG
for (PxU32 i = 0; i < tetIndiceRunSum.size(); ++i)
{
PX_ASSERT(tetIndiceRunSum[i] < 0xFFFFFFFF);
}
for (PxU32 i = 1; i < collisionMesh.mNbTetrahedrons; ++i)
{
PX_ASSERT(runSum[i - 1] < runSum[i]);
}
#endif
PX_FREE(gridModelVertices);
}
}
PX_FORCE_INLINE PxF32 tetVolume(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d)
{
return (-1.0f / 6.0f) * (a - d).dot((b - d).cross(c - d));
}
template<class T>
static void writeToSimTetraIndice(const T* tetIndices, const PxVec3* verts, TetrahedronT<PxU32>* dest)
{
const PxVec3 a = verts[tetIndices[0]];
const PxVec3 b = verts[tetIndices[1]];
const PxVec3 c = verts[tetIndices[2]];
const PxVec3 d = verts[tetIndices[3]];
if (tetVolume(a, b, c, d) < 0.f)
{
dest->v[0] = tetIndices[1];
dest->v[1] = tetIndices[0];
dest->v[2] = tetIndices[2];
dest->v[3] = tetIndices[3];
}
else
{
dest->v[0] = tetIndices[0];
dest->v[1] = tetIndices[1];
dest->v[2] = tetIndices[2];
dest->v[3] = tetIndices[3];
}
}
void TetrahedronMeshBuilder::computeTetData(const PxTetrahedronMeshDesc& desc, TetrahedronMeshData& mesh)
{
const PxU32 tetMeshNbPoints = desc.points.count;
const PxU32 tetMeshNbTets = desc.tetrahedrons.count;
mesh.mNbVertices = tetMeshNbPoints;
mesh.mVertices = PX_ALLOCATE(PxVec3, tetMeshNbPoints, "mVertices");
mesh.mNbTetrahedrons = tetMeshNbTets;
mesh.mTetrahedrons = PX_ALLOC(tetMeshNbTets * sizeof(TetrahedronT<PxU32>), "mTetrahedrons");
mesh.mFlags = desc.flags; //TODO: flags are not of same type...
computeLocalBoundsAndGeomEpsilon(mesh.mVertices, tetMeshNbPoints, mesh.mAABB, mesh.mGeomEpsilon);
}
bool transferMass(PxI32 a, PxI32 b, PxArray<PxReal>& newMasses, const PxReal* mass, PxReal maxRatio, PxReal smoothingSpeed)
{
const PxReal mA = mass[a];
const PxReal mB = mass[b];
const PxReal ratio = PxMax(mA, mB) / PxMin(mA, mB);
if (ratio > maxRatio)
{
const PxReal delta = smoothingSpeed * PxMin(mA, mB);
if (mA > mB)
{
newMasses[a] -= delta;
newMasses[b] += delta;
}
else
{
newMasses[a] += delta;
newMasses[b] -= delta;
}
return true;
}
return false;
}
void smoothMassRatiosWhilePreservingTotalMass( PxReal* massPerNode, PxU32 numNodes, const PxU32* tets, PxI32 numTets, PxReal maxRatio /*= 2.0f*/, PxReal smoothingSpeed = 0.25f)
{
if (maxRatio == FLT_MAX)
return;
PxArray<PxReal> newMasses;
newMasses.resize(numNodes);
for (PxU32 i = 0; i < numNodes; ++i)
newMasses[i] = massPerNode[i];
const PxU32 tetEdges[6][2] = { {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3} };
PxU32 l = 4 * numTets;
PxU32 counter = 0;
bool success = true;
while (success)
{
++counter;
success = false;
for (PxU32 i = 0; i < l; i += 4)
{
for (PxU32 j = 0; j < 6; ++j)
success = success || transferMass(tets[i + tetEdges[j][0]], tets[i + tetEdges[j][1]], newMasses, massPerNode, maxRatio, smoothingSpeed);
}
for (PxU32 i = 0; i < numNodes; ++i)
massPerNode[i] = newMasses[i];
if (counter > 100000)
break;
}
//printf("%i", counter);
}
void TetrahedronMeshBuilder::computeSimData(const PxTetrahedronMeshDesc& desc, TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData, const PxCookingParams& params)
{
const PxU32 simTetMeshNbPoints = desc.points.count;
const PxU32 simTetMeshNbTets = desc.tetrahedrons.count;
simulationMesh.mNbVertices = simTetMeshNbPoints;
simulationMesh.mVertices = reinterpret_cast<PxVec3*>(PX_ALLOC(simTetMeshNbPoints * sizeof(PxVec3), "mGridModelVertices"));
simulationData.mGridModelInvMass = reinterpret_cast<PxReal*>(PX_ALLOC(simTetMeshNbPoints * sizeof(PxReal), "mGridModelInvMass"));
simulationMesh.mNbTetrahedrons = simTetMeshNbTets;
simulationMesh.mTetrahedrons = PX_ALLOC(simTetMeshNbTets * sizeof(TetrahedronT<PxU32>), "mGridModelTetrahedrons");
simulationData.mNumTetsPerElement = desc.tetsPerElement;
immediateCooking::gatherStrided(desc.points.data, simulationMesh.mVertices, simTetMeshNbPoints, sizeof(PxVec3), desc.points.stride);
TetrahedronT<PxU32>* gridModelTetrahedrons = reinterpret_cast<TetrahedronT<PxU32>*>(simulationMesh.mTetrahedrons);
for (PxU32 i = 0; i < simTetMeshNbPoints; ++i)
simulationData.mGridModelInvMass[i] = 0;
TetrahedronT<PxU32>* dest = gridModelTetrahedrons;
const TetrahedronT<PxU32>* pastLastDest = gridModelTetrahedrons + simTetMeshNbTets;
const PxU8* source = reinterpret_cast<const PxU8*>(desc.tetrahedrons.data);
if (desc.flags & PxMeshFlag::e16_BIT_INDICES)
{
while (dest < pastLastDest)
{
const PxU16* tet16 = reinterpret_cast<const PxU16*>(source);
writeToSimTetraIndice<PxU16>(tet16, simulationMesh.mVertices, dest);
dest++;
source += desc.tetrahedrons.stride;
}
}
else
{
while (dest < pastLastDest)
{
const PxU32* tet32 = reinterpret_cast<const PxU32*>(source);
writeToSimTetraIndice<PxU32>(tet32, simulationMesh.mVertices, dest);
dest++;
source += desc.tetrahedrons.stride;
}
}
simulationData.mGridModelTetraRestPoses = PX_ALLOCATE(PxMat33, desc.tetrahedrons.count, "mGridModelTetraRestPoses");
computeRestPoseAndPointMass(gridModelTetrahedrons, simulationMesh.mNbTetrahedrons,
simulationMesh.mVertices, simulationData.mGridModelInvMass, simulationData.mGridModelTetraRestPoses);
PxU32* accumulatedTetrahedronPerPartition = computeGridModelTetrahedronPartitions(simulationMesh, simulationData);
if (simulationData.mNumTetsPerElement == 1)
combineGridModelPartitions(simulationMesh, simulationData, &accumulatedTetrahedronPerPartition);
else
combineGridModelPartitionsHexMesh(simulationMesh, simulationData, &accumulatedTetrahedronPerPartition, simulationData.mNumTetsPerElement);
smoothMassRatiosWhilePreservingTotalMass(simulationData.mGridModelInvMass, simulationMesh.mNbVertices, reinterpret_cast<PxU32*>(gridModelTetrahedrons), simulationMesh.mNbTetrahedrons, params.maxWeightRatioInTet);
#if PX_DEBUG
PxReal max = 0;
PxReal min = FLT_MAX;
for (PxU32 i = 0; i < simulationMesh.mNbVertices; ++i)
{
PxReal w = simulationData.mGridModelInvMass[i];
max = PxMax(w, max);
min = PxMin(w, min);
}
PxReal ratio = max / min;
PX_UNUSED(ratio);
#endif
for (PxU32 i = 0; i < simulationMesh.mNbVertices; ++i)
{
simulationData.mGridModelInvMass[i] = 1.0f / simulationData.mGridModelInvMass[i];
}
PX_FREE(accumulatedTetrahedronPerPartition);
//const PxU32 gridModelNbVerts = simulationMesh.mNbVertices;
//PxVec3* gridModelVertices = reinterpret_cast<PxVec3*>(PX_ALLOC(gridModelNbVerts * sizeof(PxVec3), "gridModelVertices"));
//PxVec4* gridModelVerticesInvMass = simulationMesh.mVerticesInvMass;
//for (PxU32 i = 0; i < gridModelNbVerts; ++i)
//{
// gridModelVertices[i] = gridModelVerticesInvMass[i].getXYZ();
//}
//writeTets("C:\\tmp\\grid.tet", gridModelVertices, simulationMesh.mNbVertices, reinterpret_cast<IndTetrahedron32*>(simulationMesh.mTetrahedrons), simulationMesh.mNbTetrahedrons);
//writeTets("C:\\tmp\\col.tet", mVertices, mNbVertices, reinterpret_cast<IndTetrahedron32*>(mTetrahedrons), mNbTetrahedrons);
//PX_FREE(gridModelVertices);
}
bool TetrahedronMeshBuilder::computeCollisionData(const PxTetrahedronMeshDesc& collisionMeshDesc, TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData,
const PxCookingParams& params, bool validateMesh)
{
const PxU32 originalTetrahedronCount = collisionMeshDesc.tetrahedrons.count;
// Create a local copy that we can modify
PxTetrahedronMeshDesc desc = collisionMeshDesc;
// Save simple params
{
// Handle implicit topology
PxU32* topology = NULL;
if (!desc.tetrahedrons.data)
{
// We'll create 32-bit indices
desc.flags &= ~PxMeshFlag::e16_BIT_INDICES;
desc.tetrahedrons.stride = sizeof(PxU32) * 4;
{
// Non-indexed mesh => create implicit topology
desc.tetrahedrons.count = desc.points.count / 4;
// Create default implicit topology
topology = PX_ALLOCATE(PxU32, desc.points.count, "topology");
for (PxU32 i = 0; i < desc.points.count; i++)
topology[i] = i;
desc.tetrahedrons.data = topology;
}
}
// Continue as usual using our new descriptor
// Convert and clean the input mesh
if (!importMesh(collisionMeshDesc, params, collisionMesh, collisionData, validateMesh))
{
PX_FREE(topology);
return false;
}
// Cleanup if needed
PX_FREE(topology);
}
//copy the original tetrahedron indices to grb tetrahedron indices if buildGRBData is true
if(!createMidPhaseStructure(collisionMesh, collisionData, params))
return false;
recordTetrahedronIndices(collisionMesh, collisionData, params.buildGPUData);
// Compute local bounds
computeLocalBoundsAndGeomEpsilon(collisionMesh.mVertices, collisionMesh.mNbVertices, collisionMesh.mAABB, collisionMesh.mGeomEpsilon);
if(!createGRBMidPhaseAndData(originalTetrahedronCount, collisionMesh, collisionData, params))
return false;
// Use collisionData.mGRB_primIndices rather than collisionMesh.mTetrahedrons: we want rest poses for the topology-remapped mesh, which is the actual one in simulation.
computeRestPoseAndPointMass(reinterpret_cast<TetrahedronT<PxU32>*>(collisionData.mGRB_primIndices), collisionMesh.mNbTetrahedrons, collisionMesh.mVertices, NULL, collisionData.mTetraRestPoses);
return true;
}
bool TetrahedronMeshBuilder::loadFromDesc(const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
PxSoftBodySimulationDataDesc softbodyDataDesc, TetrahedronMeshData& simulationMesh, SoftBodySimulationData& simulationData,
TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, CollisionMeshMappingData& mappingData, const PxCookingParams& params, bool validateMesh)
{
if (!simulationMeshDesc.isValid() || !collisionMeshDesc.isValid() || !softbodyDataDesc.isValid())
return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "TetrahedronMesh::loadFromDesc: desc.isValid() failed!");
// verify the mesh params
if (!params.midphaseDesc.isValid())
return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "TetrahedronMesh::loadFromDesc: mParams.midphaseDesc.isValid() failed!");
if (!computeCollisionData(collisionMeshDesc, collisionMesh, collisionData, params, validateMesh))
return false;
computeSimData(simulationMeshDesc, simulationMesh, simulationData, params);
computeModelsMapping(simulationMesh, collisionMesh, collisionData, mappingData, params.buildGPUData, &softbodyDataDesc.vertexToTet);
#if PX_DEBUG
for (PxU32 i = 0; i < collisionMesh.mNbVertices; ++i) {
PX_ASSERT(mappingData.mVertsRemapInGridModel[i] < simulationMesh.mNbTetrahedrons);
}
#endif
return true;
}
static void writeIndice(const PxU32 serialFlags, const PxU32* indices, const PxU32 nbIndices,
const bool platformMismatch, PxOutputStream& stream)
{
//write out tetrahedron indices
if (serialFlags & IMSF_8BIT_INDICES)
{
for (PxU32 i = 0; i < nbIndices; i++)
{
PxI8 data = PxI8(indices[i]);
stream.write(&data, sizeof(PxU8));
}
}
else if (serialFlags & IMSF_16BIT_INDICES)
{
for (PxU32 i = 0; i < nbIndices; i++)
writeWord(PxTo16(indices[i]), platformMismatch, stream);
}
else
{
writeIntBuffer(indices, nbIndices, platformMismatch, stream);
}
}
bool TetrahedronMeshBuilder::saveTetrahedronMeshData(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params, const TetrahedronMeshData& mesh)
{
// Export header
if (!writeHeader('T', 'E', 'M', 'E', PX_TET_MESH_VERSION, platformMismatch, stream))
return false;
// Export serialization flags
PxU32 serialFlags = 0;
// Compute serialization flags for indices
PxU32 maxIndex = 0;
const TetrahedronT<PxU32>* tets = reinterpret_cast<const TetrahedronT<PxU32>*>(mesh.mTetrahedrons);
for (PxU32 i = 0; i < mesh.mNbTetrahedrons; i++)
{
if (tets[i].v[0] > maxIndex) maxIndex = tets[i].v[0];
if (tets[i].v[1] > maxIndex) maxIndex = tets[i].v[1];
if (tets[i].v[2] > maxIndex) maxIndex = tets[i].v[2];
if (tets[i].v[3] > maxIndex) maxIndex = tets[i].v[3];
}
bool force32 = (params.meshPreprocessParams & PxMeshPreprocessingFlag::eFORCE_32BIT_INDICES);
if (maxIndex <= 0xFFFF && !force32)
serialFlags |= (maxIndex <= 0xFF ? IMSF_8BIT_INDICES : IMSF_16BIT_INDICES);
writeDword(serialFlags, platformMismatch, stream);
// Export mesh
writeDword(mesh.mNbVertices, platformMismatch, stream);
//writeDword(collisionData.mNbSurfaceTriangles, platformMismatch, stream);
writeDword(mesh.mNbTetrahedrons, platformMismatch, stream);
writeFloatBuffer(&mesh.mVertices->x, mesh.mNbVertices * 3, platformMismatch, stream);
const PxU32 nbTetIndices = mesh.mNbTetrahedrons * 4;
//write out tetrahedron indices
writeIndice(serialFlags, tets->v, nbTetIndices, platformMismatch, stream);
// Export local bounds
writeFloat(mesh.mGeomEpsilon, platformMismatch, stream);
writeFloat(mesh.mAABB.minimum.x, platformMismatch, stream);
writeFloat(mesh.mAABB.minimum.y, platformMismatch, stream);
writeFloat(mesh.mAABB.minimum.z, platformMismatch, stream);
writeFloat(mesh.mAABB.maximum.x, platformMismatch, stream);
writeFloat(mesh.mAABB.maximum.y, platformMismatch, stream);
writeFloat(mesh.mAABB.maximum.z, platformMismatch, stream);
return true;
}
bool TetrahedronMeshBuilder::saveSoftBodyMeshData(PxOutputStream& stream, bool platformMismatch, const PxCookingParams& params,
const TetrahedronMeshData& simulationMesh, const SoftBodySimulationData& simulationData, const TetrahedronMeshData& collisionMesh,
const SoftBodyCollisionData& collisionData, const CollisionMeshMappingData& mappingData)
{
// Export header
if (!writeHeader('S', 'O', 'M', 'E', PX_SOFTBODY_MESH_VERSION, platformMismatch, stream))
return false;
// Export serialization flags
PxU32 serialFlags = 0;
if (collisionMesh.mMaterialIndices) serialFlags |= IMSF_MATERIALS;
if (collisionData.mFaceRemap) serialFlags |= IMSF_FACE_REMAP;
//if (mTetraSurfaceHint) serialFlags |= IMSF_ADJACENCIES; // using IMSF_ADJACENCIES to represent surfaceHint for tetrahedron mesh
//if (mAdjacencies) serialFlags |= IMSF_ADJACENCIES;
if (params.buildGPUData) serialFlags |= IMSF_GRB_DATA;
// Compute serialization flags for indices
PxU32 maxIndex = 0;
const TetrahedronT<PxU32>* tets = reinterpret_cast<const TetrahedronT<PxU32>*>(collisionMesh.mTetrahedrons);
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; i++)
{
if (tets[i].v[0] > maxIndex) maxIndex = tets[i].v[0];
if (tets[i].v[1] > maxIndex) maxIndex = tets[i].v[1];
if (tets[i].v[2] > maxIndex) maxIndex = tets[i].v[2];
if (tets[i].v[3] > maxIndex) maxIndex = tets[i].v[3];
}
const TetrahedronT<PxU32>* gridModelTets = reinterpret_cast<const TetrahedronT<PxU32>*>(simulationMesh.mTetrahedrons);
for (PxU32 i = 0; i < simulationMesh.mNbTetrahedrons; i++)
{
if (gridModelTets[i].v[0] > maxIndex) maxIndex = gridModelTets[i].v[0];
if (gridModelTets[i].v[1] > maxIndex) maxIndex = gridModelTets[i].v[1];
if (gridModelTets[i].v[2] > maxIndex) maxIndex = gridModelTets[i].v[2];
if (gridModelTets[i].v[3] > maxIndex) maxIndex = gridModelTets[i].v[3];
}
bool force32 = (params.meshPreprocessParams & PxMeshPreprocessingFlag::eFORCE_32BIT_INDICES);
if (maxIndex <= 0xFFFF && !force32)
serialFlags |= (maxIndex <= 0xFF ? IMSF_8BIT_INDICES : IMSF_16BIT_INDICES);
writeDword(serialFlags, platformMismatch, stream);
// Export mesh
writeDword(collisionMesh.mNbVertices, platformMismatch, stream);
//writeDword(collisionData.mNbSurfaceTriangles, platformMismatch, stream);
writeDword(collisionMesh.mNbTetrahedrons, platformMismatch, stream);
writeFloatBuffer(&collisionMesh.mVertices->x, collisionMesh.mNbVertices * 3, platformMismatch, stream);
const PxU32 nbTetIndices = collisionMesh.mNbTetrahedrons * 4;
//write out tetrahedron indices
writeIndice(serialFlags, tets->v, nbTetIndices, platformMismatch, stream);
//const PxU32 nbSurfaceTriangleIndices = collisionData.mNbSurfaceTriangles * 3;
//const IndexedTriangle32* surfaceTriangles = reinterpret_cast<const IndexedTriangle32*>(collisionData.mSurfaceTriangles);
//write out surface triangle indices
//writeIndice(serialFlags, surfaceTriangles->v, nbSurfaceTriangleIndices, platformMismatch, stream);
if (collisionMesh.mMaterialIndices)
writeWordBuffer(collisionMesh.mMaterialIndices, collisionMesh.mNbTetrahedrons, platformMismatch, stream);
if (collisionData.mFaceRemap)
{
PxU32 maxId = computeMaxIndex(collisionData.mFaceRemap, collisionMesh.mNbTetrahedrons);
writeDword(maxId, platformMismatch, stream);
storeIndices(maxId, collisionMesh.mNbTetrahedrons, collisionData.mFaceRemap, stream, platformMismatch);
// writeIntBuffer(mMeshData.mFaceRemap, mMeshData.mNbTriangles, platformMismatch, stream);
}
/* if (mAdjacencies)
writeIntBuffer(mAdjacencies, mNbTetrahedrons * 4, platformMismatch, stream);*/
// Export midphase structure
saveMidPhaseStructure(stream, platformMismatch, collisionData);
// Export local bounds
writeFloat(collisionMesh.mGeomEpsilon, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.minimum.x, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.minimum.y, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.minimum.z, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.maximum.x, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.maximum.y, platformMismatch, stream);
writeFloat(collisionMesh.mAABB.maximum.z, platformMismatch, stream);
// GRB write -----------------------------------------------------------------
if (params.buildGPUData)
{
const PxU32* tetIndices = reinterpret_cast<PxU32*>(collisionData.mGRB_primIndices);
writeIndice(serialFlags, tetIndices, nbTetIndices, platformMismatch, stream);
//writeIntBuffer(reinterpret_cast<PxU32*>(mMeshData.mGRB_triIndices), , mMeshData.mNbTriangles*3, platformMismatch, stream);
//writeIntBuffer(reinterpret_cast<PxU32 *>(mGRB_surfaceTriIndices), mNbTriangles*3, platformMismatch, stream);
stream.write(collisionData.mGRB_tetraSurfaceHint, collisionMesh.mNbTetrahedrons * sizeof(PxU8));
//writeIntBuffer(reinterpret_cast<PxU32 *>(mGRB_primAdjacencies), mNbTetrahedrons * 4, platformMismatch, stream);
writeIntBuffer(collisionData.mGRB_faceRemap, collisionMesh.mNbTetrahedrons, platformMismatch, stream);
writeIntBuffer(collisionData.mGRB_faceRemapInverse, collisionMesh.mNbTetrahedrons, platformMismatch, stream);
stream.write(collisionData.mTetraRestPoses, collisionMesh.mNbTetrahedrons * sizeof(PxMat33));
//Export GPU midphase structure
BV32TriangleMeshBuilder::saveMidPhaseStructure(collisionData.mGRB_BV32Tree, stream, platformMismatch);
writeDword(simulationMesh.mNbTetrahedrons, platformMismatch, stream);
writeDword(simulationMesh.mNbVertices, platformMismatch, stream);
writeDword(simulationData.mGridModelNbPartitions, platformMismatch, stream);
writeDword(simulationData.mGridModelMaxTetsPerPartitions, platformMismatch, stream);
writeDword(simulationData.mGMRemapOutputSize, platformMismatch, stream);
writeDword(simulationData.mNumTetsPerElement, platformMismatch, stream);
writeDword(mappingData.mCollisionNbTetrahedronsReferences, platformMismatch, stream);
writeDword(mappingData.mTetsRemapSize, platformMismatch, stream);
const PxU32 nbGridModeIndices = 4 * simulationMesh.mNbTetrahedrons;
const PxU32* gridModelTetIndices = reinterpret_cast<PxU32*>(simulationMesh.mTetrahedrons);
writeIndice(serialFlags, gridModelTetIndices, nbGridModeIndices, platformMismatch, stream);
const PxU32 numVertsPerElement = (simulationData.mNumTetsPerElement == 5 || simulationData.mNumTetsPerElement == 6) ? 8 : 4;
const PxU32 numElements = simulationMesh.mNbTetrahedrons / simulationData.mNumTetsPerElement;
writeFloatBuffer(&simulationMesh.mVertices->x, simulationMesh.mNbVertices * 3, platformMismatch, stream);
if (simulationMesh.mMaterialIndices)
writeWordBuffer(simulationMesh.mMaterialIndices, simulationMesh.mNbTetrahedrons, platformMismatch, stream);
writeFloatBuffer(simulationData.mGridModelInvMass, simulationMesh.mNbVertices * 1, platformMismatch, stream);
stream.write(simulationData.mGridModelTetraRestPoses, simulationMesh.mNbTetrahedrons * sizeof(PxMat33));
stream.write(simulationData.mGridModelOrderedTetrahedrons, numElements * sizeof(PxU32));
stream.write(simulationData.mGMRemapOutputCP, numElements * numVertsPerElement * sizeof(PxU32));
stream.write(simulationData.mGMAccumulatedPartitionsCP, simulationData.mGridModelNbPartitions * sizeof(PxU32));
stream.write(simulationData.mGMAccumulatedCopiesCP, simulationMesh.mNbVertices * sizeof(PxU32));
stream.write(mappingData.mCollisionAccumulatedTetrahedronsRef, collisionMesh.mNbVertices * sizeof(PxU32));
stream.write(mappingData.mCollisionTetrahedronsReferences, mappingData.mCollisionNbTetrahedronsReferences * sizeof(PxU32));
stream.write(mappingData.mCollisionSurfaceVertsHint, collisionMesh.mNbVertices * sizeof(PxU8));
stream.write(mappingData.mCollisionSurfaceVertToTetRemap, collisionMesh.mNbVertices * sizeof(PxU32));
stream.write(simulationData.mGMPullIndices, numElements * numVertsPerElement *sizeof(PxU32));
writeFloatBuffer(mappingData.mVertsBarycentricInGridModel, collisionMesh.mNbVertices * 4, platformMismatch, stream);
writeIntBuffer(mappingData.mVertsRemapInGridModel, collisionMesh.mNbVertices, platformMismatch, stream);
writeIntBuffer(mappingData.mTetsRemapColToSim, mappingData.mTetsRemapSize, platformMismatch, stream);
writeIntBuffer(mappingData.mTetsAccumulatedRemapColToSim, collisionMesh.mNbTetrahedrons, platformMismatch, stream);
}
// End of GRB write ----------------------------------------------------------
return true;
}
bool TetrahedronMeshBuilder::createMidPhaseStructure(TetrahedronMeshData& collisionMesh, SoftBodyCollisionData& collisionData, const PxCookingParams& params)
{
const PxReal gBoxEpsilon = 2e-4f;
TetrahedronSourceMesh& meshInterface = collisionData.mMeshInterface;
// const PxReal gBoxEpsilon = 0.1f;
meshInterface.initRemap();
meshInterface.setNbVertices(collisionMesh.mNbVertices);
meshInterface.setNbTetrahedrons(collisionMesh.mNbTetrahedrons);
IndTetrahedron32* tetrahedrons32 = NULL;
IndTetrahedron16* tetrahedrons16 = NULL;
if (collisionMesh.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES)
tetrahedrons16 = reinterpret_cast<IndTetrahedron16*>(collisionMesh.mTetrahedrons);
else
tetrahedrons32 = reinterpret_cast<IndTetrahedron32*>(collisionMesh.mTetrahedrons);
collisionData.mMeshInterface.setPointers(tetrahedrons32, tetrahedrons16, collisionMesh.mVertices);
const PxU32 nbTetsPerLeaf = 15;
if (!BuildBV4Ex(collisionData.mBV4Tree, meshInterface, gBoxEpsilon, nbTetsPerLeaf, false))
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "BV4 tree failed to build.");
const PxU32* order = meshInterface.getRemap();
if (!params.suppressTriangleMeshRemapTable || params.buildGPUData)
{
PxU32* newMap = PX_ALLOCATE(PxU32, collisionMesh.mNbTetrahedrons, "mFaceRemap");
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; i++)
newMap[i] = collisionData.mFaceRemap ? collisionData.mFaceRemap[order[i]] : order[i];
PX_FREE(collisionData.mFaceRemap);
collisionData.mFaceRemap = newMap;
}
meshInterface.releaseRemap();
return true;
}
void TetrahedronMeshBuilder::saveMidPhaseStructure(PxOutputStream& stream, bool mismatch, const SoftBodyCollisionData& collisionData)
{
// PT: in version 1 we defined "mismatch" as:
// const bool mismatch = (littleEndian() == 1);
// i.e. the data was *always* saved to file in big-endian format no matter what.
// In version>1 we now do the same as for other structures in the SDK: the data is
// exported either as little or big-endian depending on the passed parameter.
const PxU32 bv4StructureVersion = 3;
writeChunk('B', 'V', '4', ' ', stream);
writeDword(bv4StructureVersion, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mLocalBounds.mCenter.x, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mLocalBounds.mCenter.y, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mLocalBounds.mCenter.z, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mLocalBounds.mExtentsMagnitude, mismatch, stream);
writeDword(collisionData.mBV4Tree.mInitData, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mCenterOrMinCoeff.x, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mCenterOrMinCoeff.y, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mCenterOrMinCoeff.z, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mExtentsOrMaxCoeff.x, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mExtentsOrMaxCoeff.y, mismatch, stream);
writeFloat(collisionData.mBV4Tree.mExtentsOrMaxCoeff.z, mismatch, stream);
// PT: version 3
writeDword(PxU32(collisionData.mBV4Tree.mQuantized), mismatch, stream);
writeDword(collisionData.mBV4Tree.mNbNodes, mismatch, stream);
#ifdef GU_BV4_USE_SLABS
// PT: we use BVDataPacked to get the size computation right, but we're dealing with BVDataSwizzled here!
const PxU32 NodeSize = collisionData.mBV4Tree.mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
stream.write(collisionData.mBV4Tree.mNodes, NodeSize*collisionData.mBV4Tree.mNbNodes);
PX_ASSERT(!mismatch);
#else
#error Not implemented
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool BV32TetrahedronMeshBuilder::createMidPhaseStructure(const PxCookingParams& params, TetrahedronMeshData& collisionMesh, BV32Tree& bv32Tree, SoftBodyCollisionData& collisionData)
{
PX_UNUSED(params);
PX_UNUSED(collisionMesh);
PX_UNUSED(bv32Tree);
const PxReal gBoxEpsilon = 2e-4f;
TetrahedronSourceMesh meshInterface;
// const PxReal gBoxEpsilon = 0.1f;
meshInterface.initRemap();
meshInterface.setNbVertices(collisionMesh.mNbVertices);
meshInterface.setNbTetrahedrons(collisionMesh.mNbTetrahedrons);
//meshInterface.setNbVertices(meshData.mNbVertices);
//meshInterface.setNbTriangles(meshData.mNbTriangles);
PX_ASSERT(!(collisionMesh.mFlags & PxTriangleMeshFlag::e16_BIT_INDICES));
IndTetrahedron32* tetrahedron32 = reinterpret_cast<IndTetrahedron32*>(collisionData.mGRB_primIndices);
meshInterface.setPointers(tetrahedron32, NULL, collisionMesh.mVertices);
PxU32 nbTetrahedronPerLeaf = 32;
if (!BuildBV32Ex(bv32Tree, meshInterface, gBoxEpsilon, nbTetrahedronPerLeaf))
return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "BV32 tree failed to build.");
const PxU32* order = meshInterface.getRemap();
if (collisionMesh.mMaterialIndices)
{
PxFEMMaterialTableIndex* newMat = PX_ALLOCATE(PxFEMMaterialTableIndex, collisionMesh.mNbTetrahedrons, "mMaterialIndices");
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; i++)
newMat[i] = collisionMesh.mMaterialIndices[order[i]];
PX_FREE(collisionMesh.mMaterialIndices);
collisionMesh.mMaterialIndices = newMat;
}
//suppressTriangleMeshRemapTable can use for tetrahedron mesh remap table
if (!params.suppressTriangleMeshRemapTable || params.buildGPUData)
{
PxU32* newMap = PX_ALLOCATE(PxU32, collisionMesh.mNbTetrahedrons, "mGRB_faceRemap");
for (PxU32 i = 0; i<collisionMesh.mNbTetrahedrons; i++)
newMap[i] = collisionData.mGRB_faceRemap ? collisionData.mGRB_faceRemap[order[i]] : order[i];
PX_FREE(collisionData.mGRB_faceRemap);
collisionData.mGRB_faceRemap = newMap;
PxU32* newMapInverse = PX_ALLOCATE(PxU32, collisionMesh.mNbTetrahedrons, "mGRB_faceRemapInverse");
for (PxU32 i = 0; i < collisionMesh.mNbTetrahedrons; ++i)
newMapInverse[collisionData.mGRB_faceRemap[i]] = i;
PX_FREE(collisionData.mGRB_faceRemapInverse);
collisionData.mGRB_faceRemapInverse = newMapInverse;
}
meshInterface.releaseRemap();
return true;
}
void BV32TetrahedronMeshBuilder::saveMidPhaseStructure(BV32Tree* bv32Tree, PxOutputStream& stream, bool mismatch)
{
// PT: in version 1 we defined "mismatch" as:
// const bool mismatch = (littleEndian() == 1);
// i.e. the data was *always* saved to file in big-endian format no matter what.
// In version>1 we now do the same as for other structures in the SDK: the data is
// exported either as little or big-endian depending on the passed parameter.
const PxU32 bv32StructureVersion = 2;
writeChunk('B', 'V', '3', '2', stream);
writeDword(bv32StructureVersion, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.x, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.y, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mCenter.z, mismatch, stream);
writeFloat(bv32Tree->mLocalBounds.mExtentsMagnitude, mismatch, stream);
writeDword(bv32Tree->mInitData, mismatch, stream);
writeDword(bv32Tree->mNbPackedNodes, mismatch, stream);
PX_ASSERT(bv32Tree->mNbPackedNodes > 0);
for (PxU32 i = 0; i < bv32Tree->mNbPackedNodes; ++i)
{
BV32DataPacked& node = bv32Tree->mPackedNodes[i];
const PxU32 nbElements = node.mNbNodes * 4;
writeDword(node.mNbNodes, mismatch, stream);
writeDword(node.mDepth, mismatch, stream);
WriteDwordBuffer(node.mData, node.mNbNodes, mismatch, stream);
writeFloatBuffer(&node.mMin[0].x, nbElements, mismatch, stream);
writeFloatBuffer(&node.mMax[0].x, nbElements, mismatch, stream);
}
}
///////////////////////////////////////////////////////////////////////////////
bool immediateCooking::cookTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc, PxOutputStream& stream)
{
TetrahedronMeshData data;
TetrahedronMeshBuilder::computeTetData(meshDesc, data);
TetrahedronMeshBuilder::saveTetrahedronMeshData(stream, platformMismatch(), params, data);
return true;
}
PxTetrahedronMesh* immediateCooking::createTetrahedronMesh(const PxCookingParams& /*params*/, const PxTetrahedronMeshDesc& meshDesc, PxInsertionCallback& insertionCallback)
{
PX_FPU_GUARD;
TetrahedronMeshData tetData;
TetrahedronMeshBuilder::computeTetData(meshDesc, tetData);
PxConcreteType::Enum type = PxConcreteType::eTETRAHEDRON_MESH;
PxTetrahedronMesh* tetMesh = static_cast<PxTetrahedronMesh*>(insertionCallback.buildObjectFromData(type, &tetData));
return tetMesh;
}
bool immediateCooking::cookSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxOutputStream& stream)
{
PX_FPU_GUARD;
TetrahedronMeshData simulationMesh;
SoftBodySimulationData simulationData;
TetrahedronMeshData collisionMesh;
SoftBodyCollisionData collisionData;
CollisionMeshMappingData mappingData;
SoftBodyMeshData data(simulationMesh, simulationData, collisionMesh, collisionData, mappingData);
if(!TetrahedronMeshBuilder::loadFromDesc(simulationMeshDesc, collisionMeshDesc, softbodyDataDesc, data.mSimulationMesh, data.mSimulationData, data.mCollisionMesh, data.mCollisionData, data.mMappingData, params, false))
return false;
TetrahedronMeshBuilder::saveSoftBodyMeshData(stream, platformMismatch(), params, data.mSimulationMesh, data.mSimulationData, data.mCollisionMesh, data.mCollisionData, data.mMappingData);
return true;
}
PxSoftBodyMesh* immediateCooking::createSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxInsertionCallback& insertionCallback)
{
PX_UNUSED(simulationMeshDesc);
PX_UNUSED(collisionMeshDesc);
PX_UNUSED(softbodyDataDesc);
PX_UNUSED(insertionCallback);
// cooking code does lots of float bitwise reinterpretation that generates exceptions
PX_FPU_GUARD;
TetrahedronMeshData simulationMesh;
SoftBodySimulationData simulationData;
TetrahedronMeshData collisionMesh;
SoftBodyCollisionData collisionData;
CollisionMeshMappingData mappingData;
SoftBodyMeshData data(simulationMesh, simulationData, collisionMesh, collisionData, mappingData);
if(!TetrahedronMeshBuilder::loadFromDesc(simulationMeshDesc, collisionMeshDesc, softbodyDataDesc, data.mSimulationMesh, data.mSimulationData, data.mCollisionMesh, data.mCollisionData, data.mMappingData, params, false))
return NULL;
PxConcreteType::Enum type = PxConcreteType::eSOFTBODY_MESH;
PxSoftBodyMesh* tetMesh = static_cast<PxSoftBodyMesh*>(insertionCallback.buildObjectFromData(type, &data));
/*SoftbodySimulationTetrahedronMesh simulationMesh(data.simulationMesh, data.simulationData);
SoftbodyCollisionTetrahedronMesh collisionMesh(data.collisionMesh, data.collisionData);
SoftbodyShapeMapping embedding(data.mappingData);
SoftBodyMesh* tetMesh = NULL;
PX_NEW_SERIALIZED(tetMesh, SoftBodyMesh)(simulationMesh, collisionMesh, embedding);*/
return tetMesh;
}
PxCollisionMeshMappingData* immediateCooking::computeModelsMapping(const PxCookingParams& params, PxTetrahedronMeshData& simulationMesh, const PxTetrahedronMeshData& collisionMesh,
const PxSoftBodyCollisionData& collisionData, const PxBoundedData* vertexToTet)
{
CollisionMeshMappingData* mappingData = PX_NEW(CollisionMeshMappingData);
TetrahedronMeshBuilder::computeModelsMapping(*static_cast<TetrahedronMeshData*>(&simulationMesh),
*static_cast<const TetrahedronMeshData*>(&collisionMesh), *static_cast<const SoftBodyCollisionData*>(&collisionData), *mappingData, params.buildGPUData, vertexToTet);
return mappingData;
}
PxCollisionTetrahedronMeshData* immediateCooking::computeCollisionData(const PxCookingParams& params, const PxTetrahedronMeshDesc& collisionMeshDesc)
{
PX_UNUSED(collisionMeshDesc);
TetrahedronMeshData* mesh = PX_NEW(TetrahedronMeshData);
SoftBodyCollisionData* collisionData = PX_NEW(SoftBodyCollisionData);
if(!TetrahedronMeshBuilder::computeCollisionData(collisionMeshDesc, *mesh, *collisionData, params, false)) {
PX_FREE(mesh);
PX_FREE(collisionData);
return NULL;
}
CollisionTetrahedronMeshData* data = PX_NEW(CollisionTetrahedronMeshData);
data->mMesh = mesh;
data->mCollisionData = collisionData;
return data;
}
PxSimulationTetrahedronMeshData* immediateCooking::computeSimulationData(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc)
{
TetrahedronMeshData* mesh = PX_NEW(TetrahedronMeshData);
SoftBodySimulationData* simulationData = PX_NEW(SoftBodySimulationData);
//KS - This really needs the collision mesh as well.
TetrahedronMeshBuilder::computeSimData(simulationMeshDesc, *mesh, *simulationData, params);
SimulationTetrahedronMeshData* data = PX_NEW(SimulationTetrahedronMeshData);
data->mMesh = mesh;
data->mSimulationData = simulationData;
return data;
}
PxSoftBodyMesh* immediateCooking::assembleSoftBodyMesh(PxTetrahedronMeshData& simulationMesh, PxSoftBodySimulationData& simulationData, PxTetrahedronMeshData& collisionMesh,
PxSoftBodyCollisionData& collisionData, PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback)
{
SoftBodyMeshData data(static_cast<TetrahedronMeshData&>(simulationMesh),
static_cast<SoftBodySimulationData&>(simulationData),
static_cast<TetrahedronMeshData&>(collisionMesh),
static_cast<SoftBodyCollisionData&>(collisionData),
static_cast<CollisionMeshMappingData&>(mappingData));
PxConcreteType::Enum type = PxConcreteType::eSOFTBODY_MESH;
PxSoftBodyMesh* tetMesh = static_cast<PxSoftBodyMesh*>(insertionCallback.buildObjectFromData(type, &data));
return tetMesh;
}
PxSoftBodyMesh* immediateCooking::assembleSoftBodyMesh_Sim(PxSimulationTetrahedronMeshData& simulationMesh, PxCollisionTetrahedronMeshData& collisionMesh,
PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback)
{
return assembleSoftBodyMesh(*simulationMesh.getMesh(), *simulationMesh.getData(), *collisionMesh.getMesh(), *collisionMesh.getData(), mappingData, insertionCallback);
}
| 103,596 | C++ | 34.588114 | 219 | 0.735192 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullLib.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_COOKING_CONVEX_HULL_LIB_H
#define GU_COOKING_CONVEX_HULL_LIB_H
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxCooking.h"
namespace physx
{
//////////////////////////////////////////////////////////////////////////
// base class for the convex hull libraries - inflation based and quickhull
class ConvexHullLib
{
PX_NOCOPY(ConvexHullLib)
public:
// functions
ConvexHullLib(const PxConvexMeshDesc& desc, const PxCookingParams& params)
: mConvexMeshDesc(desc), mCookingParams(params), mSwappedIndices(NULL),
mShiftedVerts(NULL)
{
}
virtual ~ConvexHullLib();
// computes the convex hull from provided points
virtual PxConvexMeshCookingResult::Enum createConvexHull() = 0;
// fills the PxConvexMeshDesc with computed hull data
virtual void fillConvexMeshDesc(PxConvexMeshDesc& desc) = 0;
// compute the edge list information if possible
virtual bool createEdgeList(const PxU32 nbIndices, const PxU8* indices, PxU8** hullDataFacesByEdges8, PxU16** edgeData16, PxU16** edges) = 0;
static const PxU32 gpuMaxVertsPerFace = 31;
protected:
// clean input vertices from duplicates, normalize etc.
bool cleanupVertices(PxU32 svcount, // input vertex count
const PxVec3* svertices, // vertices
PxU32 stride, // stride
PxU32& vcount, // output number of vertices
PxVec3* vertices); // location to store the results.
// shift vertices around origin and clean input vertices from duplicates, normalize etc.
bool shiftAndcleanupVertices(PxU32 svcount, // input vertex count
const PxVec3* svertices, // vertices
PxU32 stride, // stride
PxU32& vcount, // output number of vertices
PxVec3* vertices); // location to store the results.
void swapLargestFace(PxConvexMeshDesc& desc);
void shiftConvexMeshDesc(PxConvexMeshDesc& desc);
protected:
const PxConvexMeshDesc& mConvexMeshDesc;
const PxCookingParams& mCookingParams;
PxU32* mSwappedIndices;
PxVec3 mOriginShift;
PxVec3* mShiftedVerts;
};
}
#endif
| 3,729 | C | 39.107526 | 143 | 0.73934 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingQuickHullConvexHullLib.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_COOKING_QUICKHULL_CONVEXHULLLIB_H
#define GU_COOKING_QUICKHULL_CONVEXHULLLIB_H
#include "GuCookingConvexHullLib.h"
#include "foundation/PxArray.h"
#include "foundation/PxUserAllocated.h"
namespace local
{
class QuickHull;
struct QuickHullVertex;
}
namespace physx
{
class ConvexHull;
//////////////////////////////////////////////////////////////////////////
// Quickhull lib constructs the hull from given input points. The resulting hull
// will only contain a subset of the input points. The algorithm does incrementally
// adds most furthest vertices to the starting simplex. The produced hulls are build with high precision
// and produce more stable and correct results, than the legacy algorithm.
class QuickHullConvexHullLib: public ConvexHullLib, public PxUserAllocated
{
PX_NOCOPY(QuickHullConvexHullLib)
public:
// functions
QuickHullConvexHullLib(const PxConvexMeshDesc& desc, const PxCookingParams& params);
~QuickHullConvexHullLib();
// computes the convex hull from provided points
virtual PxConvexMeshCookingResult::Enum createConvexHull();
// fills the convexmeshdesc with computed hull data
virtual void fillConvexMeshDesc(PxConvexMeshDesc& desc);
// provide the edge list information
virtual bool createEdgeList(const PxU32, const PxU8* , PxU8** , PxU16** , PxU16** );
protected:
// if vertex limit reached we need to expand the hull using the OBB slicing
PxConvexMeshCookingResult::Enum expandHullOBB();
// if vertex limit reached we need to expand the hull using the plane shifting
PxConvexMeshCookingResult::Enum expandHull();
// checks for collinearity and co planarity
// returns true if the simplex was ok, we can reuse the computed tolerances and min/max values
bool cleanupForSimplex(PxVec3* vertices, PxU32 vertexCount, local::QuickHullVertex* minimumVertex,
local::QuickHullVertex* maximumVertex, float& tolerance, float& planeTolerance);
// fill the result desc from quick hull convex
void fillConvexMeshDescFromQuickHull(PxConvexMeshDesc& desc);
// fill the result desc from cropped hull convex
void fillConvexMeshDescFromCroppedHull(PxConvexMeshDesc& desc);
private:
local::QuickHull* mQuickHull; // the internal quick hull representation
ConvexHull* mCropedConvexHull; //the hull cropped from OBB, used for vertex limit path
PxU8* mOutMemoryBuffer; // memory buffer used for output data
PxU16* mFaceTranslateTable; // translation table mapping output faces to internal quick hull table
};
}
#endif
| 4,242 | C | 42.295918 | 105 | 0.759547 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuOverlapTestsHF.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 "GuOverlapTests.h"
#include "GuHeightFieldUtil.h"
#include "GuBoxConversion.h"
#include "GuInternal.h"
#include "GuVecConvexHull.h"
#include "GuEntityReport.h"
#include "GuDistancePointTriangle.h"
#include "GuIntersectionCapsuleTriangle.h"
#include "GuDistanceSegmentTriangle.h"
#include "GuBounds.h"
#include "GuBV4_Common.h"
#include "GuVecTriangle.h"
#include "GuConvexMesh.h"
#include "GuGJK.h"
#include "geometry/PxSphereGeometry.h"
using namespace physx;
using namespace Gu;
using namespace aos;
///////////////////////////////////////////////////////////////////////////////
namespace
{
struct HeightfieldOverlapReport : Gu::OverlapReport
{
PX_NOCOPY(HeightfieldOverlapReport)
public:
HeightfieldOverlapReport(const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose) : mHfUtil(hfGeom), mHFPose(hfPose), mOverlap(PxIntFalse) {}
const HeightFieldUtil mHfUtil;
const PxTransform& mHFPose;
PxIntBool mOverlap;
};
}
bool GeomOverlapCallback_SphereHeightfield(GU_OVERLAP_FUNC_PARAMS)
{
PX_ASSERT(geom0.getType()==PxGeometryType::eSPHERE);
PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(cache);
PX_UNUSED(threadContext);
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1);
struct SphereOverlapReport : HeightfieldOverlapReport
{
Sphere mLocalSphere;
SphereOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose, const PxVec3& localSphereCenter, float sphereRadius) : HeightfieldOverlapReport(hfGeom_, hfPose)
{
mLocalSphere.center = localSphereCenter;
mLocalSphere.radius = sphereRadius * sphereRadius;
}
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
while(nb--)
{
const PxU32 triangleIndex = *indices++;
PxTriangle currentTriangle;
mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false);
const PxVec3& p0 = currentTriangle.verts[0];
const PxVec3& p1 = currentTriangle.verts[1];
const PxVec3& p2 = currentTriangle.verts[2];
const PxVec3 edge10 = p1 - p0;
const PxVec3 edge20 = p2 - p0;
const PxVec3 cp = closestPtPointTriangle2(mLocalSphere.center, p0, p1, p2, edge10, edge20);
const float sqrDist = (cp - mLocalSphere.center).magnitudeSquared();
if(sqrDist <= mLocalSphere.radius) // mLocalSphere.radius has been pre-squared in the ctor
{
mOverlap = PxIntTrue;
return false;
}
}
return true;
}
};
PxBounds3 localBounds;
const PxVec3 localSphereCenter = getLocalSphereData(localBounds, pose0, pose1, sphereGeom.radius);
SphereOverlapReport report(hfGeom, pose1, localSphereCenter, sphereGeom.radius);
report.mHfUtil.overlapAABBTriangles(localBounds, report, 4);
return report.mOverlap!=PxIntFalse;
}
///////////////////////////////////////////////////////////////////////////////
bool GeomOverlapCallback_CapsuleHeightfield(GU_OVERLAP_FUNC_PARAMS)
{
PX_ASSERT(geom0.getType()==PxGeometryType::eCAPSULE);
PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(cache);
PX_UNUSED(threadContext);
const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom0);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1);
struct CapsuleOverlapReport : HeightfieldOverlapReport
{
Capsule mLocalCapsule;
CapsuleTriangleOverlapData mData;
CapsuleOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {}
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
while(nb--)
{
const PxU32 triangleIndex = *indices++;
PxTriangle currentTriangle;
mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false);
const PxVec3& p0 = currentTriangle.verts[0];
const PxVec3& p1 = currentTriangle.verts[1];
const PxVec3& p2 = currentTriangle.verts[2];
if(0)
{
PxReal t,u,v;
const PxVec3 p1_p0 = p1 - p0;
const PxVec3 p2_p0 = p2 - p0;
const PxReal sqrDist = distanceSegmentTriangleSquared(mLocalCapsule, p0, p1_p0, p2_p0, &t, &u, &v);
if(sqrDist <= mLocalCapsule.radius*mLocalCapsule.radius)
{
mOverlap = PxIntTrue;
return false;
}
}
else
{
const PxVec3 normal = (p0 - p1).cross(p0 - p2);
if(intersectCapsuleTriangle(normal, p0, p1, p2, mLocalCapsule, mData))
{
mOverlap = PxIntTrue;
return false;
}
}
}
return true;
}
};
CapsuleOverlapReport report(hfGeom, pose1);
// PT: TODO: move away from internal header
const PxVec3 tmp = getCapsuleHalfHeightVector(pose0, capsuleGeom);
// PT: TODO: refactor - but might be difficult because we reuse relPose for two tasks here
const PxTransform relPose = pose1.transformInv(pose0);
const PxVec3 localDelta = pose1.rotateInv(tmp);
report.mLocalCapsule.p0 = relPose.p + localDelta;
report.mLocalCapsule.p1 = relPose.p - localDelta;
report.mLocalCapsule.radius = capsuleGeom.radius;
report.mData.init(report.mLocalCapsule);
PxBounds3 localBounds;
computeCapsuleBounds(localBounds, capsuleGeom, relPose);
report.mHfUtil.overlapAABBTriangles(localBounds, report, 4);
//hfUtil.overlapAABBTriangles(pose0, pose1, getLocalCapsuleBounds(capsuleGeom.radius, capsuleGeom.halfHeight), report, 4);
return report.mOverlap!=PxIntFalse;
}
///////////////////////////////////////////////////////////////////////////////
PxIntBool intersectTriangleBoxBV4(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents);
bool GeomOverlapCallback_BoxHeightfield(GU_OVERLAP_FUNC_PARAMS)
{
PX_ASSERT(geom0.getType()==PxGeometryType::eBOX);
PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(cache);
PX_UNUSED(threadContext);
const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom0);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1);
struct BoxOverlapReport : HeightfieldOverlapReport
{
PxMat33 mRModelToBox;
PxVec3p mTModelToBox;
PxVec3p mBoxExtents;
BoxOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {}
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
while(nb--)
{
const PxU32 triangleIndex = *indices++;
PxTrianglePadded currentTriangle;
mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false);
if(intersectTriangleBoxBV4(currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], mRModelToBox, mTModelToBox, mBoxExtents))
{
mOverlap = PxIntTrue;
return false;
}
}
return true;
}
};
BoxOverlapReport report(hfGeom, pose1);
// PT: TODO: revisit / refactor all this code
const PxTransform relPose = pose1.transformInv(pose0);
Box localBox;
buildFrom(localBox, relPose.p, boxGeom.halfExtents, relPose.q);
invertBoxMatrix(report.mRModelToBox, report.mTModelToBox, localBox);
report.mBoxExtents = localBox.extents;
PxBounds3 localBounds;
{
// PT: TODO: refactor with bounds code?
const PxMat33& basis = localBox.rot;
// extended basis vectors
const Vec4V c0V = V4Scale(V4LoadU(&basis.column0.x), FLoad(localBox.extents.x));
const Vec4V c1V = V4Scale(V4LoadU(&basis.column1.x), FLoad(localBox.extents.y));
const Vec4V c2V = V4Scale(V4LoadU(&basis.column2.x), FLoad(localBox.extents.z));
// find combination of base vectors that produces max. distance for each component = sum of abs()
Vec4V extentsV = V4Add(V4Abs(c0V), V4Abs(c1V));
extentsV = V4Add(extentsV, V4Abs(c2V));
const PxVec3p origin(localBox.center);
const Vec4V originV = V4LoadU(&origin.x);
const Vec4V minV = V4Sub(originV, extentsV);
const Vec4V maxV = V4Add(originV, extentsV);
StoreBounds(localBounds, minV, maxV);
}
report.mHfUtil.overlapAABBTriangles(localBounds, report, 4);
return report.mOverlap!=PxIntFalse;
}
///////////////////////////////////////////////////////////////////////////////
bool GeomOverlapCallback_ConvexHeightfield(GU_OVERLAP_FUNC_PARAMS)
{
PX_ASSERT(geom0.getType()==PxGeometryType::eCONVEXMESH);
PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(cache);
PX_UNUSED(threadContext);
const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1);
struct ConvexOverlapReport : HeightfieldOverlapReport
{
ConvexHullV mConvex;
PxMatTransformV aToB;
ConvexOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {}
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
while(nb--)
{
const PxU32 triangleIndex = *indices++;
PxTrianglePadded currentTriangle;
mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false);
const PxVec3& p0 = currentTriangle.verts[0];
const PxVec3& p1 = currentTriangle.verts[1];
const PxVec3& p2 = currentTriangle.verts[2];
// PT: TODO: consider adding an extra triangle-vs-box culling test here
// PT: TODO: optimize
const Vec3V v0 = V3LoadU(p0);
const Vec3V v1 = V3LoadU(p1);
const Vec3V v2 = V3LoadU(p2);
// PT: TODO: refactor with ConvexVsMeshOverlapCallback
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))
{
mOverlap = PxIntTrue;
return false;
}
}
return true;
}
};
ConvexOverlapReport report(hfGeom, pose1);
const ConvexMesh* cm = static_cast<const ConvexMesh*>(convexGeom.convexMesh);
const bool idtScaleConvex = convexGeom.scale.isIdentity();
{
const ConvexHullData* hullData = &cm->getHull();
const Vec3V vScale0 = V3LoadU_SafeReadW(convexGeom.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const QuatV vQuat0 = QuatVLoadU(&convexGeom.scale.rotation.x);
report.mConvex = ConvexHullV(hullData, V3Zero(), vScale0, vQuat0, idtScaleConvex);
// PT: TODO: is that transform correct? It looks like the opposite of what we do for other prims?
report.aToB = PxMatTransformV(pose0.transformInv(pose1));
//report.aToB = PxMatTransformV(pose1.transformInv(pose0));
}
const PxTransform relPose = pose1.transformInv(pose0);
PxBounds3 localBounds;
computeBounds(localBounds, convexGeom, relPose, 0.0f, 1.0f);
report.mHfUtil.overlapAABBTriangles(localBounds, report, 4);
return report.mOverlap!=PxIntFalse;
}
| 12,744 | C++ | 34.207182 | 183 | 0.726381 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightField.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_HEIGHTFIELD_H
#define GU_HEIGHTFIELD_H
#include "geometry/PxHeightFieldSample.h"
#include "geometry/PxHeightFieldDesc.h"
#include "geometry/PxHeightField.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "foundation/PxUserAllocated.h"
#include "CmRefCountable.h"
#include "GuSphere.h"
#include "GuHeightFieldData.h"
//#define PX_HEIGHTFIELD_VERSION 0
//#define PX_HEIGHTFIELD_VERSION 1 // tiled version that was needed for PS3 only has been removed
#define PX_HEIGHTFIELD_VERSION 2 // some floats are now integers
namespace physx
{
class PxHeightFieldDesc;
namespace Gu
{
class MeshFactory;
class HeightField : public PxHeightField, public PxUserAllocated
{
public:
// PX_SERIALIZATION
HeightField(PxBaseFlags baseFlags) : PxHeightField(baseFlags), mData(PxEmpty), mModifyCount(0) {}
void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); }
virtual void exportExtraData(PxSerializationContext& context);
void importExtraData(PxDeserializationContext& context);
PX_FORCE_INLINE void setMeshFactory(MeshFactory* f) { mMeshFactory = f; }
PX_PHYSX_COMMON_API static HeightField* createObject(PxU8*& address, PxDeserializationContext& context);
PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
void resolveReferences(PxDeserializationContext&) {}
virtual void requiresObjects(PxProcessPxBaseCallback&){}
//~PX_SERIALIZATION
HeightField(MeshFactory* factory);
HeightField(MeshFactory* factory, Gu::HeightFieldData& data);
// PxHeightField
virtual void release();
virtual PxU32 saveCells(void* destBuffer, PxU32 destBufferSize) const;
virtual bool modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& subfieldDesc, bool shrinkBounds);
virtual PxU32 getNbRows() const { return mData.rows; }
virtual PxU32 getNbColumns() const { return mData.columns; }
virtual PxHeightFieldFormat::Enum getFormat() const { return mData.format; }
virtual PxU32 getSampleStride() const { return sizeof(PxHeightFieldSample); }
virtual PxReal getConvexEdgeThreshold() const { return mData.convexEdgeThreshold; }
virtual PxHeightFieldFlags getFlags() const { return mData.flags; }
virtual PxReal getHeight(PxReal x, PxReal z) const { return getHeightInternal(x, z); }
virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const
{
return getTriangleMaterial(triangleIndex);
}
virtual PxVec3 getTriangleNormal(PxTriangleID triangleIndex) const
{
return getTriangleNormalInternal(triangleIndex);
}
virtual const PxHeightFieldSample& getSample(PxU32 row, PxU32 column) const
{
const PxU32 cell = row * getNbColumnsFast() + column;
return getSample(cell);
}
virtual PxU32 getTimestamp() const { return mModifyCount; }
//~PxHeightField
// PxRefCounted
virtual void acquireReference();
virtual PxU32 getReferenceCount() const;
//~PxRefCounted
// PxBase
virtual void onRefCountZero();
//~PxBase
bool loadFromDesc(const PxHeightFieldDesc&);
bool load(PxInputStream&);
bool save(PxOutputStream& stream, bool endianSwap);
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbRowsFast() const { return mData.rows; }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbColumnsFast() const { return mData.columns; }
PX_FORCE_INLINE PxHeightFieldFormat::Enum getFormatFast() const { return mData.format; }
PX_FORCE_INLINE PxU32 getFlagsFast() const { return mData.flags; }
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZerothVertexShared(PxU32 vertexIndex) const
{
// return (getSample(vertexIndex).tessFlag & PxHeightFieldTessFlag::e0TH_VERTEX_SHARED);
return getSample(vertexIndex).tessFlag() != 0;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex0(PxU32 vertexIndex) const { return getSample(vertexIndex).materialIndex0; }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex1(PxU32 vertexIndex) const { return getSample(vertexIndex).materialIndex1; }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaterialIndex01(PxU32 vertexIndex) const
{
const PxHeightFieldSample& sample = getSample(vertexIndex);
return PxU32(sample.materialIndex0 | (sample.materialIndex1 << 16));
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getHeight(PxU32 vertexIndex) const
{
return PxReal(getSample(vertexIndex).height);
}
PX_INLINE PxReal getHeightInternal2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ) const;
PX_FORCE_INLINE PxReal getHeightInternal(PxReal x, PxReal z) const
{
PxReal fracX, fracZ;
const PxU32 vertexIndex = computeCellCoordinates(x, z, fracX, fracZ);
return getHeightInternal2(vertexIndex, fracX, fracZ);
}
PX_FORCE_INLINE bool isValidVertex(PxU32 vertexIndex) const { return vertexIndex < mData.rows*mData.columns; }
PX_INLINE PxVec3 getVertex(PxU32 vertexIndex) const;
PX_INLINE bool isConvexVertex(PxU32 vertexIndex, PxU32 row, PxU32 column) const;
PX_INLINE bool isValidEdge(PxU32 edgeIndex) const;
PX_INLINE PxU32 getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2]) const;
PX_INLINE PxU32 getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2], PxU32 cell, PxU32 row, PxU32 column) const;
PX_INLINE void getEdgeVertexIndices(PxU32 edgeIndex, PxU32& vertexIndex0, PxU32& vertexIndex1) const;
// PX_INLINE bool isConvexEdge(PxU32 edgeIndex) const;
PX_INLINE bool isConvexEdge(PxU32 edgeIndex, PxU32 cell, PxU32 row, PxU32 column) const;
PX_FORCE_INLINE bool isConvexEdge(PxU32 edgeIndex) const
{
const PxU32 cell = edgeIndex / 3;
const PxU32 row = cell / mData.columns;
const PxU32 column = cell % mData.columns;
return isConvexEdge(edgeIndex, cell, row, column);
}
PxU32 computeCellCoordinates(PxReal x, PxReal z, PxReal& fracX, PxReal& fracZ) const;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMin(PxReal x, PxU32 nb) const
{
if(x<0.0f)
return 0;
if(x>PxReal(nb))
return nb;
const PxReal cx = PxFloor(x);
const PxU32 icx = PxU32(cx);
return icx;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMax(PxReal x, PxU32 nb) const
{
if(x<0.0f)
return 0;
if(x>PxReal(nb))
return nb;
const PxReal cx = PxCeil(x);
const PxU32 icx = PxU32(cx);
return icx;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMinRow(PxReal x) const { return getMin(x, mData.rows-2); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaxRow(PxReal x) const { return getMax(x, mData.rows-1); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMinColumn(PxReal z) const { return getMin(z, mData.columns-2); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaxColumn(PxReal z) const { return getMax(z, mData.columns-1); }
PX_CUDA_CALLABLE PX_INLINE bool isValidTriangle(PxU32 triangleIndex) const;
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFirstTriangle(PxU32 triangleIndex) const { return ((triangleIndex & 0x1) == 0); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getTriangleMaterial(PxU32 triangleIndex) const
{
return isFirstTriangle(triangleIndex) ? getMaterialIndex0(triangleIndex >> 1) : getMaterialIndex1(triangleIndex >> 1);
}
PX_CUDA_CALLABLE PX_INLINE void getTriangleVertexIndices(PxU32 triangleIndex, PxU32& vertexIndex0, PxU32& vertexIndex1, PxU32& vertexIndex2) const;
PX_CUDA_CALLABLE PX_INLINE PxVec3 getTriangleNormalInternal(PxU32 triangleIndex) const;
PX_INLINE void getTriangleAdjacencyIndices(PxU32 triangleIndex,PxU32 vertexIndex0, PxU32 vertexIndex1, PxU32 vertexIndex2, PxU32& adjacencyIndex0, PxU32& adjacencyIndex1, PxU32& adjacencyIndex2) const;
PX_INLINE PxVec3 getNormal_2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const;
PX_FORCE_INLINE PxVec3 getNormal_(PxReal x, PxReal z, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const
{
PxReal fracX, fracZ;
const PxU32 vertexIndex = computeCellCoordinates(x, z, fracX, fracZ);
return getNormal_2(vertexIndex, fracX, fracZ, xcoeff, ycoeff, zcoeff);
}
PX_INLINE PxU32 getTriangleIndex(PxReal x, PxReal z) const;
PX_INLINE PxU32 getTriangleIndex2(PxU32 cell, PxReal fracX, PxReal fracZ) const;
PX_FORCE_INLINE PxU16 getMaterial(PxReal x, PxReal z) const
{
return getTriangleMaterial(getTriangleIndex(x, z));
}
PX_FORCE_INLINE PxReal getMinHeight() const { return mMinHeight; }
PX_FORCE_INLINE PxReal getMaxHeight() const { return mMaxHeight; }
PX_FORCE_INLINE const Gu::HeightFieldData& getData() const { return mData; }
PX_CUDA_CALLABLE PX_FORCE_INLINE void getTriangleVertices(PxU32 triangleIndex, PxU32 row, PxU32 column, PxVec3& v0, PxVec3& v1, PxVec3& v2) const;
// checks if current vertex is solid or not
bool isSolidVertex(PxU32 vertexIndex, PxU32 row, PxU32 coloumn, PxU16 holeMaterialIndex, bool& nbSolid) const;
// PT: TODO: I think we could drop that whole precomputation thing now
// if precomputed bitmap define is used, the collision vertex information
// is precomputed during create height field and stored as a bit in materialIndex1
PX_PHYSX_COMMON_API bool isCollisionVertexPreca(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex) const;
void parseTrianglesForCollisionVertices(PxU16 holeMaterialIndex);
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxHeightFieldSample& getSample(PxU32 vertexIndex) const
{
PX_ASSERT(isValidVertex(vertexIndex));
return mData.samples[vertexIndex];
}
#ifdef __CUDACC__
PX_CUDA_CALLABLE void setSamplePtr(PxHeightFieldSample* s) { mData.samples = s; }
#endif
Gu::HeightFieldData mData;
PxU32 mSampleStride;
PxU32 mNbSamples; // PT: added for platform conversion. Try to remove later.
PxReal mMinHeight;
PxReal mMaxHeight;
PxU32 mModifyCount;
void releaseMemory();
virtual ~HeightField();
private:
MeshFactory* mMeshFactory; // PT: changed to pointer for serialization
};
} // namespace Gu
PX_INLINE PxVec3 Gu::HeightField::getVertex(PxU32 vertexIndex) const
{
const PxU32 row = vertexIndex / mData.columns;
const PxU32 column = vertexIndex % mData.columns;
// return PxVec3(PxReal(row), getHeight(row * mData.columns + column), PxReal(column));
return PxVec3(PxReal(row), getHeight(vertexIndex), PxReal(column));
}
// PT: only called from "isCollisionVertex", should move
PX_INLINE bool Gu::HeightField::isConvexVertex(PxU32 vertexIndex, PxU32 row, PxU32 column) const
{
#ifdef PX_HEIGHTFIELD_DEBUG
PX_ASSERT(isValidVertex(vertexIndex));
#endif
PX_ASSERT((vertexIndex / mData.columns)==row);
PX_ASSERT((vertexIndex % mData.columns)==column);
// PxReal h0 = PxReal(2) * getHeight(vertexIndex);
PxI32 h0 = getSample(vertexIndex).height;
h0 += h0;
bool definedInX, definedInZ;
PxI32 convexityX, convexityZ;
if ((row > 0) && (row < mData.rows - 1))
{
// convexityX = h0 - getHeight(vertexIndex + mData.columns) - getHeight(vertexIndex - mData.columns);
convexityX = h0 - getSample(vertexIndex + mData.columns).height - getSample(vertexIndex - mData.columns).height;
definedInX = true;
}
else
{
convexityX = 0;
definedInX = false;
}
if ((column > 0) && (column < mData.columns - 1))
{
// convexityZ = h0 - getHeight(vertexIndex + 1) - getHeight(vertexIndex - 1);
convexityZ = h0 - getSample(vertexIndex + 1).height - getSample(vertexIndex - 1).height;
definedInZ = true;
}
else
{
convexityZ = 0;
definedInZ = false;
}
if(definedInX || definedInZ)
{
// PT: use XOR here
// saddle points
/* if ((convexityX > 0) && (convexityZ < 0))
return false;
if ((convexityX < 0) && (convexityZ > 0))
return false;*/
if(((convexityX ^ convexityZ) & 0x80000000)==0)
return false;
const PxReal value = PxReal(convexityX + convexityZ);
return value > mData.convexEdgeThreshold;
}
// this has to be one of the two corner vertices
return true;
}
PX_INLINE bool Gu::HeightField::isValidEdge(PxU32 edgeIndex) const
{
const PxU32 cell = (edgeIndex / 3);
const PxU32 row = cell / mData.columns;
const PxU32 column = cell % mData.columns;
// switch (edgeIndex % 3)
switch (edgeIndex - cell*3)
{
case 0:
if (row > mData.rows - 1) return false;
if (column >= mData.columns - 1) return false;
break;
case 1:
if (row >= mData.rows - 1) return false;
if (column >= mData.columns - 1) return false;
break;
case 2:
if (row >= mData.rows - 1) return false;
if (column > mData.columns - 1) return false;
break;
}
return true;
}
PX_INLINE PxU32 Gu::HeightField::getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2]) const
{
const PxU32 cell = edgeIndex / 3;
const PxU32 row = cell / mData.columns;
const PxU32 column = cell % mData.columns;
PxU32 count = 0;
// switch (edgeIndex % 3)
switch (edgeIndex - cell*3)
{
case 0:
if (column < mData.columns - 1)
{
if (row > 0)
{
/* if (isZerothVertexShared(cell - mData.columns))
triangleIndices[count++] = ((cell - mData.columns) << 1);
else
triangleIndices[count++] = ((cell - mData.columns) << 1) + 1;*/
triangleIndices[count++] = ((cell - mData.columns) << 1) + 1 - isZerothVertexShared(cell - mData.columns);
}
if (row < mData.rows - 1)
{
/* if (isZerothVertexShared(cell))
triangleIndices[count++] = (cell << 1) + 1;
else
triangleIndices[count++] = cell << 1;*/
triangleIndices[count++] = (cell << 1) + isZerothVertexShared(cell);
}
}
break;
case 1:
if ((row < mData.rows - 1) && (column < mData.columns - 1))
{
triangleIndices[count++] = cell << 1;
triangleIndices[count++] = (cell << 1) + 1;
}
break;
case 2:
if (row < mData.rows - 1)
{
if (column > 0)
triangleIndices[count++] = ((cell - 1) << 1) + 1;
if (column < mData.columns - 1)
triangleIndices[count++] = cell << 1;
}
break;
}
return count;
}
PX_INLINE PxU32 Gu::HeightField::getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2], PxU32 cell, PxU32 row, PxU32 column) const
{
// const PxU32 cell = edgeIndex / 3;
// const PxU32 row = cell / mData.columns;
// const PxU32 column = cell % mData.columns;
PxU32 count = 0;
// switch (edgeIndex % 3)
switch (edgeIndex - cell*3)
{
case 0:
if (column < mData.columns - 1)
{
if (row > 0)
{
/* if (isZerothVertexShared(cell - mData.columns))
triangleIndices[count++] = ((cell - mData.columns) << 1);
else
triangleIndices[count++] = ((cell - mData.columns) << 1) + 1;*/
triangleIndices[count++] = ((cell - mData.columns) << 1) + 1 - isZerothVertexShared(cell - mData.columns);
}
if (row < mData.rows - 1)
{
/* if (isZerothVertexShared(cell))
triangleIndices[count++] = (cell << 1) + 1;
else
triangleIndices[count++] = cell << 1;*/
triangleIndices[count++] = (cell << 1) + isZerothVertexShared(cell);
}
}
break;
case 1:
if ((row < mData.rows - 1) && (column < mData.columns - 1))
{
triangleIndices[count++] = cell << 1;
triangleIndices[count++] = (cell << 1) + 1;
}
break;
case 2:
if (row < mData.rows - 1)
{
if (column > 0)
triangleIndices[count++] = ((cell - 1) << 1) + 1;
if (column < mData.columns - 1)
triangleIndices[count++] = cell << 1;
}
break;
}
return count;
}
PX_INLINE void Gu::HeightField::getEdgeVertexIndices(PxU32 edgeIndex, PxU32& vertexIndex0, PxU32& vertexIndex1) const
{
const PxU32 cell = edgeIndex / 3;
// switch (edgeIndex % 3)
switch (edgeIndex - cell*3)
{
case 0:
vertexIndex0 = cell;
vertexIndex1 = cell + 1;
break;
case 1:
{
/* if (isZerothVertexShared(cell))
{
vertexIndex0 = cell;
vertexIndex1 = cell + mData.columns + 1;
}
else
{
vertexIndex0 = cell + 1;
vertexIndex1 = cell + mData.columns;
}*/
const bool b = isZerothVertexShared(cell);
vertexIndex0 = cell + 1 - b;
vertexIndex1 = cell + mData.columns + b;
}
break;
case 2:
vertexIndex0 = cell;
vertexIndex1 = cell + mData.columns;
break;
}
}
PX_INLINE bool Gu::HeightField::isConvexEdge(PxU32 edgeIndex, PxU32 cell, PxU32 row, PxU32 column) const
{
// const PxU32 cell = edgeIndex / 3;
PX_ASSERT(cell == edgeIndex / 3);
// const PxU32 row = cell / mData.columns;
PX_ASSERT(row == cell / mData.columns);
if (row > mData.rows-2) return false;
// const PxU32 column = cell % mData.columns;
PX_ASSERT(column == cell % mData.columns);
if (column > mData.columns-2) return false;
// PxReal h0 = 0, h1 = 0, h2 = 0, h3 = 0;
// PxReal convexity = 0;
PxI32 h0 = 0, h1 = 0, h2 = 0, h3 = 0;
PxI32 convexity = 0;
// switch (edgeIndex % 3)
switch (edgeIndex - cell*3)
{
case 0:
{
if (row < 1) return false;
/* if(isZerothVertexShared(cell - mData.columns))
{
// <------ COL
// +----+ 0 R
// | / /# O
// | / / # W
// | / / # |
// |/ / # |
// + +====1 |
// |
// |
// |
// |
// |
// |
// V
//
// h0 = getHeight(cell - mData.columns);
// h1 = getHeight(cell);
h0 = getSample(cell - mData.columns).height;
h1 = getSample(cell).height;
}
else
{
// <------ COL
// 0 +----+ R
// #\ \ | O
// # \ \ | W
// # \ \ | |
// # \ \| |
// 1====+ + |
// |
// |
// |
// |
// |
// |
// V
//
// h0 = getHeight(cell - mData.columns + 1);
// h1 = getHeight(cell + 1);
h0 = getSample(cell - mData.columns + 1).height;
h1 = getSample(cell + 1).height;
}*/
const bool b0 = !isZerothVertexShared(cell - mData.columns);
h0 = getSample(cell - mData.columns + b0).height;
h1 = getSample(cell + b0).height;
/* if(isZerothVertexShared(cell))
{
// <------ COL
// R
// O
// W
// |
// |
// |
// 2====+ 0 |
// # / /| |
// # / / | |
// # / / | |
// #/ / | |
// 3 +----+ |
// V
//
// h2 = getHeight(cell + 1);
// h3 = getHeight(cell + mData.columns + 1);
h2 = getSample(cell + 1).height;
h3 = getSample(cell + mData.columns + 1).height;
}
else
{
// <------ COL
// R
// O
// W
// |
// |
// |
// + +====2 |
// |\ \ # |
// | \ \ # |
// | \ \ # |
// | \ \# |
// +----+ 3 |
// V
//
// h2 = getHeight(cell);
// h3 = getHeight(cell + mData.columns);
h2 = getSample(cell).height;
h3 = getSample(cell + mData.columns).height;
}*/
const bool b1 = isZerothVertexShared(cell);
h2 = getSample(cell + b1).height;
h3 = getSample(cell + mData.columns + b1).height;
//convex = (h3-h2) < (h1-h0);
convexity = (h1-h0) - (h3-h2);
}
break;
case 1:
// h0 = getHeight(cell);
// h1 = getHeight(cell + 1);
// h2 = getHeight(cell + mData.columns);
// h3 = getHeight(cell + mData.columns + 1);
h0 = getSample(cell).height;
h1 = getSample(cell + 1).height;
h2 = getSample(cell + mData.columns).height;
h3 = getSample(cell + mData.columns + 1).height;
if (isZerothVertexShared(cell))
//convex = (h0 + h3) > (h1 + h2);
convexity = (h0 + h3) - (h1 + h2);
else
//convex = (h2 + h1) > (h0 + h3);
convexity = (h2 + h1) - (h0 + h3);
break;
case 2:
{
if (column < 1) return false;
/* if(isZerothVertexShared(cell-1))
{
// <-------------- COL
// 1====0 + R
// + / /| O
// + / / | W
// + / / | |
// +/ / | |
// + +----+ V
//
// h0 = getHeight(cell - 1);
// h1 = getHeight(cell);
h0 = getSample(cell - 1).height;
h1 = getSample(cell).height;
}
else
{
// <-------------- COL
// + +----+ R
// +\ \ | O
// + \ \ | W
// + \ \ | |
// + \ \| |
// 1====0 + V
//
// h0 = getHeight(cell - 1 + mData.columns);
// h1 = getHeight(cell + mData.columns);
h0 = getSample(cell - 1 + mData.columns).height;
h1 = getSample(cell + mData.columns).height;
}*/
const PxU32 offset0 = isZerothVertexShared(cell-1) ? 0 : mData.columns;
h0 = getSample(cell - 1 + offset0).height;
h1 = getSample(cell + offset0).height;
/* if(isZerothVertexShared(cell))
{
// <-------------- COL
// +----+ + R
// | / /+ O
// | / / + W
// | / / + |
// |/ / + |
// + 3====2 V
//
// h2 = getHeight(cell + mData.columns);
// h3 = getHeight(cell + mData.columns + 1);
h2 = getSample(cell + mData.columns).height;
h3 = getSample(cell + mData.columns + 1).height;
}
else
{
// <-------------- COL
// + 3====2 R
// |\ \ + O
// | \ \ + W
// | \ \ + |
// | \ \+ |
// +----+ + V
//
// h2 = getHeight(cell);
// h3 = getHeight(cell + 1);
h2 = getSample(cell).height;
h3 = getSample(cell + 1).height;
}*/
const PxU32 offset1 = isZerothVertexShared(cell) ? mData.columns : 0;
h2 = getSample(cell + offset1).height;
h3 = getSample(cell + offset1 + 1).height;
//convex = (h3-h2) < (h1-h0);
convexity = (h1-h0) - (h3-h2);
}
break;
}
const PxI32 threshold = PxI32(mData.convexEdgeThreshold);
return convexity > threshold;
}
PX_INLINE bool Gu::HeightField::isValidTriangle(PxU32 triangleIndex) const
{
const PxU32 cell = triangleIndex >> 1;
const PxU32 row = cell / mData.columns;
if (row >= (mData.rows - 1)) return false;
const PxU32 column = cell % mData.columns;
if (column >= (mData.columns - 1)) return false;
return true;
}
PX_INLINE void Gu::HeightField::getTriangleVertexIndices(PxU32 triangleIndex, PxU32& vertexIndex0, PxU32& vertexIndex1, PxU32& vertexIndex2) const
{
const PxU32 cell = triangleIndex >> 1;
if (isZerothVertexShared(cell))
{
// <---- COL
// 0----2 1 R
// | 1 / /| O
// | / / | W
// | / / | |
// |/ / 0 | |
// 1 2----0 V
//
if (isFirstTriangle(triangleIndex))
{
vertexIndex0 = cell + mData.columns;
vertexIndex1 = cell;
vertexIndex2 = cell + mData.columns + 1;
}
else
{
vertexIndex0 = cell + 1;
vertexIndex1 = cell + mData.columns + 1;
vertexIndex2 = cell;
}
}
else
{
// <---- COL
// 2 1----0 R
// |\ \ 0 | O
// | \ \ | W
// | \ \ | |
// | 1 \ \| |
// 0----1 2 V
//
if (isFirstTriangle(triangleIndex))
{
vertexIndex0 = cell;
vertexIndex1 = cell + 1;
vertexIndex2 = cell + mData.columns;
}
else
{
vertexIndex0 = cell + mData.columns + 1;
vertexIndex1 = cell + mData.columns;
vertexIndex2 = cell + 1;
}
}
}
PX_INLINE void Gu::HeightField::getTriangleAdjacencyIndices(PxU32 triangleIndex, PxU32 vertexIndex0, PxU32 vertexIndex1, PxU32 vertexIndex2, PxU32& adjacencyIndex0, PxU32& adjacencyIndex1, PxU32& adjacencyIndex2) const
{
PX_UNUSED(vertexIndex0);
PX_UNUSED(vertexIndex1);
PX_UNUSED(vertexIndex2);
const PxU32 cell = triangleIndex >> 1;
if (isZerothVertexShared(cell))
{
// <---- COL
// 0----2 1 R
// | 1 / /| O
// | / / | W
// | / / | |
// |/ / 0 | |
// 1 2----0 V
//
if (isFirstTriangle(triangleIndex))
{
adjacencyIndex0 = 0xFFFFFFFF;
adjacencyIndex1 = triangleIndex + 1;
adjacencyIndex2 = 0xFFFFFFFF;
if((cell % (mData.columns) != 0))
{
adjacencyIndex0 = triangleIndex - 1;
}
if((cell / mData.columns != mData.rows - 2))
{
const PxU32 tMod = isZerothVertexShared(cell + mData.columns) ? 1u : 0u;
adjacencyIndex2 = ((cell + mData.columns) * 2) + tMod;
}
}
else
{
adjacencyIndex0 = 0xFFFFFFFF;
adjacencyIndex1 = triangleIndex - 1;
adjacencyIndex2 = 0xFFFFFFFF;
if(cell % (mData.columns) < (mData.columns - 2))
{
adjacencyIndex0 = triangleIndex + 1;
}
if(cell >= mData.columns - 1)
{
const PxU32 tMod = isZerothVertexShared(cell - mData.columns) ? 0u : 1u;
adjacencyIndex2 = ((cell - mData.columns) * 2) + tMod;
}
}
}
else
{
// <---- COL
// 2 1----0 R
// |\ \ 0 | O
// | \ \ | W
// | \ \ | |
// | 1 \ \| |
// 0----1 2 V
//
if (isFirstTriangle(triangleIndex))
{
adjacencyIndex0 = 0xFFFFFFFF;
adjacencyIndex1 = triangleIndex + 1;
adjacencyIndex2 = 0xFFFFFFFF;
if(cell >= mData.columns - 1)
{
const PxU32 tMod = isZerothVertexShared(cell - mData.columns) ? 0u : 1u;
adjacencyIndex0 = ((cell - (mData.columns)) * 2) + tMod;
}
if((cell % (mData.columns) != 0))
{
adjacencyIndex2 = triangleIndex - 1;
}
}
else
{
adjacencyIndex0 = 0xFFFFFFFF;
adjacencyIndex1 = triangleIndex - 1;
adjacencyIndex2 = 0xFFFFFFFF;
if((cell / mData.columns != mData.rows - 2))
{
const PxU32 tMod = isZerothVertexShared(cell + mData.columns) ? 1u : 0u;
adjacencyIndex0 = (cell + (mData.columns)) * 2 + tMod;
}
if(cell % (mData.columns) < (mData.columns - 2))
{
adjacencyIndex2 = triangleIndex + 1;
}
}
}
}
PX_INLINE PxVec3 Gu::HeightField::getTriangleNormalInternal(PxU32 triangleIndex) const
{
PxU32 v0, v1, v2;
getTriangleVertexIndices(triangleIndex, v0, v1, v2);
// const PxReal h0 = getHeight(v0);
// const PxReal h1 = getHeight(v1);
// const PxReal h2 = getHeight(v2);
const PxI32 h0 = getSample(v0).height;
const PxI32 h1 = getSample(v1).height;
const PxI32 h2 = getSample(v2).height;
const float thickness = 0.0f;
const PxReal coeff = physx::intrinsics::fsel(thickness, -1.0f, 1.0f);
// PxVec3 n(0,1,0);
const PxU32 cell = triangleIndex >> 1;
if (isZerothVertexShared(cell))
{
// <---- COL
// 0----2 1 R
// | 1 / /| O
// | / / | W
// | / / | |
// |/ / 0 | |
// 1 2----0 V
//
if (isFirstTriangle(triangleIndex))
{
// n.x = -(h0-h1);
// n.z = -(h2-h0);
return PxVec3(coeff*PxReal(h1-h0), coeff, coeff*PxReal(h0-h2));
}
else
{
// n.x = -(h1-h0);
// n.z = -(h0-h2);
return PxVec3(coeff*PxReal(h0-h1), coeff, coeff*PxReal(h2-h0));
}
}
else
{
// <---- COL
// 2 1----0 R
// |\ \ 0 | O
// | \ \ | W
// | \ \ | |
// | 1 \ \| |
// 0----1 2 V
//
if (isFirstTriangle(triangleIndex))
{
// n.x = -(h2-h0);
// n.z = -(h1-h0);
return PxVec3(coeff*PxReal(h0-h2), coeff, coeff*PxReal(h0-h1));
}
else
{
// n.x = -(h0-h2);
// n.z = -(h0-h1);
return PxVec3(coeff*PxReal(h2-h0), coeff, coeff*PxReal(h1-h0));
}
}
// return n;
}
PX_INLINE PxReal Gu::HeightField::getHeightInternal2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ) const
{
if (isZerothVertexShared(vertexIndex))
{
// <----Z---+
// +----+ |
// | /| |
// | / | X
// | / | |
// |/ | |
// +----+ |
// V
const PxReal h0 = getHeight(vertexIndex);
const PxReal h2 = getHeight(vertexIndex + mData.columns + 1);
if (fracZ > fracX)
{
// <----Z---+
// 1----0 |
// | / |
// | / X
// | / |
// |/ |
// 2 |
// V
const PxReal h1 = getHeight(vertexIndex + 1);
return h0 + fracZ*(h1-h0) + fracX*(h2-h1);
}
else
{
// <----Z---+
// 0 |
// /| |
// / | X
// / | |
// / | |
// 2----1 |
// V
const PxReal h1 = getHeight(vertexIndex + mData.columns);
return h0 + fracX*(h1-h0) + fracZ*(h2-h1);
}
}
else
{
// <----Z---+
// +----+ |
// |\ | |
// | \ | X
// | \ | |
// | \| |
// +----+ |
// V
const PxReal h2 = getHeight(vertexIndex + mData.columns);
const PxReal h1 = getHeight(vertexIndex + 1);
if (fracX + fracZ < 1.0f)
{
// <----Z---+
// 1----0 |
// \ | |
// \ | X
// \ | |
// \| |
// 2 |
// V
const PxReal h0 = getHeight(vertexIndex);
return h0 + fracZ*(h1-h0) + fracX*(h2-h0);
}
else
{
// <----Z---+
// 1 |
// |\ |
// | \ X
// | \ |
// | \ |
// 0----2 |
// V
//
// Note that we need to flip fracX and fracZ since we are moving the origin
const PxReal h0 = getHeight(vertexIndex + mData.columns + 1);
return h0 + (1.0f - fracZ)*(h2-h0) + (1.0f - fracX)*(h1-h0);
}
}
}
PX_INLINE PxVec3 Gu::HeightField::getNormal_2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const
{
PxVec3 normal;
if (isZerothVertexShared(vertexIndex))
{
// <----Z---+
// +----+ |
// | /| |
// | / | X
// | / | |
// |/ | |
// +----+ |
// V
// const PxReal h0 = getHeight(vertexIndex);
// const PxReal h2 = getHeight(vertexIndex + mData.columns + 1);
const PxI32 ih0 = getSample(vertexIndex).height;
const PxI32 ih2 = getSample(vertexIndex + mData.columns + 1).height;
if (fracZ >= fracX)
{
// <----Z---+
// 1----0 |
// | / |
// | / X
// | / |
// |/ |
// 2 |
// V
// const PxReal h0 = getHeight(vertexIndex);
// const PxReal h1 = getHeight(vertexIndex + 1);
// const PxReal h2 = getHeight(vertexIndex + mData.columns + 1);
// normal.set(-(h2-h1), 1.0f, -(h1-h0));
const PxI32 ih1 = getSample(vertexIndex + 1).height;
normal = PxVec3(PxReal(ih1 - ih2)*xcoeff, ycoeff, PxReal(ih0 - ih1)*zcoeff);
}
else
{
// <----Z---+
// 0 |
// /| |
// / | X
// / | |
// / | |
// 2----1 |
// V
// const PxReal h0 = getHeight(vertexIndex);
// const PxReal h1 = getHeight(vertexIndex + mData.columns);
// const PxReal h2 = getHeight(vertexIndex + mData.columns + 1);
// normal.set(-(h1-h0), 1.0f, -(h2-h1));
const PxI32 ih1 = getSample(vertexIndex + mData.columns).height;
normal = PxVec3(PxReal(ih0 - ih1)*xcoeff, ycoeff, PxReal(ih1 - ih2)*zcoeff);
}
}
else
{
// <----Z---+
// +----+ |
// |\ | |
// | \ | X
// | \ | |
// | \| |
// +----+ |
// V
const PxI32 ih1 = getSample(vertexIndex + 1).height;
const PxI32 ih2 = getSample(vertexIndex + mData.columns).height;
if (fracX + fracZ <= PxReal(1))
{
// <----Z---+
// 1----0 |
// \ | |
// \ | X
// \ | |
// \| |
// 2 |
// V
// const PxReal h0 = getHeight(vertexIndex);
// const PxReal h1 = getHeight(vertexIndex + 1);
// const PxReal h2 = getHeight(vertexIndex + mData.columns);
// normal.set(-(h2-h0), 1.0f, -(h1-h0));
const PxI32 ih0 = getSample(vertexIndex).height;
// const PxI32 ih1 = getSample(vertexIndex + 1).height;
// const PxI32 ih2 = getSample(vertexIndex + mData.columns).height;
normal = PxVec3(PxReal(ih0 - ih2)*xcoeff, ycoeff, PxReal(ih0 - ih1)*zcoeff);
}
else
{
// <----Z---+
// 2 |
// |\ |
// | \ X
// | \ |
// | \ |
// 0----1 |
// V
//
// Note that we need to flip fracX and fracZ since we are moving the origin
// const PxReal h2 = getHeight(vertexIndex + 1);
// const PxReal h1 = getHeight(vertexIndex + mData.columns);
// const PxReal h0 = getHeight(vertexIndex + mData.columns + 1);
// normal.set(-(h0-h2), 1.0f, -(h0-h1));
// const PxI32 ih2 = getSample(vertexIndex + 1).height;
// const PxI32 ih1 = getSample(vertexIndex + mData.columns).height;
const PxI32 ih0 = getSample(vertexIndex + mData.columns + 1).height;
// normal.set(PxReal(ih2 - ih0), 1.0f, PxReal(ih1b - ih0));
normal = PxVec3(PxReal(ih1 - ih0)*xcoeff, ycoeff, PxReal(ih2 - ih0)*zcoeff);
}
}
return normal;
}
PX_INLINE PxU32 Gu::HeightField::getTriangleIndex2(PxU32 cell, PxReal fracX, PxReal fracZ) const
{
if (isZerothVertexShared(cell))
return (fracZ > fracX) ? (cell << 1) + 1 : (cell << 1);
else
return (fracX + fracZ > 1) ? (cell << 1) + 1 : (cell << 1);
}
PX_INLINE PxU32 Gu::HeightField::getTriangleIndex(PxReal x, PxReal z) const
{
PxReal fracX, fracZ;
const PxU32 cell = computeCellCoordinates(x, z, fracX, fracZ);
return getTriangleIndex2(cell, fracX, fracZ);
}
PX_FORCE_INLINE void Gu::HeightField::getTriangleVertices(PxU32 triangleIndex, PxU32 row, PxU32 column, PxVec3& v0, PxVec3& v1, PxVec3& v2) const
{
PxU32 cell = triangleIndex >> 1;
PX_ASSERT(row * getNbColumnsFast() + column == cell);
PxReal h0 = getHeight(cell);
PxReal h1 = getHeight(cell + 1);
PxReal h2 = getHeight(cell + getNbColumnsFast());
PxReal h3 = getHeight(cell + getNbColumnsFast() + 1);
if (isFirstTriangle(triangleIndex))
{
if (isZerothVertexShared(cell))
{
// <---- COL
// 1 R
// /| O
// / | W
// / | |
// / 0 | |
// 2----0 V
//
v0 = PxVec3(PxReal(row + 1), h2, PxReal(column ));
v1 = PxVec3(PxReal(row ), h0, PxReal(column ));
v2 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1));
}
else
{
// <---- COL
// 1----0 R
// \ 0 | O
// \ | W
// \ | |
// \| |
// 2 V
//
v0 = PxVec3(PxReal(row ), h0, PxReal(column ));
v1 = PxVec3(PxReal(row ), h1, PxReal(column + 1));
v2 = PxVec3(PxReal(row + 1), h2, PxReal(column ));
}
}
else
{
if (isZerothVertexShared(cell))
{
// <---- COL
// 0----2 R
// | 1 / O
// | / W
// | / |
// |/ |
// 1 V
//
v0 = PxVec3(PxReal(row ), h1, PxReal(column + 1));
v1 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1));
v2 = PxVec3(PxReal(row ), h0, PxReal(column ));
}
else
{
// <---- COL
// 2 R
// |\ O
// | \ W
// | \ |
// | 1 \ |
// 0----1 V
//
v0 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1));
v1 = PxVec3(PxReal(row + 1), h2, PxReal(column ));
v2 = PxVec3(PxReal(row ), h1, PxReal(column + 1));
}
}
}
PX_FORCE_INLINE const Gu::HeightFieldData* _getHFData(const PxHeightFieldGeometry& hfGeom)
{
return &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
}
}
#endif
| 39,101 | C | 30.893964 | 218 | 0.550753 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightFieldData.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_HEIGHTFIELD_DATA_H
#define GU_HEIGHTFIELD_DATA_H
#include "foundation/PxSimpleTypes.h"
#include "geometry/PxHeightFieldFlag.h"
#include "geometry/PxHeightFieldSample.h"
#include "GuCenterExtents.h"
namespace physx
{
namespace Gu
{
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class
#endif
struct PX_PHYSX_COMMON_API HeightFieldData
{
// PX_SERIALIZATION
PX_FORCE_INLINE HeightFieldData() {}
PX_FORCE_INLINE HeightFieldData(const PxEMPTY) : flags(PxEmpty) {}
//~PX_SERIALIZATION
//properties
// PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading
CenterExtents mAABB;
PxU32 rows; // PT: WARNING: don't change this member's name (used in ConvX)
PxU32 columns; // PT: WARNING: don't change this member's name (used in ConvX)
PxU32 rowLimit;
PxU32 colLimit;
PxU32 nbColumns;
PxHeightFieldSample* samples; // PT: WARNING: don't change this member's name (used in ConvX)
PxReal convexEdgeThreshold;
PxHeightFieldFlags flags;
PxHeightFieldFormat::Enum format;
PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const
{
// PT: see compile-time assert below
return static_cast<const CenterExtentsPadded&>(mAABB);
}
};
#if PX_VC
#pragma warning(pop)
#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::HeightFieldData, rows)>=PX_OFFSET_OF(Gu::HeightFieldData, mAABB)+4);
} // namespace Gu
}
#endif
| 3,436 | C | 38.505747 | 113 | 0.722352 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuEntityReport.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_ENTITY_REPORT_H
#define GU_ENTITY_REPORT_H
#include "PxQueryReport.h"
namespace physx
{
namespace Gu
{
class EntityReport
{
public:
virtual ~EntityReport() {}
virtual bool onEvent(PxU32 nbEntities, const PxU32* entities) = 0;
};
class OverlapReport
{
public:
virtual ~OverlapReport() {}
virtual bool reportTouchedTris(PxU32 nbEntities, const PxU32* entities) = 0;
};
} // namespace Gu
}
#endif
| 2,136 | C | 34.032786 | 78 | 0.751404 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightFieldUtil.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_HEIGHTFIELD_UTIL_H
#define GU_HEIGHTFIELD_UTIL_H
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxTriangle.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxSIMDHelpers.h"
#include "GuHeightField.h"
#include "../intersection/GuIntersectionRayTriangle.h"
#include "../intersection/GuIntersectionRayBox.h"
namespace physx
{
#define HF_SWEEP_REPORT_BUFFER_SIZE 64
#define HF_OVERLAP_REPORT_BUFFER_SIZE 64
namespace Gu
{
class OverlapReport;
// PT: this is used in the context of sphere-vs-heightfield overlaps
PX_FORCE_INLINE PxVec3 getLocalSphereData(PxBounds3& localBounds, const PxTransform& pose0, const PxTransform& pose1, float radius)
{
const PxVec3 localSphereCenter = pose1.transformInv(pose0.p);
const PxVec3 extents(radius);
localBounds.minimum = localSphereCenter - extents;
localBounds.maximum = localSphereCenter + extents;
return localSphereCenter;
}
PX_FORCE_INLINE PxBounds3 getLocalCapsuleBounds(float radius, float halfHeight)
{
const PxVec3 extents(halfHeight + radius, radius, radius);
return PxBounds3(-extents, extents);
}
class PX_PHYSX_COMMON_API HeightFieldUtil
{
public:
PxReal mOneOverRowScale;
PxReal mOneOverHeightScale;
PxReal mOneOverColumnScale;
const Gu::HeightField* mHeightField;
const PxHeightFieldGeometry* mHfGeom;
PX_FORCE_INLINE HeightFieldUtil(const PxHeightFieldGeometry& hfGeom) : mHeightField(static_cast<const Gu::HeightField*>(hfGeom.heightField)), mHfGeom(&hfGeom)
{
const PxReal absRowScale = PxAbs(mHfGeom->rowScale);
const PxReal absColScale = PxAbs(mHfGeom->columnScale);
//warning #1931-D on WIIU: sizeof is not a type, variable, or dereferenced pointer expression
PX_COMPILE_TIME_ASSERT(sizeof(reinterpret_cast<PxHeightFieldSample*>(0)->height) == 2);
//PxReal minHeightPerSample = PX_MIN_HEIGHTFIELD_Y_SCALE;
PX_ASSERT(mHfGeom->heightScale >= PX_MIN_HEIGHTFIELD_Y_SCALE);
PX_ASSERT(absRowScale >= PX_MIN_HEIGHTFIELD_XZ_SCALE);
PX_ASSERT(absColScale >= PX_MIN_HEIGHTFIELD_XZ_SCALE);
PX_UNUSED(absRowScale);
PX_UNUSED(absColScale);
//using physx::intrinsics::fsel;
//mOneOverHeightScale = fsel(mHfGeom->heightScale - minHeightPerSample, 1.0f / mHfGeom->heightScale, 1.0f / minHeightPerSample);
mOneOverHeightScale = 1.0f / mHfGeom->heightScale;
mOneOverRowScale = 1.0f / mHfGeom->rowScale;
mOneOverColumnScale = 1.0f / mHfGeom->columnScale;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const Gu::HeightField& getHeightField() const { return *mHeightField; }
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxHeightFieldGeometry& getHeightFieldGeometry() const { return *mHfGeom; }
PX_FORCE_INLINE PxReal getOneOverRowScale() const { return mOneOverRowScale; }
PX_FORCE_INLINE PxReal getOneOverHeightScale() const { return mOneOverHeightScale; }
PX_FORCE_INLINE PxReal getOneOverColumnScale() const { return mOneOverColumnScale; }
void computeLocalBounds(PxBounds3& bounds) const;
PX_FORCE_INLINE PxReal getHeightAtShapePoint(PxReal x, PxReal z) const
{
return mHfGeom->heightScale * mHeightField->getHeightInternal(x * mOneOverRowScale, z * mOneOverColumnScale);
}
PX_FORCE_INLINE PxVec3 getNormalAtShapePoint(PxReal x, PxReal z) const
{
return mHeightField->getNormal_(x * mOneOverRowScale, z * mOneOverColumnScale, mOneOverRowScale, mOneOverHeightScale, mOneOverColumnScale);
}
PxU32 getTriangle(const PxTransform&, PxTriangle& worldTri, PxU32* vertexIndices, PxU32* adjacencyIndices, PxTriangleID triangleIndex, bool worldSpaceTranslation=true, bool worldSpaceRotation=true) const;
void overlapAABBTriangles(const PxBounds3& localBounds, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const;
PX_FORCE_INLINE void overlapAABBTriangles0to1(const PxTransform& pose0to1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const
{
// PT: TODO: optimize PxBounds3::transformFast
//overlapAABBTriangles(PxBounds3::transformFast(pose0to1, bounds0), callback, batchSize);
{
// PT: below is the equivalent, slightly faster code. Still not optimal but better.
// PT: TODO: refactor with GuBounds.cpp
const PxMat33Padded basis(pose0to1.q);
// PT: TODO: pass c/e directly
const PxBounds3 b = PxBounds3::basisExtent(pose0to1.transform(bounds0.getCenter()), basis, bounds0.getExtents());
overlapAABBTriangles(b, callback, batchSize);
}
}
PX_FORCE_INLINE void overlapAABBTriangles(const PxTransform& pose1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const
{
overlapAABBTriangles0to1(pose1.getInverse(), bounds0, callback, batchSize);
}
PX_FORCE_INLINE void overlapAABBTriangles(const PxTransform& pose0, const PxTransform& pose1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const
{
overlapAABBTriangles0to1(pose1.transformInv(pose0), bounds0, callback, batchSize);
}
PX_FORCE_INLINE PxVec3 hf2shapen(const PxVec3& v) const
{
return PxVec3(v.x * mOneOverRowScale, v.y * mOneOverHeightScale, v.z * mOneOverColumnScale);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 shape2hfp(const PxVec3& v) const
{
return PxVec3(v.x * mOneOverRowScale, v.y * mOneOverHeightScale, v.z * mOneOverColumnScale);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 hf2shapep(const PxVec3& v) const
{
return PxVec3(v.x * mHfGeom->rowScale, v.y * mHfGeom->heightScale, v.z * mHfGeom->columnScale);
}
PX_INLINE PxVec3 hf2worldp(const PxTransform& pose, const PxVec3& v) const
{
const PxVec3 s = hf2shapep(v);
return pose.transform(s);
}
PX_INLINE PxVec3 hf2worldn(const PxTransform& pose, const PxVec3& v) const
{
const PxVec3 s = hf2shapen(v);
return pose.q.rotate(s);
}
};
class PX_PHYSX_COMMON_API HeightFieldTraceUtil : public HeightFieldUtil
{
public:
PX_FORCE_INLINE HeightFieldTraceUtil(const PxHeightFieldGeometry& hfGeom) : HeightFieldUtil(hfGeom) {}
// floor and ceil don't clamp down exact integers but we want that
static PX_FORCE_INLINE PxF32 floorDown(PxF32 x) { PxF32 f = PxFloor(x); return (f == x) ? f-1 : f; }
static PX_FORCE_INLINE PxF32 ceilUp (PxF32 x) { PxF32 f = PxCeil (x); return (f == x) ? f+1 : f; }
// helper class for testing triangle height and reporting the overlapped triangles
template<class T>
class OverlapTraceSegment
{
public:
// helper rectangle struct
struct OverlapRectangle
{
PxI32 mMinu;
PxI32 mMaxu;
PxI32 mMinv;
PxI32 mMaxv;
void invalidate()
{
mMinu = 1;
mMaxu = -1;
mMinv = 1;
mMaxv = -1;
}
};
// helper line struct
struct OverlapLine
{
bool mColumn;
PxI32 mLine;
PxI32 mMin;
PxI32 mMax;
void invalidate()
{
mMin = 1;
mMax = -1;
}
};
public:
void operator = (OverlapTraceSegment&) {}
OverlapTraceSegment(const HeightFieldUtil& hfUtil,const Gu::HeightField& hf)
: mInitialized(false), mHfUtil(hfUtil), mHf(hf), mNbIndices(0) {}
PX_FORCE_INLINE bool initialized() const { return mInitialized; }
// prepare for iterations, set the expand u|v
PX_INLINE void prepare(const PxVec3& aP0, const PxVec3& aP1, const PxVec3& overlapObjectExtent, PxF32& expandu, PxF32& expandv)
{
// height test bounds
mMinY = (PxMin(aP1.y,aP0.y) - overlapObjectExtent.y) * mHfUtil.getOneOverHeightScale();
mMaxY = (PxMax(aP1.y,aP0.y) + overlapObjectExtent.y) * mHfUtil.getOneOverHeightScale();
// sets the clipping variables
mMinRow = PxI32(mHf.getMinRow((PxMin(aP1.x,aP0.x) - overlapObjectExtent.x)* mHfUtil.getOneOverRowScale()));
mMaxRow = PxI32(mHf.getMaxRow((PxMax(aP1.x,aP0.x) + overlapObjectExtent.x)* mHfUtil.getOneOverRowScale()));
mMinColumn = PxI32(mHf.getMinColumn((PxMin(aP1.z,aP0.z) - overlapObjectExtent.z)* mHfUtil.getOneOverColumnScale()));
mMaxColumn = PxI32(mHf.getMaxColumn((PxMax(aP1.z,aP0.z) + overlapObjectExtent.z)* mHfUtil.getOneOverColumnScale()));
// sets the expanded u|v coordinates
expandu = PxCeil(overlapObjectExtent.x*mHfUtil.getOneOverRowScale());
expandv = PxCeil(overlapObjectExtent.z*mHfUtil.getOneOverColumnScale());
// sets the offset that will be overlapped in each axis
mOffsetU = PxI32(expandu) + 1;
mOffsetV = PxI32(expandv) + 1;
}
// sets all necessary variables and makes initial rectangle setup and overlap
PX_INLINE bool init(const PxI32 ui, const PxI32 vi, const PxI32 nbVi, const PxI32 step_ui, const PxI32 step_vi, T* aCallback)
{
mInitialized = true;
mCallback = aCallback;
mNumColumns = nbVi;
mStep_ui = step_ui > 0 ? 0 : -1;
mStep_vi = step_vi > 0 ? 0 : -1;
// sets the rectangles
mCurrentRectangle.invalidate();
mPreviousRectangle.mMinu = ui - mOffsetU;
mPreviousRectangle.mMaxu = ui + mOffsetU;
mPreviousRectangle.mMinv = vi - mOffsetV;
mPreviousRectangle.mMaxv = vi + mOffsetV;
// visits all cells in given initial rectangle
if(!visitCells(mPreviousRectangle))
return false;
// reports all overlaps
if(!reportOverlaps())
return false;
return true;
}
// u|v changed, check for new rectangle - compare with previous one and parse
// the added line, which is a result from the rectangle compare
PX_INLINE bool step(const PxI32 ui, const PxI32 vi)
{
mCurrentRectangle.mMinu = ui - mOffsetU;
mCurrentRectangle.mMaxu = ui + mOffsetU;
mCurrentRectangle.mMinv = vi - mOffsetV;
mCurrentRectangle.mMaxv = vi + mOffsetV;
OverlapLine line = OverlapLine();
line.invalidate();
computeRectangleDifference(mCurrentRectangle,mPreviousRectangle,line);
if(!visitCells(line))
return false;
if(!reportOverlaps())
return false;
mPreviousRectangle = mCurrentRectangle;
return true;
}
PX_INLINE void computeRectangleDifference(const OverlapRectangle& currentRectangle, const OverlapRectangle& previousRectangle, OverlapLine& line)
{
// check if u changes - add the row for visit
if(currentRectangle.mMinu != previousRectangle.mMinu)
{
line.mColumn = false;
line.mLine = currentRectangle.mMinu < previousRectangle.mMinu ? currentRectangle.mMinu : currentRectangle.mMaxu;
line.mMin = currentRectangle.mMinv;
line.mMax = currentRectangle.mMaxv;
return;
}
// check if v changes - add the column for visit
if(currentRectangle.mMinv != previousRectangle.mMinv)
{
line.mColumn = true;
line.mLine = currentRectangle.mMinv < previousRectangle.mMinv ? currentRectangle.mMinv : currentRectangle.mMaxv;
line.mMin = currentRectangle.mMinu;
line.mMax = currentRectangle.mMaxu;
}
}
// visits all cells in given rectangle
PX_INLINE bool visitCells(const OverlapRectangle& rectangle)
{
for(PxI32 ui = rectangle.mMinu + mStep_ui; ui <= rectangle.mMaxu + mStep_ui; ui++)
{
if(ui < mMinRow)
continue;
if(ui >= mMaxRow)
break;
for(PxI32 vi = rectangle.mMinv + mStep_vi; vi <= rectangle.mMaxv + mStep_vi; vi++)
{
if(vi < mMinColumn)
continue;
if(vi >= mMaxColumn)
break;
const PxI32 vertexIndex = ui*mNumColumns + vi;
if(!testVertexIndex(PxU32(vertexIndex)))
return false;
}
}
return true;
}
// visits all cells in given line - can be row or column
PX_INLINE bool visitCells(const OverlapLine& line)
{
if(line.mMin > line.mMax)
return true;
if(line.mColumn)
{
const PxI32 vi = line.mLine + mStep_vi;
// early exit if column is out of hf clip area
if(vi < mMinColumn)
return true;
if(vi >= mMaxColumn)
return true;
for(PxI32 ui = line.mMin + mStep_ui; ui <= line.mMax + mStep_ui; ui++)
{
// early exit or continue if row is out of hf clip area
if(ui >= mMaxRow)
break;
// continue if we did not reach the valid area, we can still get there
if(ui < mMinRow)
continue;
// if the cell has not been tested test and report
if(!testVertexIndex(PxU32(mNumColumns * ui + vi)))
return false;
}
}
else
{
const PxI32 ui = line.mLine + mStep_ui;
// early exit if row is out of hf clip area
if(ui < mMinRow)
return true;
if(ui >= mMaxRow)
return true;
for(PxI32 vi = line.mMin + mStep_vi; vi <= line.mMax + mStep_vi; vi++)
{
// early exit or continue if column is out of hf clip area
if(vi >= mMaxColumn)
break;
// continue if we did not reach the valid area, we can still get there
if(vi < mMinColumn)
continue;
// if the cell has not been tested test and report
if(!testVertexIndex(PxU32(mNumColumns * ui + vi)))
return false;
}
}
return true;
}
// does height check and if succeeded adds to report
PX_INLINE bool testVertexIndex(const PxU32 vertexIndex)
{
const PxReal h0 = mHf.getHeight(vertexIndex);
const PxReal h1 = mHf.getHeight(vertexIndex + 1);
const PxReal h2 = mHf.getHeight(vertexIndex + mNumColumns);
const PxReal h3 = mHf.getHeight(vertexIndex + mNumColumns + 1);
// actual height test, if some height pass we accept the cell
if(!((mMaxY < h0 && mMaxY < h1 && mMaxY < h2 && mMaxY < h3) || (mMinY > h0 && mMinY > h1 && mMinY > h2 && mMinY > h3)))
{
// check if the triangle is not a hole
if(mHf.getMaterialIndex0(vertexIndex) != PxHeightFieldMaterial::eHOLE)
{
if(!addIndex(vertexIndex*2))
return false;
}
if(mHf.getMaterialIndex1(vertexIndex) != PxHeightFieldMaterial::eHOLE)
{
if(!addIndex(vertexIndex*2 + 1))
return false;
}
}
return true;
}
// add triangle index, if we get out of buffer size, report them
bool addIndex(PxU32 triangleIndex)
{
if(mNbIndices == HF_SWEEP_REPORT_BUFFER_SIZE)
{
if(!reportOverlaps())
return false;
}
mIndexBuffer[mNbIndices++] = triangleIndex;
return true;
}
PX_FORCE_INLINE bool reportOverlaps()
{
if(mNbIndices)
{
if(!mCallback->onEvent(mNbIndices, mIndexBuffer))
return false;
mNbIndices = 0;
}
return true;
}
private:
bool mInitialized;
const HeightFieldUtil& mHfUtil;
const Gu::HeightField& mHf;
T* mCallback;
PxI32 mOffsetU;
PxI32 mOffsetV;
float mMinY;
float mMaxY;
PxI32 mMinRow;
PxI32 mMaxRow;
PxI32 mMinColumn;
PxI32 mMaxColumn;
PxI32 mNumColumns;
PxI32 mStep_ui;
PxI32 mStep_vi;
OverlapRectangle mPreviousRectangle;
OverlapRectangle mCurrentRectangle;
PxU32 mIndexBuffer[HF_SWEEP_REPORT_BUFFER_SIZE];
PxU32 mNbIndices;
};
// If useUnderFaceCalblack is false, traceSegment will report segment/triangle hits via
// faceHit(const Gu::HeightFieldUtil& hf, const PxVec3& point, PxU32 triangleIndex)
// Otherwise traceSegment will report all triangles the segment passes under via
// underFaceHit(const Gu::HeightFieldUtil& hf, const PxVec3& triNormal, const PxVec3& crossedEdge,
// PxF32 x, PxF32 z, PxF32 rayHeight, PxU32 triangleIndex)
// where x,z is the point of previous intercept in hf coords, rayHeight is at that same point
// crossedEdge is the edge vector crossed from last call to underFaceHit, undefined for first call
// Note that underFaceHit can be called when a line is above a triangle if it's within AABB for that hf cell
// Note that backfaceCull is ignored if useUnderFaceCallback is true
// overlapObjectExtent (localSpace) and overlap are used for triangle collecting using an inflated tracesegment
// Note that hfLocalBounds are passed as a parameter instead of being computed inside the traceSegment.
// The localBounds can be obtained: PxBounds3 hfLocalBounds; hfUtil.computeLocalBounds(hfLocalBounds); and passed as
// a parameter.
template<class T, bool useUnderFaceCallback, bool overlap>
PX_INLINE void traceSegment(const PxVec3& aP0, const PxVec3& rayDir, const float rayLength , T* aCallback, const PxBounds3& hfLocalBounds, bool backfaceCull,
const PxVec3* overlapObjectExtent = NULL) const
{
PxF32 tnear, tfar;
if(!Gu::intersectRayAABB2(hfLocalBounds.minimum, hfLocalBounds.maximum, aP0, rayDir, rayLength, tnear, tfar))
return;
const PxVec3 p0 = aP0 + rayDir * tnear;
const PxVec3 p1 = aP0 + rayDir * tfar;
// helper class used for overlap tests
OverlapTraceSegment<T> overlapTraceSegment(*this, *mHeightField);
// values which expand the HF area
PxF32 expandu = 0.0f, expandv = 0.0f;
if (overlap)
{
// setup overlap variables
overlapTraceSegment.prepare(aP0,aP0 + rayDir*rayLength,*overlapObjectExtent,expandu,expandv);
}
// row = x|u, column = z|v
const PxF32 rowScale = mHfGeom->rowScale, columnScale = mHfGeom->columnScale, heightScale = mHfGeom->heightScale;
const PxI32 nbVi = PxI32(mHeightField->getNbColumnsFast()), nbUi = PxI32(mHeightField->getNbRowsFast());
PX_ASSERT(nbVi > 0 && nbUi > 0);
// clampEps is chosen so that we get a reasonable clamp value for 65536*0.9999999f = 65535.992187500000
const PxF32 clampEps = 1e-7f; // shrink u,v to within 1e-7 away from the world bounds
// we now clamp uvs to [1e-7, rowLimit-1e-7] to avoid out of range uvs and eliminate related checks in the loop
const PxF32 nbUcells = PxF32(nbUi-1)*(1.0f-clampEps), nbVcells = PxF32(nbVi-1)*(1.0f-clampEps);
// if u0,v0 is near an integer, shift up or down in direction opposite to du,dv by PxMax(|u,v|*1e-7, 1e-7)
// (same direction as du,dv for u1,v1)
// we do this to ensure that we get at least one intersection with u or v when near the cell edge to eliminate special cases in the loop
// we need to extend the field for the inflated radius, we will now operate even with negative u|v
// map p0 from (x, z, y) to (u0, v0, h0)
// we need to use the unclamped values, otherwise we change the direction of the traversal
const PxF32 uu0 = p0.x * mOneOverRowScale;
PxF32 u0 = PxMin(PxMax(uu0, 1e-7f - expandu), nbUcells + expandu); // multiplication rescales the u,v grid steps to 1
const PxF32 uv0 = p0.z * mOneOverColumnScale;
PxF32 v0 = PxMin(PxMax(uv0, 1e-7f - expandv), nbVcells + expandv);
const PxReal h0 = p0.y; // we don't scale y
// map p1 from (x, z, y) to (u1, v1, h1)
// we need to use the unclamped values, otherwise we change the direction of the traversal
const PxF32 uu1 = p1.x * mOneOverRowScale;
const PxF32 uv1 = p1.z * mOneOverColumnScale;
const PxReal h1 = p1.y; // we don't scale y
PxF32 du = uu1 - uu0, dv = uv1 - uv0; // recompute du, dv from adjusted uvs
const PxReal dh = h1 - h0;
// grid u&v step is always either 1 or -1, we precompute as both integers and floats to avoid conversions
// so step_uif is +/-1.0f, step_ui is +/-1
const PxF32 step_uif = PxSign(du), step_vif = PxSign(dv);
const PxI32 step_ui = PxI32(step_uif), step_vi = PxI32(step_vif);
// clamp magnitude of du, dv to at least clampEpsilon to avoid special cases when dividing
const PxF32 divEpsilon = 1e-10f;
if(PxAbs(du) < divEpsilon)
du = step_uif * divEpsilon;
if(PxAbs(dv) < divEpsilon)
dv = step_vif * divEpsilon;
const PxVec3 auhP0(aP0.x*mOneOverRowScale, aP0.y, aP0.z*mOneOverColumnScale);
const PxVec3 duhv(rayDir.x*rayLength*mOneOverRowScale, rayDir.y*rayLength, rayDir.z*rayLength*mOneOverColumnScale);
const PxReal duhvLength = duhv.magnitude();
PxVec3 duhvNormalized = duhv;
if(duhvLength > PX_NORMALIZATION_EPSILON)
duhvNormalized *= 1.0f/duhvLength;
// Math derivation:
// points on 2d segment are parametrized as: [u0,v0] + t [du, dv]. We solve for t_u[n], t for nth u-intercept
// u0 + t_un du = un
// t_un = (un-u0) / du
// t_un1 = (un+1-u0) / du ; we use +1 since we rescaled the grid step to 1
// therefore step_tu = t_un - t_un1 = 1/du
// seed the initial integer cell coordinates with u0, v0 rounded up or down with standard PxFloor/Ceil behavior
// to ensure we have the correct first cell between (ui,vi) and (ui+step_ui,vi+step_vi)
PxI32 ui = (du > 0.0f) ? PxI32(PxFloor(u0)) : PxI32(PxCeil(u0));
PxI32 vi = (dv > 0.0f) ? PxI32(PxFloor(v0)) : PxI32(PxCeil(v0));
// find the nearest integer u, v in ray traversal direction and corresponding tu and tv
const PxReal uhit0 = du > 0.0f ? ceilUp(u0) : floorDown(u0);
const PxReal vhit0 = dv > 0.0f ? ceilUp(v0) : floorDown(v0);
// tu, tv can be > 1 but since the loop is structured as do {} while(tMin < tEnd) we still visit the first cell
PxF32 last_tu = 0.0f, last_tv = 0.0f;
PxReal tu = (uhit0 - uu0) / du;
PxReal tv = (vhit0 - uv0) / dv;
if(tu < 0.0f) // negative value may happen, as we may have started out of the AABB (since we did enlarge it)
tu = PxAbs(clampEps / du);
if(tv < 0.0f) // negative value may happen, as we may have started out of the AABB (since we did enlarge it)
tv = PxAbs(clampEps / dv);
// compute step_tu and step_tv; t steps per grid cell in u and v direction
const PxReal step_tu = 1.0f / PxAbs(du), step_tv = 1.0f / PxAbs(dv);
// t advances at the same rate for u, v and h therefore we can compute h at u,v grid intercepts
#define COMPUTE_H_FROM_T(t) (h0 + (t) * dh)
const PxF32 hEpsilon = 1e-4f;
PxF32 uif = PxF32(ui), vif = PxF32(vi);
// these are used to remap h values to correspond to u,v increasing order
PxI32 uflip = 1-step_ui; /*0 or 2*/
PxI32 vflip = (1-step_vi)/2; /*0 or 1*/
// this epsilon is needed to ensure that we include the last [t, t+1] range in the do {} while(t<tEnd) loop
// A.B. in case of overlap we do miss actually a line with this epsilon, should it not be +?
PxF32 tEnd = 1.0f - 1e-4f;
if(overlap)
tEnd = 1.0f + 1e-4f;
PxF32 tMinUV;
const Gu::HeightField& hf = *mHeightField;
// seed hLinePrev as h(0)
PxReal hLinePrev = COMPUTE_H_FROM_T(0);
do
{
tMinUV = PxMin(tu, tv); // determine where next closest u or v-intercept point is
PxF32 hLineNext = COMPUTE_H_FROM_T(tMinUV); // compute the corresponding h
// the operating u|v space has been extended by expandu|expandv if inflation is used
PX_ASSERT(ui >= 0 - expandu && ui < nbUi + expandu && vi >= 0 - expandv && vi < nbVi + expandv);
PX_ASSERT(ui+step_ui >= 0 - expandu && ui+step_ui < nbUi + expandu && vi+step_vi >= 0 - expandv && vi+step_vi < nbVi + expandv);
// handle overlap in overlapCallback
if(overlap)
{
if(!overlapTraceSegment.initialized())
{
// initial overlap and setup
if(!overlapTraceSegment.init(ui,vi,nbVi,step_ui,step_vi,aCallback))
return;
}
else
{
// overlap step
if(!overlapTraceSegment.step(ui,vi))
return;
}
}
else
{
const PxU32 colIndex0 = PxU32(nbVi * ui + vi);
const PxU32 colIndex1 = PxU32(nbVi * (ui + step_ui) + vi);
const PxReal h[4] = { // h[0]=h00, h[1]=h01, h[2]=h10, h[3]=h11 - oriented relative to step_uv
hf.getHeight(colIndex0) * heightScale, hf.getHeight(colIndex0 + step_vi) * heightScale,
hf.getHeight(colIndex1) * heightScale, hf.getHeight(colIndex1 + step_vi) * heightScale };
PxF32 minH = PxMin(PxMin(h[0], h[1]), PxMin(h[2], h[3]));
PxF32 maxH = PxMax(PxMax(h[0], h[1]), PxMax(h[2], h[3]));
// how much space in h have we covered from previous to current u or v intercept
PxF32 hLineCellRangeMin = PxMin(hLinePrev, hLineNext);
PxF32 hLineCellRangeMax = PxMax(hLinePrev, hLineNext);
// do a quick overlap test in h, this should be rejecting the vast majority of tests
if(!(hLineCellRangeMin-hEpsilon > maxH || hLineCellRangeMax+hEpsilon < minH) ||
(useUnderFaceCallback && hLineCellRangeMax < maxH))
{
// arrange h so that h00 corresponds to min(uif, uif+step_uif) h10 to max et c.
// this is only needed for backface culling to work so we know the proper winding order without branches
// uflip is 0 or 2, vflip is 0 or 1 (corresponding to positive and negative ui_step and vi_step)
const PxF32 h00 = h[0+uflip+vflip];
const PxF32 h01 = h[1+uflip-vflip];
const PxF32 h10 = h[2-uflip+vflip];
const PxF32 h11 = h[3-uflip-vflip];
const PxF32 minuif = PxMin(uif, uif+step_uif);
const PxF32 maxuif = PxMax(uif, uif+step_uif);
const PxF32 minvif = PxMin(vif, vif+step_vif);
const PxF32 maxvif = PxMax(vif, vif+step_vif);
const PxVec3 p00(minuif, h00, minvif);
const PxVec3 p01(minuif, h01, maxvif);
const PxVec3 p10(maxuif, h10, minvif);
const PxVec3 p11(maxuif, h11, maxvif);
const PxF32 enlargeEpsilon = 0.0001f;
const PxVec3* p00a = &p00, *p01a = &p01, *p10a = &p10, *p11a = &p11;
PxU32 minui = PxU32(PxMin(ui+step_ui, ui)), minvi = PxU32(PxMin(vi+step_vi, vi));
// row = x|u, column = z|v
const PxU32 vertIndex = nbVi * minui + minvi;
const PxU32 cellIndex = vertIndex; // this adds a dummy unused cell in the end of each row; was -minui
bool isZVS = hf.isZerothVertexShared(vertIndex);
if(!isZVS)
{
// rotate the pointers for flipped edge cells
p10a = &p00;
p00a = &p01;
p01a = &p11;
p11a = &p10;
}
// For triangle index computation, see illustration in Gu::HeightField::getTriangleNormal()
// Since row = u, column = v
// for zeroth vert shared the 10 index is the corner of the 0-index triangle, and 01 is 1-index
// if zeroth vertex is not shared, the 00 index is the corner of 0-index triangle
if(!useUnderFaceCallback)
{
PxReal triT0 = PX_MAX_REAL, triT1 = PX_MAX_REAL;
bool hit0 = false, hit1 = false;
PxF32 triU0, triV0, triU1, triV1;
// PT: TODO: consider testing hole first and skipping ray-tri test. Might be faster.
if(Gu::intersectRayTriangle(auhP0, duhvNormalized, *p10a, *p00a, *p11a, triT0, triU0, triV0, backfaceCull, enlargeEpsilon) && triT0 >= 0.0f && triT0 <= duhvLength && (hf.getMaterialIndex0(vertIndex) != PxHeightFieldMaterial::eHOLE))
{
hit0 = true;
}
else
triT0 = PX_MAX_REAL;
if(Gu::intersectRayTriangle(auhP0, duhvNormalized, *p01a, *p11a, *p00a, triT1, triU1, triV1, backfaceCull, enlargeEpsilon) && triT1 >= 0.0f && triT1 <= duhvLength && (hf.getMaterialIndex1(vertIndex) != PxHeightFieldMaterial::eHOLE))
{
hit1 = true;
}
else
triT1 = PX_MAX_REAL;
if(hit0 && triT0 <= triT1)
{
const PxVec3 hitPoint((auhP0.x + duhvNormalized.x*triT0) * rowScale, auhP0.y + duhvNormalized.y * triT0, (auhP0.z + duhvNormalized.z*triT0) * columnScale);
if(!aCallback->faceHit(*this, hitPoint, cellIndex*2, triU0, triV0))
return;
if(hit1) // possible to hit both triangles in a cell with eMESH_MULTIPLE
{
PxVec3 hitPoint1((auhP0.x + duhvNormalized.x*triT1) * rowScale, auhP0.y + duhvNormalized.y * triT1, (auhP0.z + duhvNormalized.z*triT1) * columnScale);
if(!aCallback->faceHit(*this, hitPoint1, cellIndex*2 + 1, triU1, triV1))
return;
}
}
else if(hit1 && triT1 <= triT0)
{
PxVec3 hitPoint((auhP0.x + duhvNormalized.x*triT1) * rowScale, auhP0.y + duhvNormalized.y * triT1, (auhP0.z + duhvNormalized.z*triT1) * columnScale);
if(!aCallback->faceHit(*this, hitPoint, cellIndex*2 + 1, triU1, triV1))
return;
if(hit0) // possible to hit both triangles in a cell with eMESH_MULTIPLE
{
PxVec3 hitPoint1((auhP0.x + duhvNormalized.x*triT0) * rowScale, auhP0.y + duhvNormalized.y * triT0, (auhP0.z + duhvNormalized.z*triT0) * columnScale);
if(!aCallback->faceHit(*this, hitPoint1, cellIndex*2, triU0, triV0))
return;
}
}
}
else
{
// TODO: quite a few optimizations are possible here. edges can be shared, intersectRayTriangle inlined etc
// Go to shape space. Height is already in shape space so we only scale x and z
const PxVec3 p00s(p00a->x * rowScale, p00a->y, p00a->z * columnScale);
const PxVec3 p01s(p01a->x * rowScale, p01a->y, p01a->z * columnScale);
const PxVec3 p10s(p10a->x * rowScale, p10a->y, p10a->z * columnScale);
const PxVec3 p11s(p11a->x * rowScale, p11a->y, p11a->z * columnScale);
PxVec3 triNormals[2] = { (p00s - p10s).cross(p11s - p10s), (p11s - p01s).cross(p00s-p01s) };
triNormals[0] *= PxRecipSqrt(triNormals[0].magnitudeSquared());
triNormals[1] *= PxRecipSqrt(triNormals[1].magnitudeSquared());
// since the heightfield can be mirrored with negative rowScale or columnScale, this assert doesn't hold
//PX_ASSERT(triNormals[0].y >= 0.0f && triNormals[1].y >= 0.0f);
// at this point we need to compute the edge direction that we crossed
// also since we don't DDA the w we need to find u,v for w-intercept (w refers to diagonal adjusted with isZVS)
const PxF32 wnu = isZVS ? -1.0f : 1.0f, wnv = 1.0f; // uv-normal to triangle edge that splits the cell
const PxF32 wpu = uif + 0.5f * step_uif, wpv = vif + 0.5f * step_vif; // a point on triangle edge that splits the cell
// note that (wpu, wpv) is on both edges (for isZVS and non-ZVS cases) which is nice
// we clamp tNext to 1 because we still want to issue callbacks even if we stay in one cell
// note that tNext can potentially be arbitrarily large for a segment contained within a cell
const PxF32 tNext = PxMin(PxMin(tu, tv), 1.0f), tPrev = PxMax(last_tu, last_tv);
// compute uvs corresponding to tPrev, tNext
const PxF32 unext = u0 + tNext*du, vnext = v0 + tNext*dv;
const PxF32 uprev = u0 + tPrev*du, vprev = v0 + tPrev*dv;
const PxReal& h00_ = h[0], &h01_ = h[1], &h10_ = h[2]/*, h11_ = h[3]*/; // aliases for step-oriented h
// (wpu, wpv) is a point on the diagonal
// we compute a dot of ((unext, vnext) - (wpu, wpv), wn) to see on which side of triangle edge we are
// if the dot is positive we need to add 1 to triangle index
const PxU32 dotPrevGtz = PxU32(((uprev - wpu) * wnu + (vprev - wpv) * wnv) > 0);
const PxU32 dotNextGtz = PxU32(((unext - wpu) * wnu + (vnext - wpv) * wnv) > 0);
const PxU32 triIndex0 = cellIndex*2 + dotPrevGtz;
const PxU32 triIndex1 = cellIndex*2 + dotNextGtz;
PxU32 isHole0 = PxU32(hf.getMaterialIndex0(vertIndex) == PxHeightFieldMaterial::eHOLE);
PxU32 isHole1 = PxU32(hf.getMaterialIndex1(vertIndex) == PxHeightFieldMaterial::eHOLE);
if(triIndex0 > triIndex1)
PxSwap<PxU32>(isHole0, isHole1);
// TODO: compute height at u,v inside here, change callback param to PxVec3
PxVec3 crossedEdge;
if(last_tu > last_tv) // previous intercept was at u, so we use u=const edge
crossedEdge = PxVec3(0.0f, h01_-h00_, step_vif * columnScale);
else // previous intercept at v, use v=const edge
crossedEdge = PxVec3(step_uif * rowScale, h10_-h00_, 0.0f);
if(!isHole0 && !aCallback->underFaceHit(*this, triNormals[dotPrevGtz], crossedEdge,
uprev * rowScale, vprev * columnScale, COMPUTE_H_FROM_T(tPrev), triIndex0))
return;
if(triIndex1 != triIndex0 && !isHole1) // if triIndex0 != triIndex1 that means we cross the triangle edge
{
// Need to compute tw, the t for ray intersecting the diagonal within the current cell
// dot((wnu, wnv), (u0+tw*du, v0+tw*dv)-(wpu, wpv)) = 0
// wnu*(u0+tw*du-wpu) + wnv*(v0+tw*dv-wpv) = 0
// wnu*u0+wnv*v0-wnu*wpu-wnv*wpv + tw*(du*wnu + dv*wnv) = 0
const PxF32 denom = du*wnu + dv*wnv;
if(PxAbs(denom) > 1e-6f)
{
const PxF32 tw = (wnu*(wpu-u0)+wnv*(wpv-v0)) / denom;
if(!aCallback->underFaceHit(*this, triNormals[dotNextGtz], p10s-p01s,
(u0+tw*du) * rowScale, (v0+tw*dv) * columnScale, COMPUTE_H_FROM_T(tw), triIndex1))
return;
}
}
}
}
}
if(tu < tv)
{
last_tu = tu;
ui += step_ui;
// AP: very rare condition, wasn't able to repro but we need this if anyway (DE6565)
if(ui+step_ui< (0 - expandu) || ui+step_ui>=(nbUi + expandu)) // should hold true for ui without step from previous iteration
break;
uif += step_uif;
tu += step_tu;
}
else
{
last_tv = tv;
vi += step_vi;
// AP: very rare condition, wasn't able to repro but we need this if anyway (DE6565)
if(vi+step_vi< (0 - expandv) || vi+step_vi>=(nbVi + expandv)) // should hold true for vi without step from previous iteration
break;
vif += step_vif;
tv += step_tv;
}
hLinePrev = hLineNext;
}
// since min(tu,tv) is the END of the active interval we need to check if PREVIOUS min(tu,tv) was past interval end
// since we update tMinUV in the beginning of the loop, at this point it stores the min(last tu,last tv)
while (tMinUV < tEnd);
#undef COMPUTE_H_FROM_T
}
};
} // namespace Gu
}
#endif
| 34,953 | C | 40.611905 | 238 | 0.675278 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuSweepsHF.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 "GuHeightFieldUtil.h"
#include "GuEntityReport.h"
#include "GuVecCapsule.h"
#include "GuSweepMTD.h"
#include "GuSweepTriangleUtils.h"
#include "GuVecBox.h"
#include "CmScaling.h"
#include "GuSweepCapsuleTriangle.h"
#include "GuInternal.h"
#include "GuGJKRaycast.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
using namespace physx::aos;
#include "GuSweepConvexTri.h"
#define AbortTraversal false
#define ContinueTraversal true
#if PX_VC
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
///////////////////////////////////////////////////////////////////////////////
class HeightFieldTraceSegmentSweepHelper
{
PX_NOCOPY(HeightFieldTraceSegmentSweepHelper)
public:
HeightFieldTraceSegmentSweepHelper(const HeightFieldTraceUtil& hfUtil, const PxVec3& aabbExtentHfLocalSpace)
: mHfUtil(hfUtil), mOverlapObjectExtent(aabbExtentHfLocalSpace)
{
mHfUtil.computeLocalBounds(mLocalBounds);
// extend the bounds
mLocalBounds.minimum = mLocalBounds.minimum - aabbExtentHfLocalSpace;
mLocalBounds.maximum = mLocalBounds.maximum + aabbExtentHfLocalSpace;
}
template<class T>
PX_INLINE void traceSegment(const PxVec3& aP0, const PxVec3& rayDirNorm, const float rayLength, T* aCallback) const
{
mHfUtil.traceSegment<T, false, true>(aP0, rayDirNorm, rayLength, aCallback, mLocalBounds, false, &mOverlapObjectExtent);
}
private:
const HeightFieldTraceUtil& mHfUtil;
const PxVec3& mOverlapObjectExtent;
PxBounds3 mLocalBounds;
};
///////////////////////////////////////////////////////////////////////////////
class HeightFieldTraceSegmentReport : public EntityReport
{
PX_NOCOPY(HeightFieldTraceSegmentReport)
public:
HeightFieldTraceSegmentReport(const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags) :
mHfUtil (hfUtil),
mHitFlags (hitFlags),
mStatus (false),
mInitialOverlap (false),
mIsDoubleSided ((hfUtil.getHeightFieldGeometry().heightFieldFlags & PxMeshGeometryFlag::eDOUBLE_SIDED) || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES)),
mIsAnyHit (hitFlags & PxHitFlag::eMESH_ANY)
{
}
bool underFaceHit(const Gu::HeightFieldUtil&, const PxVec3&, const PxVec3&, PxF32, PxF32, PxF32, PxU32)
{
return true;
}
bool faceHit(const Gu::HeightFieldUtil&, const PxVec3&, PxU32, PxReal, PxReal)
{
return true;
}
protected:
const HeightFieldUtil& mHfUtil;
const PxHitFlags mHitFlags;
bool mStatus;
bool mInitialOverlap;
const bool mIsDoubleSided;
const bool mIsAnyHit;
};
///////////////////////////////////////////////////////////////////////////////
class CapsuleTraceSegmentReport : public HeightFieldTraceSegmentReport
{
PX_NOCOPY(CapsuleTraceSegmentReport)
public:
CapsuleTraceSegmentReport( const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags,
const Capsule& inflatedCapsule,
const PxVec3& unitDir, PxGeomSweepHit& sweepHit, const PxTransform& pose, PxReal distance) :
HeightFieldTraceSegmentReport (hfUtil, hitFlags),
mInflatedCapsule (inflatedCapsule),
mUnitDir (unitDir),
mSweepHit (sweepHit),
mPose (pose),
mDistance (distance)
{
mSweepHit.faceIndex = 0xFFFFffff;
}
virtual bool onEvent(PxU32 nb, const PxU32* indices)
{
PX_ALIGN_PREFIX(16) PxU8 tribuf[HF_SWEEP_REPORT_BUFFER_SIZE*sizeof(PxTriangle)] PX_ALIGN_SUFFIX(16);
PxTriangle* tmpT = reinterpret_cast<PxTriangle*>(tribuf);
PX_ASSERT(nb <= HF_SWEEP_REPORT_BUFFER_SIZE);
for(PxU32 i=0; i<nb; i++)
{
const PxU32 triangleIndex = indices[i];
mHfUtil.getTriangle(mPose, tmpT[i], NULL, NULL, triangleIndex, true);
}
PxGeomSweepHit h; // PT: TODO: ctor!
// PT: this one is safe because cullbox is NULL (no need to allocate one more triangle)
// PT: TODO: is it ok to pass the initial distance here?
PxVec3 bestNormal;
const bool status = sweepCapsuleTriangles_Precise(nb, tmpT, mInflatedCapsule, mUnitDir, mDistance, NULL, h, bestNormal, mHitFlags, mIsDoubleSided);
if(status && (h.distance <= mSweepHit.distance))
{
mSweepHit.faceIndex = indices[h.faceIndex];
mSweepHit.normal = h.normal;
mSweepHit.position = h.position;
mSweepHit.distance = h.distance;
mStatus = true;
if(h.distance == 0.0f)
{
mInitialOverlap = true;
return AbortTraversal;
}
if(mIsAnyHit)
return AbortTraversal;
}
return ContinueTraversal;
}
bool finalizeHit(PxGeomSweepHit& sweepHit, const PxHeightFieldGeometry& hfGeom, const PxTransform& pose, const Capsule& lss, const Capsule& inflatedCapsule, const PxVec3& unitDir)
{
if(!mStatus)
return false;
if(mInitialOverlap)
{
// PT: TODO: consider using 'setInitialOverlapResults' here
sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
if(mHitFlags & PxHitFlag::eMTD)
{
const Vec3V p0 = V3LoadU(lss.p0);
const Vec3V p1 = V3LoadU(lss.p1);
const FloatV radius = FLoad(lss.radius);
CapsuleV capsuleV;
capsuleV.initialize(p0, p1, radius);
//calculate MTD
const bool hasContacts = computeCapsule_HeightFieldMTD(hfGeom, pose, capsuleV, inflatedCapsule.radius, mIsDoubleSided, sweepHit);
//ML: the center of mass is below the surface, we won't have MTD contact generate
if(!hasContacts)
{
sweepHit.distance = 0.0f;
sweepHit.normal = -unitDir;
}
else
{
sweepHit.flags |= PxHitFlag::ePOSITION;
}
}
else
{
sweepHit.distance = 0.0f;
sweepHit.normal = -unitDir;
}
}
else
{
sweepHit.flags = PxHitFlag::eNORMAL| PxHitFlag::ePOSITION | PxHitFlag::eFACE_INDEX;
}
return true;
}
private:
const Capsule& mInflatedCapsule;
const PxVec3& mUnitDir;
PxGeomSweepHit& mSweepHit;
const PxTransform& mPose;
const PxReal mDistance;
};
bool sweepCapsule_HeightFieldGeom(GU_CAPSULE_SWEEP_FUNC_PARAMS)
{
PX_UNUSED(threadContext);
PX_UNUSED(capsuleGeom_);
PX_UNUSED(capsulePose_);
PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom);
const Capsule inflatedCapsule(lss.p0, lss.p1, lss.radius + inflation);
// Compute swept box
Box capsuleBox;
computeBoxAroundCapsule(inflatedCapsule, capsuleBox);
const PxVec3 capsuleAABBExtents = capsuleBox.computeAABBExtent();
const HeightFieldTraceUtil hfUtil(hfGeom);
CapsuleTraceSegmentReport myReport(hfUtil, hitFlags, inflatedCapsule, unitDir, sweepHit, pose, distance);
sweepHit.distance = PX_MAX_F32;
// need hf local space stuff
const PxTransform inversePose = pose.getInverse();
const PxVec3 centerLocalSpace = inversePose.transform(capsuleBox.center);
const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir);
const PxVec3 capsuleAABBBExtentHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), capsuleAABBExtents).getExtents();
HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, capsuleAABBBExtentHfLocalSpace);
traceSegmentHelper.traceSegment<CapsuleTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &myReport);
return myReport.finalizeHit(sweepHit, hfGeom, pose, lss, inflatedCapsule, unitDir);
}
///////////////////////////////////////////////////////////////////////////////
class ConvexTraceSegmentReport : public HeightFieldTraceSegmentReport
{
PX_NOCOPY(ConvexTraceSegmentReport)
public:
ConvexTraceSegmentReport( const HeightFieldUtil& hfUtil, const ConvexHullData& hull, const PxMeshScale& convexScale,
const PxTransform& convexPose, const PxTransform& heightFieldPose,
const PxVec3& unitDir, PxReal distance, PxHitFlags hitFlags, PxReal inflation) :
HeightFieldTraceSegmentReport (hfUtil, hitFlags),
mUnitDir (unitDir),
mInflation (inflation)
{
using namespace aos;
mSweepHit.faceIndex = 0xFFFFffff;
mSweepHit.distance = distance;
const Vec3V worldDir = V3LoadU(unitDir);
const FloatV dist = FLoad(distance);
const QuatV q0 = QuatVLoadU(&heightFieldPose.q.x);
const Vec3V p0 = V3LoadU(&heightFieldPose.p.x);
const QuatV q1 = QuatVLoadU(&convexPose.q.x);
const Vec3V p1 = V3LoadU(&convexPose.p.x);
const PxTransformV meshTransf(p0, q0);
const PxTransformV convexTransf(p1, q1);
mMeshToConvex = convexTransf.transformInv(meshTransf);
mConvexPoseV = convexTransf;
mConvexSpaceDir = convexTransf.rotateInv(V3Neg(V3Scale(worldDir, dist)));
mDistance = dist;
const Vec3V vScale = V3LoadU_SafeReadW(convexScale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const QuatV vQuat = QuatVLoadU(&convexScale.rotation.x);
mMeshSpaceUnitDir = heightFieldPose.rotateInv(unitDir);
mConvexHull.initialize(&hull, V3Zero(), vScale, vQuat, convexScale.isIdentity());
}
virtual bool onEvent(PxU32 nbEntities, const PxU32* entities)
{
const PxTransform idt(PxIdentity);
for(PxU32 i=0; i<nbEntities; i++)
{
PxTriangle tri;
mHfUtil.getTriangle(idt, tri, NULL, NULL, entities[i], false, false); // First parameter not needed if local space triangle is enough
// use mSweepHit.distance as max sweep distance so far, mSweepHit.distance will be clipped by this function
if(sweepConvexVsTriangle( tri.verts[0], tri.verts[1], tri.verts[2], mConvexHull, mMeshToConvex, mConvexPoseV,
mConvexSpaceDir, mUnitDir, mMeshSpaceUnitDir, mDistance, mSweepHit.distance, mSweepHit, mIsDoubleSided,
mInflation, mInitialOverlap, entities[i]))
{
mStatus = true;
if(mIsAnyHit || mSweepHit.distance == 0.0f)
return AbortTraversal;
}
}
return ContinueTraversal;
}
bool finalizeHit(PxGeomSweepHit& sweepHit,
const PxHeightFieldGeometry& hfGeom, const PxTransform& pose,
const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose,
const PxVec3& unitDir, PxReal inflation)
{
if(!mStatus)
return false;
if(mInitialOverlap)
{
if(mHitFlags & PxHitFlag::eMTD)
{
const bool hasContacts = computeConvex_HeightFieldMTD(hfGeom, pose, convexGeom, convexPose, inflation, mIsDoubleSided, sweepHit);
sweepHit.faceIndex = mSweepHit.faceIndex;
sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
if(!hasContacts)
{
sweepHit.distance = 0.0f;
sweepHit.normal = -unitDir;
}
else
{
sweepHit.flags |= PxHitFlag::ePOSITION;
}
}
else
{
setInitialOverlapResults(sweepHit, unitDir, mSweepHit.faceIndex); // hit index must be set to closest for IO
}
}
else
{
sweepHit = mSweepHit;
sweepHit.normal = -sweepHit.normal;
sweepHit.normal.normalize();
}
return true;
}
private:
PxMatTransformV mMeshToConvex;
PxTransformV mConvexPoseV;
ConvexHullV mConvexHull;
PxGeomSweepHit mSweepHit;
Vec3V mConvexSpaceDir;
FloatV mDistance;
const PxVec3 mUnitDir;
PxVec3 mMeshSpaceUnitDir;
const PxReal mInflation;
};
bool sweepConvex_HeightFieldGeom(GU_CONVEX_SWEEP_FUNC_PARAMS)
{
PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(threadContext);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom);
const Matrix34FromTransform convexTM(convexPose);
const Matrix34FromTransform meshTM(pose);
ConvexMesh* convexMesh = static_cast<ConvexMesh*>(convexGeom.convexMesh);
const bool idtScaleConvex = convexGeom.scale.isIdentity();
FastVertex2ShapeScaling convexScaling;
if(!idtScaleConvex)
convexScaling.init(convexGeom.scale);
PX_ASSERT(!convexMesh->getLocalBoundsFast().isEmpty());
const PxBounds3 hullAABBLocalSpace = convexMesh->getLocalBoundsFast().transformFast(convexScaling.getVertex2ShapeSkew());
const HeightFieldTraceUtil hfUtil(hfGeom);
ConvexTraceSegmentReport entityReport(
hfUtil, convexMesh->getHull(), convexGeom.scale, convexPose, pose, -unitDir, distance, hitFlags, inflation);
// need hf local space stuff
const PxBounds3 hullAABB = PxBounds3::transformFast(convexPose, hullAABBLocalSpace);
const PxVec3 aabbExtents = hullAABB.getExtents() + PxVec3(inflation);
const PxTransform inversePose = pose.getInverse();
const PxVec3 centerLocalSpace = inversePose.transform(hullAABB.getCenter());
const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir);
const PxVec3 convexAABBExtentHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), aabbExtents).getExtents();
HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, convexAABBExtentHfLocalSpace);
traceSegmentHelper.traceSegment<ConvexTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &entityReport);
return entityReport.finalizeHit(sweepHit, hfGeom, pose, convexGeom, convexPose, unitDir, inflation);
}
///////////////////////////////////////////////////////////////////////////////
class BoxTraceSegmentReport : public HeightFieldTraceSegmentReport
{
PX_NOCOPY(BoxTraceSegmentReport)
public:
BoxTraceSegmentReport( const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags,
const PxTransformV& worldToBoxV, const PxTransform& pose, const BoxV& box, const PxVec3& localMotion,
PxGeomSweepHit& sweepHit, PxReal inflation) :
HeightFieldTraceSegmentReport (hfUtil, hitFlags),
mWorldToBoxV (worldToBoxV),
mPose (pose),
mBox (box),
mLocalMotion (localMotion),
mSweepHit (sweepHit),
mInflation (inflation)
{
mMinToi = FMax();
mSweepHit.faceIndex = 0xFFFFffff;
}
virtual bool onEvent(PxU32 nb, const PxU32* indices)
{
const FloatV zero = FZero();
const Vec3V zeroV = V3Zero();
const Vec3V dir = V3LoadU(mLocalMotion);
//FloatV minToi = FMax();
FloatV toi;
Vec3V closestA, normal;//closestA and normal is in the local space of box
for(PxU32 i=0; i<nb; i++)
{
const PxU32 triangleIndex = indices[i];
PxTriangle currentTriangle; // in world space
mHfUtil.getTriangle(mPose, currentTriangle, NULL, NULL, triangleIndex, true, true);
const Vec3V localV0 = V3LoadU(currentTriangle.verts[0]);
const Vec3V localV1 = V3LoadU(currentTriangle.verts[1]);
const Vec3V localV2 = V3LoadU(currentTriangle.verts[2]);
const Vec3V triV0 = mWorldToBoxV.transform(localV0);
const Vec3V triV1 = mWorldToBoxV.transform(localV1);
const Vec3V triV2 = mWorldToBoxV.transform(localV2);
if(!mIsDoubleSided)
{
const Vec3V triNormal = V3Cross(V3Sub(triV2, triV1),V3Sub(triV0, triV1));
if(FAllGrtrOrEq(V3Dot(triNormal, dir), zero))
continue;
}
const TriangleV triangle(triV0, triV1, triV2);
////move triangle to box space
//const Vec3V localV0 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[0]));
//const Vec3V localV1 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[1]));
//const Vec3V localV2 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[2]));
//TriangleV triangle(localV0, localV1, localV2);
const LocalConvex<TriangleV> convexA(triangle);
const LocalConvex<BoxV> convexB(mBox);
const Vec3V initialSearchDir = V3Sub(triangle.getCenter(), mBox.getCenter());
if(gjkRaycastPenetration<LocalConvex<TriangleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, zero, zeroV, dir, toi, normal, closestA, mInflation, false))
{
mStatus = true;
if(FAllGrtr(toi, zero))
{
if(FAllGrtr(mMinToi, toi))
{
mMinToi = toi;
FStore(toi, &mSweepHit.distance);
V3StoreU(normal, mSweepHit.normal);
V3StoreU(closestA, mSweepHit.position);
mSweepHit.faceIndex = triangleIndex;
if(mIsAnyHit)
return AbortTraversal;
}
}
else
{
mSweepHit.distance = 0.0f;
mSweepHit.faceIndex = triangleIndex;
mInitialOverlap = true;
return AbortTraversal;
}
}
}
return ContinueTraversal;
}
bool finalizeHit(PxGeomSweepHit& sweepHit,
const PxHeightFieldGeometry& hfGeom, const PxTransform& pose,
const PxTransform& boxPose_, const Box& box,
const PxVec3& unitDir, PxReal distance, PxReal inflation)
{
if(!mStatus)
return false;
if(mInitialOverlap)
{
// PT: TODO: consider using 'setInitialOverlapResults' here
sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
if(mHitFlags & PxHitFlag::eMTD)
{
const bool hasContacts = computeBox_HeightFieldMTD(hfGeom, pose, box, boxPose_, inflation, mIsDoubleSided, sweepHit);
//ML: the center of mass is below the surface, we won't have MTD contact generate
if(!hasContacts)
{
sweepHit.distance = 0.0f;
sweepHit.normal = -unitDir;
}
else
{
sweepHit.flags |= PxHitFlag::ePOSITION;
}
}
else
{
sweepHit.distance = 0.0f;
sweepHit.normal = -unitDir;
}
}
else
{
PxVec3 n = sweepHit.normal.getNormalized();
if((n.dot(mLocalMotion))>0.0f)
n = -n;
sweepHit.distance *= distance; // stored as toi [0,1] during computation -> scale
sweepHit.normal = boxPose_.rotate(n);
sweepHit.position = boxPose_.transform(sweepHit.position);
sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
}
return true;
}
private:
const PxTransformV& mWorldToBoxV;
const PxTransform& mPose;
const BoxV& mBox;
FloatV mMinToi;
const PxVec3 mLocalMotion;
PxGeomSweepHit& mSweepHit;
const PxReal mInflation;
};
bool sweepBox_HeightFieldGeom(GU_BOX_SWEEP_FUNC_PARAMS)
{
PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD);
PX_UNUSED(threadContext);
PX_UNUSED(boxGeom_);
PX_UNUSED(hitFlags);
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom);
const PxVec3 boxAABBExtent = box.computeAABBExtent() + PxVec3(inflation);
// Move to AABB space
PX_ALIGN_PREFIX(16) PxTransform WorldToBox PX_ALIGN_SUFFIX(16);
WorldToBox = boxPose_.getInverse();
const QuatV q1 = QuatVLoadA(&WorldToBox.q.x);
const Vec3V p1 = V3LoadA(&WorldToBox.p.x);
const PxTransformV WorldToBoxV(p1, q1);
const PxVec3 motion = unitDir * distance;
const PxVec3 localMotion = WorldToBox.rotate(motion);
const BoxV boxV(V3Zero(), V3LoadU(box.extents));
sweepHit.distance = PX_MAX_F32;
const HeightFieldTraceUtil hfUtil(hfGeom);
BoxTraceSegmentReport myReport(hfUtil, hitFlags, WorldToBoxV, pose, boxV, localMotion, sweepHit, inflation);
// need hf local space stuff
const PxTransform inversePose = pose.getInverse();
const PxVec3 centerLocalSpace = inversePose.transform(box.center);
const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir);
const PxVec3 boxAABBExtentInHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), boxAABBExtent).getExtents();
HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, boxAABBExtentInHfLocalSpace);
traceSegmentHelper.traceSegment<BoxTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &myReport);
return myReport.finalizeHit(sweepHit, hfGeom, pose, boxPose_, box, unitDir, distance, inflation);
}
///////////////////////////////////////////////////////////////////////////////
| 20,671 | C++ | 33.168595 | 180 | 0.727638 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightFieldUtil.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/PxMeshScale.h"
#include "GuHeightFieldUtil.h"
#include "GuSweepSharedTests.h"
#include "GuHeightField.h"
#include "GuEntityReport.h"
#include "foundation/PxIntrinsics.h"
#include "CmScaling.h"
using namespace physx;
void Gu::HeightFieldUtil::computeLocalBounds(PxBounds3& bounds) const
{
const PxMeshScale scale(PxVec3(mHfGeom->rowScale, mHfGeom->heightScale, mHfGeom->columnScale), PxQuat(PxIdentity));
const PxMat33 mat33 = Cm::toMat33(scale);
bounds.minimum = mat33.transform(mHeightField->getData().mAABB.getMin());
bounds.maximum = mat33.transform(mHeightField->getData().mAABB.getMax());
// PT: HFs will assert in Gu::intersectRayAABB2() if we don't deal with that
const float deltaY = GU_MIN_AABB_EXTENT*0.5f - (bounds.maximum.y - bounds.minimum.y);
if(deltaY>0.0f)
{
bounds.maximum.y += deltaY*0.6f;
bounds.minimum.y -= deltaY*0.6f;
}
}
static PX_FORCE_INLINE bool reportTriangle(Gu::OverlapReport& callback, PxU32 material, PxU32* PX_RESTRICT indexBuffer, const PxU32 bufferSize, PxU32& indexBufferUsed, PxU32 triangleIndex)
{
if(material != PxHeightFieldMaterial::eHOLE)
{
indexBuffer[indexBufferUsed++] = triangleIndex;
if(indexBufferUsed >= bufferSize)
{
if(!callback.reportTouchedTris(indexBufferUsed, indexBuffer))
return false;
indexBufferUsed = 0;
}
}
return true;
}
void Gu::HeightFieldUtil::overlapAABBTriangles(const PxBounds3& bounds, OverlapReport& callback, PxU32 batchSize) const
{
PX_ASSERT(batchSize<=HF_OVERLAP_REPORT_BUFFER_SIZE);
PX_ASSERT(!bounds.isEmpty());
PxBounds3 localBounds = bounds;
localBounds.minimum.x *= mOneOverRowScale;
localBounds.minimum.y *= mOneOverHeightScale;
localBounds.minimum.z *= mOneOverColumnScale;
localBounds.maximum.x *= mOneOverRowScale;
localBounds.maximum.y *= mOneOverHeightScale;
localBounds.maximum.z *= mOneOverColumnScale;
if(mHfGeom->rowScale < 0.0f)
PxSwap(localBounds.minimum.x, localBounds.maximum.x);
if(mHfGeom->columnScale < 0.0f)
PxSwap(localBounds.minimum.z, localBounds.maximum.z);
// early exit for aabb does not overlap in XZ plane
// DO NOT MOVE: since rowScale / columnScale may be negative this has to be done after scaling localBounds
const PxU32 nbRows = mHeightField->getNbRowsFast();
const PxU32 nbColumns = mHeightField->getNbColumnsFast();
if(localBounds.minimum.x > float(nbRows - 1))
return;
if(localBounds.minimum.z > float(nbColumns - 1))
return;
if(localBounds.maximum.x < 0.0f)
return;
if(localBounds.maximum.z < 0.0f)
return;
const PxU32 minRow = mHeightField->getMinRow(localBounds.minimum.x);
const PxU32 maxRow = mHeightField->getMaxRow(localBounds.maximum.x);
const PxU32 minColumn = mHeightField->getMinColumn(localBounds.minimum.z);
const PxU32 maxColumn = mHeightField->getMaxColumn(localBounds.maximum.z);
const PxU32 deltaColumn = maxColumn - minColumn;
const PxU32 maxNbTriangles = 2 * deltaColumn * (maxRow - minRow);
if(!maxNbTriangles)
return;
const PxU32 bufferSize = batchSize<=HF_OVERLAP_REPORT_BUFFER_SIZE ? batchSize : HF_OVERLAP_REPORT_BUFFER_SIZE;
PxU32 indexBuffer[HF_OVERLAP_REPORT_BUFFER_SIZE];
PxU32 indexBufferUsed = 0;
PxU32 offset = minRow * nbColumns + minColumn;
const PxReal miny = localBounds.minimum.y;
const PxReal maxy = localBounds.maximum.y;
const PxU32 columnStride = nbColumns - deltaColumn;
for(PxU32 row=minRow; row<maxRow; row++)
{
for(PxU32 column=minColumn; column<maxColumn; column++)
{
const PxReal h0 = mHeightField->getHeight(offset);
const PxReal h1 = mHeightField->getHeight(offset + 1);
const PxReal h2 = mHeightField->getHeight(offset + nbColumns);
const PxReal h3 = mHeightField->getHeight(offset + nbColumns + 1);
const bool bmax = maxy < h0 && maxy < h1 && maxy < h2 && maxy < h3;
const bool bmin = miny > h0 && miny > h1 && miny > h2 && miny > h3;
if(!(bmax || bmin))
{
if(!reportTriangle(callback, mHeightField->getMaterialIndex0(offset), indexBuffer, bufferSize, indexBufferUsed, offset << 1))
return;
if(!reportTriangle(callback, mHeightField->getMaterialIndex1(offset), indexBuffer, bufferSize, indexBufferUsed, (offset << 1) + 1))
return;
}
offset++;
}
offset += columnStride;
}
if(indexBufferUsed > 0)
callback.reportTouchedTris(indexBufferUsed, indexBuffer);
}
PxU32 Gu::HeightFieldUtil::getTriangle(const PxTransform& pose, PxTriangle& worldTri,
PxU32* _vertexIndices, PxU32* adjacencyIndices, PxTriangleID triangleIndex, bool worldSpaceTranslation, bool worldSpaceRotation) const
{
#if PX_CHECKED
if (!mHeightField->isValidTriangle(triangleIndex))
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "HeightFieldShape::getTriangle: Invalid triangle index!");
return 0;
}
#endif
PxVec3 handedness(1.0f); // Vector to invert normal coordinates according to the heightfield scales
bool wrongHanded = false;
if (mHfGeom->columnScale < 0)
{
wrongHanded = !wrongHanded;
handedness.z = -1.0f;
}
if (mHfGeom->rowScale < 0)
{
wrongHanded = !wrongHanded;
handedness.x = -1.0f;
}
/* if (0) // ptchernev: Iterating over triangles becomes a pain.
{
if (mHeightField.getTriangleMaterial(triangleIndex) == mHfGeom.holeMaterialIndex)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "HeightFieldShape::getTriangle: Non-existing triangle (triangle has hole material)!");
return 0;
}
}*/
PxU32 vertexIndices[3];
mHeightField->getTriangleVertexIndices(triangleIndex, vertexIndices[0], vertexIndices[1+wrongHanded], vertexIndices[2-wrongHanded]);
if(adjacencyIndices)
{
mHeightField->getTriangleAdjacencyIndices( triangleIndex, vertexIndices[0], vertexIndices[1+wrongHanded], vertexIndices[2-wrongHanded],
adjacencyIndices[wrongHanded ? 2 : 0], adjacencyIndices[1], adjacencyIndices[wrongHanded ? 0 : 2]);
}
if(_vertexIndices)
{
_vertexIndices[0] = vertexIndices[0];
_vertexIndices[1] = vertexIndices[1];
_vertexIndices[2] = vertexIndices[2];
}
if (worldSpaceRotation)
{
if (worldSpaceTranslation)
{
for (PxU32 vi = 0; vi < 3; vi++)
worldTri.verts[vi] = hf2worldp(pose, mHeightField->getVertex(vertexIndices[vi]));
}
else
{
for (PxU32 vi = 0; vi < 3; vi++)
{
// TTP 2390
// local space here is rotated (but not translated) world space
worldTri.verts[vi] = pose.q.rotate(hf2shapep(mHeightField->getVertex(vertexIndices[vi])));
}
}
}
else
{
const PxVec3 offset = worldSpaceTranslation ? pose.p : PxVec3(0.0f);
for (PxU32 vi = 0; vi < 3; vi++)
worldTri.verts[vi] = hf2shapep(mHeightField->getVertex(vertexIndices[vi])) + offset;
}
return PxU32(mHeightField->getTriangleMaterial(triangleIndex) != PxHeightFieldMaterial::eHOLE);
}
| 8,423 | C++ | 35.626087 | 188 | 0.739404 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightField.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 "GuHeightField.h"
#include "GuMeshFactory.h"
#include "CmSerialize.h"
#include "foundation/PxBitMap.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HeightField::HeightField(MeshFactory* factory)
: PxHeightField(PxConcreteType::eHEIGHTFIELD, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
, mSampleStride (0)
, mNbSamples (0)
, mMinHeight (0.0f)
, mMaxHeight (0.0f)
, mModifyCount (0)
, mMeshFactory (factory)
{
mData.format = PxHeightFieldFormat::eS16_TM;
mData.rows = 0;
mData.columns = 0;
mData.convexEdgeThreshold = 0;
mData.flags = PxHeightFieldFlags();
mData.samples = NULL;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HeightField::HeightField(MeshFactory* factory, HeightFieldData& data)
: PxHeightField(PxConcreteType::eHEIGHTFIELD, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
, mSampleStride (0)
, mNbSamples (0)
, mMinHeight (0.0f)
, mMaxHeight (0.0f)
, mModifyCount (0)
, mMeshFactory (factory)
{
mData = data;
data.samples = NULL; // set to null so that we don't release the memory
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HeightField::~HeightField()
{
releaseMemory();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void HeightField::onRefCountZero()
{
::onRefCountZero(this, mMeshFactory, false, "PxHeightField::release: double deletion detected!");
}
void HeightField::exportExtraData(PxSerializationContext& stream)
{
// PT: warning, order matters for the converter. Needs to export the base stuff first
const PxU32 size = mData.rows * mData.columns * sizeof(PxHeightFieldSample);
stream.alignData(PX_SERIAL_ALIGN); // PT: generic align within the generic allocator
stream.writeData(mData.samples, size);
}
void HeightField::importExtraData(PxDeserializationContext& context)
{
mData.samples = context.readExtraData<PxHeightFieldSample, PX_SERIAL_ALIGN>(mData.rows * mData.columns);
}
HeightField* HeightField::createObject(PxU8*& address, PxDeserializationContext& context)
{
HeightField* obj = PX_PLACEMENT_NEW(address, HeightField(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(HeightField);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
void HeightField::release()
{
RefCountable_decRefCount(*this);
}
void HeightField::acquireReference()
{
RefCountable_incRefCount(*this);
}
PxU32 HeightField::getReferenceCount() const
{
return RefCountable_getRefCount(*this);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool HeightField::modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& desc, bool shrinkBounds)
{
const PxU32 nbCols = getNbColumns();
const PxU32 nbRows = getNbRows();
PX_CHECK_AND_RETURN_NULL(desc.format == mData.format, "Gu::HeightField::modifySamples: desc.format mismatch");
//PX_CHECK_AND_RETURN_NULL(startCol + desc.nbColumns <= nbCols,
// "Gu::HeightField::modifySamples: startCol + nbColumns out of range");
//PX_CHECK_AND_RETURN_NULL(startRow + desc.nbRows <= nbRows,
// "Gu::HeightField::modifySamples: startRow + nbRows out of range");
//PX_CHECK_AND_RETURN_NULL(desc.samples.stride == mSampleStride, "Gu::HeightField::modifySamples: desc.samples.stride mismatch");
// by default bounds don't shrink since the whole point of this function is to avoid modifying the whole HF
// unless shrinkBounds is specified. then the bounds will be fully recomputed later
PxReal minHeight = mMinHeight;
PxReal maxHeight = mMaxHeight;
PxU32 hiRow = PxMin(PxU32(PxMax(0, startRow + PxI32(desc.nbRows))), nbRows);
PxU32 hiCol = PxMin(PxU32(PxMax(0, startCol + PxI32(desc.nbColumns))), nbCols);
for (PxU32 row = PxU32(PxMax(startRow, 0)); row < hiRow; row++)
{
for (PxU32 col = PxU32(PxMax(startCol, 0)); col < hiCol; col++)
{
const PxU32 vertexIndex = col + row*nbCols;
PxHeightFieldSample* targetSample = &mData.samples[vertexIndex];
// update target sample from source sample
const PxHeightFieldSample& sourceSample =
(reinterpret_cast<const PxHeightFieldSample*>(desc.samples.data))[col - startCol + (row - startRow) * desc.nbColumns];
*targetSample = sourceSample;
if(isCollisionVertexPreca(vertexIndex, row, col, PxHeightFieldMaterial::eHOLE))
targetSample->materialIndex1.setBit();
else
targetSample->materialIndex1.clearBit();
// grow (but not shrink) the height extents
const PxReal h = getHeight(vertexIndex);
minHeight = physx::intrinsics::selectMin(h, minHeight);
maxHeight = physx::intrinsics::selectMax(h, maxHeight);
}
}
if (shrinkBounds)
{
// do a full recompute on vertical bounds to allow shrinking
minHeight = PX_MAX_REAL;
maxHeight = -PX_MAX_REAL;
// have to recompute the min&max from scratch...
for (PxU32 vertexIndex = 0; vertexIndex < nbRows * nbCols; vertexIndex ++)
{
// update height extents
const PxReal h = getHeight(vertexIndex);
minHeight = physx::intrinsics::selectMin(h, minHeight);
maxHeight = physx::intrinsics::selectMax(h, maxHeight);
}
}
mMinHeight = minHeight;
mMaxHeight = maxHeight;
// update local space aabb
CenterExtents& bounds = mData.mAABB;
bounds.mCenter.y = (maxHeight + minHeight)*0.5f;
bounds.mExtents.y = (maxHeight - minHeight)*0.5f;
mModifyCount++;
return true;
}
bool HeightField::load(PxInputStream& stream)
{
// release old memory
releaseMemory();
// Import header
PxU32 version;
bool endian;
if(!readHeader('H', 'F', 'H', 'F', version, endian, stream))
return false;
// load mData
mData.rows = readDword(endian, stream);
mData.columns = readDword(endian, stream);
if(version>=2)
{
mData.rowLimit = readDword(endian, stream);
mData.colLimit = readDword(endian, stream);
mData.nbColumns = readDword(endian, stream);
}
else
{
mData.rowLimit = PxU32(readFloat(endian, stream));
mData.colLimit = PxU32(readFloat(endian, stream));
mData.nbColumns = PxU32(readFloat(endian, stream));
}
const float thickness = readFloat(endian, stream);
PX_UNUSED(thickness);
mData.convexEdgeThreshold = readFloat(endian, stream);
PxU16 flags = readWord(endian, stream);
mData.flags = PxHeightFieldFlags(flags);
PxU32 format = readDword(endian, stream);
mData.format = PxHeightFieldFormat::Enum(format);
PxBounds3 minMaxBounds;
minMaxBounds.minimum.x = readFloat(endian, stream);
minMaxBounds.minimum.y = readFloat(endian, stream);
minMaxBounds.minimum.z = readFloat(endian, stream);
minMaxBounds.maximum.x = readFloat(endian, stream);
minMaxBounds.maximum.y = readFloat(endian, stream);
minMaxBounds.maximum.z = readFloat(endian, stream);
mData.mAABB = CenterExtents(minMaxBounds);
mSampleStride = readDword(endian, stream);
mNbSamples = readDword(endian, stream);
mMinHeight = readFloat(endian, stream);
mMaxHeight = readFloat(endian, stream);
// allocate height samples
mData.samples = NULL;
const PxU32 nbVerts = mData.rows * mData.columns;
if (nbVerts > 0)
{
mData.samples = PX_ALLOCATE(PxHeightFieldSample, nbVerts, "PxHeightFieldSample");
if (mData.samples == NULL)
return PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "Gu::HeightField::load: PX_ALLOC failed!");
stream.read(mData.samples, mNbSamples*sizeof(PxHeightFieldSample));
if (endian)
for(PxU32 i = 0; i < mNbSamples; i++)
{
PxHeightFieldSample& s = mData.samples[i];
PX_ASSERT(sizeof(PxU16) == sizeof(s.height));
flip(s.height);
}
}
return true;
}
bool HeightField::loadFromDesc(const PxHeightFieldDesc& desc)
{
// verify descriptor
PX_CHECK_AND_RETURN_NULL(desc.isValid(), "Gu::HeightField::loadFromDesc: desc.isValid() failed!");
// release old memory
releaseMemory();
// copy trivial data
mData.format = desc.format;
mData.rows = desc.nbRows;
mData.columns = desc.nbColumns;
mData.convexEdgeThreshold = desc.convexEdgeThreshold;
mData.flags = desc.flags;
mSampleStride = desc.samples.stride;
mData.rowLimit = mData.rows - 2;
mData.colLimit = mData.columns - 2;
mData.nbColumns = desc.nbColumns;
// allocate and copy height samples
// compute extents too
mData.samples = NULL;
const PxU32 nbVerts = desc.nbRows * desc.nbColumns;
mMinHeight = PX_MAX_REAL;
mMaxHeight = -PX_MAX_REAL;
if(nbVerts > 0)
{
mData.samples = PX_ALLOCATE(PxHeightFieldSample, nbVerts, "PxHeightFieldSample");
if(!mData.samples)
return PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "Gu::HeightField::load: PX_ALLOC failed!");
const PxU8* PX_RESTRICT src = reinterpret_cast<const PxU8*>(desc.samples.data);
PxHeightFieldSample* PX_RESTRICT dst = mData.samples;
PxI16 minHeight = PX_MAX_I16;
PxI16 maxHeight = PX_MIN_I16;
for(PxU32 i=0;i<nbVerts;i++)
{
const PxHeightFieldSample& sample = *reinterpret_cast<const PxHeightFieldSample*>(src);
*dst++ = sample;
const PxI16 height = sample.height;
minHeight = height < minHeight ? height : minHeight;
maxHeight = height > maxHeight ? height : maxHeight;
src += desc.samples.stride;
}
mMinHeight = PxReal(minHeight);
mMaxHeight = PxReal(maxHeight);
}
PX_ASSERT(mMaxHeight >= mMinHeight);
parseTrianglesForCollisionVertices(PxHeightFieldMaterial::eHOLE);
// PT: "mNbSamples" only used by binary converter
mNbSamples = mData.rows * mData.columns;
//Compute local space aabb.
PxBounds3 bounds;
bounds.minimum.y = getMinHeight();
bounds.maximum.y = getMaxHeight();
bounds.minimum.x = 0;
bounds.maximum.x = PxReal(getNbRowsFast() - 1);
bounds.minimum.z = 0;
bounds.maximum.z = PxReal(getNbColumnsFast() - 1);
mData.mAABB=bounds;
return true;
}
bool HeightField::save(PxOutputStream& stream, bool endian)
{
// write header
if(!writeHeader('H', 'F', 'H', 'F', PX_HEIGHTFIELD_VERSION, endian, stream))
return false;
const Gu::HeightFieldData& hfData = getData();
// write mData members
writeDword(hfData.rows, endian, stream);
writeDword(hfData.columns, endian, stream);
writeDword(hfData.rowLimit, endian, stream);
writeDword(hfData.colLimit, endian, stream);
writeDword(hfData.nbColumns, endian, stream);
writeFloat(0.0f, endian, stream); // thickness
writeFloat(hfData.convexEdgeThreshold, endian, stream);
writeWord(hfData.flags, endian, stream);
writeDword(hfData.format, endian, stream);
writeFloat(hfData.mAABB.getMin(0), endian, stream);
writeFloat(hfData.mAABB.getMin(1), endian, stream);
writeFloat(hfData.mAABB.getMin(2), endian, stream);
writeFloat(hfData.mAABB.getMax(0), endian, stream);
writeFloat(hfData.mAABB.getMax(1), endian, stream);
writeFloat(hfData.mAABB.getMax(2), endian, stream);
// write this-> members
writeDword(mSampleStride, endian, stream);
writeDword(mNbSamples, endian, stream);
writeFloat(mMinHeight, endian, stream);
writeFloat(mMaxHeight, endian, stream);
// write samples
for(PxU32 i=0; i<mNbSamples; i++)
{
const PxHeightFieldSample& s = hfData.samples[i];
writeWord(PxU16(s.height), endian, stream);
stream.write(&s.materialIndex0, sizeof(s.materialIndex0));
stream.write(&s.materialIndex1, sizeof(s.materialIndex1));
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxU32 HeightField::saveCells(void* destBuffer, PxU32 destBufferSize) const
{
PxU32 n = mData.columns * mData.rows * sizeof(PxHeightFieldSample);
if (n > destBufferSize) n = destBufferSize;
PxMemCopy(destBuffer, mData.samples, n);
return n;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void HeightField::releaseMemory()
{
if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
{
PX_FREE(mData.samples);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace
{
struct EdgeData
{
PxU32 edgeIndex;
PxU32 cell;
PxU32 row;
PxU32 column;
};
}
// PT: TODO: use those faster functions everywhere
static PxU32 getVertexEdgeIndices(const HeightField& heightfield, PxU32 vertexIndex, PxU32 row, PxU32 column, EdgeData edgeIndices[8])
{
const PxU32 nbColumns = heightfield.getData().columns;
const PxU32 nbRows = heightfield.getData().rows;
PX_ASSERT((vertexIndex / nbColumns)==row);
PX_ASSERT((vertexIndex % nbColumns)==column);
PxU32 count = 0;
if (row > 0)
{
// edgeIndices[count++] = 3 * (vertexIndex - nbColumns) + 2;
const PxU32 cell = vertexIndex - nbColumns;
edgeIndices[count].edgeIndex = 3 * cell + 2;
edgeIndices[count].cell = cell;
edgeIndices[count].row = row-1;
edgeIndices[count].column = column;
count++;
}
if (column < nbColumns-1)
{
if (row > 0)
{
if (!heightfield.isZerothVertexShared(vertexIndex - nbColumns))
{
// edgeIndices[count++] = 3 * (vertexIndex - nbColumns) + 1;
const PxU32 cell = vertexIndex - nbColumns;
edgeIndices[count].edgeIndex = 3 * cell + 1;
edgeIndices[count].cell = cell;
edgeIndices[count].row = row-1;
edgeIndices[count].column = column;
count++;
}
}
// edgeIndices[count++] = 3 * vertexIndex;
edgeIndices[count].edgeIndex = 3 * vertexIndex;
edgeIndices[count].cell = vertexIndex;
edgeIndices[count].row = row;
edgeIndices[count].column = column;
count++;
if (row < nbRows - 1)
{
if (heightfield.isZerothVertexShared(vertexIndex))
{
// edgeIndices[count++] = 3 * vertexIndex + 1;
edgeIndices[count].edgeIndex = 3 * vertexIndex + 1;
edgeIndices[count].cell = vertexIndex;
edgeIndices[count].row = row;
edgeIndices[count].column = column;
count++;
}
}
}
if (row < nbRows - 1)
{
// edgeIndices[count++] = 3 * vertexIndex + 2;
edgeIndices[count].edgeIndex = 3 * vertexIndex + 2;
edgeIndices[count].cell = vertexIndex;
edgeIndices[count].row = row;
edgeIndices[count].column = column;
count++;
}
if (column > 0)
{
if (row < nbRows - 1)
{
if (!heightfield.isZerothVertexShared(vertexIndex - 1))
{
// edgeIndices[count++] = 3 * (vertexIndex - 1) + 1;
const PxU32 cell = vertexIndex - 1;
edgeIndices[count].edgeIndex = 3 * cell + 1;
edgeIndices[count].cell = cell;
edgeIndices[count].row = row;
edgeIndices[count].column = column-1;
count++;
}
}
// edgeIndices[count++] = 3 * (vertexIndex - 1);
const PxU32 cell = vertexIndex - 1;
edgeIndices[count].edgeIndex = 3 * cell;
edgeIndices[count].cell = cell;
edgeIndices[count].row = row;
edgeIndices[count].column = column-1;
count++;
if (row > 0)
{
if (heightfield.isZerothVertexShared(vertexIndex - nbColumns - 1))
{
// edgeIndices[count++] = 3 * (vertexIndex - nbColumns - 1) + 1;
const PxU32 cell1 = vertexIndex - nbColumns - 1;
edgeIndices[count].edgeIndex = 3 * cell1 + 1;
edgeIndices[count].cell = cell1;
edgeIndices[count].row = row-1;
edgeIndices[count].column = column-1;
count++;
}
}
}
return count;
}
static PxU32 getEdgeTriangleIndices(const HeightField& heightfield, const EdgeData& edgeData, PxU32* PX_RESTRICT triangleIndices)
{
const PxU32 nbColumns = heightfield.getData().columns;
const PxU32 nbRows = heightfield.getData().rows;
const PxU32 edgeIndex = edgeData.edgeIndex;
const PxU32 cell = edgeData.cell;
const PxU32 row = edgeData.row;
const PxU32 column = edgeData.column;
PX_ASSERT(cell==edgeIndex / 3);
PX_ASSERT(row==cell / nbColumns);
PX_ASSERT(column==cell % nbColumns);
PxU32 count = 0;
switch (edgeIndex - cell*3)
{
case 0:
if (column < nbColumns - 1)
{
if (row > 0)
{
if (heightfield.isZerothVertexShared(cell - nbColumns))
triangleIndices[count++] = ((cell - nbColumns) << 1);
else
triangleIndices[count++] = ((cell - nbColumns) << 1) + 1;
}
if (row < nbRows - 1)
{
if (heightfield.isZerothVertexShared(cell))
triangleIndices[count++] = (cell << 1) + 1;
else
triangleIndices[count++] = cell << 1;
}
}
break;
case 1:
if ((row < nbRows - 1) && (column < nbColumns - 1))
{
triangleIndices[count++] = cell << 1;
triangleIndices[count++] = (cell << 1) + 1;
}
break;
case 2:
if (row < nbRows - 1)
{
if (column > 0)
{
triangleIndices[count++] = ((cell - 1) << 1) + 1;
}
if (column < nbColumns - 1)
{
triangleIndices[count++] = cell << 1;
}
}
break;
}
return count;
}
PX_FORCE_INLINE PxU32 anyHole(PxU32 doubleMatIndex, PxU16 holeMaterialIndex)
{
return PxU32((doubleMatIndex & 0xFFFF) == holeMaterialIndex) | (PxU32(doubleMatIndex >> 16) == holeMaterialIndex);
}
void HeightField::parseTrianglesForCollisionVertices(PxU16 holeMaterialIndex)
{
const PxU32 nbColumns = getNbColumnsFast();
const PxU32 nbRows = getNbRowsFast();
PxBitMap rowHoles[2];
rowHoles[0].resizeAndClear(nbColumns + 1);
rowHoles[1].resizeAndClear(nbColumns + 1);
for (PxU32 iCol = 0; iCol < nbColumns; iCol++)
{
if (anyHole(getMaterialIndex01(iCol), holeMaterialIndex))
{
rowHoles[0].set(iCol);
rowHoles[0].set(iCol + 1);
}
PxU32 vertIndex = iCol;
if(isCollisionVertexPreca(vertIndex, 0, iCol, holeMaterialIndex))
mData.samples[vertIndex].materialIndex1.setBit();
else
mData.samples[vertIndex].materialIndex1.clearBit();
}
PxU32 nextRow = 1, currentRow = 0;
for (PxU32 iRow = 1; iRow < nbRows; iRow++)
{
PxU32 rowOffset = iRow*nbColumns;
for (PxU32 iCol = 0; iCol < nbColumns; iCol++)
{
const PxU32 vertIndex = rowOffset + iCol; // column index plus current row offset (vertex/cell index)
if(anyHole(getMaterialIndex01(vertIndex), holeMaterialIndex))
{
rowHoles[currentRow].set(iCol);
rowHoles[currentRow].set(iCol + 1);
rowHoles[nextRow].set(iCol);
rowHoles[nextRow].set(iCol + 1);
}
if ((iCol == 0) || (iCol == nbColumns - 1) || (iRow == nbRows - 1) || rowHoles[currentRow].test(iCol))
{
if(isCollisionVertexPreca(vertIndex, iRow, iCol, holeMaterialIndex))
mData.samples[vertIndex].materialIndex1.setBit();
else
mData.samples[vertIndex].materialIndex1.clearBit();
} else
{
if (isConvexVertex(vertIndex, iRow, iCol))
mData.samples[vertIndex].materialIndex1.setBit();
}
}
rowHoles[currentRow].clear();
// swap prevRow and prevPrevRow
nextRow ^= 1; currentRow ^= 1;
}
}
bool HeightField::isSolidVertex(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex, bool& nbSolid) const
{
// check if solid and boundary
// retrieve edge indices for current vertexIndex
EdgeData edgeIndices[8];
const PxU32 edgeCount = ::getVertexEdgeIndices(*this, vertexIndex, row, column, edgeIndices);
PxU32 faceCounts[8];
PxU32 faceIndices[2 * 8];
PxU32* dst = faceIndices;
for (PxU32 i = 0; i < edgeCount; i++)
{
faceCounts[i] = ::getEdgeTriangleIndices(*this, edgeIndices[i], dst);
dst += 2;
}
nbSolid = false;
const PxU32* currentfaceIndices = faceIndices; // parallel array of pairs of face indices per edge index
for (PxU32 i = 0; i < edgeCount; i++)
{
if (faceCounts[i] > 1)
{
const PxU16& material0 = getTriangleMaterial(currentfaceIndices[0]);
const PxU16& material1 = getTriangleMaterial(currentfaceIndices[1]);
// ptchernev TODO: this is a bit arbitrary
if (material0 != holeMaterialIndex)
{
nbSolid = true;
if (material1 == holeMaterialIndex)
return true; // edge between solid and hole => return true
}
if (material1 != holeMaterialIndex)
{
nbSolid = true;
if (material0 == holeMaterialIndex)
return true; // edge between hole and solid => return true
}
}
else
{
if (getTriangleMaterial(currentfaceIndices[0]) != holeMaterialIndex)
return true;
}
currentfaceIndices += 2; // 2 face indices per edge
}
return false;
}
bool HeightField::isCollisionVertexPreca(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex) const
{
#ifdef PX_HEIGHTFIELD_DEBUG
PX_ASSERT(isValidVertex(vertexIndex));
#endif
PX_ASSERT((vertexIndex / getNbColumnsFast()) == row);
PX_ASSERT((vertexIndex % getNbColumnsFast()) == column);
// check boundary conditions - boundary edges shouldn't produce collision with eNO_BOUNDARY_EDGES flag
if(mData.flags & PxHeightFieldFlag::eNO_BOUNDARY_EDGES)
if ((row == 0) || (column == 0) || (row >= mData.rows-1) || (column >= mData.columns-1))
return false;
bool nbSolid;
if(isSolidVertex(vertexIndex, row, column, holeMaterialIndex, nbSolid))
return true;
// return true if it is boundary or solid and convex
return (nbSolid && isConvexVertex(vertexIndex, row, column));
}
// AP: this naming is confusing and inconsistent with return value. the function appears to compute vertex coord rather than cell coords
// it would most likely be better to stay in cell coords instead, since fractional vertex coords just do not make any sense
PxU32 HeightField::computeCellCoordinates(PxReal x, PxReal z, PxReal& fracX, PxReal& fracZ) const
{
namespace i = physx::intrinsics;
x = i::selectMax(x, 0.0f);
z = i::selectMax(z, 0.0f);
#if 0 // validation code for scaled clamping epsilon computation
for (PxReal ii = 1.0f; ii < 100000.0f; ii+=1.0f)
{
PX_UNUSED(ii);
PX_ASSERT(PxFloor(ii+(1-1e-7f*ii)) == ii);
}
#endif
const PxF32 epsx = 1.0f - PxAbs(x+1.0f) * 1e-6f; // epsilon needs to scale with values of x,z...
const PxF32 epsz = 1.0f - PxAbs(z+1.0f) * 1e-6f;
PxF32 x1 = i::selectMin(x, float(mData.rowLimit)+epsx);
PxF32 z1 = i::selectMin(z, float(mData.colLimit)+epsz);
x = PxFloor(x1);
fracX = x1 - x;
z = PxFloor(z1);
fracZ = z1 - z;
PX_ASSERT(x >= 0.0f && x < PxF32(mData.rows));
PX_ASSERT(z >= 0.0f && z < PxF32(mData.columns));
const PxU32 vertexIndex = PxU32(x) * mData.nbColumns + PxU32(z);
PX_ASSERT(vertexIndex < mData.rows*mData.columns);
return vertexIndex;
}
| 24,425 | C++ | 31.874832 | 199 | 0.658956 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactBoxConvex.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 "GuGJKPenetration.h"
#include "GuEPA.h"
#include "GuVecBox.h"
#include "GuVecConvexHull.h"
#include "GuVecConvexHullNoScale.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
#define PCM_BOX_HULL_DEBUG 0
using namespace physx;
using namespace Gu;
using namespace aos;
static bool fullContactsGenerationBoxConvex(const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1,
PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, PersistentContactManifold& manifold, Vec3VArg normal,
const Vec3VArg closestA, const Vec3VArg closestB, const FloatVArg contactDist, bool idtScale, bool doOverlapTest, PxRenderOutput* renderOutput,
PxReal toleranceLength)
{
PolygonalData polyData0;
const BoxV& box = relativeConvex->getConvex<BoxV>();
const ConvexHullV& convexHull = localConvex->getConvex<ConvexHullV>();
PxVec3 halfExtents;
V3StoreU(box.extents, halfExtents);
PCMPolygonalBox polyBox0(halfExtents);
polyBox0.getPolygonalData(&polyData0);
polyData0.mPolygonVertexRefs = gPCMBoxPolygonData;
PolygonalData polyData1;
getPCMConvexData(convexHull, idtScale, polyData1);
const Mat33V identity = M33Identity();
SupportLocalImpl<BoxV> map0(box, transf0, identity, identity, true);
PX_ALIGN(16, PxU8 buff1[sizeof(SupportLocalImpl<ConvexHullV>)]);
SupportLocal* map1 = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) :
static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)));
PxU32 numContacts = 0;
if(generateFullContactManifold(polyData0, polyData1, &map0, map1, manifoldContacts, numContacts, contactDist, normal, closestA, closestB, box.getMarginF(), convexHull.getMarginF(),
doOverlapTest, renderOutput, toleranceLength))
{
if (numContacts > 0)
{
//reduce contacts
manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
}
else
{
//if doOverlapTest is true, which means GJK/EPA degenerate so we won't have any contact in the manifoldContacts array
if (!doOverlapTest)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
}
}
return true;
}
return false;
}
static bool generateOrProcessContactsBoxConvex( const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1,
const PxMatTransformV& aToB, GjkStatus status, GjkOutput& output, PersistentContactManifold& manifold, PxContactBuffer& contactBuffer,
PxU32 initialContacts, const FloatV minMargin, const FloatV contactDist,
bool idtScale, PxReal toleranceLength, PxRenderOutput* renderOutput)
{
if (status == GJK_NON_INTERSECT)
{
return false;
}
else
{
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
const Vec3V localNor = manifold.mNumContacts ? manifold.getLocalNormal() : V3Zero();
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
//addGJKEPAContacts will increase the number of contacts in manifold. If status == EPA_CONTACT, we need to run epa algorithm and generate closest points, normal and
//pentration. If epa doesn't degenerate, we will store the contacts information in the manifold. Otherwise, we will return true to do the fallback test
const bool doOverlapTest = addGJKEPAContacts(relativeConvex, localConvex, aToB, status, manifoldContacts, replaceBreakingThreshold, FLoad(toleranceLength), output, manifold);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
//ML: after we refresh the contacts(newContacts) and generate a GJK/EPA contacts(we will store that in the manifold), if the number of contacts is still less than the original contacts,
//which means we lose too mang contacts and we should regenerate all the contacts in the current configuration
//Also, we need to look at the existing contacts, if the existing contacts has very different normal than the GJK/EPA contacts,
//which means we should throw away the existing contacts and do full contact gen
const bool fullContactGen = FAllGrtr(FLoad(0.707106781f), V3Dot(localNor, output.normal)) || (manifold.mNumContacts < initialContacts);
if (fullContactGen || doOverlapTest)
{
return fullContactsGenerationBoxConvex(relativeConvex, localConvex, transf0, transf1, manifoldContacts, contactBuffer,
manifold, output.normal, output.closestA, output.closestB, contactDist, idtScale, doOverlapTest, renderOutput, toleranceLength);
}
else
{
const Vec3V newLocalNor = V3Add(localNor, output.normal);
const Vec3V worldNormal = V3Normalize(transf1.rotate(newLocalNor));
//const Vec3V worldNormal = transf1.rotate(normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
return true;
}
}
}
bool Gu::pcmContactBoxConvex(GU_CONTACT_METHOD_ARGS)
{
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1);
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0);
PersistentContactManifold& manifold = cache.getManifold();
const ConvexHullData* hullData = _getHullData(shapeConvex);
PxPrefetchLine(hullData);
const FloatV contactDist = FLoad(params.mContactDistance);
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans(transf1.transformInv(transf0));
const PxMatTransformV aToB(curRTrans);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength);
const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength);
#if PCM_BOX_HULL_DEBUG
const PxVec3* verts = hullData->getHullVertices();
for (PxU32 i = 0; i < hullData->mNbPolygons; ++i)
{
const HullPolygonData& polygon = hullData->mPolygons[i];
const PxU8* inds = hullData->getVertexData8() + polygon.mVRef8;
Vec3V* points = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*polygon.mNbVerts, 16));
for (PxU32 j = 0; j < polygon.mNbVerts; ++j)
{
points[j] = V3LoadU_SafeReadW(verts[inds[j]]);
}
PersistentContactManifold::drawPolygon(*renderOutput, transf1, points, (PxU32)polygon.mNbVerts, 0x00ff0000);
}
#endif
const FloatV minMargin = FMin(convexMargin, boxMargin);//FMin(boxMargin, convexMargin);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f));
const PxU32 initialContacts = manifold.mNumContacts;
manifold.refreshContactPoints(aToB, projectBreakingThreshold, contactDist);
const Vec3V extents = V3Mul(V3LoadU(hullData->mInternal.mExtents), vScale);
const FloatV radiusA = V3Length(boxExtents);
const FloatV radiusB = V3Length(extents);
//After the refresh contact points, the numcontacts in the manifold will be changed
const bool bLostContacts = (manifold.mNumContacts != initialContacts);
if(bLostContacts || manifold.invalidate_BoxConvex(curRTrans, transf0.q, transf1.q, minMargin, radiusA, radiusB))
{
manifold.setRelativeTransform(curRTrans, transf0.q, transf1.q);
GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT;
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const bool idtScale = shapeConvex.scale.isIdentity();
const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale);
const BoxV box(V3Zero(), boxExtents);
GjkOutput output;
const RelativeConvex<BoxV> relativeConvex(box, aToB);
if(idtScale)
{
const LocalConvex<ConvexHullNoScaleV> localConvex(static_cast<const ConvexHullNoScaleV&>(convexHull));
status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<ConvexHullNoScaleV> >(relativeConvex, localConvex, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
return generateOrProcessContactsBoxConvex(&relativeConvex, &localConvex, transf0, transf1, aToB,
status, output, manifold, contactBuffer, initialContacts,
minMargin, contactDist, idtScale, toleranceLength, renderOutput);
}
else
{
const LocalConvex<ConvexHullV> localConvex(convexHull);
status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<ConvexHullV> >(relativeConvex, localConvex, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
return generateOrProcessContactsBoxConvex(&relativeConvex, &localConvex, transf0, transf1, aToB,
status, output, manifold, contactBuffer, initialContacts,
minMargin, contactDist, idtScale, toleranceLength, renderOutput);
}
}
else if(manifold.getNumContacts()>0)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
return false;
}
| 11,634 | C++ | 44.272373 | 247 | 0.776947 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleMesh.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 "GuVecTriangle.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactConvexCommon.h"
#include "GuInternal.h"
#include "GuPCMContactMeshCallback.h"
#include "GuBarycentricCoordinates.h"
#include "GuBox.h"
using namespace physx;
using namespace Gu;
using namespace aos;
namespace
{
struct PCMCapsuleVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback< PCMCapsuleVsMeshContactGenerationCallback >
{
PCMCapsuleVsMeshContactGenerationCallback& operator=(const PCMCapsuleVsMeshContactGenerationCallback&);
PCMCapsuleVsMeshContactGeneration mGeneration;
PCMCapsuleVsMeshContactGenerationCallback(
const CapsuleV& capsule,
const FloatVArg contactDist,
const FloatVArg replaceBreakingThreshold,
const PxTransformV& sphereTransform,
const PxTransformV& meshTransform,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
const PxU8* extraTriData,
const Cm::FastVertex2ShapeScaling& meshScaling,
bool idtMeshScale,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
PxRenderOutput* renderOutput = NULL
) :
PCMMeshContactGenerationCallback<PCMCapsuleVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale),
mGeneration(capsule, contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer,
deferredContacts, renderOutput)
{
}
PX_FORCE_INLINE bool doTest(const PxVec3&, const PxVec3&, const PxVec3&) { return true; }
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMCapsuleVsMeshContactGeneration>(cache);
}
};
}
bool Gu::pcmContactCapsuleMesh(GU_CONTACT_METHOD_ARGS)
{
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0);
const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1);
//gRenderOutPut = cache.mRenderOutput;
const FloatV capsuleRadius = FLoad(shapeCapsule.radius);
const FloatV contactDist = FLoad(params.mContactDistance);
const PxTransformV capsuleTransform = loadTransformA(transform0);//capsule transform
const PxTransformV meshTransform = loadTransformA(transform1);//triangleMesh
const PxTransformV curTransform = meshTransform.transformInv(capsuleTransform);
// We must be in local space to use the cache
if(multiManifold.invalidate(curTransform, capsuleRadius, FLoad(0.02f)))
{
const FloatV replaceBreakingThreshold = FMul(capsuleRadius, FLoad(0.001f));
//const FloatV capsuleHalfHeight = FloatV_From_F32(shapeCapsule.halfHeight);
Cm::FastVertex2ShapeScaling meshScaling;
const bool idtMeshScale = shapeMesh.scale.isIdentity();
if(!idtMeshScale)
meshScaling.init(shapeMesh.scale);
// Capsule data
const PxVec3 tmp = getCapsuleHalfHeightVector(transform0, shapeCapsule);
const Segment worldCapsule(transform0.p + tmp, transform0.p - tmp);
const Segment meshCapsule( // Capsule in mesh space
transform1.transformInv(worldCapsule.p0),
transform1.transformInv(worldCapsule.p1));
const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance;
const PxVec3 capsuleCenterInMesh = transform1.transformInv(transform0.p);
const PxVec3 capsuleDirInMesh = transform1.rotateInv(tmp);
const CapsuleV capsule(V3LoadU(capsuleCenterInMesh), V3LoadU(capsuleDirInMesh), capsuleRadius);
// We must be in local space to use the cache
const Capsule queryCapsule(meshCapsule, inflatedRadius);
const TriangleMesh* meshData = _getMeshData(shapeMesh);
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData();
// mesh scale is not baked into cached verts
PCMCapsuleVsMeshContactGenerationCallback callback(
capsule,
contactDist,
replaceBreakingThreshold,
capsuleTransform,
meshTransform,
multiManifold,
contactBuffer,
extraData,
meshScaling,
idtMeshScale,
NULL,
renderOutput);
//bound the capsule in shape space by an OBB:
Box queryBox;
queryBox.create(queryCapsule);
//apply the skew transform to the box:
if(!idtMeshScale)
meshScaling.transformQueryBounds(queryBox.center, queryBox.extents, queryBox.rot);
Midphase::intersectOBB(meshData, queryBox, callback, true);
callback.flushCache();
callback.mGeneration.processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE, false);
}
else
{
const PxMatTransformV aToB(curTransform);
const FloatV projectBreakingThreshold = FMul(capsuleRadius, FLoad(0.05f));
const FloatV refereshDistance = FAdd(capsuleRadius, contactDist);
//multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist);
multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance);
}
//multiManifold.drawManifold(*gRenderOutPut, capsuleTransform, meshTransform);
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, capsuleTransform, meshTransform, capsuleRadius);
}
void Gu::PCMCapsuleVsMeshContactGeneration::generateEE(const Vec3VArg p, const Vec3VArg q, const FloatVArg sqInflatedRadius,
const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg a, const Vec3VArg b,
MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
const FloatV zero = FZero();
const Vec3V ab = V3Sub(b, a);
const Vec3V n = V3Cross(ab, normal);
const FloatV d = V3Dot(n, a);
const FloatV np = V3Dot(n, p);
const FloatV nq = V3Dot(n,q);
const FloatV signP = FSub(np, d);
const FloatV signQ = FSub(nq, d);
const FloatV temp = FMul(signP, signQ);
if(FAllGrtr(temp, zero))
return;//If both points in the same side as the plane, no intersect points
// if colliding edge (p3,p4) and plane are parallel return no collision
const Vec3V pq = V3Sub(q, p);
const FloatV npq= V3Dot(n, pq);
if(FAllEq(npq, zero))
return;
const FloatV one = FOne();
//calculate the intersect point in the segment pq
const FloatV segTValue = FDiv(FSub(d, np), npq);
const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p);
//calculate a normal perpendicular to ray localPointA + normal, 2D segment segment intersection
const Vec3V perNormal = V3Cross(normal, pq);
const Vec3V ap = V3Sub(localPointA, a);
const FloatV nom = V3Dot(perNormal, ap);
const FloatV denom = V3Dot(perNormal, ab);
//const FloatV tValue = FClamp(FDiv(nom, denom), zero, FOne());
const FloatV tValue = FDiv(nom, denom);
const BoolV con = BAnd(FIsGrtrOrEq(one, tValue), FIsGrtrOrEq(tValue, zero));
if(BAllEqFFFF(con))
return;
//const Vec3V localPointB = V3ScaleAdd(ab, tValue, a); v = V3Sub(localPointA, localPointB); v = V3NegScaleSub(ab, tValue, tap)
const Vec3V v = V3NegScaleSub(ab, tValue, ap);
const FloatV sqDist = V3Dot(v, v);
if(FAllGrtr(sqInflatedRadius, sqDist))
{
const Vec3V localPointB = V3Sub(localPointA, v);
const FloatV signedDist = V3Dot(v, normal);
manifoldContacts[numContacts].mLocalPointA = localPointA;
manifoldContacts[numContacts].mLocalPointB = localPointB;
manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist);
manifoldContacts[numContacts++].mFaceIndex = triangleIndex;
}
}
void Gu::PCMCapsuleVsMeshContactGeneration::generateEEContacts(const Vec3VArg a, const Vec3VArg b,
const Vec3VArg c, const Vec3VArg normal,
PxU32 triangleIndex, const Vec3VArg p,
const Vec3VArg q, const FloatVArg sqInflatedRadius,
PxU32 previousNumContacts, MeshPersistentContact* manifoldContacts,
PxU32& numContacts)
{
if((numContacts - previousNumContacts) < 2)
generateEE(p, q, sqInflatedRadius, normal, triangleIndex, a, b, manifoldContacts, numContacts);
if((numContacts - previousNumContacts) < 2)
generateEE(p, q, sqInflatedRadius, normal, triangleIndex, b, c, manifoldContacts, numContacts);
if((numContacts - previousNumContacts) < 2)
generateEE(p, q, sqInflatedRadius, normal, triangleIndex, a, c, manifoldContacts, numContacts);
}
void Gu::PCMCapsuleVsMeshContactGeneration::generateEEMTD( const Vec3VArg p, const Vec3VArg q, const FloatVArg inflatedRadius,
const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg a, const Vec3VArg b,
MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
const FloatV zero = FZero();
const Vec3V ab = V3Sub(b, a);
const Vec3V n = V3Cross(ab, normal);
const FloatV d = V3Dot(n, a);
const FloatV np = V3Dot(n, p);
const FloatV nq = V3Dot(n,q);
const FloatV signP = FSub(np, d);
const FloatV signQ = FSub(nq, d);
const FloatV temp = FMul(signP, signQ);
if(FAllGrtr(temp, zero))
return;//If both points in the same side as the plane, no intersect points
// if colliding edge (p3,p4) and plane are parallel return no collision
const Vec3V pq = V3Sub(q, p);
const FloatV npq= V3Dot(n, pq);
if(FAllEq(npq, zero))
return;
//calculate the intersect point in the segment pq
const FloatV segTValue = FDiv(FSub(d, np), npq);
const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p);
//calculate a normal perpendicular to ray localPointA + normal, 2D segment segment intersection
const Vec3V perNormal = V3Cross(normal, pq);
const Vec3V ap = V3Sub(localPointA, a);
const FloatV nom = V3Dot(perNormal, ap);
const FloatV denom = V3Dot(perNormal, ab);
const FloatV tValue = FClamp(FDiv(nom, denom), zero, FOne());
const Vec3V v = V3NegScaleSub(ab, tValue, ap);
const FloatV signedDist = V3Dot(v, normal);
if(FAllGrtr(inflatedRadius, signedDist))
{
const Vec3V localPointB = V3Sub(localPointA, v);
manifoldContacts[numContacts].mLocalPointA = localPointA;
manifoldContacts[numContacts].mLocalPointB = localPointB;
manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist);
manifoldContacts[numContacts++].mFaceIndex = triangleIndex;
}
}
void Gu::PCMCapsuleVsMeshContactGeneration::generateEEContactsMTD( const Vec3VArg a, const Vec3VArg b,
const Vec3VArg c, const Vec3VArg normal,
PxU32 triangleIndex, const Vec3VArg p,
const Vec3VArg q, const FloatVArg inflatedRadius,
MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, a, b, manifoldContacts, numContacts);
generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, b, c, manifoldContacts, numContacts);
generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, a, c, manifoldContacts, numContacts);
}
void Gu::PCMCapsuleVsMeshContactGeneration::generateContacts(const Vec3VArg a, const Vec3VArg b,
const Vec3VArg c, const Vec3VArg planeNormal,
const Vec3VArg normal, PxU32 triangleIndex,
const Vec3VArg p, const Vec3VArg q,
const FloatVArg inflatedRadius,
MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V ap = V3Sub(p, a);
const Vec3V aq = V3Sub(q, a);
//This is used to calculate the barycentric coordinate
const FloatV d00 = V3Dot(ab, ab);
const FloatV d01 = V3Dot(ab, ac);
const FloatV d11 = V3Dot(ac, ac);
const FloatV zero = FZero();
const FloatV largeValue = FLoad(1e+20f);
const FloatV tDenom = FSub(FMul(d00, d11), FMul(d01, d01));
const FloatV bdenom = FSel(FIsGrtr(tDenom, zero), FRecip(tDenom), largeValue);
//compute the intersect point of p and triangle plane abc
const FloatV inomp = V3Dot(planeNormal, V3Neg(ap));
const FloatV ideom = V3Dot(planeNormal, normal);
const FloatV ipt = FSel(FIsGrtr(ideom, zero), FNeg(FDiv(inomp, ideom)), largeValue);
const Vec3V closestP31 = V3NegScaleSub(normal, ipt, p);
const Vec3V closestP30 = p;
//Compute the barycentric coordinate for project point of q
const Vec3V pV20 = V3Sub(closestP31, a);
const FloatV pD20 = V3Dot(pV20, ab);
const FloatV pD21 = V3Dot(pV20, ac);
const FloatV v0 = FMul(FSub(FMul(d11, pD20), FMul(d01, pD21)), bdenom);
const FloatV w0 = FMul(FSub(FMul(d00, pD21), FMul(d01, pD20)), bdenom);
//check closestP3 is inside the triangle
const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0);
const BoolV tempCon0 = BAnd(con0, FIsGrtr(inflatedRadius, ipt));
if(BAllEqTTTT(tempCon0))
{
manifoldContacts[numContacts].mLocalPointA = closestP30;//transform to B space, it will get convert to A space later
manifoldContacts[numContacts].mLocalPointB = closestP31;
manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), ipt);
manifoldContacts[numContacts++].mFaceIndex = triangleIndex;
}
const FloatV inomq = V3Dot(planeNormal, V3Neg(aq));
const FloatV iqt = FSel(FIsGrtr(ideom, FZero()), FNeg(FDiv(inomq, ideom)), FLoad(1e+20f));
const Vec3V closestP41 = V3NegScaleSub(normal, iqt, q);
const Vec3V closestP40 = q;
//Compute the barycentric coordinate for project point of q
const Vec3V qV20 = V3Sub(closestP41, a);
const FloatV qD20 = V3Dot(qV20, ab);
const FloatV qD21 = V3Dot(qV20, ac);
const FloatV v1 = FMul(FSub(FMul(d11, qD20), FMul(d01, qD21)), bdenom);
const FloatV w1 = FMul(FSub(FMul(d00, qD21), FMul(d01, qD20)), bdenom);
const BoolV con1 = isValidTriangleBarycentricCoord(v1, w1);
const BoolV tempCon1 = BAnd(con1, FIsGrtr(inflatedRadius, iqt));
if(BAllEqTTTT(tempCon1))
{
manifoldContacts[numContacts].mLocalPointA = closestP40;
manifoldContacts[numContacts].mLocalPointB = closestP41;
manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), iqt);
manifoldContacts[numContacts++].mFaceIndex = triangleIndex;
}
}
static PX_FORCE_INLINE Vec4V pcmDistanceSegmentSegmentSquared4(const Vec3VArg p, const Vec3VArg d0,
const Vec3VArg p02, const Vec3VArg d02,
const Vec3VArg p12, const Vec3VArg d12,
const Vec3VArg p22, const Vec3VArg d22,
const Vec3VArg p32, const Vec3VArg d32,
Vec4V& s, Vec4V& t)
{
const Vec4V zero = V4Zero();
const Vec4V one = V4One();
const Vec4V eps = V4Eps();
const Vec4V half = V4Splat(FHalf());
const Vec4V d0X = V4Splat(V3GetX(d0));
const Vec4V d0Y = V4Splat(V3GetY(d0));
const Vec4V d0Z = V4Splat(V3GetZ(d0));
const Vec4V pX = V4Splat(V3GetX(p));
const Vec4V pY = V4Splat(V3GetY(p));
const Vec4V pZ = V4Splat(V3GetZ(p));
Vec4V d024 = Vec4V_From_Vec3V(d02);
Vec4V d124 = Vec4V_From_Vec3V(d12);
Vec4V d224 = Vec4V_From_Vec3V(d22);
Vec4V d324 = Vec4V_From_Vec3V(d32);
Vec4V p024 = Vec4V_From_Vec3V(p02);
Vec4V p124 = Vec4V_From_Vec3V(p12);
Vec4V p224 = Vec4V_From_Vec3V(p22);
Vec4V p324 = Vec4V_From_Vec3V(p32);
Vec4V d0123X, d0123Y, d0123Z;
Vec4V p0123X, p0123Y, p0123Z;
PX_TRANSPOSE_44_34(d024, d124, d224, d324, d0123X, d0123Y, d0123Z);
PX_TRANSPOSE_44_34(p024, p124, p224, p324, p0123X, p0123Y, p0123Z);
const Vec4V rX = V4Sub(pX, p0123X);
const Vec4V rY = V4Sub(pY, p0123Y);
const Vec4V rZ = V4Sub(pZ, p0123Z);
//TODO - store this in a transposed state and avoid so many dot products?
const FloatV dd = V3Dot(d0, d0);
const Vec4V e = V4MulAdd(d0123Z, d0123Z, V4MulAdd(d0123X, d0123X, V4Mul(d0123Y, d0123Y)));
const Vec4V b = V4MulAdd(d0Z, d0123Z, V4MulAdd(d0X, d0123X, V4Mul(d0Y, d0123Y)));
const Vec4V c = V4MulAdd(d0Z, rZ, V4MulAdd(d0X, rX, V4Mul(d0Y, rY)));
const Vec4V f = V4MulAdd(d0123Z, rZ, V4MulAdd(d0123X, rX, V4Mul(d0123Y, rY)));
const Vec4V a(V4Splat(dd));
const Vec4V aRecip(V4Recip(a));
const Vec4V eRecip(V4Recip(e));
//if segments not parallell, compute closest point on two segments and clamp to segment1
const Vec4V denom = V4Sub(V4Mul(a, e), V4Mul(b, b));
const Vec4V temp = V4Sub(V4Mul(b, f), V4Mul(c, e));
//const Vec4V s0 = V4Clamp(V4Div(temp, denom), zero, one);
//In PS3, 0(temp)/0(denom) will produce QNaN and V4Clamp can't clamp the value to zero and one. In PC, 0/0 will produce inf and V4Clamp clamp the value to be one.
//Therefore, we need to add the select code to protect against this case
const Vec4V value = V4Sel(V4IsEq(denom, zero), one, V4Div(temp, denom));
const Vec4V s0 = V4Clamp(value, zero, one);
//test whether segments are parallel
const BoolV con2 = V4IsGrtrOrEq(eps, denom);
const Vec4V sTmp = V4Sel(con2, half, s0);
//compute point on segment2 closest to segment1
//const Vec4V tTmp = V4Mul(V4Add(V4Mul(b, sTmp), f), eRecip);
const Vec4V tTmp = V4Sel(V4IsEq(e, zero), one, V4Mul(V4Add(V4Mul(b, sTmp), f), eRecip));
//if t is in [zero, one], done. otherwise clamp t
const Vec4V t2 = V4Clamp(tTmp, zero, one);
//recompute s for the new value
//const Vec4V comp = V4Mul(V4Sub(V4Mul(b,t2), c), aRecip);
const Vec4V comp = V4Sel(V4IsEq(a, zero), one, V4Mul(V4Sub(V4Mul(b,t2), c), aRecip));
const Vec4V s2 = V4Clamp(comp, zero, one);
s = s2;
t = t2;
const Vec4V closest1X = V4MulAdd(d0X, s2, pX);
const Vec4V closest1Y = V4MulAdd(d0Y, s2, pY);
const Vec4V closest1Z = V4MulAdd(d0Z, s2, pZ);
const Vec4V closest2X = V4MulAdd(d0123X, t2, p0123X);
const Vec4V closest2Y = V4MulAdd(d0123Y, t2, p0123Y);
const Vec4V closest2Z = V4MulAdd(d0123Z, t2, p0123Z);
const Vec4V vvX = V4Sub(closest1X, closest2X);
const Vec4V vvY = V4Sub(closest1Y, closest2Y);
const Vec4V vvZ = V4Sub(closest1Z, closest2Z);
const Vec4V vd = V4MulAdd(vvX, vvX, V4MulAdd(vvY, vvY, V4Mul(vvZ, vvZ)));
return vd;
}
// t is the barycenteric coordinate of a segment
// u is the barycenteric coordinate of a triangle
// v is the barycenteric coordinate of a triangle
static FloatV pcmDistanceSegmentTriangleSquared(const Vec3VArg p, const Vec3VArg q,
const Vec3VArg a, const Vec3VArg b, const Vec3VArg c,
FloatV& t, FloatV& u, FloatV& v)
{
const FloatV one = FOne();
const FloatV zero = FZero();
const Vec3V pq = V3Sub(q, p);
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V bc = V3Sub(c, b);
const Vec3V ap = V3Sub(p, a);
const Vec3V aq = V3Sub(q, a);
const Vec3V n = V3Normalize(V3Cross(ab, ac)); // normalize vector
const Vec4V combinedDot = V3Dot4(ab, ab, ab, ac, ac, ac, ap, n);
const FloatV d00 = V4GetX(combinedDot);
const FloatV d01 = V4GetY(combinedDot);
const FloatV d11 = V4GetZ(combinedDot);
const FloatV dist3 = V4GetW(combinedDot);
// PT: the new version is copied from Gu::distanceSegmentTriangleSquared
const FloatV tDenom = FSub(FMul(d00, d11), FMul(d01, d01));
const FloatV bdenom = FSel(FIsGrtr(tDenom, zero), FRecip(tDenom), zero);
const FloatV sqDist3 = FMul(dist3, dist3);
//compute the closest point of q and triangle plane abc
const FloatV dist4 = V3Dot(aq, n);
const FloatV sqDist4 = FMul(dist4, dist4);
const FloatV dMul = FMul(dist3, dist4);
const BoolV con = FIsGrtr(zero, dMul);
if(BAllEqTTTT(con))
{
//compute the intersect point
const FloatV nom = FNeg(V3Dot(n, ap));
const FloatV denom = FRecip(V3Dot(n, pq));
const FloatV t0 = FMul(nom, denom);
const Vec3V ip = V3ScaleAdd(pq, t0, p);//V3Add(p, V3Scale(pq, t));
const Vec3V v2 = V3Sub(ip, a);
const FloatV d20 = V3Dot(v2, ab);
const FloatV d21 = V3Dot(v2, ac);
const FloatV v0 = FMul(FNegScaleSub(d01, d21, FMul(d11, d20)), bdenom);
const FloatV w0 = FMul(FNegScaleSub(d01, d20, FMul(d00, d21)), bdenom);
const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0);
if(BAllEqTTTT(con0))
{
t = t0;
u = v0;
v = w0;
return zero;
}
}
const Vec3V closestP31 = V3NegScaleSub(n, dist3, p);//V3Sub(p, V3Scale(n, dist3));
const Vec3V closestP41 = V3NegScaleSub(n, dist4, q);// V3Sub(q, V3Scale(n, dist4));
//Compute the barycentric coordinate for project point of q
const Vec3V pV20 = V3Sub(closestP31, a);
const Vec3V qV20 = V3Sub(closestP41, a);
const Vec4V pD2 = V3Dot4(pV20, ab, pV20, ac, qV20, ab, qV20, ac);
const Vec4V pD2Swizzle = V4PermYXWZ(pD2);
const Vec4V d11d00 = V4UnpackXY(V4Splat(d11), V4Splat(d00));
const Vec4V v0w0v1w1 = V4Scale(V4NegMulSub(V4Splat(d01), pD2Swizzle, V4Mul(d11d00, pD2)), bdenom);
const FloatV v0 = V4GetX(v0w0v1w1);
const FloatV w0 = V4GetY(v0w0v1w1);
const FloatV v1 = V4GetZ(v0w0v1w1);
const FloatV w1 = V4GetW(v0w0v1w1);
const BoolV _con = isValidTriangleBarycentricCoord2(v0w0v1w1);
const BoolV con0 = BGetX(_con);
const BoolV con1 = BGetY(_con);
const BoolV cond2 = BAnd(con0, con1);
if(BAllEqTTTT(cond2))
{
// both p and q project points are interior point
const BoolV d2 = FIsGrtr(sqDist4, sqDist3);
t = FSel(d2, zero, one);
u = FSel(d2, v0, v1);
v = FSel(d2, w0, w1);
return FSel(d2, sqDist3, sqDist4);
}
else
{
Vec4V t40, t41;
const Vec4V sqDist44 = pcmDistanceSegmentSegmentSquared4(p,pq,a,ab, b,bc, a,ac, a,ab, t40, t41);
const FloatV t00 = V4GetX(t40);
const FloatV t10 = V4GetY(t40);
const FloatV t20 = V4GetZ(t40);
const FloatV t01 = V4GetX(t41);
const FloatV t11 = V4GetY(t41);
const FloatV t21 = V4GetZ(t41);
//edge ab
const FloatV u01 = t01;
const FloatV v01 = zero;
//edge bc
const FloatV u11 = FSub(one, t11);
const FloatV v11 = t11;
//edge ac
const FloatV u21 = zero;
const FloatV v21 = t21;
const FloatV sqDist0(V4GetX(sqDist44));
const FloatV sqDist1(V4GetY(sqDist44));
const FloatV sqDist2(V4GetZ(sqDist44));
const BoolV con2 = BAnd(FIsGrtr(sqDist1, sqDist0), FIsGrtr(sqDist2, sqDist0));
const BoolV con3 = FIsGrtr(sqDist2, sqDist1);
const FloatV sqDistPE = FSel(con2, sqDist0, FSel(con3, sqDist1, sqDist2));
const FloatV uEdge = FSel(con2, u01, FSel(con3, u11, u21));
const FloatV vEdge = FSel(con2, v01, FSel(con3, v11, v21));
const FloatV tSeg = FSel(con2, t00, FSel(con3, t10, t20));
if(BAllEqTTTT(con0))
{
//p's project point is an interior point
const BoolV d2 = FIsGrtr(sqDistPE, sqDist3);
t = FSel(d2, zero, tSeg);
u = FSel(d2, v0, uEdge);
v = FSel(d2, w0, vEdge);
return FSel(d2, sqDist3, sqDistPE);
}
else if(BAllEqTTTT(con1))
{
//q's project point is an interior point
const BoolV d2 = FIsGrtr(sqDistPE, sqDist4);
t = FSel(d2, one, tSeg);
u = FSel(d2, v1, uEdge);
v = FSel(d2, w1, vEdge);
return FSel(d2, sqDist4, sqDistPE);
}
else
{
t = tSeg;
u = uEdge;
v = vEdge;
return sqDistPE;
}
}
}
static bool selectNormal(const FloatVArg u, FloatVArg v, PxU8 data)
{
const FloatV zero = FLoad(1e-6f);
const FloatV one = FLoad(0.999999f);
// Analysis
if(FAllGrtr(zero, u))
{
if(FAllGrtr(zero, v))
{
// Vertex 0
if(!(data & (ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_20)))
return true;
}
else if(FAllGrtr(v, one))
{
// Vertex 2
if(!(data & (ETD_CONVEX_EDGE_12|ETD_CONVEX_EDGE_20)))
return true;
}
else
{
// Edge 0-2
if(!(data & ETD_CONVEX_EDGE_20))
return true;
}
}
else if(FAllGrtr(u,one))
{
if(FAllGrtr(zero, v))
{
// Vertex 1
if(!(data & (ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_12)))
return true;
}
}
else
{
if(FAllGrtr(zero, v))
{
// Edge 0-1
if(!(data & ETD_CONVEX_EDGE_01))
return true;
}
else
{
const FloatV threshold = FLoad(0.9999f);
const FloatV temp = FAdd(u, v);
if(FAllGrtrOrEq(temp, threshold))
{
// Edge 1-2
if(!(data & ETD_CONVEX_EDGE_12))
return true;
}
else
{
// Face
return true;
}
}
}
return false;
}
bool Gu::PCMCapsuleVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds)
{
PX_UNUSED(vertInds);
const FloatV zero = FZero();
const Vec3V p0 = V3LoadU(verts[0]);
const Vec3V p1 = V3LoadU(verts[1]);
const Vec3V p2 = V3LoadU(verts[2]);
const Vec3V p10 = V3Sub(p1, p0);
const Vec3V p20 = V3Sub(p2, p0);
const Vec3V n = V3Normalize(V3Cross(p10, p20));//(p1 - p0).cross(p2 - p0).getNormalized();
const FloatV d = V3Dot(p0, n);//d = -p0.dot(n);
const FloatV dist = FSub(V3Dot(mCapsule.getCenter(), n), d);//p.dot(n) + d;
// Backface culling
if(FAllGrtr(zero, dist))
return false;
FloatV t, u, v;
const FloatV sqDist = pcmDistanceSegmentTriangleSquared(mCapsule.p0, mCapsule.p1, p0, p1, p2, t, u, v);
if(FAllGrtr(mSqInflatedRadius, sqDist))
{
Vec3V patchNormalInTriangle;
if(selectNormal(u, v, triFlags))
{
patchNormalInTriangle = n;
}
else
{
if(FAllEq(sqDist, zero))
{
//segment intersect with the triangle
patchNormalInTriangle = n;
}
else
{
const Vec3V pq = V3Sub(mCapsule.p1, mCapsule.p0);
const Vec3V pointOnSegment = V3ScaleAdd(pq, t, mCapsule.p0);
const FloatV w = FSub(FOne(), FAdd(u, v));
const Vec3V pointOnTriangle = V3ScaleAdd(p0, w, V3ScaleAdd(p1, u, V3Scale(p2, v)));
patchNormalInTriangle = V3Normalize(V3Sub(pointOnSegment, pointOnTriangle));
}
}
const PxU32 previousNumContacts = mNumContacts;
generateContacts(p0, p1, p2, n, patchNormalInTriangle, triangleIndex, mCapsule.p0, mCapsule.p1, mInflatedRadius, mManifoldContacts, mNumContacts);
//ML: this need to use the sqInflatedRadius to avoid some bad contacts
generateEEContacts(p0, p1, p2, patchNormalInTriangle, triangleIndex, mCapsule.p0, mCapsule.p1, mSqInflatedRadius, previousNumContacts, mManifoldContacts, mNumContacts);
PxU32 numContacts = mNumContacts - previousNumContacts;
PX_ASSERT(numContacts <= 2);
if(numContacts > 0)
{
FloatV maxPen = FMax();
for(PxU32 i = previousNumContacts; i<mNumContacts; ++i)
{
const FloatV pen = V4GetW(mManifoldContacts[i].mLocalNormalPen);
mManifoldContacts[i].mLocalPointA = mMeshToConvex.transform(mManifoldContacts[i].mLocalPointA);
maxPen = FMin(maxPen, pen);
}
for(PxU32 i = previousNumContacts; i<mNumContacts; ++i)
{
Vec3V contact0 = mManifoldContacts[i].mLocalPointB;
for(PxU32 j=i+1; j<mNumContacts; ++j)
{
Vec3V contact1 = mManifoldContacts[j].mLocalPointB;
Vec3V dif = V3Sub(contact1, contact0);
FloatV d1 = V3Dot(dif, dif);
if(FAllGrtr(mSqReplaceBreakingThreshold, d1))
{
mManifoldContacts[j] = mManifoldContacts[mNumContacts-1];
mNumContacts--;
j--;
}
}
}
PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE);
addManifoldPointToPatch(patchNormalInTriangle, maxPen, previousNumContacts);
PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE);
if(mNumContacts >= 16)
{
PX_ASSERT(mNumContacts <= 64);
processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE);
}
}
}
return true;
}
bool Gu::PCMCapsuleVsMeshContactGeneration::processTriangle(const TriangleV& triangleV, PxU32 triangleIndex, const CapsuleV& capsule, const FloatVArg inflatedRadius, const PxU8 trigFlag,
MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
const FloatV zero = FZero();
const Vec3V p0 = triangleV.verts[0];
const Vec3V p1 = triangleV.verts[1];
const Vec3V p2 = triangleV.verts[2];
const Vec3V n = triangleV.normal();
const FloatV sqInflatedRadius = FMul(inflatedRadius, inflatedRadius);
FloatV t, u, v;
const FloatV sqDist = pcmDistanceSegmentTriangleSquared(capsule.p0, capsule.p1, p0, p1, p2, t, u, v);
if(FAllGrtr(sqInflatedRadius, sqDist))
{
Vec3V patchNormalInTriangle;
if(selectNormal(u, v, trigFlag))
{
patchNormalInTriangle = n;
}
else
{
if(FAllEq(sqDist, zero))
{
//segment intersect with the triangle
patchNormalInTriangle = n;
}
else
{
const Vec3V pq = V3Sub(capsule.p1, capsule.p0);
const Vec3V pointOnSegment = V3ScaleAdd(pq, t, capsule.p0);
const FloatV w = FSub(FOne(), FAdd(u, v));
const Vec3V pointOnTriangle = V3ScaleAdd(p0, w, V3ScaleAdd(p1, u, V3Scale(p2, v)));
patchNormalInTriangle = V3Normalize(V3Sub(pointOnSegment, pointOnTriangle));
}
}
generateContacts(p0, p1, p2, n, patchNormalInTriangle, triangleIndex, capsule.p0, capsule.p1, inflatedRadius, manifoldContacts, numContacts);
generateEEContactsMTD(p0, p1, p2, patchNormalInTriangle, triangleIndex, capsule.p0, capsule.p1, inflatedRadius, manifoldContacts, numContacts);
}
return true;
}
// PT: below is just for internal testing
PX_PHYSX_COMMON_API FloatV pcmDistanceSegmentTriangleSquaredExported( const Vec3VArg p, const Vec3VArg q,
const Vec3VArg a, const Vec3VArg b, const Vec3VArg c,
FloatV& t, FloatV& u, FloatV& v)
{
return pcmDistanceSegmentTriangleSquared(p, q, a, b, c, t, u, v);
}
| 30,025 | C++ | 34.241784 | 186 | 0.718768 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleConvex.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 "GuGJKPenetration.h"
#include "GuEPA.h"
#include "GuVecCapsule.h"
#include "GuVecConvexHull.h"
#include "GuVecConvexHullNoScale.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static bool fullContactsGenerationCapsuleConvex(const CapsuleV& capsule, const ConvexHullV& convexHull, const PxMatTransformV& aToB, const PxTransformV& transf0,const PxTransformV& transf1,
PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, bool idtScale, PersistentContactManifold& manifold, Vec3VArg normal,
const Vec3VArg closest, PxReal tolerance, const FloatVArg contactDist, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength)
{
PX_UNUSED(renderOutput);
PolygonalData polyData;
getPCMConvexData(convexHull,idtScale, polyData);
PX_ALIGN(16, PxU8 buff[sizeof(SupportLocalImpl<ConvexHullV>)]);
SupportLocal* map = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) :
static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)));
PxU32 numContacts = 0;
if(!generateFullContactManifold(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, normal, closest, tolerance, doOverlapTest, toleranceLength))
return false;
if (numContacts > 0)
{
manifold.addBatchManifoldContacts2(manifoldContacts, numContacts);
//transform normal into the world space
normal = transf1.rotate(normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist);
}
else
{
if (!doOverlapTest)
{
normal = transf1.rotate(normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist);
}
}
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
bool Gu::pcmContactCapsuleConvex(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1);
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0);
PersistentContactManifold& manifold = cache.getManifold();
const ConvexHullData* hullData = _getHullData(shapeConvex);
PxPrefetchLine(hullData);
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const FloatV contactDist = FLoad(params.mContactDistance);
const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight);
const FloatV capsuleRadius = FLoad(shapeCapsule.radius);
//Transfer A into the local space of B
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans(transf1.transformInv(transf0));
const PxMatTransformV aToB(curRTrans);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength);
const FloatV capsuleMinMargin = CalculateCapsuleMinMargin(capsuleRadius);
const FloatV minMargin = FMin(convexMargin, capsuleMinMargin);
const PxU32 initialContacts = manifold.mNumContacts;
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(1.25f));
const FloatV refreshDist = FAdd(contactDist, capsuleRadius);
manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDist);
//ML: after refreshContactPoints, we might lose some contacts
const bool bLostContacts = (manifold.mNumContacts != initialContacts);
GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT;
if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin))
{
const bool idtScale = shapeConvex.scale.isIdentity();
manifold.setRelativeTransform(curRTrans);
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale);
//transform capsule(a) into the local space of convexHull(b)
const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), capsuleRadius);
GjkOutput output;
const LocalConvex<CapsuleV> convexA(capsule);
const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), convexHull.getCenter());
if(idtScale)
{
const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull));
status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, initialSearchDir, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull);
status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
}
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
bool doOverlapTest = false;
if(status == GJK_NON_INTERSECT)
{
return false;
}
else if(status == GJK_DEGENERATE)
{
return fullContactsGenerationCapsuleConvex(capsule, convexHull, aToB, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal,
output.closestB, convexHull.getMarginF(), contactDist, true, renderOutput, toleranceLength);
}
else
{
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
if(status == GJK_CONTACT)
{
const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
//Add contact to contact stream
manifoldContacts[0].mLocalPointA = localPointA;
manifoldContacts[0].mLocalPointB = output.closestB;
manifoldContacts[0].mLocalNormalPen = localNormalPen;
//Add contact to manifold
manifold.addManifoldPoint2(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold);
}
else
{
PX_ASSERT(status == EPA_CONTACT);
if(idtScale)
{
const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull));
status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull);
status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
}
if(status == EPA_CONTACT)
{
const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
//Add contact to contact stream
manifoldContacts[0].mLocalPointA = localPointA;
manifoldContacts[0].mLocalPointB = output.closestB;
manifoldContacts[0].mLocalNormalPen = localNormalPen;
//Add contact to manifold
manifold.addManifoldPoint2(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold);
}
else
{
doOverlapTest = true;
}
}
if(initialContacts == 0 || bLostContacts || doOverlapTest)
{
return fullContactsGenerationCapsuleConvex(capsule, convexHull, aToB, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal,
output.closestB, convexHull.getMarginF(), contactDist, doOverlapTest, renderOutput, toleranceLength);
}
else
{
//This contact is either come from GJK or EPA
const Vec3V normal = transf1.rotate(output.normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
}
}
else if (manifold.getNumContacts() > 0)
{
const Vec3V normal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
return false;
}
| 10,406 | C++ | 42.3625 | 245 | 0.769652 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereBox.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 "GuVecBox.h"
#include "GuVecSphere.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
bool Gu::pcmContactSphereBox(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_UNUSED(cache);
using namespace aos;
// Get actual shape data
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1);
//const PsTransformV transf0(transform0);
const Vec3V sphereOrigin = V3LoadA(&transform0.p.x);
//const PsTransformV transf1(transform1);
const QuatV q1 = QuatVLoadA(&transform1.q.x);
const Vec3V p1 = V3LoadA(&transform1.p.x);
const FloatV radius = FLoad(shapeSphere.radius);
const PxTransformV transf1(p1, q1);
const FloatV cDist = FLoad(params.mContactDistance);
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
//translate sphere center into the box space
const Vec3V sphereCenter = transf1.transformInv(sphereOrigin);
const Vec3V nBoxExtents = V3Neg(boxExtents);
//const FloatV radSq = FMul(radius, radius);
const FloatV inflatedSum = FAdd(radius, cDist);
const FloatV sqInflatedSum = FMul(inflatedSum, inflatedSum);
const Vec3V p = V3Clamp(sphereCenter, nBoxExtents, boxExtents);
const Vec3V v = V3Sub(sphereCenter, p);
const FloatV lengthSq = V3Dot(v, v);
PX_ASSERT(contactBuffer.count < PxContactBuffer::MAX_CONTACTS);
if(FAllGrtr(sqInflatedSum, lengthSq))//intersect
{
//check whether the spherCenter is inside the box
const BoolV bInsideBox = V3IsGrtrOrEq(boxExtents, V3Abs(sphereCenter));
// PT: TODO: ??? revisit this, why do we have both BAllEqTTTT and BAllTrue3?
if(BAllEqTTTT(BAllTrue3(bInsideBox)))//sphere center inside the box
{
//Pick directions and sign
const Vec3V absP = V3Abs(p);
const Vec3V distToSurface = V3Sub(boxExtents, absP);//dist from embedded center to box surface along 3 dimensions.
const FloatV x = V3GetX(distToSurface);
const FloatV y = V3GetY(distToSurface);
const FloatV z = V3GetZ(distToSurface);
const Vec3V xV = V3Splat(x);
const Vec3V zV = V3Splat(z);
//find smallest element of distToSurface
const BoolV con0 = BAllTrue3(V3IsGrtrOrEq(distToSurface, zV));
const BoolV con1 = BAllTrue3(V3IsGrtrOrEq(distToSurface, xV));
const Vec3V sign = V3Sign(p);
const Vec3V tmpX = V3Mul(V3UnitX(), sign);
const Vec3V tmpY = V3Mul(V3UnitY(), sign);
const Vec3V tmpZ = V3Mul(V3UnitZ(), sign);
const Vec3V locNorm = V3Sel(con0, tmpZ, V3Sel(con1, tmpX, tmpY));////local coords contact normal
const FloatV dist = FNeg(FSel(con0, z, FSel(con1, x, y)));
//separation so far is just the embedding of the center point; we still have to push out all of the radius.
const Vec3V normal = transf1.rotate(locNorm);
const FloatV penetration = FSub(dist, radius);
const Vec3V point = V3Sub(sphereOrigin , V3Scale(normal, dist));
outputSimplePCMContact(contactBuffer, point, normal, penetration);
}
else
{
//get the closest point from the center to the box surface
const FloatV recipLength = FRsqrt(lengthSq);
const FloatV length = FRecip(recipLength);
const Vec3V locNorm = V3Scale(v, recipLength);
const FloatV penetration = FSub(length, radius);
const Vec3V normal = transf1.rotate(locNorm);
const Vec3V point = transf1.transform(p);
outputSimplePCMContact(contactBuffer, point, normal, penetration);
}
return true;
}
return false;
}
| 5,191 | C++ | 38.333333 | 117 | 0.746484 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPersistentContactManifold.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_PERSISTENTCONTACTMANIFOLD_H
#define Gu_PERSISTENTCONTACTMANIFOLD_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxUnionCast.h"
#include "foundation/PxMemory.h"
#include "foundation/PxVecTransform.h"
#define PCM_LOW_LEVEL_DEBUG 0
namespace physx
{
#define VISUALIZE_PERSISTENT_CONTACT 1
//This is for primitives vs primitives
#define GU_MANIFOLD_CACHE_SIZE 4
//These are for primitives vs mesh
#define GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE 5
#define GU_SINGLE_MANIFOLD_CACHE_SIZE 6
#define GU_SPHERE_MANIFOLD_CACHE_SIZE 1
#define GU_CAPSULE_MANIFOLD_CACHE_SIZE 3
#define GU_MAX_MANIFOLD_SIZE 6 // PT: max nb of manifolds (e.g. for multi-manifolds), NOT the max size of a single manifold
#define GU_MESH_CONTACT_REDUCTION_THRESHOLD 16
#define GU_MANIFOLD_INVALID_INDEX 0xffffffff
//ML: this is used to compared with the shape's margin to decide the final tolerance used in the manifold to validate the existing contacts.
//In the case of big shape and relatively speaking small triangles in the mesh, we need to take a smaller margin. This helps because the PCM
//recycling thresholds are proportionate to margin so it makes it less likely to discard previous contacts due to separation
#define GU_PCM_MESH_MANIFOLD_EPSILON 0.05f
class PxRenderOutput;
class PxContactBuffer;
namespace Gu
{
struct GjkOutput;
extern const PxF32 invalidateThresholds[5];
extern const PxF32 invalidateQuatThresholds[5];
extern const PxF32 invalidateThresholds2[3];
extern const PxF32 invalidateQuatThresholds2[3];
aos::Mat33V findRotationMatrixFromZAxis(const aos::Vec3VArg to);
//This contact is used in the primitives vs primitives contact gen
class PersistentContact
{
public:
PersistentContact()
{
}
PersistentContact(aos::Vec3V _localPointA, aos::Vec3V _localPointB, aos::Vec4V _localNormalPen) :
mLocalPointA(_localPointA), mLocalPointB(_localPointB), mLocalNormalPen(_localNormalPen)
{
}
aos::Vec3V mLocalPointA;
aos::Vec3V mLocalPointB;
aos::Vec4V mLocalNormalPen; // the (x, y, z) is the local normal, and the w is the penetration depth
};
//This contact is used in the mesh contact gen to store an extra variable
class MeshPersistentContact : public PersistentContact
{
public:
PxU32 mFaceIndex;
};
//This contact is used in the compress stream buffer(NpCacheStreamPair in the PxcNpThreadContext) to store the data we need
PX_ALIGN_PREFIX(16)
class CachedMeshPersistentContact
{
public:
PxVec3 mLocalPointA; //16 byte aligned
PxU32 mFaceIndex; //face index
PxVec3 mLocalPointB; //16 byte aligned
PxU32 mPad; //pad
PxVec3 mLocalNormal; //16 byte aligned
PxReal mPen; //penetration
}PX_ALIGN_SUFFIX(16);
#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
//This class is used to store the start and end index of the mesh persistent contacts in an array.
struct PCMContactPatch
{
public:
PCMContactPatch()
{
mNextPatch = NULL;
mEndPatch = NULL;
mRoot = this;
mPatchMaxPen = aos::FMax();
}
aos::Vec3V mPatchNormal;
PCMContactPatch* mNextPatch;//store the next patch pointer in the patch list
PCMContactPatch* mEndPatch;//store the last patch pointer in the patch list
PCMContactPatch* mRoot;//if this is the start of the patch list which has very similar patch normal, the root will be itself
aos::FloatV mPatchMaxPen;//store the deepest penetration of the whole patch
PxU32 mStartIndex;//store the start index of the manifold contacts in the manifold contacts stream
PxU32 mEndIndex;//store the end index of the manifold contacts in the manifold contacts stream
PxU32 mTotalSize;//if this is the root, the total size will store the total number of manifold contacts in the whole patch list
};
#if PX_VC
#pragma warning(pop)
#endif
//ML: this is needed because it seems NEON doesn't force the alignment on SIMD type, which cause some of the PCM unit tests fail
PX_ALIGN_PREFIX(16)
class PersistentContactManifold
{
public:
PersistentContactManifold(PersistentContact* contactPointsBuff, PxU8 capacity): mNumContacts(0), mCapacity(capacity), mNumWarmStartPoints(0), mContactPoints(contactPointsBuff)
{
using namespace physx::aos;
mRelativeTransform.invalidate();
mQuatA = QuatIdentity();
mQuatB = QuatIdentity();
}
PX_FORCE_INLINE PxU32 getNumContacts() const { return mNumContacts;}
PX_FORCE_INLINE bool isEmpty() const { return mNumContacts==0; }
PX_FORCE_INLINE PersistentContact& getContactPoint(const PxU32 index)
{
PX_ASSERT(index < GU_MANIFOLD_CACHE_SIZE);
return mContactPoints[index];
}
PX_FORCE_INLINE aos::FloatV maxTransformdelta(const aos::PxTransformV& curTransform) const
{
using namespace aos;
const Vec4V p0 = Vec4V_From_Vec3V(mRelativeTransform.p);
const Vec4V q0 = mRelativeTransform.q;
const Vec4V p1 = Vec4V_From_Vec3V(curTransform.p);
const Vec4V q1 = curTransform.q;
const Vec4V dp = V4Abs(V4Sub(p1, p0));
const Vec4V dq = V4Abs(V4Sub(q1, q0));
const Vec4V max0 = V4Max(dp, dq);
//need to work out max from a single vector...
return V4ExtractMax(max0);
}
PX_FORCE_INLINE aos::Vec4V maxTransformdelta2(const aos::PxTransformV& curTransform) const
{
using namespace aos;
const Vec4V p0 = Vec4V_From_Vec3V(mRelativeTransform.p);
const Vec4V q0 = mRelativeTransform.q;
const Vec4V p1 = Vec4V_From_Vec3V(curTransform.p);
const Vec4V q1 = curTransform.q;
const Vec4V dp = V4Abs(V4Sub(p1, p0));
const Vec4V dq = V4Abs(V4Sub(q1, q0));
const Vec4V max0 = V4Max(dp, dq);
//need to work out max from a single vector...
return max0;
}
PX_FORCE_INLINE aos::FloatV maxTransformPositionDelta(const aos::Vec3V& curP) const
{
using namespace aos;
const Vec3V deltaP = V3Sub(curP, mRelativeTransform.p);
const Vec4V delta = Vec4V_From_Vec3V(V3Abs(deltaP));
//need to work out max from a single vector...
return V4ExtractMax(delta);
}
PX_FORCE_INLINE aos::FloatV maxTransformQuatDelta(const aos::QuatV& curQ) const
{
using namespace aos;
const Vec4V deltaQ = V4Sub(curQ, mRelativeTransform.q);
const Vec4V delta = V4Abs(deltaQ);
//need to work out max from a single vector...
return V4ExtractMax(delta);
}
PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform)
{
mRelativeTransform = transform;
}
PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform, const aos::QuatV quatA, const aos::QuatV quatB)
{
mRelativeTransform = transform;
mQuatA = quatA;
mQuatB = quatB;
}
//This is used for the box/convexhull vs box/convexhull contact gen to decide whether the relative movement of a pair of objects are
//small enough. In this case, we can skip the collision detection all together
PX_FORCE_INLINE PxU32 invalidate_BoxConvex(const aos::PxTransformV& curRTrans, const aos::QuatV& quatA, const aos::QuatV& quatB,
const aos::FloatVArg minMargin, const aos::FloatVArg radiusA, const aos::FloatVArg radiusB) const
{
using namespace aos;
PX_ASSERT(mNumContacts <= GU_MANIFOLD_CACHE_SIZE);
const FloatV ratio = FLoad(invalidateThresholds[mNumContacts]);
const FloatV thresholdP = FMul(minMargin, ratio);
const FloatV deltaP = maxTransformPositionDelta(curRTrans.p);
const FloatV thresholdQ = FLoad(invalidateQuatThresholds[mNumContacts]);
const FloatV deltaQA = QuatDot(quatA, mQuatA);
const FloatV deltaQB = QuatDot(quatB, mQuatB);
const BoolV con0 = BOr(FIsGrtr(deltaP, thresholdP), BOr(FIsGrtr(thresholdQ, deltaQA), FIsGrtr(thresholdQ, deltaQB)));
PxU32 generateContacts = BAllEqTTTT(con0);
if (!generateContacts)
{
PxReal dqA, dqB;
FStore(deltaQA, &dqA);
FStore(deltaQB, &dqB);
const PxReal aRadian = dqA < 1.0f ? PxAcos(dqA) : 0.f;
const FloatV travelDistA = FMul(FLoad(aRadian), radiusA);
const PxReal bRadian = dqB < 1.0f ? PxAcos(dqB) : 0.f;
const FloatV travelDistB = FMul(FLoad(bRadian), radiusB);
const BoolV con = BOr(FIsGrtr(travelDistA, thresholdP), FIsGrtr(travelDistB, thresholdP));
generateContacts = BAllEqTTTT(con);
}
return generateContacts;
}
//This is used for the sphere/capsule vs other primitives contact gen to decide whether the relative movement of a pair of objects are
//small enough. In this case, we can skip the collision detection all together
PX_FORCE_INLINE PxU32 invalidate_SphereCapsule(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin) const
{
using namespace aos;
PX_ASSERT(mNumContacts <= 2);
const FloatV ratio = FLoad(invalidateThresholds2[mNumContacts]);
const FloatV thresholdP = FMul(minMargin, ratio);
const FloatV deltaP = maxTransformPositionDelta(curRTrans.p);
const FloatV thresholdQ = FLoad(invalidateQuatThresholds2[mNumContacts]);
const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q);
const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ));
return BAllEqTTTT(con);
}
//This is used for plane contact gen to decide whether the relative movement of a pair of objects are small enough. In this case,
//we can skip the collision detection all together
PX_FORCE_INLINE PxU32 invalidate_PrimitivesPlane(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin, const aos::FloatVArg ratio) const
{
using namespace aos;
const FloatV thresholdP = FMul(minMargin, ratio);
const FloatV deltaP = maxTransformPositionDelta(curRTrans.p);
const FloatV thresholdQ = FLoad(0.99996f);//about 0.5 degree
const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q);
const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ));
return BAllEqTTTT(con);
}
PX_FORCE_INLINE void removeContactPoint(PxU32 index)
{
mNumContacts--;
mContactPoints[index] = mContactPoints[mNumContacts];
}
/*bool validContactDistance(const PersistentContact& pt, const aos::FloatVArg breakingThreshold) const
{
using namespace aos;
const FloatV dist = V4GetW(pt.mLocalNormalPen);
return FAllGrtr(breakingThreshold, dist) != 0;
}*/
PX_FORCE_INLINE void clearManifold()
{
mNumWarmStartPoints = 0;
mNumContacts = 0;
mRelativeTransform.invalidate();
}
PX_FORCE_INLINE void initialize()
{
clearManifold();
}
//This function is used to replace the existing contact with the newly created contact if their distance are within some threshold
bool replaceManifoldPoint(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen, const aos::FloatVArg replaceBreakingThreshold);
//This function is to add a point(in box/convexhull contact gen) to the exising manifold. If the number of manifold is more than 4, we need to do contact reduction
PxU32 addManifoldPoint(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalAPen, const aos::FloatVArg replaceBreakingThreshold);
//This function is to add a point(in capsule contact gen) to the exising manifold. If the number of manifold is more than 4, we need to do contact reduction
PxU32 addManifoldPoint2(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalAPen, const aos::FloatVArg replaceBreakingThreshold);//max two points of contacts
//This function is used in box-plane contact gen to add the plane contacts to the manifold
void addBatchManifoldContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints);
//This function is used in the capsule full manifold contact genenation(maximum 2 points).
void addBatchManifoldContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints);//max two points of contacts
//This function is used in the box/convexhull full manifold contact generation(maximum 4 points).
void addBatchManifoldContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal toleranceLength);
//This function is using the cluster algorithm to reduce contacts
void reduceBatchContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints);
//This function is called by addBatchManifoldContacts2 to reduce the manifold contacts to 2 points;
void reduceBatchContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints);
//This function is called by addBatchManifoldContacts to reduce the manifold contacts to 4 points
void reduceBatchContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal toleranceLength);
//This function is used for incremental manifold contact reduction for box/convexhull
PxU32 reduceContactsForPCM(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen);
//This function is used for incremental manifold contact reduction for capsule
PxU32 reduceContactSegment(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen);
// This function recalculate the contacts in the manifold based on the current relative transform between a pair of objects. If the recalculated contacts are within some threshold,
// we will keep the contacts; Otherwise, we will remove the contacts.
void refreshContactPoints(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactOffset);
//This function is just used in boxbox contact gen for fast transform
void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::PxMatTransformV& transf1);
//This function is for adding box/convexhull manifold contacts to the contact buffer
void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::PxTransformV& transf1, const aos::FloatVArg contactOffset);
//This function is for adding sphere/capsule manifold contacts to the contact buffer
void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::Vec3VArg projectionNormal, const aos::PxTransformV& transf0, const aos::FloatVArg radius, const aos::FloatVArg contactOffset);
//get the average normal in the manifold in world space
aos::Vec3V getWorldNormal(const aos::PxTransformV& trB) const;
//get the average normal in the manifold in local B object space
aos::Vec3V getLocalNormal() const;
void recordWarmStart(PxU8* aIndices, PxU8* bIndices, PxU8& nbWarmStartPoints);
void setWarmStart(const PxU8* aIndices, const PxU8* bIndices, const PxU8 nbWarmStartPoints);
void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const;
void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB, const aos::FloatVArg radius) const;
void drawManifold(const PersistentContact& m, PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const;
static void drawPoint(PxRenderOutput& out, const aos::Vec3VArg p, const PxF32 size, PxU32 color = 0x0000ff00);
static void drawLine(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, PxU32 color = 0xff00ffff);
static void drawTriangle(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, PxU32 color = 0xffff0000);
static void drawTetrahedron(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, PxU32 color = 0xffff0000);
static void drawPolygon(PxRenderOutput& out, const aos::PxTransformV& transform, const aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff);
static void drawPolygon(PxRenderOutput& out, const aos::PxMatTransformV& transform, const aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff);
aos::PxTransformV mRelativeTransform;//aToB
aos::QuatV mQuatA;
aos::QuatV mQuatB;
PxU8 mNumContacts;
PxU8 mCapacity;
PxU8 mNumWarmStartPoints;
PxU8 mAIndice[4];
PxU8 mBIndice[4];
PersistentContact* mContactPoints;
} PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16)
class LargePersistentContactManifold : public PersistentContactManifold
{
public:
LargePersistentContactManifold() : PersistentContactManifold(mContactPointsBuff, GU_MANIFOLD_CACHE_SIZE)
{
}
PersistentContact mContactPointsBuff[GU_MANIFOLD_CACHE_SIZE];
}PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16)
class SpherePersistentContactManifold : public PersistentContactManifold
{
public:
SpherePersistentContactManifold() : PersistentContactManifold(mContactPointsBuff, GU_SPHERE_MANIFOLD_CACHE_SIZE)
{
}
PersistentContact mContactPointsBuff[GU_SPHERE_MANIFOLD_CACHE_SIZE];
}PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16)
class SinglePersistentContactManifold
{
public:
SinglePersistentContactManifold(): mNumContacts(0)
{
}
PX_FORCE_INLINE PxU32 getNumContacts() const { return mNumContacts;}
PX_FORCE_INLINE bool isEmpty() const { return mNumContacts==0; }
PX_FORCE_INLINE MeshPersistentContact& getContactPoint(const PxU32 index)
{
PX_ASSERT(index < GU_SINGLE_MANIFOLD_CACHE_SIZE);
return mContactPoints[index];
}
PX_FORCE_INLINE void removeContactPoint (PxU32 index)
{
mNumContacts--;
mContactPoints[index] = mContactPoints[mNumContacts];
}
PX_FORCE_INLINE void clearManifold()
{
mNumContacts = 0;
}
PX_FORCE_INLINE void initialize()
{
clearManifold();
}
PX_FORCE_INLINE aos::Vec3V getWorldNormal(const aos::PxTransformV& trB) const
{
using namespace aos;
Vec4V nPen = mContactPoints[0].mLocalNormalPen;
for(PxU32 i=1; i<mNumContacts; ++i)
{
nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen);
}
const Vec3V n = Vec3V_From_Vec4V(nPen);
return V3Normalize(trB.rotate(n));
}
PX_FORCE_INLINE aos::Vec3V getLocalNormal() const
{
using namespace aos;
Vec4V nPen = mContactPoints[0].mLocalNormalPen;
for(PxU32 i=1; i<mNumContacts; ++i)
{
nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen);
}
return V3Normalize(Vec3V_From_Vec4V(nPen));
}
//This function reduces the manifold contact list in a patch for box/convexhull vs mesh
aos::FloatV reduceBatchContactsConvex(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch);
//This function reduces the manifold contact list in a patch for sphere vs mesh
aos::FloatV reduceBatchContactsSphere(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch);
//This function reduces the manifold contact list in a patch for capsuel vs mesh
aos::FloatV reduceBatchContactsCapsule(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch);
//This function adds the manifold contact list in a patch for box/convexhull vs mesh
aos::FloatV addBatchManifoldContactsConvex(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold);
//This function adds the manifold contact list in a patch for sphere vs mesh
aos::FloatV addBatchManifoldContactsSphere(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold);
//This function adds the manifold contact list in a patch for capsule vs mesh
aos::FloatV addBatchManifoldContactsCapsule(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold);
//This is used for in the addContactsToPatch for convex mesh contact gen.
static PxU32 reduceContacts(MeshPersistentContact* manifoldContactExt, PxU32 numContacts);
//This function is to recalculate the contacts based on the relative transform between a pair of objects
aos::FloatV refreshContactPoints(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactOffset);
void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const;
MeshPersistentContact mContactPoints[GU_SINGLE_MANIFOLD_CACHE_SIZE];//384 bytes
PxU32 mNumContacts;//400 bytes
} PX_ALIGN_SUFFIX(16);
//This is a structure used to cache a multi-persistent-manifold in the cache stream
struct MultiPersistentManifoldHeader
{
aos::PxTransformV mRelativeTransform;//aToB
PxU32 mNumManifolds;
PxU32 pad[3];
};
struct SingleManifoldHeader
{
PxU32 mNumContacts;
PxU32 pad[3];
};
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class
#endif
PX_ALIGN_PREFIX(16)
class PX_PHYSX_COMMON_API MultiplePersistentContactManifold
{
public:
MultiplePersistentContactManifold():mNumManifolds(0), mNumTotalContacts(0)
{
mRelativeTransform.invalidate();
}
PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform)
{
mRelativeTransform = transform;
}
PX_FORCE_INLINE aos::FloatV maxTransformPositionDelta(const aos::Vec3V& curP) const
{
using namespace aos;
const Vec3V deltaP = V3Sub(curP, mRelativeTransform.p);
const Vec4V delta = Vec4V_From_Vec3V(V3Abs(deltaP));
//need to work out max from a single vector...
return V4ExtractMax(delta);
}
PX_FORCE_INLINE aos::FloatV maxTransformQuatDelta(const aos::QuatV& curQ) const
{
using namespace aos;
const Vec4V deltaQ = V4Sub(curQ, mRelativeTransform.q);
const Vec4V delta = V4Abs(deltaQ);
//need to work out max from a single vector...
return V4ExtractMax(delta);
}
PX_FORCE_INLINE PxU32 invalidate(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin, const aos::FloatVArg ratio) const
{
using namespace aos;
const FloatV thresholdP = FMul(minMargin, ratio);
const FloatV deltaP = maxTransformPositionDelta(curRTrans.p);
const FloatV thresholdQ = FLoad(0.9998f);//about 1 degree
const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q);
const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ));
return BAllEqTTTT(con);
}
PX_FORCE_INLINE PxU32 invalidate(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin) const
{
using namespace aos;
return invalidate(curRTrans, minMargin, FLoad(0.2f));
}
// This function work out the contact patch connectivity. If two patches's normal are within 5 degree, we would link these two patches together and reset the total size.
PX_FORCE_INLINE void refineContactPatchConnective(PCMContactPatch** contactPatch, PxU32 numContactPatch, MeshPersistentContact* manifoldContacts, const aos::FloatVArg acceptanceEpsilon) const
{
PX_UNUSED(manifoldContacts);
using namespace aos;
//work out the contact patch connectivity, the patchNormal should be in the local space of mesh
for(PxU32 i=0; i<numContactPatch; ++i)
{
PCMContactPatch* patch = contactPatch[i];
patch->mRoot = patch;
patch->mEndPatch = patch;
patch->mTotalSize = patch->mEndIndex - patch->mStartIndex;
patch->mNextPatch = NULL;
for(PxU32 j=i; j>0; --j)
{
PCMContactPatch* other = contactPatch[j-1];
const FloatV d = V3Dot(patch->mPatchNormal, other->mRoot->mPatchNormal);
if(FAllGrtrOrEq(d, acceptanceEpsilon))//less than 5 degree
{
other->mNextPatch = patch;
other->mRoot->mEndPatch = patch;
patch->mRoot = other->mRoot;
other->mRoot->mTotalSize += patch->mEndIndex - patch->mStartIndex;
break;
}
}
}
}
// This function uses to reduce the manifold contacts which are in different connected patchs but are within replace breaking threshold
PX_FORCE_INLINE PxU32 reduceManifoldContactsInDifferentPatches(PCMContactPatch** contactPatch, PxU32 numContactPatch, MeshPersistentContact* manifoldContacts, PxU32 numContacts, const aos::FloatVArg sqReplaceBreaking) const
{
using namespace aos;
for(PxU32 i=0; i<numContactPatch; ++i)
{
PCMContactPatch* currentPatch = contactPatch[i];
//this make sure the patch is the root before we do the contact reduction, otherwise, we will do duplicate work
if(currentPatch->mRoot == currentPatch)
{
while(currentPatch)
{
PCMContactPatch* nextPatch = currentPatch->mNextPatch;
if(nextPatch)
{
for(PxU32 k = currentPatch->mStartIndex; k<currentPatch->mEndIndex; ++k)
{
for(PxU32 l = nextPatch->mStartIndex; l < nextPatch->mEndIndex; ++l)
{
Vec3V dif = V3Sub(manifoldContacts[l].mLocalPointB, manifoldContacts[k].mLocalPointB);
FloatV d = V3Dot(dif, dif);
if(FAllGrtr(sqReplaceBreaking, d))
{
//if two manifold contacts are within threshold, we will get rid of the manifold contacts in the other contact patch
manifoldContacts[l] = manifoldContacts[nextPatch->mEndIndex-1];
nextPatch->mEndIndex--;
numContacts--;
l--;
}
}
}
}
currentPatch = nextPatch;
}
}
}
return numContacts;
}
// This function is for the multiple manifold loop through each individual single manifold to recalculate the contacts based on the relative transform between a pair of objects
PX_FORCE_INLINE void refreshManifold(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactDist)
{
using namespace aos;
//refresh manifold contacts
for(PxU32 i=0; i<mNumManifolds; ++i)
{
const PxU8 ind = mManifoldIndices[i];
PX_ASSERT(mManifoldIndices[i] < GU_MAX_MANIFOLD_SIZE);
const PxU32 nextInd = PxMin(i, mNumManifolds-2u)+1;
PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]]);
PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]],128);
PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]],256);
const FloatV _maxPen = mManifolds[ind].refreshContactPoints(relTra, projectBreakingThreshold, contactDist);
if(mManifolds[ind].isEmpty())
{
//swap the index with the next manifolds
const PxU8 index = mManifoldIndices[--mNumManifolds];
mManifoldIndices[mNumManifolds] = ind;
mManifoldIndices[i] = index;
i--;
}
else
{
FStore(_maxPen, &mMaxPen[ind]);
}
}
}
PX_FORCE_INLINE void initialize()
{
mNumManifolds = 0;
mNumTotalContacts = 0;
mRelativeTransform.invalidate();
for(PxU8 i=0; i<GU_MAX_MANIFOLD_SIZE; ++i)
{
mManifolds[i].initialize();
mManifoldIndices[i] = i;
}
}
PX_FORCE_INLINE void clearManifold()
{
for(PxU8 i=0; i<mNumManifolds; ++i)
{
mManifolds[i].clearManifold();
}
mNumManifolds = 0;
mNumTotalContacts = 0;
mRelativeTransform.invalidate();
}
PX_FORCE_INLINE const SinglePersistentContactManifold* getManifold(PxU32 index) const
{
PX_ASSERT(index < GU_MAX_MANIFOLD_SIZE);
return &mManifolds[mManifoldIndices[index]];
}
PX_FORCE_INLINE SinglePersistentContactManifold* getManifold(PxU32 index)
{
PX_ASSERT(index < GU_MAX_MANIFOLD_SIZE);
return &mManifolds[mManifoldIndices[index]];
}
PX_FORCE_INLINE SinglePersistentContactManifold* getEmptyManifold()
{
if(mNumManifolds < GU_MAX_MANIFOLD_SIZE)
return &mManifolds[mManifoldIndices[mNumManifolds]];
return NULL;
}
//This function adds the manifold contacts with different patches into the corresponding single persistent contact manifold
void addManifoldContactPoints(MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch** contactPatch, PxU32 numPatch,
const aos::FloatVArg sqReplaceBreakingThreshold, const aos::FloatVArg acceptanceEpsilon, PxU8 maxContactsPerManifold);
//This function adds the box/convexhull manifold contacts to the contact buffer
bool addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::PxTransformV& transf1);
//This function adds the sphere/capsule manifold contacts to the contact buffer
bool addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::PxTransformV& trA, const aos::PxTransformV& trB, const aos::FloatVArg radius);
void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const;
//Code to load from a buffer and store to a buffer.
void fromBuffer(PxU8* PX_RESTRICT buffer);
void toBuffer(PxU8* PX_RESTRICT buffer) const;
static void drawLine(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, PxU32 color = 0xff00ffff);
static void drawLine(PxRenderOutput& out, const PxVec3 p0, const PxVec3 p1, PxU32 color = 0xff00ffff);
static void drawPoint(PxRenderOutput& out, const aos::Vec3VArg p, const PxF32 size, PxU32 color = 0x00ff0000);
static void drawPolygon(PxRenderOutput& out, const aos::PxTransformV& transform, aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff);
aos::PxTransformV mRelativeTransform;//aToB
PxF32 mMaxPen[GU_MAX_MANIFOLD_SIZE];
PxU8 mManifoldIndices[GU_MAX_MANIFOLD_SIZE];
PxU8 mNumManifolds;
PxU8 mNumTotalContacts;
SinglePersistentContactManifold mManifolds[GU_MAX_MANIFOLD_SIZE];
} PX_ALIGN_SUFFIX(16);
#if PX_VC
#pragma warning(pop)
#endif
// This function calculates the average normal in the manifold in world space
PX_FORCE_INLINE aos::Vec3V PersistentContactManifold::getWorldNormal(const aos::PxTransformV& trB) const
{
using namespace aos;
Vec4V nPen = mContactPoints[0].mLocalNormalPen;
for(PxU32 i=1; i<mNumContacts; ++i)
{
nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen);
}
const Vec3V n = Vec3V_From_Vec4V(nPen);
const FloatV sqLength = V3Dot(n, n);
const Vec3V nn = V3Sel(FIsGrtr(sqLength, FEps()), n, Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen));
return V3Normalize(trB.rotate(nn));
}
// This function calculates the average normal in the manifold in local B space
PX_FORCE_INLINE aos::Vec3V PersistentContactManifold::getLocalNormal() const
{
using namespace aos;
Vec4V nPen = mContactPoints[0].mLocalNormalPen;
for(PxU32 i=1; i<mNumContacts; ++i)
{
nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen);
}
return V3Normalize(Vec3V_From_Vec4V(nPen));
}
// This function recalculates the contacts in the manifold based on the current relative transform between a pair of objects. If the recalculated contacts are within some threshold,
// we will keep the contacts; Otherwise, we will remove the contacts.
PX_FORCE_INLINE void PersistentContactManifold::refreshContactPoints(const aos::PxMatTransformV& aToB, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg /*contactOffset*/)
{
using namespace aos;
const FloatV sqProjectBreakingThreshold = FMul(projectBreakingThreshold, projectBreakingThreshold);
// first refresh worldspace positions and distance
for (PxU32 i=mNumContacts; i > 0; --i)
{
PersistentContact& manifoldPoint = mContactPoints[i-1];
const Vec3V localAInB = aToB.transform( manifoldPoint.mLocalPointA ); // from a to b
const Vec3V localBInB = manifoldPoint.mLocalPointB;
const Vec3V v = V3Sub(localAInB, localBInB);
const Vec3V localNormal = Vec3V_From_Vec4V(manifoldPoint.mLocalNormalPen); // normal in b space
const FloatV dist = V3Dot(v, localNormal);
const Vec3V projectedPoint = V3NegScaleSub(localNormal, dist, localAInB);//manifoldPoint.worldPointA - manifoldPoint.worldPointB * manifoldPoint.m_distance1;
const Vec3V projectedDifference = V3Sub(localBInB, projectedPoint);
const FloatV distance2d = V3Dot(projectedDifference, projectedDifference);
//const BoolV con = BOr(FIsGrtr(dist, contactOffset), FIsGrtr(distance2d, sqProjectBreakingThreshold));
const BoolV con = FIsGrtr(distance2d, sqProjectBreakingThreshold);
if(BAllEqTTTT(con))
{
removeContactPoint(i-1);
}
else
{
manifoldPoint.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), dist);
}
}
}
#define PX_CP_TO_PCP(contactPoint) (reinterpret_cast<PersistentContact*>(contactPoint)) //this is used in the normal pcm contact gen
#define PX_CP_TO_MPCP(contactPoint) (reinterpret_cast<MeshPersistentContact*>(contactPoint))//this is used in the mesh pcm contact gen
void addManifoldPoint(PersistentContact* manifoldContacts, PersistentContactManifold& manifold, GjkOutput& output,
const aos::PxMatTransformV& aToB, const aos::FloatV replaceBreakingThreshold);
}//Gu
}//physx
#endif
| 33,657 | C | 39.896719 | 238 | 0.767894 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenSphereCapsule.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 "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
#include "common/PxRenderOutput.h"
#include "GuPCMContactGenUtil.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxAlloca.h"
#include "GuVecCapsule.h"
#include "GuVecBox.h"
using namespace physx;
using namespace Gu;
using namespace aos;
//ML: this function is shared by the sphere/capsule vs convex hulls full contact gen, capsule in the local space of polyData
static bool testPolyDataAxis(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& separatingAxis)
{
FloatV _minOverlap = FMax();//minOverlap;
FloatV min0, max0;
FloatV min1, max1;
Vec3V tempAxis = V3UnitY();
//capsule in the local space of polyData
for(PxU32 i=0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const FloatV planeDist = FLoad(polygon.mPlane.d);
const Vec3V vertexSpacePlaneNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
//transform plane n to shape space
const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(map->shape2Vertex, vertexSpacePlaneNormal);
const FloatV magnitude = FRecip(V3Length(shapeSpacePlaneNormal));
//normalize shape space normal
const Vec3V planeN = V3Scale(shapeSpacePlaneNormal, magnitude);
//ML::use this to avoid LHS
min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude);
max0 = FMul(FNeg(planeDist), magnitude);
const FloatV tempMin = V3Dot(capsule.p0, planeN);
const FloatV tempMax = V3Dot(capsule.p1, planeN);
min1 = FMin(tempMin, tempMax);
max1 = FMax(tempMin, tempMax);
min1 = FSub(min1, capsule.radius);
max1 = FAdd(max1, capsule.radius);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if(FAllGrtr(_minOverlap, tempOverlap))
{
_minOverlap = tempOverlap;
tempAxis = planeN;
}
}
separatingAxis = tempAxis;
minOverlap = _minOverlap;
return true;
}
//ML: this function is shared by sphere/capsule. Point a and direction d need to be in the local space of polyData
static bool intersectRayPolyhedron(const Vec3VArg a, const Vec3VArg dir, const PolygonalData& polyData, FloatV& tEnter, FloatV& tExit)
{
const FloatV zero = FZero();
const FloatV eps = FLoad(1e-7f);
FloatV tFirst = zero;
FloatV tLast= FMax();
for(PxU32 k=0; k<polyData.mNbPolygons; ++k)
{
const HullPolygonData& data = polyData.mPolygons[k];
const Vec3V n = V3LoadU_SafeReadW(data.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
FloatV d = FLoad(data.mPlane.d);
const FloatV denominator = V3Dot(n, dir);
const FloatV distToPlane = FAdd(V3Dot(n, a), d);
if(FAllGrtr(eps, FAbs(denominator)))
{
if(FAllGrtr(distToPlane, zero))
return false;
}
else
{
FloatV tTemp = FNeg(FDiv(distToPlane, denominator));
//ML: denominator < 0 means the ray is entering halfspace; denominator > 0 means the ray is exiting halfspace
const BoolV con = FIsGrtr(zero, denominator);
const BoolV con0 = FIsGrtr(tTemp, tFirst);
const BoolV con1 = FIsGrtr(tLast, tTemp);
tFirst = FSel(BAnd(con, con0), tTemp, tFirst);
tLast = FSel(BAndNot(con1, con), tTemp, tLast);
}
if(FAllGrtr(tFirst, tLast))
return false;
}
//calculate the intersect p in the local space
tEnter = tFirst;
tExit = tLast;
return true;
}
//Precompute the convex data
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
static bool testSATCapsulePoly(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& separatingAxis)
{
FloatV _minOverlap = FMax();//minOverlap;
FloatV min0, max0;
FloatV min1, max1;
Vec3V tempAxis = V3UnitY();
const FloatV eps = FEps();
//ML: project capsule to polydata axis
if(!testPolyDataAxis(capsule, polyData, map, contactDist, _minOverlap, tempAxis))
return false;
const Vec3V capsuleAxis = V3Sub(capsule.p1, capsule.p0);
for(PxU32 i=0;i<polyData.mNbPolygons;i++)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const PxU8* inds1 = polyData.mPolygonVertexRefs + polygon.mVRef8;
for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = lStart++)
{
//in the vertex space
const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds1[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds1[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const Vec3V vertexSpaceV = V3Sub(p11, p10);
//transform v to shape space
const Vec3V shapeSpaceV = M33TrnspsMulV3(map->shape2Vertex, vertexSpaceV);
const Vec3V dir = V3Cross(capsuleAxis, shapeSpaceV);
const FloatV lenSq = V3Dot(dir, dir);
if(FAllGrtr(eps, lenSq))
continue;
const Vec3V normal = V3ScaleInv(dir, FSqrt(lenSq));
map->doSupport(normal, min0, max0);
const FloatV tempMin = V3Dot(capsule.p0, normal);
const FloatV tempMax = V3Dot(capsule.p1, normal);
min1 = FMin(tempMin, tempMax);
max1 = FMax(tempMin, tempMax);
min1 = FSub(min1, capsule.radius);
max1 = FAdd(max1, capsule.radius);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if(FAllGrtr(_minOverlap, tempOverlap))
{
_minOverlap = tempOverlap;
tempAxis = normal;
}
}
}
separatingAxis = tempAxis;
minOverlap = _minOverlap;
return true;
}
static void generatedCapsuleBoxFaceContacts(const CapsuleV& capsule, const PolygonalData& polyData, const HullPolygonData& referencePolygon, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, const Vec3VArg normal)
{
const FloatV radius = FAdd(capsule.radius, contactDist);
//calculate the intersect point of ray to plane
const Vec3V planeNormal = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, V3LoadU(referencePolygon.mPlane.n)));
const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon.mVRef8;
const Vec3V a = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[0]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const FloatV denom0 = V3Dot(planeNormal, V3Sub(capsule.p0, a));
const FloatV denom1 = V3Dot(planeNormal, V3Sub(capsule.p1, a));
const FloatV projPlaneN = V3Dot(planeNormal, normal);
const FloatV numer = FSel(FIsGrtr(projPlaneN, FZero()), FRecip(projPlaneN), FZero());
const FloatV t0 = FMul(denom0, numer);
const FloatV t1 = FMul(denom1, numer);
const BoolV con0 = FIsGrtrOrEq(radius, t0);
const BoolV con1 = FIsGrtrOrEq(radius, t1);
if(BAllEqTTTT(BOr(con0, con1)))
{
const Mat33V rot = findRotationMatrixFromZAxis(planeNormal);
Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16));
map->populateVerts(inds, referencePolygon.mNbVerts, polyData.mVerts, points0In0);
Vec3V rPolygonMin = V3Splat(FMax());
Vec3V rPolygonMax = V3Neg(rPolygonMin);
for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i)
{
points0In0[i] = M33MulV3(rot, points0In0[i]);
rPolygonMin = V3Min(rPolygonMin, points0In0[i]);
rPolygonMax = V3Max(rPolygonMax, points0In0[i]);
}
if(BAllEqTTTT(con0))
{
//add contact
const Vec3V proj = V3NegScaleSub(normal, t0, capsule.p0);//V3ScaleAdd(t0, normal, capsule.p0);
//transform proj0 to 2D
const Vec3V point = M33MulV3(rot, proj);
if(contains(points0In0, referencePolygon.mNbVerts, point, rPolygonMin, rPolygonMax))
{
manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p0);
manifoldContacts[numContacts].mLocalPointB = proj;
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), t0);
}
}
if(BAllEqTTTT(con1))
{
const Vec3V proj = V3NegScaleSub(normal, t1, capsule.p1);//V3ScaleAdd(t1, normal, capsule.p1);
//transform proj0 to 2D
const Vec3V point = M33MulV3(rot, proj);
if(contains(points0In0, referencePolygon.mNbVerts, point, rPolygonMin, rPolygonMax))
{
manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p1);
manifoldContacts[numContacts].mLocalPointB = proj;
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal),t1);
}
}
}
}
static void generatedFaceContacts(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, const Vec3VArg normal)
{
const FloatV zero = FZero();
FloatV tEnter = zero, tExit = zero;
const FloatV inflatedRadius = FAdd(capsule.radius, contactDist);
const Vec3V dir = V3Neg(normal);
const Vec3V vertexSpaceDir = M33MulV3(map->shape2Vertex, dir);
const Vec3V p0 = M33MulV3(map->shape2Vertex, capsule.p0);
if(intersectRayPolyhedron(p0, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter))
{
manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p0);
manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p0);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter);
}
const Vec3V p1 = M33MulV3(map->shape2Vertex, capsule.p1);
if(intersectRayPolyhedron(p1, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter))
{
manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p1);
manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p1);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter);
}
}
static void generateEE(const Vec3VArg p, const Vec3VArg q, const Vec3VArg normal, const Vec3VArg a, const Vec3VArg b, const PxMatTransformV& aToB,
PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg inflatedRadius)
{
const FloatV zero = FZero();
const FloatV expandedRatio = FLoad(0.005f);
const Vec3V ab = V3Sub(b, a);
const Vec3V n = V3Cross(ab, normal);
const FloatV d = V3Dot(n, a);
const FloatV np = V3Dot(n, p);
const FloatV nq = V3Dot(n,q);
const FloatV signP = FSub(np, d);
const FloatV signQ = FSub(nq, d);
const FloatV temp = FMul(signP, signQ);
if(FAllGrtr(temp, zero)) return;//If both points in the same side as the plane, no intersect points
// if colliding edge (p3,p4) and plane are parallel return no collision
const Vec3V pq = V3Sub(q, p);
const FloatV npq = V3Dot(n, pq);
if(FAllEq(npq, zero)) return;
//calculate the intersect point in the segment pq with plane n(x - a).
const FloatV segTValue = FDiv(FSub(d, np), npq);
const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p);
//ML: ab, localPointA and normal is in the same plane, so that we can do 2D segment segment intersection
//calculate a normal perpendicular to ray localPointA + normal*t, then do 2D segment segment intersection
const Vec3V perNormal = V3Cross(normal, pq);
const Vec3V ap = V3Sub(localPointA, a);
const FloatV nom = V3Dot(perNormal, ap);
const FloatV denom = V3Dot(perNormal, ab);
const FloatV tValue = FDiv(nom, denom);
const FloatV max = FAdd(FOne(), expandedRatio);
const FloatV min = FSub(zero, expandedRatio);
if(FAllGrtr(tValue, max) || FAllGrtr(min, tValue))
return;
const Vec3V v = V3NegScaleSub(ab, tValue, ap);
const FloatV signedDist = V3Dot(v, normal);
if(FAllGrtrOrEq(inflatedRadius, signedDist))
{
const Vec3V localPointB = V3Sub(localPointA, v);
manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(localPointA);
manifoldContacts[numContacts].mLocalPointB = localPointB;
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist);
}
}
static void generatedContactsEEContacts(const CapsuleV& capsule, const PolygonalData& polyData, const HullPolygonData& referencePolygon, const SupportLocal* map, const PxMatTransformV& aToB,
PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, const Vec3VArg contactNormal)
{
const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon.mVRef8;
Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16));
//Transform all the verts from vertex space to shape space
map->populateVerts(inds, referencePolygon.mNbVerts, polyData.mVerts, points0In0);
const FloatV inflatedRadius = FAdd(capsule.radius, contactDist);
for (PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++)
{
generateEE(capsule.p0, capsule.p1, contactNormal,points0In0[rStart], points0In0[rEnd], aToB, manifoldContacts, numContacts, inflatedRadius);
}
}
bool Gu::generateCapsuleBoxFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, Vec3V& normal, const Vec3VArg closest, PxReal margin, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput)
{
PX_UNUSED(renderOutput);
const PxU32 originalContacts = numContacts;
const HullPolygonData* referencePolygon = NULL;
if(doOverlapTest)
{
FloatV minOverlap;
//overwrite the normal
if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, normal))
return false;
referencePolygon = &polyData.mPolygons[getPolygonIndex(polyData, map, V3Neg(normal))];
}
else
{
const PxReal lowerEps = toleranceScale * PCM_WITNESS_POINT_LOWER_EPS;
const PxReal upperEps = toleranceScale * PCM_WITNESS_POINT_UPPER_EPS;
const PxReal tolerance = PxClamp(margin, lowerEps, upperEps);
const PxU32 featureIndex = getWitnessPolygonIndex(polyData, map, V3Neg(normal), closest, tolerance);
referencePolygon = &polyData.mPolygons[featureIndex];
}
#if PCM_LOW_LEVEL_DEBUG
const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon->mVRef8;
Vec3V* pointsInRef = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon->mNbVerts, 16));
map->populateVerts(inds, referencePolygon->mNbVerts, polyData.mVerts, pointsInRef);
PersistentContactManifold::drawPolygon(*renderOutput, map->transform, pointsInRef, referencePolygon->mNbVerts, 0x00ff0000);
#endif
generatedCapsuleBoxFaceContacts(capsule, polyData, *referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, normal);
const PxU32 faceContacts = numContacts - originalContacts;
if(faceContacts < 2)
{
generatedContactsEEContacts(capsule, polyData, *referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, normal);
}
return true;
}
//capsule is in the local space of polyData
bool Gu::generateFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, Vec3V& normal, const Vec3VArg closest, PxReal margin, bool doOverlapTest, PxReal toleranceLength)
{
const PxU32 originalContacts = numContacts;
Vec3V tNormal = normal;
if(doOverlapTest)
{
FloatV minOverlap;
//overwrite the normal with the sperating axis
if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, tNormal))
return false;
generatedFaceContacts(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, tNormal);
const PxU32 faceContacts = numContacts - originalContacts;
if(faceContacts < 2)
{
const HullPolygonData& referencePolygon = polyData.mPolygons[getPolygonIndex(polyData, map, V3Neg(tNormal))];
generatedContactsEEContacts(capsule, polyData,referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, tNormal);
}
}
else
{
generatedFaceContacts(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, tNormal);
const PxU32 faceContacts = numContacts - originalContacts;
if(faceContacts < 2)
{
const PxReal lowerEps = toleranceLength * PCM_WITNESS_POINT_LOWER_EPS;
const PxReal upperEps = toleranceLength * PCM_WITNESS_POINT_UPPER_EPS;
const PxReal tolerance = PxClamp(margin, lowerEps, upperEps);
const PxU32 featureIndex = getWitnessPolygonIndex(polyData, map, V3Neg(tNormal), closest, tolerance);
const HullPolygonData& referencePolygon = polyData.mPolygons[featureIndex];
generatedContactsEEContacts(capsule, polyData,referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, tNormal);
}
}
normal = tNormal;
return true;
}
//sphere is in the local space of polyData, we treate sphere as capsule
bool Gu::generateSphereFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, Vec3V& normal, bool doOverlapTest)
{
if(doOverlapTest)
{
FloatV minOverlap;
//overwrite the normal with the sperating axis
if(!testPolyDataAxis(capsule, polyData, map, contactDist, minOverlap, normal))
return false;
}
const FloatV zero = FZero();
FloatV tEnter = zero, tExit = zero;
const FloatV inflatedRadius = FAdd(capsule.radius, contactDist);
const Vec3V dir = V3Neg(normal);
const Vec3V vertexSpaceDir = M33MulV3(map->shape2Vertex, dir);
const Vec3V p0 = M33MulV3(map->shape2Vertex, capsule.p0);
if(intersectRayPolyhedron(p0, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter))
{
//ML: for sphere, the contact point A is always zeroV in its local space
manifoldContacts[numContacts].mLocalPointA = V3Zero();
manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p0);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter);
}
return true;
}
//capsule is in the shape space of polyData
bool Gu::computeMTD(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, FloatV& penDepth, Vec3V& normal)
{
const FloatV contactDist = FZero();
Vec3V separatingAxis;
FloatV minOverlap;
if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, separatingAxis))
return false;
//transform normal in to the worl space
normal = map->transform.rotate(separatingAxis);
penDepth = minOverlap;
return true;
}
| 20,676 | C++ | 39.306043 | 252 | 0.746905 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereMesh.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/PxSort.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactConvexCommon.h"
#include "GuPCMContactMeshCallback.h"
#include "GuFeatureCode.h"
#include "GuBox.h"
using namespace physx;
using namespace Gu;
using namespace aos;
namespace
{
struct PCMSphereVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback< PCMSphereVsMeshContactGenerationCallback >
{
PCMSphereVsMeshContactGeneration mGeneration;
PCMSphereVsMeshContactGenerationCallback(
const Vec3VArg sphereCenter,
const FloatVArg sphereRadius,
const FloatVArg contactDist,
const FloatVArg replaceBreakingThreshold,
const PxTransformV& sphereTransform,
const PxTransformV& meshTransform,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
const PxU8* extraTriData,
const Cm::FastVertex2ShapeScaling& meshScaling,
bool idtMeshScale,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
PxRenderOutput* renderOutput = NULL
) :
PCMMeshContactGenerationCallback<PCMSphereVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale),
mGeneration(sphereCenter, sphereRadius, contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, deferredContacts, renderOutput)
{
}
PX_FORCE_INLINE bool doTest(const PxVec3&, const PxVec3&, const PxVec3&) { return true; }
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMSphereVsMeshContactGeneration>(cache);
}
};
}
bool Gu::pcmContactSphereMesh(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(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 meshTransform(p1, q1);//triangleMesh
const PxTransformV curTransform = meshTransform.transformInv(sphereTransform);
// We must be in local space to use the cache
if(multiManifold.invalidate(curTransform, sphereRadius, FLoad(0.02f)))
{
const FloatV replaceBreakingThreshold = FMul(sphereRadius, FLoad(0.001f));
const PxVec3 sphereCenterShape1Space = transform1.transformInv(transform0.p);
PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance;
const Vec3V sphereCenter = V3LoadU(sphereCenterShape1Space);
const TriangleMesh* meshData = _getMeshData(shapeMesh);
Cm::FastVertex2ShapeScaling meshScaling; // PT: TODO: get rid of default ctor :(
const bool idtMeshScale = shapeMesh.scale.isIdentity();
if(!idtMeshScale)
meshScaling.init(shapeMesh.scale);
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts;
const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData();
// mesh scale is not baked into cached verts
PCMSphereVsMeshContactGenerationCallback callback(
sphereCenter,
sphereRadius,
contactDist,
replaceBreakingThreshold,
sphereTransform,
meshTransform,
multiManifold,
contactBuffer,
extraData,
meshScaling,
idtMeshScale,
&delayedContacts,
renderOutput);
PxVec3 obbCenter = sphereCenterShape1Space;
PxVec3 obbExtents = PxVec3(inflatedRadius);
PxMat33 obbRot(PxIdentity);
if(!idtMeshScale)
meshScaling.transformQueryBounds(obbCenter, obbExtents, obbRot);
const Box obb(obbCenter, obbExtents, obbRot);
Midphase::intersectOBB(meshData, obb, callback, true);
callback.flushCache();
callback.mGeneration.generateLastContacts();
callback.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);
}
//multiManifold.drawManifold(*gRenderOutPut, sphereTransform, meshTransform);
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, sphereTransform, meshTransform, sphereRadius);
}
static FloatV pcmDistancePointTriangleSquared( const Vec3VArg p,
const Vec3VArg a,
const Vec3VArg b,
const Vec3VArg c,
Vec3V& closestP,
FeatureCode& fc)
{
const FloatV zero = FZero();
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V bc = V3Sub(c, b);
const Vec3V ap = V3Sub(p, a);
const Vec3V bp = V3Sub(p, b);
const Vec3V cp = V3Sub(p, 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);
const Vec3V n = V3Cross(ab, ac);
const VecCrossV crossA = V3PrepareCross(ap);
const VecCrossV crossB = V3PrepareCross(bp);
const VecCrossV crossC = V3PrepareCross(cp);
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
//check if p in vertex region outside a
const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0
const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0
const BoolV con0 = BAnd(con00, con01); // vertex region a
if(BAllEqTTTT(con0))
{
//Vertex 0
fc = FC_VERTEX0;
closestP = a;
return V3Dot(ap, ap);
}
//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))
{
//Vertex 1
fc = FC_VERTEX1;
closestP = b;
return V3Dot(bp, bp);
}
//check if p in vertex region outside c
const BoolV con20 = FIsGrtrOrEq(d6, zero);
const BoolV con21 = FIsGrtrOrEq(d6, d5);
const BoolV con2 = BAnd(con20, con21); // vertex region c
if(BAllEqTTTT(con2))
{
//Vertex 2
fc = FC_VERTEX2;
closestP = c;
return V3Dot(cp, cp);
}
//check if p in edge region of AB
//const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2));
const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c
const BoolV con30 = FIsGrtr(zero, vc);
const BoolV con31 = FIsGrtrOrEq(d1, zero);
const BoolV con32 = FIsGrtr(zero, d3);
const BoolV con3 = BAnd(con30, BAnd(con31, con32));
if(BAllEqTTTT(con3))
{
// Edge 01
fc = FC_EDGE01;
const FloatV sScale = FDiv(d1, FSub(d1, d3));
const Vec3V closest3 = V3ScaleAdd(ab, sScale, a);//V3Add(a, V3Scale(ab, sScale));
const Vec3V vv = V3Sub(p, closest3);
closestP = closest3;
return V3Dot(vv, vv);
}
//check if p in edge region of BC
//const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4));
const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a
const BoolV con40 = FIsGrtr(zero, va);
const BoolV con41 = FIsGrtrOrEq(d4, d3);
const BoolV con42 = FIsGrtrOrEq(d5, d6);
const BoolV con4 = BAnd(con40, BAnd(con41, con42));
if(BAllEqTTTT(con4))
{
// Edge 12
fc = FC_EDGE12;
const FloatV uScale = FDiv(unom, FAdd(unom, udenom));
const Vec3V closest4 = V3ScaleAdd(bc, uScale, b);//V3Add(b, V3Scale(bc, uScale));
const Vec3V vv = V3Sub(p, closest4);
closestP = closest4;
return V3Dot(vv, vv);
}
//check if p in edge region of AC
//const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6));
const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b
const BoolV con50 = FIsGrtr(zero, vb);
const BoolV con51 = FIsGrtrOrEq(d2, zero);
const BoolV con52 = FIsGrtr(zero, d6);
const BoolV con5 = BAnd(con50, BAnd(con51, con52));
if(BAllEqTTTT(con5))
{
//Edge 20
fc = FC_EDGE20;
const FloatV tScale = FDiv(d2, FSub(d2, d6));
const Vec3V closest5 = V3ScaleAdd(ac, tScale, a);//V3Add(a, V3Scale(ac, tScale));
const Vec3V vv = V3Sub(p, closest5);
closestP = closest5;
return V3Dot(vv, vv);
}
fc = FC_FACE;
//P must project inside face region. Compute Q using Barycentric coordinates
const FloatV nn = V3Dot(n, n);
const FloatV t = FDiv(V3Dot(n, V3Sub(a, p)), nn);
const Vec3V vv = V3Scale(n, t);
closestP = V3Add(p, vv);
return V3Dot(vv, vv);
}
bool Gu::PCMSphereVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds)
{
const FloatV zero = FZero();
const Vec3V v0 = V3LoadU(verts[0]);
const Vec3V v1 = V3LoadU(verts[1]);
const Vec3V v2 = V3LoadU(verts[2]);
const Vec3V v10 = V3Sub(v1, v0);
const Vec3V v20 = V3Sub(v2, v0);
const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized();
const FloatV d = V3Dot(v0, n);//d = -p0.dot(n);
const FloatV dist0 = FSub(V3Dot(mSphereCenter, n), d);//p.dot(n) + d;
// Backface culling
if(FAllGrtr(zero, dist0))
return false;
Vec3V closestP;
//mSphereCenter will be in the local space of the triangle mesh
FeatureCode fc;
FloatV sqDist = pcmDistancePointTriangleSquared(mSphereCenter, v0, v1, v2, closestP, fc);
//sphere overlap with triangles
if (FAllGrtr(mSqInflatedSphereRadius, sqDist))
{
//sphere center is on the triangle surface, we take triangle normal as the patchNormal. Otherwise, we need to calculate the patchNormal
if(fc==FC_FACE)
{
const Vec3V patchNormal = n;
const FloatV dist = FSqrt(sqDist);
mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1]));
mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2]));
mEdgeCache.addData(CachedEdge(vertInds[2], vertInds[0]));
mVertexCache.addData(CachedVertex(vertInds[0]));
mVertexCache.addData(CachedVertex(vertInds[1]));
mVertexCache.addData(CachedVertex(vertInds[2]));
addToPatch(closestP, patchNormal, dist, triangleIndex);
}
else
{
const Vec3V patchNormal = V3Normalize(V3Sub(mSphereCenter, closestP));
//ML : defer the contacts generation
const PxU32 nb = sizeof(PCMDeferredPolyData) / sizeof(PxU32);
PxU32 newSize = nb + mDeferredContacts->size();
if(mDeferredContacts->capacity() < newSize)
mDeferredContacts->reserve(2*(newSize+1));
PCMDeferredPolyData* PX_RESTRICT data = reinterpret_cast<PCMDeferredPolyData*>(mDeferredContacts->end());
mDeferredContacts->forceSize_Unsafe(newSize);
SortedTriangle sortedTriangle;
sortedTriangle.mSquareDist = sqDist;
sortedTriangle.mIndex = mSortedTriangle.size();
mSortedTriangle.pushBack(sortedTriangle);
data->mTriangleIndex = triangleIndex;
data->mFeatureIndex = fc;
data->triFlags32 = PxU32(triFlags);
data->mInds[0] = vertInds[0];
data->mInds[1] = vertInds[1];
data->mInds[2] = vertInds[2];
V3StoreU(closestP, data->mVerts[0]);
V3StoreU(patchNormal, data->mVerts[1]);
V3StoreU(V3Splat(sqDist), data->mVerts[2]);
}
}
return true;
}
void Gu::PCMSphereVsMeshContactGeneration::addToPatch(const Vec3VArg contactP, const Vec3VArg patchNormal, const FloatV dist, PxU32 triangleIndex)
{
PX_ASSERT(mNumContactPatch < PCM_MAX_CONTACTPATCH_SIZE);
const Vec3V sphereCenter = V3Zero(); // in sphere local space
bool foundPatch = false;
if (mNumContactPatch > 0)
{
if (FAllGrtr(V3Dot(mContactPatch[mNumContactPatch - 1].mPatchNormal, patchNormal), mAcceptanceEpsilon))
{
PCMContactPatch& patch = mContactPatch[mNumContactPatch - 1];
PX_ASSERT((patch.mEndIndex - patch.mStartIndex) == 1);
if (FAllGrtr(patch.mPatchMaxPen, dist))
{
//overwrite the old contact
mManifoldContacts[patch.mStartIndex].mLocalPointA = sphereCenter;//in sphere's space
mManifoldContacts[patch.mStartIndex].mLocalPointB = contactP;
mManifoldContacts[patch.mStartIndex].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(patchNormal), dist);
mManifoldContacts[patch.mStartIndex].mFaceIndex = triangleIndex;
patch.mPatchMaxPen = dist;
}
foundPatch = true;
}
}
if (!foundPatch)
{
mManifoldContacts[mNumContacts].mLocalPointA = sphereCenter;//in sphere's space
mManifoldContacts[mNumContacts].mLocalPointB = contactP;
mManifoldContacts[mNumContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(patchNormal), dist);
mManifoldContacts[mNumContacts++].mFaceIndex = triangleIndex;
mContactPatch[mNumContactPatch].mStartIndex = mNumContacts - 1;
mContactPatch[mNumContactPatch].mEndIndex = mNumContacts;
mContactPatch[mNumContactPatch].mPatchMaxPen = dist;
mContactPatch[mNumContactPatch++].mPatchNormal = patchNormal;
}
PX_ASSERT(mNumContactPatch < PCM_MAX_CONTACTPATCH_SIZE);
if (mNumContacts >= 16)
{
PX_ASSERT(mNumContacts <= 64);
processContacts(GU_SPHERE_MANIFOLD_CACHE_SIZE);
}
}
void Gu::PCMSphereVsMeshContactGeneration::generateLastContacts()
{
// Process delayed contacts
PxU32 nbSortedTriangle = mSortedTriangle.size();
if (nbSortedTriangle)
{
PxSort(mSortedTriangle.begin(), mSortedTriangle.size(), PxLess<SortedTriangle>());
const PCMDeferredPolyData* PX_RESTRICT cd = reinterpret_cast<const PCMDeferredPolyData*>(mDeferredContacts->begin());
for (PxU32 i = 0; i < nbSortedTriangle; ++i)
{
const PCMDeferredPolyData& currentContact = cd[mSortedTriangle[i].mIndex];
const PxU32 ref0 = currentContact.mInds[0];
const PxU32 ref1 = currentContact.mInds[1];
const PxU32 ref2 = currentContact.mInds[2];
//if addData sucessful, which means mEdgeCache doesn't have the edge
const bool noEdge01 = mEdgeCache.addData(CachedEdge(ref0, ref1));
const bool noEdge12 = mEdgeCache.addData(CachedEdge(ref1, ref2));
const bool noEdge20 = mEdgeCache.addData(CachedEdge(ref2, ref0));
const bool noVertex0 = mVertexCache.addData(CachedVertex(ref0));
const bool noVertex1 = mVertexCache.addData(CachedVertex(ref1));
const bool noVertex2 = mVertexCache.addData(CachedVertex(ref2));
bool needsProcessing = false;
{
switch(currentContact.mFeatureIndex)
{
case FC_VERTEX0:
needsProcessing = noVertex0;
break;
case FC_VERTEX1:
needsProcessing = noVertex1;
break;
case FC_VERTEX2:
needsProcessing = noVertex2;
break;
case FC_EDGE01:
needsProcessing = noEdge01;
break;
case FC_EDGE12:
needsProcessing = noEdge12;
break;
case FC_EDGE20:
needsProcessing = noEdge20;
break;
case FC_FACE:
case FC_UNDEFINED:
PX_ASSERT(0); // PT: should not be possible
break;
};
}
if (needsProcessing)
{
//we store the contact, patch normal and sq distance in the vertex memory in PCMDeferredPolyData
const Vec3V contactP = V3LoadU(currentContact.mVerts[0]);
const Vec3V patchNormal = V3LoadU(currentContact.mVerts[1]);
const FloatV sqDist = FLoad(currentContact.mVerts[2].x);
const FloatV dist = FSqrt(sqDist);
addToPatch(contactP, patchNormal, dist, currentContact.mTriangleIndex);
}
}
}
}
| 17,383 | C++ | 33.629482 | 174 | 0.730484 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenBoxConvex.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 "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
#include "GuPCMContactGenUtil.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxAlloca.h"
#include "GuVecCapsule.h"
#include "GuVecBox.h"
#include "GuEPA.h"
#include "geomutils/PxContactBuffer.h"
#include "common/PxRenderOutput.h"
#define PCM_USE_INTERNAL_OBJECT 1
using namespace physx;
using namespace Gu;
using namespace aos;
//Precompute the convex data
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
static bool testFaceNormal(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, const PxMatTransformV& transform1To0, const FloatVArg contactDist,
FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status)
{
PX_UNUSED(polyData1);
FloatV _minOverlap = FMax();//minOverlap;
PxU32 _feature = 0;
Vec3V _faceNormal = faceNormal;
FloatV min0, max0;
FloatV min1, max1;
const Vec3V center1To0 = transform1To0.p;
#if PCM_USE_INTERNAL_OBJECT
const Vec3V zeroV = V3Zero();
const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter);
const Vec3V internalCenter1In0 = transform1To0.transform(shapeSpaceCenter1);
const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius);
const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents);
const Vec3V negInternalExtents1 = V3Neg(internalExtents1);
#endif
//in the local space of polyData0
for(PxU32 i=0; i<polyData0.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData0.mPolygons[i];
const Vec3V minVert = V3LoadU(polyData0.mVerts[polygon.mMinIndex]);
const FloatV planeDist = FLoad(polygon.mPlane.d);
const Vec3V vertexSpacePlaneNormal = V3LoadU(polygon.mPlane.n);
//transform plane n to shape space
const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(map0->shape2Vertex, vertexSpacePlaneNormal);
const FloatV magnitude = FRecip(V3Length(shapeSpacePlaneNormal));
//ML::use this to avoid LHS
min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude);
max0 = FMul(FNeg(planeDist), magnitude);
//normalize shape space normal
const Vec3V n0 = V3Scale(shapeSpacePlaneNormal, magnitude);
//calculate polyData1 projection
//rotate polygon's normal into the local space of polyData1
const Vec3V n1 = transform0To1.rotate(n0);
#if PCM_USE_INTERNAL_OBJECT
//test internal object
//ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale,
//the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal.
//If polyData0 have scale, internalExtens1 will be 0.
const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1);
const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1);
const FloatV internalTrans = V3Dot(internalCenter1In0, n0);
const FloatV _min1 = FSub(internalTrans, radius);
const FloatV _max1 = FAdd(internalTrans, radius);
const FloatV _min = FMax(min0, _min1);
const FloatV _max = FMin(max0, _max1);
const FloatV _tempOverlap = FSub(_max, _min);
//const FloatV _tempOverlap = FSub(max0, _min1);
//Internal object overlaps more than current min, so can skip it
//because (a) it isn't a separating axis and (b) it isn't the smallest axis
if(FAllGrtr(_tempOverlap, _minOverlap))
continue;
#endif
const FloatV translate = V3Dot(center1To0, n0);
map1->doSupport(n1, min1, max1);
min1 = FAdd(translate, min1);
max1 = FAdd(translate, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if(FAllGrtr(_minOverlap, tempOverlap))
{
_minOverlap = tempOverlap;
_feature = i;
_faceNormal = n0;
}
}
if(FAllGrtr(minOverlap, _minOverlap))
{
faceNormal = _faceNormal;
minOverlap = _minOverlap;
status = faceStatus;
}
feature = _feature;
return true;
}
//plane is in the shape space of polyData
static void buildPartialHull(const PolygonalData& polyData, const SupportLocal* map, SeparatingAxes& validAxes, const Vec3VArg planeP, const Vec3VArg planeDir)
{
const FloatV zero = FZero();
const Vec3V dir = V3Normalize(planeDir);
for(PxU32 i=0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8;
Vec3V v0 = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[polygon.mNbVerts - 1]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData
FloatV dist0 = V3Dot(dir, V3Sub(v0, planeP));
for (PxU32 iStart = 0; iStart < polygon.mNbVerts; iStart++)
{
const Vec3V v1 = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[iStart]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const FloatV dist1 = V3Dot(dir, V3Sub(v1, planeP));
const BoolV con = BOr(FIsGrtr(dist0, zero), FIsGrtr(dist1, zero));
//cull edge if either of the vertex will on the positive size of the plane
if(BAllEqTTTT(con))
{
const Vec3V tempV = V3Sub(v0, v1);
PxVec3 temp;
V3StoreU(tempV, temp);
validAxes.addAxis(temp.getNormalized());
}
v0 = v1;
dist0 = dist1;
}
}
}
static bool testEdgeNormal(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, const PxMatTransformV& transform1To0, const FloatVArg contactDist,
FloatV& minOverlap, Vec3V& edgeNormalIn0, FeatureStatus edgeStatus, FeatureStatus& status)
{
FloatV overlap = minOverlap;
FloatV min0, max0;
FloatV min1, max1;
const FloatV eps = FEps();
const Vec3V shapeSpaceCenter0 = V3LoadU(polyData0.mCenter);
const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter);
#if PCM_USE_INTERNAL_OBJECT
const Vec3V zeroV = V3Zero();
const Vec3V internalCenter1In0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0);
const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius);
const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents);
const Vec3V negInternalExtents1 = V3Neg(internalExtents1);
const FloatV internalRadius0 = FLoad(polyData0.mInternal.mRadius);
const Vec3V internalExtents0 = V3LoadU(polyData0.mInternal.mExtents);
const Vec3V negInternalExtents0 = V3Neg(internalExtents0);
#endif
const Vec3V center1To0 = transform1To0.p;
//in polyData0 shape space
const Vec3V dir0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0);
const Vec3V support0 = map0->doSupport(dir0);
//in polyData1 shape space
const Vec3V dir1 = transform0To1.rotate(V3Neg(dir0));
const Vec3V support1 = map1->doSupport(dir1);
const Vec3V support0In1 = transform0To1.transform(support0);
const Vec3V support1In0 = transform1To0.transform(support1);
SeparatingAxes mSA0;
SeparatingAxes mSA1;
mSA0.reset();
mSA1.reset();
buildPartialHull(polyData0, map0, mSA0, support1In0, dir0);
buildPartialHull(polyData1, map1, mSA1, support0In1, dir1);
const PxVec3* axe0 = mSA0.getAxes();
const PxVec3* axe1 = mSA1.getAxes();
const PxU32 numAxe0 = mSA0.getNumAxes();
const PxU32 numAxe1 = mSA1.getNumAxes();
for(PxU32 i=0; i < numAxe0; ++i)
{
//axe0[i] is in the shape space of polyData0
const Vec3V v0 = V3LoadU(axe0[i]);
for(PxU32 j=0; j< numAxe1; ++j)
{
//axe1[j] is in the shape space of polyData1
const Vec3V v1 = V3LoadU(axe1[j]);
const Vec3V dir = V3Cross(v0, transform1To0.rotate(v1));
const FloatV lenSq = V3Dot(dir, dir);
if(FAllGrtr(eps, lenSq))
continue;
//n0 is in polyData0's local space
const Vec3V n0 = V3Scale(dir, FRsqrt(lenSq));
//n1 is in polyData1's local space
const Vec3V n1 = transform0To1.rotate(n0);
#if PCM_USE_INTERNAL_OBJECT
//ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale,
//the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal.
//If polyData0 have scale, internalExtens1 will be 0.
//vertex space n1
const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1);
const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1);
const FloatV internalTrans = V3Dot(internalCenter1In0, n0);
const FloatV _min1 = FSub(internalTrans, radius);
const FloatV _max1 = FAdd(internalTrans, radius);
const Vec3V proj0 = V3Sel(V3IsGrtr(n0, zeroV), internalExtents0, negInternalExtents0);
const FloatV radius0 = FMax(V3Dot(n0, proj0), internalRadius0);
const FloatV _max0 = radius0;
const FloatV _min0 = FNeg(radius0);
PX_ASSERT(FAllGrtrOrEq(_max0, _min0));
PX_ASSERT(FAllGrtrOrEq(_max1, _min1));
const FloatV _min = FMax(_min0, _min1);
const FloatV _max = FMin(_max0, _max1);
const FloatV _tempOverlap = FSub(_max, _min);
//Internal object overlaps more than current min, so can skip it
//because (a) it isn't a separating axis and (b) it isn't the smallest axis
if(FAllGrtr(_tempOverlap, overlap))
continue;
#endif
//get polyData0's projection
map0->doSupport(n0, min0, max0);
const FloatV translate = V3Dot(center1To0, n0);
//get polyData1's projection
map1->doSupport(n1, min1, max1);
min1 = FAdd(translate, min1);
max1 = FAdd(translate, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
#if PCM_USE_INTERNAL_OBJECT
PX_ASSERT(FAllGrtrOrEq(tempOverlap, _tempOverlap));
#endif
if(FAllGrtr(overlap, tempOverlap))
{
overlap = tempOverlap;
edgeNormalIn0 = n0;
status = edgeStatus;
}
}
}
minOverlap = overlap;
return true;
}
//contactNormal is in the space of polyData0
static void generatedContacts(const PolygonalData& polyData0, const PolygonalData& polyData1, const HullPolygonData& referencePolygon, const HullPolygonData& incidentPolygon,
const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, PersistentContact* manifoldContacts,
PxU32& numContacts, const FloatVArg contactDist, PxRenderOutput* renderOutput)
{
PX_UNUSED(renderOutput);
const FloatV zero = FZero();
const PxU8* inds0 = polyData0.mPolygonVertexRefs + referencePolygon.mVRef8;
//transform the plane normal to shape space
const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(map0->shape2Vertex, V3LoadU(referencePolygon.mPlane.n)));
//this is the matrix transform all points to the 2d plane
const Mat33V rot = findRotationMatrixFromZAxis(contactNormal);
const PxU8* inds1 = polyData1.mPolygonVertexRefs + incidentPolygon.mVRef8;
Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16));
Vec3V* points1In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*incidentPolygon.mNbVerts, 16));
bool* points1In0Penetration = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*incidentPolygon.mNbVerts));
FloatV* points1In0TValue = reinterpret_cast<FloatV*>(PxAllocaAligned(sizeof(FloatV)*incidentPolygon.mNbVerts, 16));
//Transform all the verts from vertex space to shape space
map0->populateVerts(inds0, referencePolygon.mNbVerts, polyData0.mVerts, points0In0);
map1->populateVerts(inds1, incidentPolygon.mNbVerts, polyData1.mVerts, points1In0);
#if PCM_LOW_LEVEL_DEBUG
PersistentContactManifold::drawPolygon(*renderOutput, map0->transform, points0In0, (PxU32)referencePolygon.mNbVerts, 0x00ff0000);
PersistentContactManifold::drawPolygon(*renderOutput, map1->transform, points1In0, (PxU32)incidentPolygon.mNbVerts, 0x0000ff00);
#endif
//This is used to calculate the project point when the 2D reference face points is inside the 2D incident face point
const Vec3V sPoint = points1In0[0];
PX_ASSERT(incidentPolygon.mNbVerts <= 64);
Vec3V eps = Vec3V_From_FloatV(FEps());
Vec3V max = Vec3V_From_FloatV(FMax());
Vec3V nmax = V3Neg(max);
//transform reference polygon to 2d, calculate min and max
Vec3V rPolygonMin= max;
Vec3V rPolygonMax = nmax;
for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i)
{
points0In0[i] = M33MulV3(rot, points0In0[i]);
rPolygonMin = V3Min(rPolygonMin, points0In0[i]);
rPolygonMax = V3Max(rPolygonMax, points0In0[i]);
}
rPolygonMin = V3Sub(rPolygonMin, eps);
rPolygonMax = V3Add(rPolygonMax, eps);
const FloatV d = V3GetZ(points0In0[0]);
const FloatV rd = FAdd(d, contactDist);
Vec3V iPolygonMin= max;
Vec3V iPolygonMax = nmax;
PxU32 inside = 0;
for(PxU32 i=0; i<incidentPolygon.mNbVerts; ++i)
{
const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space
const Vec3V a = transform0To1.transformInv(vert1);
points1In0[i] = M33MulV3(rot, a);
const FloatV z = V3GetZ(points1In0[i]);
points1In0TValue[i] = FSub(z, d);
points1In0[i] = V3SetZ(points1In0[i], d);
iPolygonMin = V3Min(iPolygonMin, points1In0[i]);
iPolygonMax = V3Max(iPolygonMax, points1In0[i]);
if(FAllGrtr(rd, z))
{
points1In0Penetration[i] = true;
if(contains(points0In0, referencePolygon.mNbVerts, points1In0[i], rPolygonMin, rPolygonMax))
{
inside++;
if (numContacts == PxContactBuffer::MAX_CONTACTS)
return;
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), points1In0TValue[i]);
manifoldContacts[numContacts].mLocalPointA = vert1;
manifoldContacts[numContacts].mLocalPointB = M33TrnspsMulV3(rot, points1In0[i]);
manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen;
}
}
else
{
points1In0Penetration[i] = false;
}
}
if(inside == incidentPolygon.mNbVerts)
return;
inside = 0;
iPolygonMin = V3Sub(iPolygonMin, eps);
iPolygonMax = V3Add(iPolygonMax, eps);
const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n)));
const Vec3V contactNormalIn1 = transform0To1.rotate(contactNormal);
for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i)
{
if(contains(points1In0, incidentPolygon.mNbVerts, points0In0[i], iPolygonMin, iPolygonMax))
{
//const Vec3V vert0=Vec3V_From_PxVec3(polyData0.mVerts[inds0[i]]);
const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]);
const Vec3V a = transform0To1.transform(vert0);
const FloatV nom = V3Dot(incidentNormal, V3Sub(sPoint, a));
const FloatV denom = V3Dot(incidentNormal, contactNormalIn1);
PX_ASSERT(FAllEq(denom, zero)==0);
const FloatV t = FDiv(nom, denom);
if(FAllGrtr(t, contactDist))
continue;
inside++;
if (numContacts == PxContactBuffer::MAX_CONTACTS)
return;
const Vec3V projPoint = V3ScaleAdd(contactNormalIn1, t, a);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), t);
manifoldContacts[numContacts].mLocalPointA = projPoint;
manifoldContacts[numContacts].mLocalPointB = vert0;
manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen;
}
}
if(inside == referencePolygon.mNbVerts)
return;
//(2) segment intersection
for (PxU32 iStart = 0, iEnd = PxU32(incidentPolygon.mNbVerts - 1); iStart < incidentPolygon.mNbVerts; iEnd = iStart++)
{
if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd] ) )//|| (points1In0[i].status == POINT_OUTSIDE && points1In0[incidentIndex].status == POINT_OUTSIDE))
continue;
const Vec3V ipA = points1In0[iStart];
const Vec3V ipB = points1In0[iEnd];
Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d));
Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d));
const Vec3V iMin = V3Min(ipA, ipB);
const Vec3V iMax = V3Max(ipA, ipB);
for (PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++)
{
const Vec3V rpA = points0In0[rStart];
const Vec3V rpB = points0In0[rEnd];
const Vec3V rMin = V3Min(rpA, rpB);
const Vec3V rMax = V3Max(rpA, rpB);
const BoolV tempCon =BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax));
const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon));
if(BAllEqTTTT(con))
continue;
FloatV a1 = signed2DTriArea(rpA, rpB, ipA);
FloatV a2 = signed2DTriArea(rpA, rpB, ipB);
if(FAllGrtr(zero, FMul(a1, a2)))
{
FloatV a3 = signed2DTriArea(ipA, ipB, rpA);
FloatV a4 = signed2DTriArea(ipA, ipB, rpB);
if(FAllGrtr(zero, FMul(a3, a4)))
{
//these two segment intersect
const FloatV t = FDiv(a1, FSub(a2, a1));
const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri);
const Vec3V pAA = V3SetZ(pBB, d);
const Vec3V pA = M33TrnspsMulV3(rot, pAA);
const Vec3V pB = transform0To1.transform(M33TrnspsMulV3(rot, pBB));
const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA));
if(FAllGrtr(pen, contactDist))
continue;
if (numContacts == PxContactBuffer::MAX_CONTACTS)
return;
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), pen);
manifoldContacts[numContacts].mLocalPointA = pB;
manifoldContacts[numContacts].mLocalPointB = pA;
manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen;
}
}
}
}
}
bool Gu::generateFullContactManifold(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, PersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, const Vec3VArg normal, const Vec3VArg closestA, const Vec3VArg closestB, PxReal marginA, PxReal marginB, bool doOverlapTest,
PxRenderOutput* renderOutput, PxReal toleranceLength)
{
const PxMatTransformV transform1To0V = map0->transform.transformInv(map1->transform);
const PxMatTransformV transform0To1V = map1->transform.transformInv(map0->transform);
if(doOverlapTest)
{
//if gjk fail, SAT based yes/no test
FeatureStatus status = POLYDATA0;
FloatV minOverlap = FMax();
Vec3V minNormal = V3Zero();
PxU32 feature0;
//in the local space of polyData0, minNormal is in polyData0 space
if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status))
return false;
PxU32 feature1;
//in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space
if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status))
return false;
bool doEdgeTest = false;
EdgeTest:
if(doEdgeTest)
{
if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE, status))
return false;
if(status != EDGE)
return true;
}
if(status == POLYDATA0)
{
//minNormal is in the local space of polydata0
const HullPolygonData& referencePolygon = polyData0.mPolygons[feature0];
const Vec3V n = transform0To1V.rotate(minNormal);
const HullPolygonData& incidentPolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, n)];
generatedContacts(polyData0, polyData1, referencePolygon, incidentPolygon, map0, map1, transform0To1V, manifoldContacts, numContacts, contactDist, renderOutput);
if (numContacts > 0)
{
const Vec3V nn = V3Neg(n);
//flip the contacts
for(PxU32 i=0; i<numContacts; ++i)
{
const Vec3V localPointB = manifoldContacts[i].mLocalPointB;
manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA;
manifoldContacts[i].mLocalPointA = localPointB;
manifoldContacts[i].mLocalNormalPen = V4SetW(nn, V4GetW(manifoldContacts[i].mLocalNormalPen));
}
}
}
else if(status == POLYDATA1)
{
//minNormal is in the local space of polydata1
const HullPolygonData& referencePolygon = polyData1.mPolygons[feature1];
const HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, transform1To0V.rotate(minNormal))];
//reference face is polyData1
generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput);
}
else //if(status == EDGE0)
{
//minNormal is in the local space of polydata0
const HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, V3Neg(minNormal))];
const HullPolygonData& referencePolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, transform0To1V.rotate(minNormal))];
generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput);
}
if(numContacts == 0 && !doEdgeTest)
{
doEdgeTest = true;
goto EdgeTest;
}
}
else
{
const PxReal lowerEps = toleranceLength * PCM_WITNESS_POINT_LOWER_EPS;
const PxReal upperEps = toleranceLength * PCM_WITNESS_POINT_UPPER_EPS;
const PxReal toleranceA = PxClamp(marginA, lowerEps, upperEps);
const PxReal toleranceB = PxClamp(marginB, lowerEps, upperEps);
const Vec3V negNormal = V3Neg(normal);
const Vec3V normalIn0 = transform0To1V.rotateInv(normal);
PxU32 faceIndex1 = getWitnessPolygonIndex(polyData1, map1, negNormal, closestB, toleranceB);
PxU32 faceIndex0 = getWitnessPolygonIndex(polyData0, map0, normalIn0, transform0To1V.transformInv(closestA),
toleranceA);
const HullPolygonData& referencePolygon = polyData1.mPolygons[faceIndex1];
const HullPolygonData& incidentPolygon = polyData0.mPolygons[faceIndex0];
const Vec3V referenceNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(referencePolygon.mPlane.n)));
const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map0->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n)));
const FloatV referenceProject = FAbs(V3Dot(referenceNormal, negNormal));
const FloatV incidentProject = FAbs(V3Dot(incidentNormal, normalIn0));
if (FAllGrtrOrEq(referenceProject, incidentProject))
{
generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput);
}
else
{
generatedContacts(polyData0, polyData1, incidentPolygon, referencePolygon, map0, map1, transform0To1V, manifoldContacts, numContacts, contactDist, renderOutput);
if (numContacts > 0)
{
const Vec3V n = transform0To1V.rotate(incidentNormal);
const Vec3V nn = V3Neg(n);
//flip the contacts
for (PxU32 i = 0; i<numContacts; ++i)
{
const Vec3V localPointB = manifoldContacts[i].mLocalPointB;
manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA;
manifoldContacts[i].mLocalPointA = localPointB;
manifoldContacts[i].mLocalNormalPen = V4SetW(nn, V4GetW(manifoldContacts[i].mLocalNormalPen));
}
}
}
}
return true;
}
//This function called by box/convex and convex/convex pcm function
bool Gu::addGJKEPAContacts(const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxMatTransformV& aToB, GjkStatus status,
PersistentContact* manifoldContacts, const FloatV replaceBreakingThreshold, const FloatV tolerenceLength, GjkOutput& output,
PersistentContactManifold& manifold)
{
bool doOverlapTest = false;
if (status == GJK_DEGENERATE)
{
const Vec3V normal = output.normal;
const FloatV costheta = V3Dot(output.searchDir, normal);
if (FAllGrtr(costheta, FLoad(0.9999f)))
{
const Vec3V centreA = relativeConvex->getCenter();
const Vec3V centreB = localConvex->getCenter();
const Vec3V dir = V3Normalize(V3Sub(centreA, centreB));
const FloatV theta = V3Dot(dir, normal);
if (FAllGrtr(theta, FLoad(0.707f)))
{
addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold);
}
else
{
doOverlapTest = true;
}
}
else
{
doOverlapTest = true;
}
}
else if (status == GJK_CONTACT)
{
addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold);
}
else
{
PX_ASSERT(status == EPA_CONTACT);
status = epaPenetration(*relativeConvex, *localConvex, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, tolerenceLength, output);
if (status == EPA_CONTACT)
{
addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold);
}
else
{
doOverlapTest = true;
}
}
return doOverlapTest;
}
bool Gu::computeMTD(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, FloatV& penDepth, Vec3V& normal)
{
using namespace aos;
const PxMatTransformV transform1To0V = map0->transform.transformInv(map1->transform);
const PxMatTransformV transform0To1V = map1->transform.transformInv(map0->transform);
FeatureStatus status = POLYDATA0;
FloatV minOverlap = FMax();
Vec3V minNormal = V3Zero();
const FloatV contactDist = FZero();
PxU32 feature0;
//in the local space of polyData0, minNormal is in polyData0 space
if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status))
return false;
PxU32 feature1;
//in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space
if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status))
return false;
if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE, status))
return false;
penDepth = minOverlap;
if(status == POLYDATA1)
{
//minNormal is in the local space of polydata1
normal = map1->transform.rotate(minNormal);
}
else
{
PX_ASSERT(status == POLYDATA0 || status == EDGE);
//ML: status == POLYDATA0 or status == EDGE, minNormal is in the local space of polydata0
normal = V3Neg(map0->transform.rotate(minNormal));
}
return true;
}
| 28,043 | C++ | 35.754915 | 248 | 0.736619 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMShapeConvex.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_SHAPE_CONVEX_H
#define GU_PCM_SHAPE_CONVEX_H
#include "GuConvexSupportTable.h"
#include "GuPersistentContactManifold.h"
#include "GuShapeConvex.h"
namespace physx
{
class PxConvexMeshGeometry;
namespace Gu
{
extern const PxU8 gPCMBoxPolygonData[24];
class PCMPolygonalBox
{
public:
PCMPolygonalBox(const PxVec3& halfSide);
void getPolygonalData(Gu::PolygonalData* PX_RESTRICT dst) const;
const PxVec3& mHalfSide;
PxVec3 mVertices[8];
Gu::HullPolygonData mPolygons[6];
private:
PCMPolygonalBox& operator=(const PCMPolygonalBox&);
};
void getPCMConvexData(const Gu::ConvexHullV& convexHull, bool idtScale, Gu::PolygonalData& polyData);
bool getPCMConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, Gu::PolygonalData& polyData);
}
}
#endif
| 2,561 | C | 39.031249 | 150 | 0.763764 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMTriangleContactGen.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 "GuPCMTriangleContactGen.h"
#include "GuPCMContactConvexCommon.h"
#include "GuVecTriangle.h"
#include "GuBarycentricCoordinates.h"
#include "GuConvexEdgeFlags.h"
#include "foundation/PxAlloca.h"
#if PCM_LOW_LEVEL_DEBUG
#include "common/PxRenderBuffer.h"
#endif
#define EDGE_EDGE_GAUSS_MAP 0
#define BRUTE_FORCE_EDGE_EDGE 0
using namespace physx;
using namespace Gu;
using namespace aos;
static bool testPolyFaceNormal(const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status)
{
FloatV _minOverlap = FMax();
PxU32 _feature = 0;
Vec3V _faceNormal = faceNormal;
FloatV min0, max0;
FloatV min1, max1;
const FloatV eps = FEps();
if(polyMap->isIdentityScale)
{
//in the local space of polyData0
for(PxU32 i=0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const FloatV planeDist = FLoad(polygon.mPlane.d);
//shapeSpace and vertexSpace are the same
const Vec3V planeNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
//ML::avoid lHS, don't use the exiting function
min0 = V3Dot(planeNormal, minVert);
max0 = FNeg(planeDist);
triMap->doSupport(planeNormal, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if(FAllGrtr(_minOverlap, tempOverlap))
{
_minOverlap = tempOverlap;
_feature = i;
_faceNormal = planeNormal;
}
}
}
else
{
//in the local space of polyData0
for(PxU32 i=0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const FloatV planeDist = FLoad(polygon.mPlane.d);
const Vec3V vertexSpacePlaneNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
//transform plane n to shape space
const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(polyMap->shape2Vertex, vertexSpacePlaneNormal);
const FloatV magnitude = FRsqrtFast(V3LengthSq(shapeSpacePlaneNormal)); //FRecip(V3Length(shapeSpacePlaneNormal));
//ML::avoid lHS, don't use the exiting function
min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude);
max0 = FMul(FNeg(planeDist), magnitude);
//normalize the shapeSpacePlaneNormal
const Vec3V planeN = V3Scale(shapeSpacePlaneNormal, magnitude);
triMap->doSupport(planeN, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if(FAllGrtr(_minOverlap, tempOverlap))
{
_minOverlap = tempOverlap;
_feature = i;
_faceNormal = planeN;
}
}
}
if(FAllGrtr(minOverlap, FAdd(_minOverlap, eps)))
{
faceNormal = _faceNormal;
minOverlap = _minOverlap;
status = faceStatus;
}
feature = _feature;
return true;
}
//triangle is in the local space of polyData
static bool testTriangleFaceNormal(const TriangleV& triangle, const PolygonalData& /*polyData*/, const SupportLocalImpl<TriangleV>* /*triMap*/, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status)
{
FloatV min1, max1;
const FloatV eps = FEps();
const Vec3V triangleLocNormal = triangle.normal();
const FloatV min0 = V3Dot(triangleLocNormal, triangle.verts[0]);
const FloatV max0 = min0;
//triangle normal is in the vertex space
polyMap->doSupport(triangleLocNormal, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
minOverlap = FSub(FSub(max0, min1), eps);
status = faceStatus;
feature = 0;
faceNormal = triangleLocNormal;
return true;
}
static bool testPolyEdgeNormal(const TriangleV& triangle, const PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status)
{
FloatV overlap = minOverlap;
FloatV min0, max0;
FloatV min1, max1;
const FloatV zero = FZero();
const Vec3V eps2 = V3Splat(FLoad(1e-6f));
const Vec3V v0 = M33MulV3(polyMap->shape2Vertex, triangle.verts[0]);
const Vec3V v1 = M33MulV3(polyMap->shape2Vertex, triangle.verts[1]);
const Vec3V v2 = M33MulV3(polyMap->shape2Vertex, triangle.verts[2]);
const TriangleV vertexSpaceTriangle(v0, v1, v2);
PxU32 nbTriangleAxes = 0;
Vec3V triangleAxes[3];
for(PxI8 kStart = 0, kEnd =2; kStart<3; kEnd = kStart++)
{
const bool active = (triFlags & (1 << (kEnd+3))) != 0;
if(active)
{
const Vec3V p00 = vertexSpaceTriangle.verts[kStart];
const Vec3V p01 = vertexSpaceTriangle.verts[kEnd];
triangleAxes[nbTriangleAxes++] = V3Sub(p01, p00);
}
}
if(nbTriangleAxes == 0)
return true;
//create localTriPlane in the vertex space
const Vec3V vertexSpaceTriangleNormal = vertexSpaceTriangle.normal();
for(PxU32 i =0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8;
const Vec3V vertexSpacePlaneNormal = V3LoadU(polygon.mPlane.n);
//fast culling.
if(FAllGrtr(V3Dot(vertexSpacePlaneNormal, vertexSpaceTriangleNormal), zero))
continue;
// Loop through polygon vertices == polygon edges;
for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = PxU32(lStart++))
{
//in the vertex space
const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const Vec3V convexEdge = V3Sub(p11, p10);
for(PxU32 j = 0; j < nbTriangleAxes; ++j)
{
const Vec3V currentPolyEdge = triangleAxes[j];
const Vec3V v = V3Cross(convexEdge, currentPolyEdge);
//two edges aren't parallel
if((!V3AllGrtr(eps2, V3Abs(v))) && (FAllGrtr(V3Dot(v, vertexSpaceTriangleNormal), zero)))
{
//transform the v back to the shape space
const Vec3V shapeSpaceV = M33TrnspsMulV3(polyMap->shape2Vertex, v);
const Vec3V n0 = V3Normalize(shapeSpaceV);
triMap->doSupport(n0, min0, max0);
polyMap->doSupport(n0, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap0 = FSub(max0, min1);
const FloatV tempOverlap1 = FSub(max1, min0);
if(FAllGrtr(overlap, tempOverlap0))
{
overlap = tempOverlap0;
minNormal = n0;
status = edgeStatus;
}
if(FAllGrtr(overlap, tempOverlap1))
{
overlap = tempOverlap1;
minNormal = V3Neg(n0);
status = edgeStatus;
}
}
}
}
}
minOverlap = overlap;
return true;
}
#if BRUTE_FORCE_EDGE_EDGE
static bool testPolyEdgeNormalBruteForce(const TriangleV& triangle, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status)
{
PX_UNUSED(triFlags);
FloatV min0, max0;
FloatV min1, max1;
FloatV bestDist = FLoad(PX_MAX_F32);
Vec3V bestAxis = V3Zero();
const Vec3V eps2 = V3Splat(FLoad(1e-6));
PxU32 bestPolyIndex = 0;
PxU32 bestStart = 0;
PxU32 bestEnd = 0;
PxI8 bestTriStart = 0;
PxI8 bestTriEnd = 0;
for(PxU32 i =0; i<polyData.mNbPolygons; ++i)
{
const HullPolygonData& polygon = polyData.mPolygons[i];
const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8;
// Loop through polygon vertices == polygon edges;
for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = PxU32(lStart++))
{
//in the vertex space
const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData
//shape sapce
const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, p10);
const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, p11);
const Vec3V convexEdge = V3Sub(vertex11, vertex10);
for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++)
{
const Vec3V triVert0 = triangle.verts[kStart];
const Vec3V triVert1 = triangle.verts[kEnd];
const Vec3V triangleEdge = V3Sub(triVert1, triVert0);
const Vec3V v = V3Cross(convexEdge, triangleEdge);
if (!V3AllGrtr(eps2, V3Abs(v)))
{
//transform the v back to the shape space
const Vec3V n0 = V3Normalize(v);
triMap->doSupport(n0, min0, max0);
polyMap->doSupport(n0, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if(BAllEqTTTT(con))
return false;
const FloatV tempOverlap = FSub(max0, min1);
if (FAllGrtr(bestDist, tempOverlap))
{
bestDist = tempOverlap;
bestAxis = n0;
bestPolyIndex = i;
bestStart = lStart;
bestEnd = lEnd;
bestTriStart = kStart;
bestTriEnd = kEnd;
}
}
}
}
}
if (FAllGrtr(minOverlap, bestDist))
{
minOverlap = bestDist;
minNormal = bestAxis;
status = edgeStatus;
}
return true;
}
static bool testPolyEdgeNormalBruteForceVertsByEdges(const TriangleV& triangle, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status, PxU32& bestEdgeIndex, PxI8& bestTriStart, PxI8& bestTriEnd)
{
PX_UNUSED(triFlags);
const PxU32 numConvexEdges = polyData.mNbEdges;
const PxU16* verticesByEdges16 = polyData.mVerticesByEdges;
const PxVec3* vertices = polyData.mVerts;
FloatV bestDist = FLoad(PX_MAX_F32);
Vec3V bestAxis = V3Zero();
const Vec3V eps2 = V3Splat(FLoad(1e-6));
for (PxU32 convexEdgeIdx = 0; convexEdgeIdx < numConvexEdges; ++convexEdgeIdx)
{
const PxU16 v0idx1 = verticesByEdges16[convexEdgeIdx * 2];
const PxU32 v1idx1 = verticesByEdges16[convexEdgeIdx * 2 + 1];
//shape sapce
const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v0idx1]));
const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v1idx1]));
Vec3V convexEdge = V3Sub(vertex11, vertex10);
for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++)
{
const Vec3V triVert0 = triangle.verts[kStart];
const Vec3V triVert1 = triangle.verts[kEnd];
const Vec3V triEdge = V3Sub(triVert1, triVert0);
// compute the separation along this axis in vertex space
Vec3V axis = V3Cross(convexEdge, triEdge);
if (!V3AllGrtr(eps2, V3Abs(axis)))
{
axis = V3Normalize(axis);
FloatV min0, max0;
FloatV min1, max1;
triMap->doSupport(axis, min0, max0);
polyMap->doSupport(axis, min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if (BAllEqTTTT(con))
return false;
const FloatV dist0 = FSub(max0, min1);
const FloatV dist1 = FSub(max1, min0);
if (FAllGrtr(dist0, dist1))
axis = V3Neg(axis);
const FloatV dist = FMin(dist0, dist1);
if (FAllGrtr(bestDist, dist))
{
bestDist = dist;
bestAxis = axis;
bestEdgeIndex = convexEdgeIdx;
bestTriStart = kStart;
bestTriEnd = kEnd;
}
}
}
}
if (FAllGrtr(minOverlap, bestDist))
{
minOverlap = bestDist;
minNormal = bestAxis;
status = edgeStatus;
}
return true;
}
#endif
#if EDGE_EDGE_GAUSS_MAP
static bool isMinkowskiFace(const Vec3V& A, const Vec3V& B, const Vec3V& B_x_A, const Vec3V& C, const Vec3V& D, const Vec3V& D_x_C)
{
const FloatV zero = FZero();
// Two edges build a face on the Minkowski sum if the associated arcs AB and CD intersect on the Gauss map.
// The associated arcs are defined by the adjacent face normals of each edge.
const FloatV CBA = V3Dot(C, B_x_A);
const FloatV DBA = V3Dot(D, B_x_A);
const FloatV ADC = V3Dot(A, D_x_C);
const FloatV BDC = V3Dot(B, D_x_C);
const BoolV con0 = FIsGrtrOrEq(zero, FMul(CBA, DBA));
const BoolV con1 = FIsGrtrOrEq(zero, FMul(ADC, BDC));
const BoolV con2 = FIsGrtr(FMul(CBA, BDC), zero);
const BoolV con = BAnd(con2, BAnd(con0, con1));
return (BAllEqTTTT(con) != 0);
//return CBA * DBA < 0.0f && ADC * BDC < 0.0f && CBA * BDC > 0.0f;
}
#define SAT_VARIFY 0
static bool testPolyEdgeNormalGaussMap(const TriangleV& triangle, PxU8 /*triFlags*/, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* /*triMap*/, const SupportLocal* polyMap, const FloatVArg contactDist,
FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status, PxU32& gaussMapBestEdgeIndex, PxI8& gaussMapBestTriStart, PxI8& gaussMapBestTriEnd)
{
const FloatV zero = FZero();
const Vec3V triNormal = triangle.normal();
const PxU32 numConvexEdges = polyData.mNbEdges;
const PxU16* verticesByEdges16 = polyData.mVerticesByEdges;
const PxU8* facesByEdges8 = polyData.mFacesByEdges;
const PxVec3* vertices = polyData.mVerts;
FloatV bestDist = FLoad(-PX_MAX_F32);
Vec3V axis = V3Zero();
Vec3V bestAxis = V3Zero();
const Vec3V eps2 = V3Splat(FLoad(1e-6));
//Center is in shape space
const Vec3V shapeSpaceCOM = V3LoadU(polyData.mCenter);
const Vec3V vertexSpaceCOM = M33MulV3(polyMap->shape2Vertex, shapeSpaceCOM);
PxVec3 vertexCOM;
V3StoreU(vertexSpaceCOM, vertexCOM);
for (PxU32 convexEdgeIdx = 0; convexEdgeIdx < numConvexEdges; ++convexEdgeIdx)
{
const PxU16 v0idx1 = verticesByEdges16[convexEdgeIdx*2];
const PxU32 v1idx1 = verticesByEdges16[convexEdgeIdx * 2 + 1];
const PxU8 f10 = facesByEdges8[convexEdgeIdx * 2];
const PxU8 f11 = facesByEdges8[convexEdgeIdx * 2 + 1];
//shape sapce
const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v0idx1]));
const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v1idx1]));
Vec3V convexEdge = V3Sub(vertex11, vertex10);
const HullPolygonData& face0 = polyData.mPolygons[f10];
const HullPolygonData& face1 = polyData.mPolygons[f11];
const Vec3V convexNormal0 = M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(face0.mPlane.n));
const Vec3V convexNormal1 = M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(face1.mPlane.n));
float signDist0 = face0.mPlane.distance(vertexCOM);
float signDist1 = face1.mPlane.distance(vertexCOM);
PX_ASSERT(signDist0 < 0.f);
PX_ASSERT(signDist1 < 0.f);
for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++)
{
const Vec3V triVert0 = triangle.verts[kStart];
const Vec3V triVert1 = triangle.verts[kEnd];
const Vec3V triEdge = V3Sub(triVert1, triVert0);
//if (isMinkowskiFace(convexNormal0, convexNormal1, V3Neg(convexEdge), V3Neg(triNormal), triNormal, V3Neg(triEdge)))
if (isMinkowskiFace(convexNormal0, convexNormal1, convexEdge, V3Neg(triNormal), triNormal, triEdge))
{
// compute the separation along this axis in vertex space
axis = V3Cross(convexEdge, triEdge);
if (!V3AllGrtr(eps2, V3Abs(axis)))
{
axis = V3Normalize(axis);
const Vec3V v = V3Sub(vertex10, shapeSpaceCOM);
// ensure the axis is outward pointing on the edge on the minkowski sum. Assure normal points from convex hull to triangle
const FloatV temp = V3Dot(axis, v);
if (FAllGrtr(zero, temp))
axis = V3Neg(axis);
//compute the distance from any of the verts in the triangle to plane(axis, vertex10)(n.dot(p-a))
const Vec3V ap = V3Sub(triVert0, vertex10);
const FloatV dist = V3Dot(axis, ap);
if (FAllGrtr(dist, contactDist))
return false;
#if SAT_VARIFY
FloatV min0, max0;
FloatV min1, max1;
triMap->doSupport(V3Neg(axis), min0, max0);
polyMap->doSupport(V3Neg(axis), min1, max1);
const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist)));
if (BAllEqTTTT(con))
return false;
/*const FloatV dist = FSub(max0, min1);
if (FAllGrtr(bestDist, dist))
{
bestDist = dist;
bestAxis = axis;
}*/
const FloatV tempDist = FSub(max0, min1);
const FloatV dif = FAbs(FAdd(tempDist, dist));
PX_UNUSED(dif);
PX_ASSERT(FAllGrtr(FLoad(1e-4f), dif));
#endif
if (FAllGrtr(dist, bestDist))
{
bestDist = dist;
bestAxis = axis;
gaussMapBestEdgeIndex = convexEdgeIdx;
gaussMapBestTriStart = kStart;
gaussMapBestTriEnd = kEnd;
}
}
}
}
}
if (FAllGrtr(minOverlap, bestDist))
{
minOverlap = bestDist;
minNormal = bestAxis;
status = edgeStatus;
}
return true;
}
#endif
static PX_FORCE_INLINE PxU32 addMeshContacts(MeshPersistentContact* manifoldContacts, const Vec3V& pA, const Vec3V& pB, const Vec4V& normalPen, PxU32 triangleIndex, PxU32 numContacts)
{
manifoldContacts[numContacts].mLocalPointA = pA;
manifoldContacts[numContacts].mLocalPointB = pB;
manifoldContacts[numContacts].mLocalNormalPen = normalPen;
manifoldContacts[numContacts].mFaceIndex = triangleIndex;
return numContacts+1;
}
static void generatedTriangleContacts(const TriangleV& triangle, PxU32 triangleIndex, PxU8/* _triFlags*/, const PolygonalData& polyData1, const HullPolygonData& incidentPolygon, const SupportLocal* map1, MeshPersistentContact* manifoldContacts, PxU32& numManifoldContacts,
const FloatVArg contactDist, const Vec3VArg contactNormal, PxRenderOutput* renderOutput)
{
PX_UNUSED(renderOutput);
//PxU8 triFlags = _triFlags;
const PxU32 previousContacts = numManifoldContacts;
const FloatV zero = FZero();
const Mat33V rot = findRotationMatrixFromZAxis(contactNormal);
const PxU8* inds1 = polyData1.mPolygonVertexRefs + incidentPolygon.mVRef8;
Vec3V points0In0[3];
Vec3V* points1In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*incidentPolygon.mNbVerts, 16));
FloatV* points1In0TValue = reinterpret_cast<FloatV*>(PxAllocaAligned(sizeof(FloatV)*incidentPolygon.mNbVerts, 16));
bool* points1In0Penetration = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*incidentPolygon.mNbVerts));
points0In0[0] = triangle.verts[0];
points0In0[1] = triangle.verts[1];
points0In0[2] = triangle.verts[2];
//Transform all the verts from vertex space to shape space
map1->populateVerts(inds1, incidentPolygon.mNbVerts, polyData1.mVerts, points1In0);
#if PCM_LOW_LEVEL_DEBUG
PersistentContactManifold::drawPolygon(*renderOutput, map1->transform, points1In0, incidentPolygon.mNbVerts, (PxU32)PxDebugColor::eARGB_RED);
//PersistentContactManifold::drawTriangle(*renderOutput, map1->transform.transform(points1In0[0]), map1->transform.transform(points0In0[1]), map1->transform.transform(points0In0[2]), (PxU32)PxDebugColor::eARGB_BLUE);
#endif
Vec3V eps = Vec3V_From_FloatV(FEps());
Vec3V max = Vec3V_From_FloatV(FMax());
Vec3V nmax = V3Neg(max);
//transform reference polygon to 2d, calculate min and max
Vec3V rPolygonMin= max;
Vec3V rPolygonMax = nmax;
for(PxU32 i=0; i<3; ++i)
{
points0In0[i] = M33MulV3(rot, points0In0[i]);
rPolygonMin = V3Min(rPolygonMin, points0In0[i]);
rPolygonMax = V3Max(rPolygonMax, points0In0[i]);
}
rPolygonMin = V3Sub(rPolygonMin, eps);
rPolygonMax = V3Add(rPolygonMax, eps);
const FloatV d = V3GetZ(points0In0[0]);
const FloatV rd = FAdd(d, contactDist);
Vec3V iPolygonMin= max;
Vec3V iPolygonMax = nmax;
PxU32 inside = 0;
for(PxU32 i=0; i<incidentPolygon.mNbVerts; ++i)
{
const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space
points1In0[i] = M33MulV3(rot, vert1);
const FloatV z = V3GetZ(points1In0[i]);
points1In0TValue[i] = FSub(z, d);
points1In0[i] = V3SetZ(points1In0[i], d);
iPolygonMin = V3Min(iPolygonMin, points1In0[i]);
iPolygonMax = V3Max(iPolygonMax, points1In0[i]);
bool penetrated = false;
if(FAllGrtr(rd, z))
{
penetrated = true;
if(contains(points0In0, 3, points1In0[i], rPolygonMin, rPolygonMax))
{
inside++;
//add this contact to the buffer
const FloatV t = V3Dot(contactNormal, V3Sub(triangle.verts[0], vert1));
const Vec3V projectPoint = V3ScaleAdd(contactNormal, t, vert1);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), FNeg(t));
numManifoldContacts = addMeshContacts(manifoldContacts, vert1, projectPoint, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(6) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
points1In0Penetration[i] = penetrated;
}
if(inside == incidentPolygon.mNbVerts)
return;
inside = 0;
iPolygonMin = V3Sub(iPolygonMin, eps);
iPolygonMax = V3Add(iPolygonMax, eps);
const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n)));
const FloatV iPlaneD = V3Dot(incidentNormal, M33MulV3(map1->vertex2Shape, V3LoadU(polyData1.mVerts[inds1[0]])));
for(PxU32 i=0; i<3; ++i)
{
if(contains(points1In0, incidentPolygon.mNbVerts, points0In0[i], iPolygonMin, iPolygonMax))
{
inside++;
const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]);
const FloatV t = FSub(V3Dot(incidentNormal, vert0), iPlaneD);
if(FAllGrtr(t, contactDist))
continue;
const Vec3V projPoint = V3NegScaleSub(incidentNormal, t, vert0);
const Vec3V v = V3Sub(projPoint, vert0);
const FloatV t3 = V3Dot(v, contactNormal);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), t3);
numManifoldContacts = addMeshContacts(manifoldContacts, projPoint, vert0, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
if(inside == 3)
return;
//(2) segment intersection
for(PxU32 rStart = 0, rEnd = 2; rStart < 3; rEnd = rStart++)
{
const Vec3V rpA = points0In0[rStart];
const Vec3V rpB = points0In0[rEnd];
const Vec3V rMin = V3Min(rpA, rpB);
const Vec3V rMax = V3Max(rpA, rpB);
for(PxU32 iStart = 0, iEnd = PxU32(incidentPolygon.mNbVerts - 1); iStart < incidentPolygon.mNbVerts; iEnd = iStart++)
{
if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd]))//|| (points1In0[i].status == POINT_OUTSIDE && points1In0[incidentIndex].status == POINT_OUTSIDE))
continue;
const Vec3V ipA = points1In0[iStart];
const Vec3V ipB = points1In0[iEnd];
const Vec3V iMin = V3Min(ipA, ipB);
const Vec3V iMax = V3Max(ipA, ipB);
const BoolV tempCon = BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax));
const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon));
if(BAllEqTTTT(con))
continue;
const FloatV a1 = signed2DTriArea(rpA, rpB, ipA);
const FloatV a2 = signed2DTriArea(rpA, rpB, ipB);
if(FAllGrtr(zero, FMul(a1, a2)))
{
const FloatV a3 = signed2DTriArea(ipA, ipB, rpA);
const FloatV a4 = signed2DTriArea(ipA, ipB, rpB);
if(FAllGrtr(zero, FMul(a3, a4)))
{
//these two segment intersect in 2d
const FloatV t = FMul(a1, FRecip(FSub(a2, a1)));
const Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d));
const Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d));
const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri);
const Vec3V pAA = V3SetZ(pBB, d);
const Vec3V pA = M33TrnspsMulV3(rot, pAA);
const Vec3V pB = M33TrnspsMulV3(rot, pBB);
const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA));
if(FAllGrtr(pen, contactDist))
continue;
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), pen);
numManifoldContacts = addMeshContacts(manifoldContacts, pB, pA, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
}
}
}
static void generatedPolyContacts(const PolygonalData& polyData0, const HullPolygonData& referencePolygon, const TriangleV& triangle, PxU32 triangleIndex, PxU8 triFlags,
const SupportLocal* map0, MeshPersistentContact* manifoldContacts, PxU32& numManifoldContacts, const FloatVArg contactDist, const Vec3VArg contactNormal, PxRenderOutput* renderOutput)
{
PX_UNUSED(triFlags);
PX_UNUSED(renderOutput);
const FloatV zero = FZero();
const PxU32 previousContacts = numManifoldContacts;
const PxU8* inds0 = polyData0.mPolygonVertexRefs + referencePolygon.mVRef8;
const Vec3V nContactNormal = V3Neg(contactNormal);
//this is the matrix transform all points to the 2d plane
const Mat33V rot = findRotationMatrixFromZAxis(contactNormal);
Vec3V* points0In0=reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16));
Vec3V points1In0[3];
FloatV points1In0TValue[3];
bool points1In0Penetration[3] = { false, false, false };
//Transform all the verts from vertex space to shape space
map0->populateVerts(inds0, referencePolygon.mNbVerts, polyData0.mVerts, points0In0);
points1In0[0] = triangle.verts[0];
points1In0[1] = triangle.verts[1];
points1In0[2] = triangle.verts[2];
#if PCM_LOW_LEVEL_DEBUG
PersistentContactManifold::drawPolygon(*renderOutput, map0->transform, points0In0, referencePolygon.mNbVerts, (PxU32)PxDebugColor::eARGB_GREEN);
//PersistentContactManifold::drawTriangle(*gRenderOutPut, map0->transform.transform(points1In0[0]), map0->transform.transform(points1In0[1]), map0->transform.transform(points1In0[2]), (PxU32)PxDebugColor::eARGB_BLUE);
#endif
//the first point in the reference plane
const Vec3V referencePoint = points0In0[0];
Vec3V eps = Vec3V_From_FloatV(FEps());
Vec3V max = Vec3V_From_FloatV(FMax());
Vec3V nmax = V3Neg(max);
//transform reference polygon to 2d, calculate min and max
Vec3V rPolygonMin= max;
Vec3V rPolygonMax = nmax;
for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i)
{
//points0In0[i].vertext = M33TrnspsMulV3(rot, Vec3V_From_PxVec3(polyData0.mVerts[inds0[i]]));
points0In0[i] = M33MulV3(rot, points0In0[i]);
rPolygonMin = V3Min(rPolygonMin, points0In0[i]);
rPolygonMax = V3Max(rPolygonMax, points0In0[i]);
}
rPolygonMin = V3Sub(rPolygonMin, eps);
rPolygonMax = V3Add(rPolygonMax, eps);
const FloatV d = V3GetZ(points0In0[0]);
const FloatV rd = FAdd(d, contactDist);
Vec3V iPolygonMin= max;
Vec3V iPolygonMax = nmax;
PxU32 inside = 0;
for(PxU32 i=0; i<3; ++i)
{
const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space
points1In0[i] = M33MulV3(rot, vert1);
const FloatV z = V3GetZ(points1In0[i]);
points1In0TValue[i] = FSub(z, d);
points1In0[i] = V3SetZ(points1In0[i], d);
iPolygonMin = V3Min(iPolygonMin, points1In0[i]);
iPolygonMax = V3Max(iPolygonMax, points1In0[i]);
if(FAllGrtr(rd, z))
{
points1In0Penetration[i] = true;
//ML : check to see whether all the points of triangles in 2D space are within reference polygon's range
if(contains(points0In0, referencePolygon.mNbVerts, points1In0[i], rPolygonMin, rPolygonMax))
{
inside++;
//calculate projection point
const FloatV t = V3Dot(contactNormal, V3Sub(vert1, referencePoint));
const Vec3V projectPoint = V3NegScaleSub(contactNormal, t, vert1);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), t);
numManifoldContacts = addMeshContacts(manifoldContacts, projectPoint, vert1, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
}
if(inside == 3)
return;
inside = 0;
iPolygonMin = V3Sub(iPolygonMin, eps);
iPolygonMax = V3Add(iPolygonMax, eps);
const Vec3V incidentNormal = triangle.normal();
const FloatV iPlaneD = V3Dot(incidentNormal, triangle.verts[0]);
const FloatV one = FOne();
for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i)
{
if(contains(points1In0, 3, points0In0[i], iPolygonMin, iPolygonMax))
{
const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]);
const FloatV t = FSub(V3Dot(incidentNormal, vert0), iPlaneD);
if(FAllGrtr(t, contactDist))
continue;
const Vec3V projPoint = V3NegScaleSub(incidentNormal, t, vert0);
FloatV u, w;
barycentricCoordinates(projPoint, triangle.verts[0], triangle.verts[1], triangle.verts[2], u, w);
const BoolV con = BAnd(FIsGrtrOrEq(u, zero), BAnd(FIsGrtrOrEq(w, zero), FIsGrtrOrEq(one, FAdd(u, w))));
if(BAllEqTTTT(con))
{
inside++;
const Vec3V v = V3Sub(projPoint, vert0);
const FloatV t3 = V3Dot(v, contactNormal);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), t3);
numManifoldContacts = addMeshContacts(manifoldContacts, vert0, projPoint, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
}
if(inside == referencePolygon.mNbVerts)
return;
//Always generate segment contacts
//(2) segment intersection
for(PxU32 iStart = 0, iEnd = 2; iStart < 3; iEnd = iStart++)
{
if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd] ) )
continue;
const Vec3V ipA = points1In0[iStart];
const Vec3V ipB = points1In0[iEnd];
const Vec3V iMin = V3Min(ipA, ipB);
const Vec3V iMax = V3Max(ipA, ipB);
for(PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++)
{
const Vec3V rpA = points0In0[rStart];
const Vec3V rpB = points0In0[rEnd];
const Vec3V rMin = V3Min(rpA, rpB);
const Vec3V rMax = V3Max(rpA, rpB);
const BoolV tempCon = BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax));
const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon));
if(BAllEqTTTT(con))
continue;
const FloatV a1 = signed2DTriArea(rpA, rpB, ipA);
const FloatV a2 = signed2DTriArea(rpA, rpB, ipB);
if(FAllGrtr(zero, FMul(a1, a2)))
{
const FloatV a3 = signed2DTriArea(ipA, ipB, rpA);
const FloatV a4 = signed2DTriArea(ipA, ipB, rpB);
if(FAllGrtr(zero, FMul(a3, a4)))
{
//these two segment intersect
const FloatV t = FMul(a1, FRecip(FSub(a2, a1)));
const Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d));
const Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d));
const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri);
const Vec3V pAA = V3SetZ(pBB, d);
const Vec3V pA = M33TrnspsMulV3(rot, pAA);
const Vec3V pB = M33TrnspsMulV3(rot, pBB);
const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA));
if(FAllGrtr(pen, contactDist))
continue;
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), pen);
numManifoldContacts = addMeshContacts(manifoldContacts, pA, pB, localNormalPen, triangleIndex, numManifoldContacts);
//if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction
const PxU32 numContacts = numManifoldContacts - previousContacts;
if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
//a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce
//the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points
SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts);
numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
}
}
}
}
}
bool Gu::PCMConvexVsMeshContactGeneration::generateTriangleFullContactManifold(const TriangleV& localTriangle, PxU32 triangleIndex, const PxU32* triIndices, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* localTriMap, const SupportLocal* polyMap, MeshPersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, Vec3V& patchNormal)
{
FeatureStatus status = POLYDATA0;
FloatV minOverlap = FMax();
//minNormal will be in the local space of polyData
Vec3V minNormal = V3Zero();
PxU32 feature0;
if(!testTriangleFaceNormal(localTriangle, polyData, localTriMap, polyMap, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status))
return false;
PxU32 feature1;
if(!testPolyFaceNormal(polyData, localTriMap, polyMap, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status))
return false;
if(!testPolyEdgeNormal(localTriangle, triFlags, polyData, localTriMap, polyMap, contactDist, minOverlap, minNormal, EDGE, status))
return false;
const Vec3V triNormal = localTriangle.normal();
if(status == POLYDATA0)
{
//minNormal is the triangle normal and it is in the local space of polydata0
PxI32 index2;
PxI32 polyIndex = getPolygonIndex(polyData, polyMap, minNormal, index2);
const HullPolygonData& referencePolygon = polyData.mPolygons[polyIndex];
patchNormal = triNormal;
generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput);
if(index2 != -1)
{
generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, polyData.mPolygons[index2], polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput);
}
}
else
{
if(status == POLYDATA1)
{
const HullPolygonData* referencePolygon = &polyData.mPolygons[feature1];
const FloatV cosTheta = V3Dot(V3Neg(minNormal), triNormal);
const FloatV threshold = FLoad(0.707106781f);//about 45 degree0
if(FAllGrtr(cosTheta, threshold))
{
patchNormal = triNormal;
generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, *referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput);
}
else
{
//ML : defer the contacts generation
if(mSilhouetteEdgesAreActive ||
!(triFlags & (ETD_SILHOUETTE_EDGE_01 | ETD_SILHOUETTE_EDGE_12 | ETD_SILHOUETTE_EDGE_20)))
{
const PxU32 nb = sizeof(PCMDeferredPolyData) / sizeof(PxU32);
PxU32 newSize = nb + mDeferredContacts->size();
if(mDeferredContacts->capacity() < newSize)
mDeferredContacts->reserve((newSize+1)*2);
PCMDeferredPolyData* PX_RESTRICT data = reinterpret_cast<PCMDeferredPolyData*>(mDeferredContacts->end());
mDeferredContacts->forceSize_Unsafe(newSize);
data->mTriangleIndex = triangleIndex;
data->mFeatureIndex = feature1;
data->triFlags32 = PxU32(triFlags);
data->mInds[0] = triIndices[0];
data->mInds[1] = triIndices[1];
data->mInds[2] = triIndices[2];
V3StoreU(localTriangle.verts[0], data->mVerts[0]);
V3StoreU(localTriangle.verts[1], data->mVerts[1]);
V3StoreU(localTriangle.verts[2], data->mVerts[2]);
}
return true;
}
}
else
{
PxI32 index2;
feature1 = PxU32(getPolygonIndex(polyData, polyMap, minNormal, index2));
const HullPolygonData* referencePolygon = &polyData.mPolygons[feature1];
const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(referencePolygon->mPlane.n)));
const Vec3V nContactNormal = V3Neg(contactNormal);
//if the minimum sperating axis is edge case, we don't defer it because it is an activeEdge
patchNormal = nContactNormal;
generatedPolyContacts(polyData, *referencePolygon, localTriangle, triangleIndex, triFlags, polyMap, manifoldContacts, numContacts, contactDist, contactNormal, mRenderOutput);
}
}
return true;
}
bool Gu::PCMConvexVsMeshContactGeneration::generateTriangleFullContactManifold(const TriangleV& localTriangle, PxU32 triangleIndex, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* localTriMap, const SupportLocal* polyMap, MeshPersistentContact* manifoldContacts, PxU32& numContacts,
const FloatVArg contactDist, Vec3V& patchNormal, PxRenderOutput* renderOutput)
{
const FloatV threshold = FLoad(0.7071f);//about 45 degree
PX_UNUSED(threshold);
{
FeatureStatus status = POLYDATA0;
FloatV minOverlap = FMax();
//minNormal will be in the local space of polyData
Vec3V minNormal = V3Zero();
PxU32 feature0;
if(!testTriangleFaceNormal(localTriangle, polyData, localTriMap, polyMap, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status))
return false;
PxU32 feature1;
if(!testPolyFaceNormal(polyData, localTriMap, polyMap, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status))
return false;
if(!testPolyEdgeNormal(localTriangle, triFlags, polyData, localTriMap, polyMap, contactDist, minOverlap, minNormal, EDGE, status))
return false;
const Vec3V triNormal = localTriangle.normal();
patchNormal = triNormal;
const HullPolygonData* referencePolygon = &polyData.mPolygons[getPolygonIndex(polyData, polyMap, triNormal)];
generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, *referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, renderOutput);
}
return true;
}
bool Gu::PCMConvexVsMeshContactGeneration::generatePolyDataContactManifold(const TriangleV& localTriangle, PxU32 featureIndex, PxU32 triangleIndex, PxU8 triFlags, MeshPersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& patchNormal)
{
const HullPolygonData* referencePolygon = &mPolyData.mPolygons[featureIndex];
const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(mPolyMap->shape2Vertex, V3LoadU(referencePolygon->mPlane.n)));
const Vec3V nContactNormal = V3Neg(contactNormal);
patchNormal = nContactNormal;
generatedPolyContacts(mPolyData, *referencePolygon, localTriangle, triangleIndex, triFlags, mPolyMap, manifoldContacts, numContacts, contactDist, contactNormal, mRenderOutput);
return true;
}
| 43,008 | C++ | 36.108714 | 340 | 0.729887 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereCapsule.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 "GuVecSphere.h"
#include "GuVecCapsule.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
using namespace aos;
static PX_FORCE_INLINE FloatV distancePointSegmentSquared(const Vec3VArg a, const Vec3VArg b, const Vec3VArg p, FloatV& param)
{
const FloatV zero = FZero();
const FloatV one = FOne();
const Vec3V ap = V3Sub(p, a);
const Vec3V ab = V3Sub(b, a);
const FloatV nom = V3Dot(ap, ab);
const FloatV denom = V3Dot(ab, ab);
const FloatV tValue = FClamp(FDiv(nom, denom), zero, one);
const FloatV t = FSel(FIsEq(denom, zero), zero, tValue);
const Vec3V v = V3NegScaleSub(ab, t, ap);
param = t;
return V3Dot(v, v);
}
bool Gu::pcmContactSphereCapsule(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(cache);
PX_UNUSED(renderOutput);
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1);
//Sphere in world space
const Vec3V sphereCenter = 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 capsuleRadius = FLoad(shapeCapsule.radius);
const FloatV cDist = FLoad(params.mContactDistance);
//const FloatV r0 = FloatV_From_F32(shapeCapsule.radius);
const FloatV halfHeight0 = FLoad(shapeCapsule.halfHeight);
const Vec3V basisVector0 = QuatGetBasisVector0(q1);
const Vec3V tmp0 = V3Scale(basisVector0, halfHeight0);
const Vec3V s = V3Add(p1, tmp0);
const Vec3V e = V3Sub(p1, tmp0);
const FloatV radiusSum = FAdd(sphereRadius, capsuleRadius);
const FloatV inflatedSum = FAdd(radiusSum, cDist);
// Collision detection
FloatV t;
const FloatV squareDist = distancePointSegmentSquared(s, e, sphereCenter, t);
const FloatV sqInflatedSum = FMul(inflatedSum, inflatedSum);
if(FAllGrtr(sqInflatedSum, squareDist))//BAllEq(con, bTrue))
{
const Vec3V p = V3ScaleAdd(V3Sub(e, s), t, s);
const Vec3V dir = V3Sub(sphereCenter, p);
const Vec3V normal = V3NormalizeSafe(dir, V3UnitX());
const Vec3V point = V3NegScaleSub(normal, sphereRadius, sphereCenter);//transform back to the world space
const FloatV dist = FSub(FSqrt(squareDist), radiusSum);
//context.mContactBuffer.contact(point, normal, FSub(FSqrt(squareDist), radiusSum));
return outputSimplePCMContact(contactBuffer, point, normal, dist);
}
return false;
}
| 4,174 | C++ | 39.53398 | 126 | 0.756349 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexMesh.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 "GuPCMShapeConvex.h"
#include "GuConvexUtilsInternal.h"
#include "GuPCMContactConvexCommon.h"
#include "GuPCMContactMeshCallback.h"
#include "GuIntersectionTriangleBox.h"
#include "GuBox.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
using namespace aos;
namespace
{
struct PCMConvexVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback<PCMConvexVsMeshContactGenerationCallback>
{
PCMConvexVsMeshContactGenerationCallback& operator=(const PCMConvexVsMeshContactGenerationCallback&);
PCMConvexVsMeshContactGeneration mGeneration;
const BoxPadded& mBox;
PCMConvexVsMeshContactGenerationCallback(
const FloatVArg contactDistance,
const FloatVArg replaceBreakingThreshold,
const PxTransformV& convexTransform,
const PxTransformV& meshTransform,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
const PolygonalData& polyData,
const SupportLocal* polyMap,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts,
const FastVertex2ShapeScaling& convexScaling,
bool idtConvexScale,
const FastVertex2ShapeScaling& meshScaling,
const PxU8* extraTriData,
bool idtMeshScale,
bool silhouetteEdgesAreActive,
const BoxPadded& box,
PxRenderOutput* renderOutput = NULL
) :
PCMMeshContactGenerationCallback<PCMConvexVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale),
mGeneration(contactDistance, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer, polyData,
polyMap, delayedContacts, convexScaling, idtConvexScale, silhouetteEdgesAreActive, renderOutput),
mBox(box)
{
}
PX_FORCE_INLINE PxIntBool doTest(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2)
{
// PT: this one is safe because midphase vertices are directly passed to the function
return intersectTriangleBox(mBox, v0, v1, v2);
}
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMConvexVsMeshContactGeneration>(cache);
}
};
}
bool Gu::PCMContactConvexMesh(const PolygonalData& polyData, const SupportLocal* polyMap, const FloatVArg minMargin, const PxBounds3& hullAABB, const PxTriangleMeshGeometry& shapeMesh,
const PxTransform& transform0, const PxTransform& transform1,
PxReal contactDistance, PxContactBuffer& contactBuffer,
const FastVertex2ShapeScaling& convexScaling, const FastVertex2ShapeScaling& meshScaling,
bool idtConvexScale, bool idtMeshScale, MultiplePersistentContactManifold& multiManifold,
PxRenderOutput* renderOutput)
{
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 contactDist = FLoad(contactDistance);
//Transfer A into the local space of B
const PxTransformV convexTransform(p0, q0);//box
const PxTransformV meshTransform(p1, q1);//triangleMesh
const PxTransformV curTransform = meshTransform.transformInv(convexTransform);
if(multiManifold.invalidate(curTransform, minMargin))
{
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
////////////////////
const TriangleMesh* PX_RESTRICT meshData = _getMeshData(shapeMesh);
const Matrix34FromTransform world0(transform0);
const Matrix34FromTransform world1(transform1);
BoxPadded hullOBB;
computeHullOBB(hullOBB, hullAABB, contactDistance, world0, world1, meshScaling, idtMeshScale);
// Setup the collider
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts;
const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData();
PCMConvexVsMeshContactGenerationCallback blockCallback(
contactDist, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer,
polyData, polyMap, &delayedContacts, convexScaling, idtConvexScale, meshScaling, extraData, idtMeshScale, true,
hullOBB, renderOutput);
Midphase::intersectOBB(meshData, hullOBB, blockCallback, true);
PX_ASSERT(multiManifold.mNumManifolds <= GU_MAX_MANIFOLD_SIZE);
blockCallback.flushCache();
//This is very important
blockCallback.mGeneration.generateLastContacts();
blockCallback.mGeneration.processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE, false);
#if PCM_LOW_LEVEL_DEBUG
multiManifold.drawManifold(*renderOutput, transform0, transform1);
#endif
}
else
{
const PxMatTransformV aToB(curTransform);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f));
multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist);
}
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, meshTransform);
}
bool Gu::pcmContactConvexMesh(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0);
const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1);
const ConvexHullData* hullData = _getHullData(shapeConvex);
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const PxTransformV convexTransform = loadTransformA(transform0);
const bool idtScaleMesh = shapeMesh.scale.isIdentity();
FastVertex2ShapeScaling meshScaling;
if(!idtScaleMesh)
meshScaling.init(shapeMesh.scale);
FastVertex2ShapeScaling convexScaling;
PxBounds3 hullAABB;
PolygonalData polyData;
const bool idtScaleConvex = getPCMConvexData(shapeConvex, convexScaling, hullAABB, polyData);
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const PxReal toleranceScale = params.mToleranceLength;
const FloatV minMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceScale, GU_PCM_MESH_MANIFOLD_EPSILON);
const ConvexHullV convexHull(hullData, V3Zero(), vScale, vQuat, idtScaleConvex);
if(idtScaleConvex)
{
SupportLocalImpl<ConvexHullNoScaleV> convexMap(static_cast<const ConvexHullNoScaleV&>(convexHull), convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, true);
return PCMContactConvexMesh(polyData, &convexMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling,
meshScaling, idtScaleConvex, idtScaleMesh, multiManifold, renderOutput);
}
else
{
SupportLocalImpl<ConvexHullV> convexMap(convexHull, convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, false);
return PCMContactConvexMesh(polyData, &convexMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling,
meshScaling, idtScaleConvex, idtScaleMesh, multiManifold, renderOutput);
}
}
bool Gu::pcmContactBoxMesh(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0);
const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1);
const PxBounds3 hullAABB(-shapeBox.halfExtents, shapeBox.halfExtents);
const bool idtMeshScale = shapeMesh.scale.isIdentity();
FastVertex2ShapeScaling meshScaling;
if(!idtMeshScale)
meshScaling.init(shapeMesh.scale);
FastVertex2ShapeScaling idtScaling;
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV minMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength, GU_PCM_MESH_MANIFOLD_EPSILON);
const BoxV boxV(V3Zero(), boxExtents);
const PxTransformV boxTransform = loadTransformA(transform0);//box
PolygonalData polyData;
PCMPolygonalBox polyBox(shapeBox.halfExtents);
polyBox.getPolygonalData(&polyData);
const Mat33V identity = M33Identity();
SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity, true);
return PCMContactConvexMesh(polyData, &boxMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, idtScaling, meshScaling,
true, idtMeshScale, multiManifold, renderOutput);
}
| 10,213 | C++ | 40.520325 | 184 | 0.800255 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexHeightField.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 "GuPCMShapeConvex.h"
#include "GuHeightField.h"
#include "GuHeightFieldUtil.h"
#include "GuPCMContactConvexCommon.h"
#include "GuPCMContactMeshCallback.h"
#include "foundation/PxVecMath.h"
using namespace physx;
using namespace Gu;
using namespace aos;
namespace
{
struct PCMConvexVsHeightfieldContactGenerationCallback
: PCMHeightfieldContactGenerationCallback< PCMConvexVsHeightfieldContactGenerationCallback >
{
PCMConvexVsHeightfieldContactGenerationCallback& operator=(const PCMConvexVsHeightfieldContactGenerationCallback&);
PCMConvexVsMeshContactGeneration mGeneration;
PCMConvexVsHeightfieldContactGenerationCallback(
const FloatVArg contactDistance,
const FloatVArg replaceBreakingThreshold,
const PolygonalData& polyData,
const SupportLocal* polyMap,
const Cm::FastVertex2ShapeScaling& convexScaling,
bool idtConvexScale,
const PxTransformV& convexTransform,
const PxTransformV& heightfieldTransform,
const PxTransform& heightfieldTransform1,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
HeightFieldUtil& hfUtil,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts,
bool silhouetteEdgesAreActive,
PxRenderOutput* renderOutput = NULL
) :
PCMHeightfieldContactGenerationCallback< PCMConvexVsHeightfieldContactGenerationCallback >(hfUtil, heightfieldTransform1),
mGeneration(contactDistance, replaceBreakingThreshold, convexTransform, heightfieldTransform, multiManifold,
contactBuffer, polyData, polyMap, delayedContacts, convexScaling, idtConvexScale, silhouetteEdgesAreActive, renderOutput)
{
}
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMConvexVsMeshContactGeneration>(cache);
}
};
}
bool Gu::PCMContactConvexHeightfield(
const PolygonalData& polyData, const SupportLocal* polyMap, const FloatVArg minMargin,
const PxBounds3& hullAABB, const PxHeightFieldGeometry& shapeHeightfield,
const PxTransform& transform0, const PxTransform& transform1,
PxReal contactDistance, PxContactBuffer& contactBuffer,
const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale,
MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput)
{
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 contactDist = FLoad(contactDistance);
//Transfer A into the local space of B
const PxTransformV convexTransform(p0, q0);//box
const PxTransformV heightfieldTransform(p1, q1);//heightfield
const PxTransformV curTransform = heightfieldTransform.transformInv(convexTransform);
if(multiManifold.invalidate(curTransform, minMargin))
{
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
////////////////////
HeightFieldUtil hfUtil(shapeHeightfield);
const HeightField& hf = hfUtil.getHeightField();
////////////////////
/*const Cm::Matrix34 world0(transform0);
const Cm::Matrix34 world1(transform1);
const PxU8* PX_RESTRICT extraData = meshData->mExtraTrigData;*/
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts;
PCMConvexVsHeightfieldContactGenerationCallback blockCallback(
contactDist,
replaceBreakingThreshold,
polyData,
polyMap,
convexScaling,
idtConvexScale,
convexTransform,
heightfieldTransform,
transform1,
multiManifold,
contactBuffer,
hfUtil,
&delayedContacts,
!(hf.getFlags() & PxHeightFieldFlag::eNO_BOUNDARY_EDGES),
renderOutput
);
hfUtil.overlapAABBTriangles(transform0, transform1, hullAABB, blockCallback);
PX_ASSERT(multiManifold.mNumManifolds <= GU_MAX_MANIFOLD_SIZE);
blockCallback.mGeneration.generateLastContacts();
blockCallback.mGeneration.processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE, false);
}
else
{
const PxMatTransformV aToB(curTransform);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.6f));
multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist);
}
#if PCM_LOW_LEVEL_DEBUG
multiManifold.drawManifold(*renderOutput, convexTransform, heightfieldTransform);
#endif
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, heightfieldTransform);
}
bool Gu::pcmContactConvexHeightField(GU_CONTACT_METHOD_ARGS)
{
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0);
const PxHeightFieldGeometry& shapeHeightField = checkedCast<PxHeightFieldGeometry>(shape1);
const ConvexHullData* hullData = _getHullData(shapeConvex);
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const QuatV q0 = QuatVLoadA(&transform0.q.x);
const Vec3V p0 = V3LoadA(&transform0.p.x);
const PxTransformV convexTransform(p0, q0);
//const bool idtScaleMesh = shapeMesh.scale.isIdentity();
//Cm::FastVertex2ShapeScaling meshScaling;
//if(!idtScaleMesh)
// meshScaling.init(shapeMesh.scale);
Cm::FastVertex2ShapeScaling convexScaling;
PxBounds3 hullAABB;
PolygonalData polyData;
const bool idtScaleConvex = getPCMConvexData(shapeConvex, convexScaling, hullAABB, polyData);
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const PxReal toleranceLength = params.mToleranceLength;
const FloatV minMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength, GU_PCM_MESH_MANIFOLD_EPSILON);
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const ConvexHullV convexHull(hullData, V3Zero(), vScale, vQuat, shapeConvex.scale.isIdentity());
if(idtScaleConvex)
{
SupportLocalImpl<ConvexHullNoScaleV> convexMap(static_cast<const ConvexHullNoScaleV&>(convexHull), convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScaleConvex);
return PCMContactConvexHeightfield(polyData, &convexMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling,
idtScaleConvex, multiManifold, renderOutput);
}
else
{
SupportLocalImpl<ConvexHullV> convexMap(convexHull, convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScaleConvex);
return PCMContactConvexHeightfield(polyData, &convexMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling,
idtScaleConvex, multiManifold, renderOutput);
}
}
bool Gu::pcmContactBoxHeightField(GU_CONTACT_METHOD_ARGS)
{
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0);
const PxHeightFieldGeometry& shapeHeightField = checkedCast<PxHeightFieldGeometry>(shape1);
const PxVec3 ext = shapeBox.halfExtents + PxVec3(params.mContactDistance);
const PxBounds3 hullAABB(-ext, ext);
const Cm::FastVertex2ShapeScaling idtScaling;
const QuatV q0 = QuatVLoadA(&transform0.q.x);
const Vec3V p0 = V3LoadA(&transform0.p.x);
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
const PxReal toranceLength = params.mToleranceLength;
const FloatV minMargin = CalculatePCMBoxMargin(boxExtents, toranceLength, GU_PCM_MESH_MANIFOLD_EPSILON);
const BoxV boxV(V3Zero(), boxExtents);
const PxTransformV boxTransform(p0, q0);//box
PolygonalData polyData;
PCMPolygonalBox polyBox(shapeBox.halfExtents);
polyBox.getPolygonalData(&polyData);
const Mat33V identity = M33Identity();
//SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity);
SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity, true);
return PCMContactConvexHeightfield(polyData, &boxMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer,
idtScaling, true, multiManifold, renderOutput);
}
| 9,905 | C++ | 39.268293 | 184 | 0.798082 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereSphere.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 "foundation/PxVecTransform.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
bool Gu::pcmContactSphereSphere(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(cache);
PX_UNUSED(renderOutput);
using namespace aos;
const PxSphereGeometry& shapeSphere0 = checkedCast<PxSphereGeometry>(shape0);
const PxSphereGeometry& shapeSphere1 = checkedCast<PxSphereGeometry>(shape1);
const FloatV cDist = FLoad(params.mContactDistance);
const Vec3V p0 = V3LoadA(&transform0.p.x);
const Vec3V p1 = V3LoadA(&transform1.p.x);
const FloatV r0 = FLoad(shapeSphere0.radius);
const FloatV r1 = FLoad(shapeSphere1.radius);
const Vec3V _delta = V3Sub(p0, p1);
const FloatV distanceSq = V3Dot(_delta, _delta);
const FloatV radiusSum = FAdd(r0, r1);
const FloatV inflatedSum = FAdd(radiusSum, cDist);
if(FAllGrtr(FMul(inflatedSum, inflatedSum), distanceSq))
{
const FloatV eps = FLoad(0.00001f);
const FloatV dist = FSqrt(distanceSq);
const BoolV bCon = FIsGrtrOrEq(eps, dist);
const Vec3V normal = V3Sel(bCon, V3UnitX(), V3ScaleInv(_delta, dist));
const Vec3V point = V3ScaleAdd(normal, r1, p1);
const FloatV pen = FSub(dist, radiusSum);
return outputSimplePCMContact(contactBuffer, point, normal, pen);
}
return false;
}
| 3,016 | C++ | 42.099999 | 78 | 0.758952 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneBox.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 "GuVecBox.h"
#include "GuContactMethodImpl.h"
#include "GuPersistentContactManifold.h"
using namespace physx;
bool Gu::pcmContactPlaneBox(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(shape0);
PX_UNUSED(renderOutput);
using namespace aos;
PersistentContactManifold& manifold = cache.getManifold();
PxPrefetchLine(&manifold, 256);
// Get actual shape data
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1);
const PxTransformV transf0 = loadTransformA(transform1);//box transform
const PxTransformV transf1 = loadTransformA(transform0);//plane transform
//box to plane
const PxTransformV curTransf(transf1.transformInv(transf0));
//in world space
const Vec3V negPlaneNormal = V3Normalize(V3Neg(QuatGetBasisVector0(transf1.q)));
const FloatV contactDist = FLoad(params.mContactDistance);
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength);
const FloatV projectBreakingThreshold = FMul(boxMargin, FLoad(0.2f));
const PxU32 initialContacts = manifold.mNumContacts;
manifold.refreshContactPoints(curTransf, projectBreakingThreshold, contactDist);
const PxU32 newContacts = manifold.mNumContacts;
const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts));
if(bLostContacts || manifold.invalidate_PrimitivesPlane(curTransf, boxMargin, FLoad(0.2f)))
{
//ML:localNormal is the local space of plane normal, however, because shape1 is box and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints
//work out the correct pentration for points
const Vec3V localNormal = V3UnitX();
manifold.mNumContacts = 0;
manifold.setRelativeTransform(curTransf);
const PxMatTransformV aToB(curTransf);
const FloatV bx = V3GetX(boxExtents);
const FloatV by = V3GetY(boxExtents);
const FloatV bz = V3GetZ(boxExtents);
const FloatV nbx = FNeg(bx);
const FloatV nby = FNeg(by);
const FloatV nbz = FNeg(bz);
const Vec3V temp0 = V3Scale(aToB.getCol0(), bx);
const Vec3V temp1 = V3Scale(aToB.getCol1(), by);
const Vec3V temp2 = V3Scale(aToB.getCol2(), bz);
const Vec3V ntemp2 = V3Neg(temp2);
const FloatV px = V3GetX(aToB.p);
//box's points in the local space of plane
const Vec3V temp01 = V3Add(temp0, temp1);//(x, y)
const Vec3V temp02 = V3Sub(temp0, temp1);//(x, -y)
const FloatV s0 = V3GetX(V3Add(temp2, temp01));//(x, y, z)
const FloatV s1 = V3GetX(V3Add(ntemp2, temp01));//(x, y, -z)
const FloatV s2 = V3GetX(V3Add(temp2, temp02));//(x, -y, z)
const FloatV s3 = V3GetX(V3Add(ntemp2, temp02));//(x, -y, -z)
const FloatV s4 = V3GetX(V3Sub(temp2, temp02));//(-x, y, z)
const FloatV s5 = V3GetX(V3Sub(ntemp2, temp02));//(-x, y, -z)
const FloatV s6 = V3GetX(V3Sub(temp2, temp01));//(-x, -y, z)
const FloatV s7 = V3GetX(V3Sub(ntemp2, temp01));//(-x, -y, -z)
const FloatV acceptanceDist = FSub(contactDist, px);
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
PxU32 numContacts = 0;
if(FAllGrtr(acceptanceDist, s0))
{
const FloatV pen = FAdd(s0, px);
//(x, y, z)
manifoldContacts[numContacts].mLocalPointA = boxExtents;//aToB.transformInv(p);
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(boxExtents));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s1))
{
const FloatV pen = FAdd(s1, px);
//(x, y, -z)
const Vec3V p = V3Merge(bx, by, nbz);
//add to contact stream
manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p);
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s2))
{
const FloatV pen = FAdd(s2, px);
//(x, -y, z)
const Vec3V p = V3Merge(bx, nby, bz);
manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p);
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s3))
{
const FloatV pen = FAdd(s3, px);
//(x, -y, -z)
const Vec3V p = V3Merge(bx, nby, nbz);
manifoldContacts[numContacts].mLocalPointA = p;
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s4))
{
const FloatV pen = FAdd(s4, px);
//(-x, y, z)
const Vec3V p = V3Merge(nbx, by, bz);
manifoldContacts[numContacts].mLocalPointA = p;
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s5))
{
const FloatV pen = FAdd(s5, px);
//(-x, y, -z)
const Vec3V p = V3Merge(nbx, by, nbz);
manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p);
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s6))
{
const FloatV pen = FAdd(s6, px);
//(-x, -y, z)
const Vec3V p = V3Merge(nbx, nby, bz);
manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p);
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
if(FAllGrtr(acceptanceDist, s7))
{
const FloatV pen = FAdd(s7, px);
//(-x, -y, -z)
const Vec3V p = V3Merge(nbx, nby, nbz);
manifoldContacts[numContacts].mLocalPointA = p;
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p));
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
//reduce contacts
manifold.addBatchManifoldContactsCluster(manifoldContacts, numContacts);
manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist);
return manifold.getNumContacts() > 0;
}
else
{
manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist);
//manifold.drawManifold(*gRenderOutPut, transf0, transf1);
return manifold.getNumContacts() > 0;
}
}
| 8,603 | C++ | 39.971428 | 216 | 0.734511 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMTriangleContactGen.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_TRIANGLE_CONTACT_GEN_H
#define GU_PCM_TRIANGLE_CONTACT_GEN_H
#include "GuPCMContactGenUtil.h"
#include "GuPersistentContactManifold.h"
namespace physx
{
class PxTriangleMeshGeometry;
class PxHeightFieldGeometry;
namespace Gu
{
bool PCMContactConvexMesh(const Gu::PolygonalData& polyData0, const Gu::SupportLocal* polyMap, const aos::FloatVArg minMargin, const PxBounds3& hullAABB,
const PxTriangleMeshGeometry& shapeMesh,
const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer,
const Cm::FastVertex2ShapeScaling& convexScaling, const Cm::FastVertex2ShapeScaling& meshScaling,
bool idtConvexScale, bool idtMeshScale,
Gu::MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput);
bool PCMContactConvexHeightfield(const Gu::PolygonalData& polyData0, const Gu::SupportLocal* polyMap, const aos::FloatVArg minMargin, const PxBounds3& hullAABB,
const PxHeightFieldGeometry& shapeHeightfield,
const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer,
const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale,
Gu::MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput);
}
}
#endif
| 3,034 | C | 51.327585 | 162 | 0.782465 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactBoxBox.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 "GuGJKPenetration.h"
#include "GuEPA.h"
#include "GuVecBox.h"
#include "GuConvexHelper.h"
#include "GuPCMShapeConvex.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static void getIncidentPolygon(Vec3V* pts, Vec3V& faceNormal, const Vec3VArg axis, const PxMatTransformV& transf1To0, const Vec3VArg extents)
{
const FloatV zero = FZero();
FloatV ex = V3GetX(extents);
FloatV ey = V3GetY(extents);
FloatV ez = V3GetZ(extents);
const Vec3V u0 = transf1To0.getCol0();
const Vec3V u1 = transf1To0.getCol1();
const Vec3V u2 = transf1To0.getCol2();
//calculate the insident face for b
const FloatV d0 = V3Dot(u0, axis);
const FloatV d1 = V3Dot(u1, axis);
const FloatV d2 = V3Dot(u2, axis);
const FloatV absd0 = FAbs(d0);
const FloatV absd1 = FAbs(d1);
const FloatV absd2 = FAbs(d2);
if(FAllGrtrOrEq(absd0, absd1) && FAllGrtrOrEq(absd0, absd2))
{
//the incident face is on u0
const BoolV con = FIsGrtr(d0, zero);
faceNormal = V3Sel(con, V3Neg(u0), u0);
ex = FSel(con, FNeg(ex), ex);
const Vec3V r0 = V3Scale(u0, ex);
const Vec3V r1 = V3Scale(u1, ey);
const Vec3V r2 = V3Scale(u2, ez);
const Vec3V temp0 = V3Add(transf1To0.p, r0);
const Vec3V temp1 = V3Add(r1, r2);
const Vec3V temp2 = V3Sub(r1, r2);
pts[0] = V3Add(temp0, temp1); // (-x/x, y, z)
pts[1] = V3Add(temp0, temp2); // (-x/x, y, -z)
pts[2] = V3Sub(temp0, temp1); // (-x/x, -y, -z)
pts[3] = V3Sub(temp0, temp2); // (-x/x, -y, z)
}
else if(FAllGrtrOrEq(absd1, absd2))
{
//the incident face is on u1
const BoolV con = FIsGrtr(d1, zero);
faceNormal = V3Sel(con, V3Neg(u1), u1);
ey = FSel(con, FNeg(ey), ey);
const Vec3V r0 = V3Scale(u0, ex);
const Vec3V r1 = V3Scale(u1, ey);
const Vec3V r2 = V3Scale(u2, ez);
const Vec3V temp0 = V3Add(transf1To0.p, r1);
const Vec3V temp1 = V3Add(r0, r2);
const Vec3V temp2 = V3Sub(r0, r2);
pts[0] = V3Add(temp0, temp1); // (x, -y/y, z)
pts[1] = V3Add(temp0, temp2); // (x, -y/y, -z)
pts[2] = V3Sub(temp0, temp1); // (-x, -y/y, -z)
pts[3] = V3Sub(temp0, temp2); // (-x, -y/y, z)
}
else
{
//the incident face is on u2
const BoolV con = FIsGrtr(d2, zero);
faceNormal = V3Sel(con, V3Neg(u2), u2);
ez = FSel(con, FNeg(ez), ez);
const Vec3V r0 = V3Scale(u0, ex);
const Vec3V r1 = V3Scale(u1, ey);
const Vec3V r2 = V3Scale(u2, ez);
const Vec3V temp0 = V3Add(transf1To0.p, r2);
const Vec3V temp1 = V3Add(r0, r1);
const Vec3V temp2 = V3Sub(r0, r1);
pts[0] = V3Add(temp0, temp1); // ( x, y, z)
pts[1] = V3Add(temp0, temp2); // ( x, -y, z)
pts[2] = V3Sub(temp0, temp1); // (-x, -y, z)
pts[3] = V3Sub(temp0, temp2); // (-x, y, z)
}
}
//p0 and p1 is in the local space of AABB
static bool intersectSegmentAABB(const Vec3VArg p0, const Vec3VArg d, const Vec3VArg max, const Vec3VArg min, FloatV& tmin, FloatV& tmax)
{
const Vec3V eps = V3Load(1e-6f);
const Vec3V absV = V3Abs(d);
const FloatV one = FOne();
const Vec3V zero = V3Zero();
const Vec3V fMax = Vec3V_From_FloatV(FMax());
FloatV tminf = FZero();
FloatV tmaxf = one;
const BoolV isParallel = V3IsGrtr(eps, absV);
const BoolV isOutsideOfRange = BOr(V3IsGrtr(p0, max), V3IsGrtr(min, p0));
//const BoolV isParallelAndOutOfRange = BAnd(isParallel, isOutsideOfRange);
if(!BAllEqFFFF(BAnd(isParallel, isOutsideOfRange)))
return false;
const Vec3V odd = V3RecipFast(d);
const Vec3V t1 = V3Sel(isParallel, zero, V3Mul(V3Sub(min, p0), odd));
const Vec3V t2 = V3Sel(isParallel, fMax, V3Mul(V3Sub(max, p0), odd));
const Vec3V tt1 = V3Min(t1, t2);
const Vec3V tt2 = V3Max(t1, t2);
const FloatV ft1 = V3ExtractMax(tt1);
const FloatV ft2 = V3ExtractMin(tt2);
tminf = FMax(ft1, tminf);
tmaxf = FMin(tmaxf, ft2);
tmin = tminf;
tmax = tmaxf;
const BoolV con0 = FIsGrtr(tminf, tmaxf);
const BoolV con1 = FIsGrtr(tminf, one);
const BoolV isNotIntersect = BOr(con0, con1);
return BAllEqFFFF(isNotIntersect) == 1;
}
//pts, faceNormal and contact normal are in the local space of new space
static void calculateContacts(const FloatVArg extentX_, const FloatVArg extentY_, Vec3V* pts, const Vec3VArg incidentFaceNormalInNew, const Vec3VArg localNormal, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist)
{
const FloatV zero = FZero();
const FloatV max = FMax();
const FloatV eps = FLoad(1.0001f);
const FloatV extentX = FMul(extentX_, eps);
const FloatV extentY = FMul(extentY_, eps);
const FloatV nExtentX = FNeg(extentX);
const FloatV nExtentY = FNeg(extentY);
bool pPenetration[4];
bool pArea[4];
Vec3V bmin = V3Splat(max);
Vec3V bmax = V3Neg(bmin);
const Vec3V bound = V3Merge(extentX, extentY, max);
//get the projection point of pts
for(PxU32 i=0; i< 4; ++i)
{
bmin = V3Min(bmin, pts[i]);
bmax = V3Max(bmax, pts[i]);
const FloatV z = FNeg(V3GetZ(pts[i]));
if(FAllGrtr(contactDist, z))
{
pPenetration[i] = true;
const Vec3V absPt = V3Abs(pts[i]);
const BoolV con = V3IsGrtrOrEq(bound, absPt);
if(BAllEqTTTT(con))
{
pArea[i] = true;
//Add the point to the manifold
manifoldContacts[numContacts].mLocalPointA = V3SetZ(pts[i], zero); //transformNewTo0.transform(localPointA);
manifoldContacts[numContacts].mLocalPointB = pts[i];//transform1ToNew.transformInv(pts[i]);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), z);
}
else
{
pArea[i] = false;
}
}
else
{
pPenetration[i] = false;
pArea[i] = false;
}
}
if(numContacts == 4)
return;
//if(pPenetration[0] && pPenetration[1] && pPenetration[2] && pPenetration[3])
{
//if(!pArea[0] || !pArea[1] || !pArea[2] || !pArea[3])
{
const FloatV denom = V3GetZ(incidentFaceNormalInNew);
{
const Vec3V q0 = V3Merge(extentX, extentY, zero);
if(contains(pts, 4, q0, bmin, bmax))
{
const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0));
const FloatV t = FDiv(nom, denom);
const FloatV pen = FNeg(t);
if(FAllGrtr(contactDist, pen))
{
manifoldContacts[numContacts].mLocalPointA = q0;
manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
}
}
{
const Vec3V q0 = V3Merge(extentX, nExtentY, zero);
if(contains(pts, 4, q0, bmin, bmax))
{
const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0));
const FloatV t = FDiv(nom, denom);
const FloatV pen = FNeg(t);
if(FAllGrtr(contactDist, pen))
{
manifoldContacts[numContacts].mLocalPointA = q0;
manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
}
}
{
const Vec3V q0 = V3Merge( nExtentX, extentY, zero);
if(contains(pts, 4, q0, bmin, bmax))
{
const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0));
const FloatV t = FDiv(nom, denom);
const FloatV pen = FNeg(t);
if(FAllGrtr(contactDist, pen))
{
manifoldContacts[numContacts].mLocalPointA = q0;
manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
}
}
{
const Vec3V q0 = V3Merge(nExtentX, nExtentY, zero);
if(contains(pts, 4, q0, bmin, bmax))
{
const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0));
const FloatV t = FDiv(nom, denom);
const FloatV pen = FNeg(t);
if(FAllGrtr(contactDist, pen))
{
manifoldContacts[numContacts].mLocalPointA = q0;
manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen);
}
}
}
}
}
const Vec3V ext = V3Merge(extentX, extentY, max);
const Vec3V negExt = V3Merge(nExtentX, nExtentY, FNeg(FAdd(contactDist, FEps())));
for (PxU32 rStart = 0, rEnd = 3; rStart < 4; rEnd = rStart++)
{
const Vec3V p0 = pts[rStart];
const Vec3V p1 = pts[rEnd];
if(!pPenetration[rStart] && !pPenetration[rEnd])
continue;
const bool con0 = pPenetration[rStart] && pArea[rStart];
const bool con1 = pPenetration[rEnd] && pArea[rEnd];
if(con0 && con1)
continue;
//intersect t value with x plane
const Vec3V p0p1 = V3Sub(p1, p0);
FloatV tmin, tmax;
if(::intersectSegmentAABB(p0, p0p1, ext, negExt, tmin, tmax))
{
if(!con0)
{
const Vec3V intersectP = V3ScaleAdd(p0p1, tmin, p0);
manifoldContacts[numContacts].mLocalPointA = V3SetZ(intersectP, zero);
manifoldContacts[numContacts].mLocalPointB = intersectP;
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), FNeg(V3GetZ(intersectP)));
}
if(!con1)
{
const Vec3V intersectP = V3ScaleAdd(p0p1, tmax, p0);
manifoldContacts[numContacts].mLocalPointA = V3SetZ(intersectP, zero);
manifoldContacts[numContacts].mLocalPointB = intersectP;
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), FNeg(V3GetZ(intersectP)));
}
}
}
}
static PxU32 doBoxBoxGenerateContacts(const Vec3VArg box0Extent, const Vec3VArg box1Extent, const PxMatTransformV& transform0, const PxMatTransformV& transform1, const FloatVArg contactDist, PersistentContact* manifoldContacts, PxU32& numContacts)
{
const FloatV ea0 = V3GetX(box0Extent);
const FloatV ea1 = V3GetY(box0Extent);
const FloatV ea2 = V3GetZ(box0Extent);
const FloatV eb0 = V3GetX(box1Extent);
const FloatV eb1 = V3GetY(box1Extent);
const FloatV eb2 = V3GetZ(box1Extent);
const PxMatTransformV transform1To0 = transform0.transformInv(transform1);
const Mat33V rot0To1 =M33Trnsps(transform1To0.rot);
const Vec3V uEps = V3Load(1e-6f);
const FloatV zero = FZero();
const FloatV tx = V3GetX(transform1To0.p);
const FloatV ty = V3GetY(transform1To0.p);
const FloatV tz = V3GetZ(transform1To0.p);
const Vec3V col0 = transform1To0.getCol0();
const Vec3V col1 = transform1To0.getCol1();
const Vec3V col2 = transform1To0.getCol2();
const Vec3V abs1To0Col0 = V3Add(V3Abs(col0), uEps);
const Vec3V abs1To0Col1 = V3Add(V3Abs(col1), uEps);
const Vec3V abs1To0Col2 = V3Add(V3Abs(col2), uEps);
const Vec3V abs0To1Col0 = V3Add(V3Abs(rot0To1.col0), uEps);
const Vec3V abs0To1Col1 = V3Add(V3Abs(rot0To1.col1), uEps);
const Vec3V abs0To1Col2 = V3Add(V3Abs(rot0To1.col2), uEps);
FloatV sign[6];
FloatV overlap[6];
FloatV ra, rb, radiusSum;
//ua0
{
sign[0] = tx;
const Vec3V vtemp3 = V3Mul(abs0To1Col0, box1Extent);
rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ea0, rb);
overlap[0] = FAdd(FSub(radiusSum, FAbs(sign[0])), contactDist);
if(FAllGrtr(zero, overlap[0]))
return false;
}
//ua1
{
sign[1] = ty;
const Vec3V vtemp3 = V3Mul(abs0To1Col1, box1Extent);
rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ea1, rb);
overlap[1] = FAdd(FSub(radiusSum, FAbs(sign[1])), contactDist);
if(FAllGrtr(zero, overlap[1]))
return false;
}
//ua2
{
sign[2] = tz;
ra = ea2;
const Vec3V vtemp3 = V3Mul(abs0To1Col2, box1Extent);
rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ea2, rb);
overlap[2] = FAdd(FSub(radiusSum, FAbs(sign[2])), contactDist);
if(FAllGrtr(zero, overlap[2]))
return false;
}
//ub0
{
sign[3] = V3Dot(transform1To0.p, col0);
const Vec3V vtemp3 = V3Mul(abs1To0Col0, box0Extent);
ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ra, eb0);
overlap[3] = FAdd(FSub(radiusSum, FAbs(sign[3])), contactDist);
if(FAllGrtr(zero, overlap[3]))
return false;
}
//ub1
{
sign[4] = V3Dot(transform1To0.p, col1);
const Vec3V vtemp3 = V3Mul(abs1To0Col1, box0Extent);
ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ra, eb1);
overlap[4] = FAdd(FSub(radiusSum, FAbs(sign[4])), contactDist);
if(FAllGrtr(zero, overlap[4]))
return false;
}
//ub2
{
sign[5] = V3Dot(transform1To0.p, col2);
const Vec3V vtemp3 = V3Mul(abs1To0Col2, box0Extent);
ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3)));
radiusSum = FAdd(ra, eb2);
overlap[5] = FAdd(FSub(radiusSum, FAbs(sign[5])), contactDist);
if(FAllGrtr(zero, overlap[5]))
return false;
}
//ua0 X ub0
{
//B into A's space, ua0Xub0[0,-b3, b2]
const FloatV absSign = FAbs(FSub(FMul(V3GetY(col0), tz), FMul(V3GetZ(col0), ty)));
//B into A's space, ua0Xub0[0,-b3, b2]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col0), ea1);
const FloatV vtemp1 = FMul(V3GetY(abs1To0Col0), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub0[0, a3, -a2]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col0), eb1);
const FloatV vtemp02 = FMul(V3GetY(abs0To1Col0), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum)) return false;
}
//ua0 X ub1
{
//B into A's space, ua0Xub0[0, -b3, b2]
const FloatV absSign = FAbs(FSub(FMul(V3GetY(col1), tz), FMul(V3GetZ(col1), ty)));
//B into A's space, ua0Xub0[0, -b3, b2]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col1), ea1);
const FloatV vtemp1 = FMul(V3GetY(abs1To0Col1), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[-a3, 0, a1]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col0), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col0), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum)) return false;
}
//ua0 X ub2
{
//B into A's space, ua0Xub0[0, -b3, b2]
const FloatV absSign = FAbs(FSub(FMul(V3GetY(col2), tz), FMul(V3GetZ(col2), ty)));
//B into A's space, ua0Xub0[0, -b3, b2]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col2), ea1);
const FloatV vtemp1 = FMul(V3GetY(abs1To0Col2), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[a2, -a1, 0]
const FloatV vtemp01 = FMul(V3GetY(abs0To1Col0), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col0), eb1);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum)) return false;
}
//ua1 X ub0
{
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV absSign = FAbs(FSub(FMul(V3GetZ(col0), tx), FMul(V3GetX(col0), tz)));
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col0), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col0), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[0, a3, -a2]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col1), eb1);
const FloatV vtemp02 = FMul(V3GetY(abs0To1Col1), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
//ua1 X ub1
{
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV absSign = FAbs(FSub(FMul(V3GetZ(col1), tx), FMul(V3GetX(col1), tz)));
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col1), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col1), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[-a3, 0, -a1]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col1), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col1), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
//ua1 X ub2
{
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV absSign=FAbs(FSub(FMul(V3GetZ(col2), tx), FMul(V3GetX(col2), tz)));
//B into A's space, ua0Xub0[b3, 0, -b1]
const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col2), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col2), ea2);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[a2, -a1, 0]
const FloatV vtemp01 = FMul(V3GetY(abs0To1Col1), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col1), eb1);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
//ua2 X ub0
{
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV absSign = FAbs(FSub(FMul(V3GetX(col0), ty), FMul(V3GetY(col0), tx)));
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV vtemp0 = FMul(V3GetY(abs1To0Col0), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col0), ea1);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[0, a3, -a2]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col2), eb1);
const FloatV vtemp02 = FMul(V3GetY(abs0To1Col2), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
//ua2 X ub1
{
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV absSign = FAbs(FSub(FMul(V3GetX(col1), ty), FMul(V3GetY(col1), tx)));
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV vtemp0 = FMul(V3GetY(abs1To0Col1), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col1), ea1);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[-a3, 0, a1]
const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col2), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col2), eb2);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
//ua2 X ub2
{
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV absSign=FAbs(FSub(FMul(V3GetX(col2), ty), FMul(V3GetY(col2), tx)));
//B into A's space, ua2Xub0[-b2, b1, 0]
const FloatV vtemp0 = FMul(V3GetY(abs1To0Col2), ea0);
const FloatV vtemp1 = FMul(V3GetX(abs1To0Col2), ea1);
ra = FAdd(vtemp0, vtemp1);
//A into B's space, ua0Xub1[a2, -a1, 0]
const FloatV vtemp01 = FMul(V3GetY(abs0To1Col2), eb0);
const FloatV vtemp02 = FMul(V3GetX(abs0To1Col2), eb1);
rb = FAdd(vtemp01, vtemp02);
radiusSum = FAdd(FAdd(ra, rb), contactDist);
if(FAllGrtr(absSign, radiusSum))return false;
}
Vec3V mtd;
PxU32 feature = 0;
FloatV minOverlap = overlap[0];
for(PxU32 i=1; i<6; ++i)
{
if(FAllGrtr(minOverlap, overlap[i]))
{
minOverlap = overlap[i];
feature = i;
}
}
PxMatTransformV newTransformV;
const Vec3V axis00 = transform0.getCol0();
const Vec3V axis01 = transform0.getCol1();
const Vec3V axis02 = transform0.getCol2();
const Vec3V axis10 = transform1.getCol0();
const Vec3V axis11 = transform1.getCol1();
const Vec3V axis12 = transform1.getCol2();
Vec3V incidentFaceNormalInNew;
Vec3V pts[4];
bool flip = false;
switch(feature)
{
case 0: //ua0
{
if(FAllGrtrOrEq(zero, sign[0]))
{
mtd = axis00;
newTransformV.rot.col0 = V3Neg(axis02);
newTransformV.rot.col1 = axis01;
newTransformV.rot.col2 = axis00;
newTransformV.p = V3NegScaleSub(axis00, ea0, transform0.p);
}
else
{
const Vec3V nAxis00 = V3Neg(axis00);
mtd = nAxis00;
newTransformV.rot.col0 = axis02;
newTransformV.rot.col1 = axis01;
newTransformV.rot.col2 = nAxis00;
newTransformV.p = V3ScaleAdd(axis00, ea0, transform0.p);
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent);
calculateContacts(ea2, ea1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
};
case 1: //ua1
{
if(FAllGrtrOrEq(zero, sign[1]))
{
mtd = axis01;
newTransformV.rot.col0 = axis00;
newTransformV.rot.col1 = V3Neg(axis02);
newTransformV.rot.col2 = axis01;
newTransformV.p = V3NegScaleSub(axis01, ea1, transform0.p);
}
else
{
const Vec3V nAxis01 = V3Neg(axis01);
mtd = nAxis01;
newTransformV.rot.col0 = axis00;
newTransformV.rot.col1 = axis02;
newTransformV.rot.col2 = nAxis01;
newTransformV.p = V3ScaleAdd(axis01, ea1, transform0.p);
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent);
calculateContacts(ea0, ea2, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
};
case 2: //ua2
{
if(FAllGrtrOrEq(zero, sign[2]))
{
mtd = axis02;
newTransformV.rot.col0 = axis00;
newTransformV.rot.col1 = axis01;
newTransformV.rot.col2 = axis02;
newTransformV.p = V3NegScaleSub(axis02, ea2, transform0.p);
}
else
{
const Vec3V nAxis02 = V3Neg(axis02);
mtd = nAxis02;
newTransformV.rot.col0 = axis00;
newTransformV.rot.col1 = V3Neg(axis01);
newTransformV.rot.col2 = nAxis02;
newTransformV.p = V3ScaleAdd(axis02, ea2, transform0.p);
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent);
calculateContacts(ea0, ea1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
};
case 3: //ub0
{
flip = true;
if(FAllGrtrOrEq(zero, sign[3]))
{
mtd = axis10;
newTransformV.rot.col0 = axis12;
newTransformV.rot.col1 = axis11;
newTransformV.rot.col2 = V3Neg(axis10);
newTransformV.p = V3ScaleAdd(axis10, eb0, transform1.p); //transform0.p - extents0.x*axis00;
}
else
{
mtd = V3Neg(axis10);
newTransformV.rot.col0 = V3Neg(axis12);
newTransformV.rot.col1 = axis11;
newTransformV.rot.col2 = axis10;
newTransformV.p = V3NegScaleSub(axis10, eb0, transform1.p);//transform0.p + extents0.x*axis00;
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent);
calculateContacts(eb2, eb1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
};
case 4: //ub1;
{
flip = true;
if(FAllGrtrOrEq(zero, sign[4]))
{
mtd = axis11;
newTransformV.rot.col0 = axis10;
newTransformV.rot.col1 = axis12;
newTransformV.rot.col2 = V3Neg(axis11);
newTransformV.p = V3ScaleAdd(axis11, eb1, transform1.p);
}
else
{
mtd = V3Neg(axis11);
newTransformV.rot.col0 = axis10;
newTransformV.rot.col1 = V3Neg(axis12);
newTransformV.rot.col2 = axis11;
newTransformV.p = V3NegScaleSub(axis11, eb1, transform1.p); //transform0.p + extents0.x*axis00;
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent);
calculateContacts(eb0, eb2, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
}
case 5: //ub2;
{
flip = true;
if(FAllGrtrOrEq(zero, sign[5]))
{
mtd = axis12;
newTransformV.rot.col0 = axis10;
newTransformV.rot.col1 = V3Neg(axis11);
newTransformV.rot.col2 = V3Neg(axis12);
newTransformV.p = V3ScaleAdd(axis12, eb2, transform1.p);
}
else
{
mtd = V3Neg(axis12);
newTransformV.rot.col0 = axis10;
newTransformV.rot.col1 = axis11;
newTransformV.rot.col2 = axis12;
newTransformV.p = V3NegScaleSub(axis12, eb2, transform1.p);
}
const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0);
const Vec3V localNormal = newTransformV.rotateInv(mtd);
getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent);
calculateContacts(eb0, eb1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist);
break;
};
default:
return false;
}
if(numContacts != 0)
{
if(flip)
{
for(PxU32 i=0; i<numContacts; ++i)
{
const Vec3V localB = manifoldContacts[i].mLocalPointB;
manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA;
manifoldContacts[i].mLocalPointA = localB;
}
}
const PxMatTransformV transformNewTo1 = transform1.transformInv(newTransformV);
const PxMatTransformV transformNewTo0 = transform0.transformInv(newTransformV);
//transform points to the local space of transform0 and transform1
const Vec3V localNormalInB = transformNewTo1.rotate(Vec3V_From_Vec4V(manifoldContacts[0].mLocalNormalPen));
for(PxU32 i=0; i<numContacts; ++i)
{
manifoldContacts[i].mLocalPointA = transformNewTo0.transform(manifoldContacts[i].mLocalPointA);
manifoldContacts[i].mLocalPointB = transformNewTo1.transform(manifoldContacts[i].mLocalPointB);
manifoldContacts[i].mLocalNormalPen = V4SetW(localNormalInB, V4GetW(manifoldContacts[i].mLocalNormalPen));
}
}
return true;
}
bool Gu::pcmContactBoxBox(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const PxBoxGeometry& shapeBox0 = checkedCast<PxBoxGeometry>(shape0);
const PxBoxGeometry& shapeBox1 = checkedCast<PxBoxGeometry>(shape1);
// Get actual shape data
PersistentContactManifold& manifold = cache.getManifold();
PxPrefetchLine(&manifold, 256);
const FloatV contactDist = FLoad(params.mContactDistance);
const Vec3V boxExtents0 = V3LoadU(shapeBox0.halfExtents);
const Vec3V boxExtents1 = V3LoadU(shapeBox1.halfExtents);
//Transfer A into the local space of B
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans(transf1.transformInv(transf0));
const PxMatTransformV aToB(curRTrans);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV boxMargin0 = CalculatePCMBoxMargin(boxExtents0, toleranceLength);
const FloatV boxMargin1 = CalculatePCMBoxMargin(boxExtents1, toleranceLength);
const FloatV minMargin = FMin(boxMargin0, boxMargin1);
const PxU32 initialContacts = manifold.mNumContacts;
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f));
manifold.refreshContactPoints(aToB, projectBreakingThreshold, contactDist);
const PxU32 newContacts = manifold.mNumContacts;
const bool bLostContacts = (newContacts != initialContacts);
const FloatV radiusA = V3Length(boxExtents0);
const FloatV radiusB = V3Length(boxExtents1);
if(bLostContacts || manifold.invalidate_BoxConvex(curRTrans, transf0.q, transf1.q, minMargin, radiusA, radiusB))
{
manifold.setRelativeTransform(curRTrans, transf0.q, transf1.q);
PxMatTransformV transfV0(transf0);
PxMatTransformV transfV1(transf1);
transfV0.rot.col0 = V3Normalize(transfV0.rot.col0);
transfV0.rot.col1 = V3Normalize(transfV0.rot.col1);
transfV0.rot.col2 = V3Normalize(transfV0.rot.col2);
transfV1.rot.col0 = V3Normalize(transfV1.rot.col0);
transfV1.rot.col1 = V3Normalize(transfV1.rot.col1);
transfV1.rot.col2 = V3Normalize(transfV1.rot.col2);
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
PxU32 numContacts = 0;
if(doBoxBoxGenerateContacts(boxExtents0, boxExtents1, transfV0, transfV1, contactDist, manifoldContacts, numContacts))
{
if(numContacts > 0)
{
manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength);
const Vec3V worldNormal = V3Normalize(transfV1.rotate(Vec3V_From_Vec4V(manifold.mContactPoints[0].mLocalNormalPen)));
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transfV1);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
else
{
const Vec3V zeroV = V3Zero();
const BoxV box0(zeroV, boxExtents0);
const BoxV box1(zeroV, boxExtents1);
manifold.mNumWarmStartPoints = 0;
const RelativeConvex<BoxV> convexA(box0, aToB);
const LocalConvex<BoxV> convexB(box1);
GjkOutput output;
GjkStatus status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<BoxV> >(convexA, convexB, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
if(status == EPA_CONTACT)
{
const RelativeConvex<BoxV> convexA1(box0, aToB);
const LocalConvex<BoxV> convexB1(box1);
status = epaPenetration(convexA1, convexB1, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
}
if(status == GJK_CONTACT || status == EPA_CONTACT)
{
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA);
const Vec3V localPointB = output.closestB;
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
numContacts += manifold.addManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold);
//transform the normal back to world space
const Vec3V worldNormal = V3Normalize(transf1.rotate(output.normal));
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
}
}
}
else if(manifold.getNumContacts() > 0)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
return false;
}
| 31,690 | C++ | 31.603909 | 247 | 0.698927 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexCommon.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 "GuVecTriangle.h"
#include "GuPCMContactConvexCommon.h"
#include "GuConvexEdgeFlags.h"
#include "GuBarycentricCoordinates.h"
using namespace physx;
using namespace Gu;
using namespace aos;
// This function adds the newly created manifold contacts to a new patch or existing patches
void PCMConvexVsMeshContactGeneration::addContactsToPatch(const Vec3VArg patchNormal, PxU32 previousNumContacts)
{
const Vec3V patchNormalInTriangle = mMeshToConvex.rotateInv(patchNormal);
const PxU32 newContacts = mNumContacts - previousNumContacts;
if(newContacts > GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE)
{
//if the current created manifold contacts are more than GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points, we will reduce the total numContacts
//to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE. However, after we add these points into a patch, the patch contacts will be variable. Then we will
//do contact reduction for that patch in the processContacts. After the contact reduction, there will be no more than GU_SINGLE_MANIFOLD_CACHE_SIZE(6)
//contacts inside a signlePersistentContactManifold
SinglePersistentContactManifold::reduceContacts(&mManifoldContacts[previousNumContacts], newContacts);
mNumContacts = previousNumContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
//get rid of duplicate manifold contacts for the newly created contacts
for(PxU32 i = previousNumContacts; i<mNumContacts; ++i)
{
for(PxU32 j=i+1; j<mNumContacts; ++j)
{
Vec3V dif = V3Sub(mManifoldContacts[j].mLocalPointB, mManifoldContacts[i].mLocalPointB);
FloatV d = V3Dot(dif, dif);
if(FAllGrtr(mSqReplaceBreakingThreshold, d))
{
mManifoldContacts[j] = mManifoldContacts[mNumContacts-1];
mNumContacts--;
j--;
}
}
}
//calculate the maxPen and transform the patch normal and localPointB into mesh's local space
FloatV maxPen = FMax();
for(PxU32 i = previousNumContacts; i<mNumContacts; ++i)
{
const FloatV pen = V4GetW(mManifoldContacts[i].mLocalNormalPen);
mManifoldContacts[i].mLocalNormalPen = V4SetW(patchNormalInTriangle, pen);
mManifoldContacts[i].mLocalPointB = mMeshToConvex.transformInv(mManifoldContacts[i].mLocalPointB);
maxPen = FMin(maxPen, pen);
}
//Based on the patch normal and add the newly avaiable manifold points to the corresponding patch
addManifoldPointToPatch(patchNormalInTriangle, maxPen, previousNumContacts);
PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE);
if(mNumContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD)
{
PX_ASSERT(mNumContacts <= PxContactBuffer::MAX_CONTACTS);
processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE);
}
}
void PCMConvexVsMeshContactGeneration::generateLastContacts()
{
// Process delayed contacts
PxU32 nbEntries = mDeferredContacts->size();
if(nbEntries)
{
nbEntries /= sizeof(PCMDeferredPolyData)/sizeof(PxU32);
const PCMDeferredPolyData* PX_RESTRICT cd = reinterpret_cast<const PCMDeferredPolyData*>(mDeferredContacts->begin());
for(PxU32 i=0;i<nbEntries;i++)
{
const PCMDeferredPolyData& currentContact = cd[i];
const PxU32 ref0 = currentContact.mInds[0];
const PxU32 ref1 = currentContact.mInds[1];
const PxU32 ref2 = currentContact.mInds[2];
const PxU8 triFlags = PxU8(currentContact.triFlags32);
const bool needsProcessing = (((triFlags & ETD_CONVEX_EDGE_01) != 0 || mEdgeCache.get(CachedEdge(ref0, ref1)) == NULL)) &&
(((triFlags & ETD_CONVEX_EDGE_12) != 0 || mEdgeCache.get(CachedEdge(ref1, ref2)) == NULL)) &&
(((triFlags & ETD_CONVEX_EDGE_20) != 0 || mEdgeCache.get(CachedEdge(ref2, ref0)) == NULL));
if(needsProcessing)
{
const TriangleV localTriangle(currentContact.mVerts);
Vec3V patchNormal;
const PxU32 previousNumContacts = mNumContacts;
//the localTriangle is in the convex space
//Generate contacts - we didn't generate contacts with any neighbours
generatePolyDataContactManifold(localTriangle, currentContact.mFeatureIndex, currentContact.mTriangleIndex, triFlags, mManifoldContacts, mNumContacts, mContactDist, patchNormal);
FloatV v, w;
const FloatV upperBound = FLoad(0.97f);
const FloatV lowerBound = FSub(FOne(), upperBound);
PxU32 currentContacts = mNumContacts;
for(PxU32 j=currentContacts; j>previousNumContacts; --j)
{
PxU32 ind = j-1;
//calculate the barycentric coordinate of the contacts in localTriangle, p = a + v(b-a) + w(c-a)., p=ua+vb+wc
barycentricCoordinates(mManifoldContacts[ind].mLocalPointB, localTriangle.verts[0], localTriangle.verts[1], localTriangle.verts[2], v, w);
//const FloatV u = FSub(one, FAdd(v, w));
bool keepContact = true;
if(FAllGrtr(v, upperBound))//v > upperBound
{
//vertex1
keepContact = !mVertexCache.contains(CachedVertex(ref1));
}
else if(FAllGrtr(w, upperBound))// w > upperBound
{
//vertex2
keepContact = !mVertexCache.contains(CachedVertex(ref2));
}
else if(FAllGrtrOrEq(lowerBound, FAdd(v, w))) // u(1-(v+w)) > upperBound
{
//vertex0
keepContact = !mVertexCache.contains(CachedVertex(ref0));
}
if(!keepContact)
{
//ML: if feature code is any of the vertex in this triangle and we have generated contacts with any other triangles which contains this vertex, we should drop it
currentContacts--;
for(PxU32 k = ind; k < currentContacts; ++k)
{
mManifoldContacts[k] = mManifoldContacts[k+1];
}
}
}
mNumContacts = currentContacts;
if(currentContacts > previousNumContacts)
{
addContactsToPatch(patchNormal, previousNumContacts);
}
}
}
}
}
bool PCMConvexVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds)
{
const Mat33V identity = M33Identity();
const FloatV zero = FZero();
const Vec3V v0 = V3LoadU(verts[0]);
const Vec3V v1 = V3LoadU(verts[1]);
const Vec3V v2 = V3LoadU(verts[2]);
const Vec3V v10 = V3Sub(v1, v0);
const Vec3V v20 = V3Sub(v2, v0);
const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized();
const FloatV d = V3Dot(v0, n);//d = -p0.dot(n);
const FloatV dist = FSub(V3Dot(mHullCenterMesh, n), d);//p.dot(n) + d;
// Backface culling
if(FAllGrtr(zero, dist))
return false;
//tranform verts into the box local space
const Vec3V locV0 = mMeshToConvex.transform(v0);
const Vec3V locV1 = mMeshToConvex.transform(v1);
const Vec3V locV2 = mMeshToConvex.transform(v2);
const TriangleV localTriangle(locV0, locV1, locV2);
{
SupportLocalImpl<TriangleV> localTriMap(localTriangle, mConvexTransform, identity, identity, true);
const PxU32 previousNumContacts = mNumContacts;
Vec3V patchNormal;
generateTriangleFullContactManifold(localTriangle, triangleIndex, vertInds, triFlags, mPolyData, &localTriMap, mPolyMap, mManifoldContacts, mNumContacts, mContactDist, patchNormal);
if(mNumContacts > previousNumContacts)
{
#if PCM_LOW_LEVEL_DEBUG
PersistentContactManifold::drawTriangle(*mRenderOutput, mMeshTransform.transform(v0), mMeshTransform.transform(v1), mMeshTransform.transform(v2), 0x00ff00);
#endif
const bool inActiveEdge0 = (triFlags & ETD_CONVEX_EDGE_01) == 0;
const bool inActiveEdge1 = (triFlags & ETD_CONVEX_EDGE_12) == 0;
const bool inActiveEdge2 = (triFlags & ETD_CONVEX_EDGE_20) == 0;
if(inActiveEdge0)
mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1]));
if(inActiveEdge1)
mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2]));
if(inActiveEdge2)
mEdgeCache.addData(CachedEdge(vertInds[2], vertInds[0]));
mVertexCache.addData(CachedVertex(vertInds[0]));
mVertexCache.addData(CachedVertex(vertInds[1]));
mVertexCache.addData(CachedVertex(vertInds[2]));
addContactsToPatch(patchNormal, previousNumContacts);
}
}
return true;
}
bool PCMConvexVsMeshContactGeneration::processTriangle(const PolygonalData& polyData, const SupportLocal* polyMap, const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const FloatVArg inflation, bool isDoubleSided,
const PxTransformV& convexTransform, const PxMatTransformV& meshToConvex, MeshPersistentContact* manifoldContacts, PxU32& numContacts)
{
const Mat33V identity = M33Identity();
const FloatV zero = FZero();
const Vec3V v0 = V3LoadU(verts[0]);
const Vec3V v1 = V3LoadU(verts[1]);
const Vec3V v2 = V3LoadU(verts[2]);
//tranform verts into the box local space
const Vec3V locV0 = meshToConvex.transform(v0);
const Vec3V locV1 = meshToConvex.transform(v1);
const Vec3V locV2 = meshToConvex.transform(v2);
const Vec3V v10 = V3Sub(locV1, locV0);
const Vec3V v20 = V3Sub(locV2, locV0);
const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized();
const FloatV d = V3Dot(locV0, n);//d = -p0.dot(n);
const FloatV dist = FSub(V3Dot(polyMap->shapeSpaceCenterOfMass, n), d);//p.dot(n) + d;
// Backface culling
const bool culled = !isDoubleSided && (FAllGrtr(zero, dist));
if(culled)
return false;
const TriangleV localTriangle(locV0, locV1, locV2);
SupportLocalImpl<TriangleV> localTriMap(localTriangle, convexTransform, identity, identity, true);
Vec3V patchNormal;
generateTriangleFullContactManifold(localTriangle, triangleIndex, triFlags, polyData, &localTriMap, polyMap, manifoldContacts, numContacts, inflation, patchNormal);
return true;
}
| 11,132 | C++ | 39.191336 | 219 | 0.738951 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactMeshCallback.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_MESH_CALLBACK_H
#define GU_PCM_CONTACT_MESH_CALLBACK_H
#include "GuMidphaseInterface.h"
#include "GuEntityReport.h"
#include "GuHeightFieldUtil.h"
#include "GuTriangleCache.h"
#include "GuConvexEdgeFlags.h"
namespace physx
{
namespace Gu
{
template <typename Derived>
struct PCMMeshContactGenerationCallback : MeshHitCallback<PxGeomRaycastHit>
{
public:
const Cm::FastVertex2ShapeScaling& mMeshScaling;
const PxU8* PX_RESTRICT mExtraTrigData;
bool mIdtMeshScale;
static const PxU32 CacheSize = 16;
Gu::TriangleCache<CacheSize> mCache;
PCMMeshContactGenerationCallback(const Cm::FastVertex2ShapeScaling& meshScaling, const PxU8* extraTrigData, bool idtMeshScale)
: MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE),
mMeshScaling(meshScaling), mExtraTrigData(extraTrigData), mIdtMeshScale(idtMeshScale)
{
}
void flushCache()
{
if (!mCache.isEmpty())
{
(static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(mCache);
mCache.reset();
}
}
virtual PxAgain processHit(
const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds)
{
if (!(static_cast<Derived*>(this))->doTest(v0, v1, v2))
return true;
const PxU32 triangleIndex = hit.faceIndex;
PxU8 extraData = getConvexEdgeFlags(mExtraTrigData, triangleIndex);
const PxU32* vertexIndices = vinds;
PxVec3 v[3];
PxU32 localStorage[3];
if(mIdtMeshScale)
{
v[0] = v0;
v[1] = v1;
v[2] = v2;
}
else
{
const PxI32 winding = mMeshScaling.flipsNormal() ? 1 : 0;
v[0] = mMeshScaling * v0;
v[1 + winding] = mMeshScaling * v1;
v[2 - winding] = mMeshScaling * v2;
if(winding)
{
flipConvexEdgeFlags(extraData);
localStorage[0] = vinds[0];
localStorage[1] = vinds[2];
localStorage[2] = vinds[1];
vertexIndices = localStorage;
}
}
if (mCache.isFull())
{
(static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(mCache);
mCache.reset();
}
mCache.addTriangle(v, vertexIndices, triangleIndex, extraData);
return true;
}
protected:
PCMMeshContactGenerationCallback& operator=(const PCMMeshContactGenerationCallback&);
};
template <typename Derived>
struct PCMHeightfieldContactGenerationCallback : Gu::OverlapReport
{
public:
const Gu::HeightFieldUtil& mHfUtil;
const PxTransform& mHeightfieldTransform;
bool mBoundaryCollisions;
PCMHeightfieldContactGenerationCallback(const Gu::HeightFieldUtil& hfUtil, const PxTransform& heightfieldTransform) :
mHfUtil(hfUtil), mHeightfieldTransform(heightfieldTransform)
{
mBoundaryCollisions = !(hfUtil.getHeightField().getFlags() & PxHeightFieldFlag::eNO_BOUNDARY_EDGES);
}
// PT: TODO: refactor/unify with similar code in other places
virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices)
{
const PxU32 CacheSize = 16;
Gu::TriangleCache<CacheSize> cache;
const PxU32 nbPasses = (nb+(CacheSize-1))/CacheSize;
PxU32 nbTrigs = nb;
const PxU32* inds0 = indices;
const PxU8 nextInd[] = {2,0,1};
for(PxU32 i = 0; i < nbPasses; ++i)
{
cache.mNumTriangles = 0;
PxU32 trigCount = PxMin(nbTrigs, CacheSize);
nbTrigs -= trigCount;
while(trigCount--)
{
PxU32 triangleIndex = *(inds0++);
PxU32 vertIndices[3];
PxTriangle currentTriangle; // in world space
PxU32 adjInds[3];
mHfUtil.getTriangle(mHeightfieldTransform, 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;
PxU32 inds[3];
mHfUtil.getTriangle(mHeightfieldTransform, adjTri, inds, NULL, adjInds[a], false, false);
//We now compare the triangles to see if this edge is active
PX_ASSERT(inds[0] == vertIndices[a] || inds[1] == vertIndices[a] || inds[2] == vertIndices[a]);
PX_ASSERT(inds[0] == vertIndices[(a + 1) % 3] || inds[1] == vertIndices[(a + 1) % 3] || inds[2] == vertIndices[(a + 1) % 3]);
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.997f)
{
triFlags |= (1 << (a + 3));
}
}
}
else if (mBoundaryCollisions)
{
triFlags |= (1 << (a + 3)); //Mark boundary edge active
}
else
triFlags |= (1 << a); //Mark as silhouette edge
}
cache.addTriangle(currentTriangle.verts, vertIndices, triangleIndex, triFlags);
}
PX_ASSERT(cache.mNumTriangles <= 16);
(static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(cache);
}
return true;
}
protected:
PCMHeightfieldContactGenerationCallback& operator=(const PCMHeightfieldContactGenerationCallback&);
};
template <typename Derived>
struct PCMTetMeshContactGenerationCallback : TetMeshHitCallback<PxGeomRaycastHit>
{
public:
static const PxU32 CacheSize = 16;
Gu::TetrahedronCache<CacheSize> mCache;
PCMTetMeshContactGenerationCallback(): TetMeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE)
{
}
void flushCache()
{
if (!mCache.isEmpty())
{
(static_cast<Derived*>(this))->template processTetrahedronCache< CacheSize >(mCache);
mCache.reset();
}
}
virtual PxAgain processHit(
const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& v3, PxReal&, const PxU32* vinds)
{
if (!(static_cast<Derived*>(this))->doTest(v0, v1, v2, v3))
return true;
PxVec3 v[4] = { v0, v1, v2, v3 };
const PxU32 tetIndex = hit.faceIndex;
if (mCache.isFull())
{
(static_cast<Derived*>(this))->template processTetrahedronCache< CacheSize >(mCache);
mCache.reset();
}
mCache.addTetrahedrons(v, vinds, tetIndex);
return true;
}
protected:
PCMTetMeshContactGenerationCallback& operator=(const PCMTetMeshContactGenerationCallback&);
};
}//Gu
}//physx
#endif
| 7,926 | C | 29.488461 | 131 | 0.709311 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPersistentContactManifold.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 "foundation/PxAlloca.h"
#include "foundation/PxVecTransform.h"
#include "foundation/PxUtilities.h"
#include "GuPersistentContactManifold.h"
#include "GuGJKUtil.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
using namespace aos;
using namespace Gu;
// This local function is to avoid DLL call
static FloatV distancePointSegmentSquaredLocal(const Vec3VArg a, const Vec3VArg b, const Vec3VArg p)
{
const FloatV zero = FZero();
const FloatV one = FOne();
const Vec3V ap = V3Sub(p, a);
const Vec3V ab = V3Sub(b, a);
const FloatV nom = V3Dot(ap, ab);
const FloatV denom = V3Dot(ab, ab);
const FloatV tValue = FClamp(FDiv(nom, denom), zero, one);
const FloatV t = FSel(FIsEq(denom, zero), zero, tValue);
const Vec3V v = V3NegScaleSub(ab, t, ap);
return V3Dot(v, v);
}
// This local function is to avoid DLL call
static FloatV distancePointTriangleSquaredLocal(const Vec3VArg p,
const Vec3VArg a,
const Vec3VArg b,
const Vec3VArg c)
{
const FloatV zero = FZero();
//const Vec3V zero = V3Zero();
const Vec3V ab = V3Sub(b, a);
const Vec3V ac = V3Sub(c, a);
const Vec3V bc = V3Sub(c, b);
const Vec3V ap = V3Sub(p, a);
const Vec3V bp = V3Sub(p, b);
const Vec3V cp = V3Sub(p, 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);
//check if p in vertex region outside a
const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0
const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0
const BoolV con0 = BAnd(con00, con01); // vertex region a
if(BAllEqTTTT(con0))
{
const Vec3V vv = V3Sub(p, a);
return V3Dot(vv, vv);
}
//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))
{
const Vec3V vv = V3Sub(p, b);
return V3Dot(vv, vv);
}
//check if p in vertex region outside c
const BoolV con20 = FIsGrtrOrEq(d6, zero);
const BoolV con21 = FIsGrtrOrEq(d6, d5);
const BoolV con2 = BAnd(con20, con21); // vertex region c
if(BAllEqTTTT(con2))
{
const Vec3V vv = V3Sub(p, c);
return V3Dot(vv, vv);
}
//check if p in edge region of AB
const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2));
const BoolV con30 = FIsGrtr(zero, vc);
const BoolV con31 = FIsGrtrOrEq(d1, zero);
const BoolV con32 = FIsGrtr(zero, d3);
const BoolV con3 = BAnd(con30, BAnd(con31, con32));
if(BAllEqTTTT(con3))
{
const FloatV sScale = FDiv(d1, FSub(d1, d3));
const Vec3V closest3 = V3ScaleAdd(ab, sScale, a);//V3Add(a, V3Scale(ab, sScale));
const Vec3V vv = V3Sub(p, closest3);
return V3Dot(vv, vv);
}
//check if p in edge region of BC
const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4));
const BoolV con40 = FIsGrtr(zero, va);
const BoolV con41 = FIsGrtrOrEq(d4, d3);
const BoolV con42 = FIsGrtrOrEq(d5, d6);
const BoolV con4 = BAnd(con40, BAnd(con41, con42));
if(BAllEqTTTT(con4))
{
const FloatV uScale = FDiv(unom, FAdd(unom, udenom));
const Vec3V closest4 = V3ScaleAdd(bc, uScale, b);//V3Add(b, V3Scale(bc, uScale));
const Vec3V vv = V3Sub(p, closest4);
return V3Dot(vv, vv);
}
//check if p in edge region of AC
const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6));
const BoolV con50 = FIsGrtr(zero, vb);
const BoolV con51 = FIsGrtrOrEq(d2, zero);
const BoolV con52 = FIsGrtr(zero, d6);
const BoolV con5 = BAnd(con50, BAnd(con51, con52));
if(BAllEqTTTT(con5))
{
const FloatV tScale = FDiv(d2, FSub(d2, d6));
const Vec3V closest5 = V3ScaleAdd(ac, tScale, a);//V3Add(a, V3Scale(ac, tScale));
const Vec3V vv = V3Sub(p, closest5);
return V3Dot(vv, vv);
}
//P must project inside face region. Compute Q using Barycentric coordinates
const Vec3V n = V3Cross(ab, ac);
const FloatV nn = V3Dot(n,n);
const FloatV t = FSel(FIsGrtr(nn, zero),FDiv(V3Dot(n, V3Sub(a, p)), nn), zero);
const Vec3V closest6 = V3Add(p, V3Scale(n, t));
const Vec3V vv = V3Sub(p, closest6);
return V3Dot(vv, vv);
}
namespace physx
{
namespace Gu
{
//This is the translational threshold used in invalidate_BoxConvexHull. 0.5 is 50% of the object margin. we use different threshold between
//0 and 4 points. This threashold is a scale that is multiplied by the objects' margins.
const PxF32 invalidateThresholds[5] = { 0.5f, 0.125f, 0.25f, 0.375f, 0.375f };
//This is the translational threshold used in invalidate_SphereCapsule. 0.5 is 50% of the object margin, we use different threshold between
//0 and 2 points. This threshold is a scale that is multiplied by the objects' margin
const PxF32 invalidateThresholds2[3] = { 0.5f, 0.1f, 0.75f };
//This is the rotational threshold used in invalidate_BoxConvexHull. 0.9998 is a threshold for quat difference
//between previous and current frame
const PxF32 invalidateQuatThresholds[5] = { 0.9998f, 0.9999f, 0.9999f, 0.9999f, 0.9999f };
//This is the rotational threshold used in invalidate_SphereCapsule. 0.9995f is a threshold for quat difference
//between previous and current frame
const PxF32 invalidateQuatThresholds2[3] = { 0.9995f, 0.9999f, 0.9997f };
}
}
#if VISUALIZE_PERSISTENT_CONTACT
#include "common/PxRenderOutput.h"
static void drawManifoldPoint(const PersistentContact& manifold, const PxTransformV& trA, const PxTransformV& trB, PxRenderOutput& out, PxU32 color=0xffffff)
{
PX_UNUSED(color);
const Vec3V worldA = trA.transform(manifold.mLocalPointA);
const Vec3V worldB = trB.transform(manifold.mLocalPointB);
const Vec3V localNormal = Vec3V_From_Vec4V(manifold.mLocalNormalPen);
const FloatV pen = V4GetW(manifold.mLocalNormalPen);
const Vec3V worldNormal = trB.rotate(localNormal);
PxVec3 a, b, v;
V3StoreU(worldA, a);
V3StoreU(worldB, b);
V3StoreU(worldNormal, v);
PxF32 dist;
FStore(pen, &dist);
PxVec3 e = a - v*dist;
PxF32 size = 0.05f;
const PxVec3 up(0.f, size, 0.f);
const PxVec3 right(size, 0.f, 0.f);
const PxVec3 forwards(0.f, 0.f, size);
PxF32 size2 = 0.1f;
const PxVec3 up2(0.f, size2, 0.f);
const PxVec3 right2(size2, 0.f, 0.f);
const PxVec3 forwards2(0.f, 0.f, size2);
const PxMat44 m = PxMat44(PxIdentity);
out << m << PxRenderOutput::LINES;
out << 0xffff00ff << a << e;
out << 0xff00ffff << a + up << a - up;
out << 0xff00ffff << a + right << a - right;
out << 0xff00ffff << a + forwards << a - forwards;
out << 0xffff0000 << b + up2 << b - up2;
out << 0xffff0000 << b + right2 << b - right2;
out << 0xffff0000 << b + forwards2 << b - forwards2;
out << 0xffff0000 << a << b;
const PxVec3 c = a - v*10.f;
out << 0xffff00ff << a << c;
}
static void drawManifoldPoint(const PersistentContact& manifold, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius, PxRenderOutput& out, PxU32 color=0xffffff)
{
PX_UNUSED(color);
const Vec3V localNormal = Vec3V_From_Vec4V(manifold.mLocalNormalPen);
const Vec3V worldNormal = trB.rotate(localNormal);
const Vec3V worldA = V3NegScaleSub(worldNormal, radius, trA.transform(manifold.mLocalPointA));
const Vec3V worldB = trB.transform(manifold.mLocalPointB);
const FloatV pen = FSub(V4GetW(manifold.mLocalNormalPen), radius);
PxVec3 a, b, v;
V3StoreU(worldA, a);
V3StoreU(worldB, b);
V3StoreU(worldNormal, v);
PxF32 dist;
FStore(pen, &dist);
PxVec3 e = a - v*dist;
PxF32 size = 0.05f;
const PxVec3 up(0.f, size, 0.f);
const PxVec3 right(size, 0.f, 0.f);
const PxVec3 forwards(0.f, 0.f, size);
PxF32 size2 = 0.1f;
const PxVec3 up2(0.f, size2, 0.f);
const PxVec3 right2(size2, 0.f, 0.f);
const PxVec3 forwards2(0.f, 0.f, size2);
PxMat44 m = PxMat44(PxIdentity);
out << 0xffff00ff << m << PxRenderOutput::LINES << a << e;
out << 0xff00ffff << m << PxRenderOutput::LINES << a + up << a - up;
out << 0xff00ffff << m << PxRenderOutput::LINES << a + right << a - right;
out << 0xff00ffff << m << PxRenderOutput::LINES << a + forwards << a - forwards;
out << 0xffff0000 << m << PxRenderOutput::LINES << b + up2 << b - up2;
out << 0xffff0000 << m << PxRenderOutput::LINES << b + right2 << b - right2;
out << 0xffff0000 << m << PxRenderOutput::LINES << b + forwards2 << b - forwards2;
out << 0xffff0000 << m << PxRenderOutput::LINES << a << b;
}
static PxU32 gColors[8] = { 0xff0000ff, 0xff00ff00, 0xffff0000,
0xff00ffff, 0xffff00ff, 0xffffff00,
0xff000080, 0xff008000};
#endif
// SIMD version
Mat33V Gu::findRotationMatrixFromZAxis(const Vec3VArg to)
{
const FloatV one = FOne();
const FloatV threshold = FLoad(0.9999f);
const FloatV e = V3GetZ(to);
const FloatV f = FAbs(e);
if(FAllGrtr(threshold, f))
{
const FloatV vx = FNeg(V3GetY(to));
const FloatV vy = V3GetX(to);
const FloatV h = FRecip(FAdd(one, e));
const FloatV hvx = FMul(h,vx);
const FloatV hvxy = FMul(hvx, vy);
const Vec3V col0 = V3Merge(FScaleAdd(hvx, vx, e), hvxy, vy);
const Vec3V col1 = V3Merge(hvxy, FScaleAdd(h, FMul(vy, vy), e), FNeg(vx));
const Vec3V col2 = V3Merge(FNeg(vy), vx, e);
return Mat33V(col0, col1, col2);
}
else
{
const FloatV two = FLoad(2.f);
const Vec3V from = V3UnitZ();
const Vec3V absFrom = V3UnitY();
const Vec3V u = V3Sub(absFrom, from);
const Vec3V v = V3Sub(absFrom, to);
const FloatV dotU = V3Dot(u, u);
const FloatV dotV = V3Dot(v, v);
const FloatV dotUV = V3Dot(u, v);
const FloatV c1 = FNeg(FDiv(two, dotU));
const FloatV c2 = FNeg(FDiv(two, dotV));
const FloatV c3 = FMul(c1, FMul(c2, dotUV));
const Vec3V c1u = V3Scale(u, c1);
const Vec3V c2v = V3Scale(v, c2);
const Vec3V c3v = V3Scale(v, c3);
FloatV temp0 = V3GetX(c1u);
FloatV temp1 = V3GetX(c2v);
FloatV temp2 = V3GetX(c3v);
Vec3V col0 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2)));
col0 = V3SetX(col0, FAdd(V3GetX(col0), one));
temp0 = V3GetY(c1u);
temp1 = V3GetY(c2v);
temp2 = V3GetY(c3v);
Vec3V col1 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2)));
col1 = V3SetY(col1, FAdd(V3GetY(col1), one));
temp0 = V3GetZ(c1u);
temp1 = V3GetZ(c2v);
temp2 = V3GetZ(c3v);
Vec3V col2 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2)));
col2 = V3SetZ(col2, FAdd(V3GetZ(col2), one));
return Mat33V(col0, col1, col2);
}
}
void PersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b;
V3StoreU(trA.p, a);
V3StoreU(trB.p, b);
for(PxU32 i = 0; i< mNumContacts; ++i)
{
PersistentContact& m = mContactPoints[i];
drawManifoldPoint(m, trA, trB, out, gColors[i]);
}
#else
PX_UNUSED(out);
PX_UNUSED(trA);
PX_UNUSED(trB);
#endif
}
void PersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius) const
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b;
V3StoreU(trA.p, a);
V3StoreU(trB.p, b);
for(PxU32 i = 0; i< mNumContacts; ++i)
{
PersistentContact& m = mContactPoints[i];
drawManifoldPoint(m, trA, trB, radius, out, gColors[i]);
}
#else
PX_UNUSED(out);
PX_UNUSED(trA);
PX_UNUSED(trB);
PX_UNUSED(radius);
#endif
}
void PersistentContactManifold::drawManifold(const PersistentContact& m, PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const
{
#if VISUALIZE_PERSISTENT_CONTACT
drawManifoldPoint(m, trA, trB, out, gColors[0]);
#else
PX_UNUSED(out);
PX_UNUSED(trA);
PX_UNUSED(trB);
PX_UNUSED(m);
#endif
}
void PersistentContactManifold::drawPoint(PxRenderOutput& out, const Vec3VArg p, const PxF32 size, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
const PxVec3 up(0.f, size, 0.f);
const PxVec3 right(size, 0.f, 0.f);
const PxVec3 forwards(0.f, 0.f, size);
PxVec3 a;
V3StoreU(p, a);
const PxMat44 m(PxIdentity);
out << color << m << PxRenderOutput::LINES << a + up << a - up;
out << color << m << PxRenderOutput::LINES << a + right << a - right;
out << color << m << PxRenderOutput::LINES << a + forwards << a - forwards;
#else
PX_UNUSED(out);
PX_UNUSED(p);
PX_UNUSED(size);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::drawLine(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b;
V3StoreU(p0, a);
V3StoreU(p1, b);
const PxMat44 m(PxIdentity);
out << color << m << PxRenderOutput::LINES << a << b;
#else
PX_UNUSED(out);
PX_UNUSED(p0);
PX_UNUSED(p1);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::drawTriangle(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, const Vec3VArg p2, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b, c;
V3StoreU(p0, a);
V3StoreU(p1, b);
V3StoreU(p2, c);
const PxMat44 m(PxIdentity);
out << color << m << PxRenderOutput::TRIANGLES << a << b << c;
#else
PX_UNUSED(out);
PX_UNUSED(p0);
PX_UNUSED(p1);
PX_UNUSED(p2);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::drawTetrahedron(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, const Vec3VArg p2, const Vec3VArg p3, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b, c, d;
V3StoreU(p0, a);
V3StoreU(p1, b);
V3StoreU(p2, c);
V3StoreU(p3, d);
const PxMat44 m(PxIdentity);
out << color << m << PxRenderOutput::LINES << a << b;
out << color << m << PxRenderOutput::LINES << a << c;
out << color << m << PxRenderOutput::LINES << a << d;
out << color << m << PxRenderOutput::LINES << b << c;
out << color << m << PxRenderOutput::LINES << b << d;
out << color << m << PxRenderOutput::LINES << c << d;
#else
PX_UNUSED(out);
PX_UNUSED(p0);
PX_UNUSED(p1);
PX_UNUSED(p2);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxTransformV& transform, const Vec3V* points, PxU32 numVerts, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
for(PxU32 i=0; i<numVerts; ++i)
{
Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1];
Vec3V tempV1 = points[i];
drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color);
}
#else
PX_UNUSED(out);
PX_UNUSED(transform);
PX_UNUSED(points);
PX_UNUSED(numVerts);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxMatTransformV& transform, const Vec3V* points, PxU32 numVerts, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
for(PxU32 i=0; i<numVerts; ++i)
{
Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1];
Vec3V tempV1 = points[i];
drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color);
}
#else
PX_UNUSED(out);
PX_UNUSED(transform);
PX_UNUSED(points);
PX_UNUSED(numVerts);
PX_UNUSED(color);
#endif
}
void PersistentContactManifold::recordWarmStart(PxU8* aIndices, PxU8* bIndices, PxU8& nbWarmStartPoints)
{
nbWarmStartPoints = mNumWarmStartPoints;
for(PxU8 i = 0; i < mNumWarmStartPoints; ++i)
{
aIndices[i] = mAIndice[i];
bIndices[i] = mBIndice[i];
}
}
void PersistentContactManifold::setWarmStart(const PxU8* aIndices, const PxU8* bIndices, const PxU8 nbWarmStartPoints)
{
mNumWarmStartPoints = nbWarmStartPoints;
for(PxU8 i = 0; i < nbWarmStartPoints; ++i)
{
mAIndice[i] = aIndices[i];
mBIndice[i] = bIndices[i];
}
}
// If a new point and the exisitng point's distance are within some replace breaking threshold, we will replace the existing point with the new point.
// This is used for incremental manifold strategy.
bool PersistentContactManifold::replaceManifoldPoint(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen
, const FloatVArg replaceBreakingThreshold)
{
const FloatV shortestDist = FMul(replaceBreakingThreshold, replaceBreakingThreshold);
for(PxU32 i=0; i<mNumContacts; ++i)
{
const PersistentContact& mp = mContactPoints[i];
const Vec3V diffB = V3Sub(mp.mLocalPointB, localPointB);
const FloatV sqDifB = V3Dot(diffB, diffB);
const Vec3V diffA = V3Sub(mp.mLocalPointA, localPointA);
const FloatV sqDifA = V3Dot(diffA, diffA);
const FloatV minSqDif = FMin(sqDifB, sqDifA);
if(FAllGrtr(shortestDist, minSqDif))
{
mContactPoints[i].mLocalPointA = localPointA;
mContactPoints[i].mLocalPointB = localPointB;
mContactPoints[i].mLocalNormalPen = localNormalPen;
return true;
}
}
return false;
}
PxU32 PersistentContactManifold::reduceContactSegment(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen)
{
const Vec3V p = localPointB;
const Vec3V p0 = mContactPoints[0].mLocalPointB;
const Vec3V p1 = mContactPoints[1].mLocalPointB;
const Vec3V v0 = V3Sub(p0, p);
const Vec3V v1 = V3Sub(p1, p);
const FloatV dist0 = V3Dot(v0, v0);
const FloatV dist1 = V3Dot(v1, v1);
if(FAllGrtr(dist0, dist1))
{
mContactPoints[1].mLocalPointA = localPointA;
mContactPoints[1].mLocalPointB = localPointB;
mContactPoints[1].mLocalNormalPen = localNormalPen;
}
else
{
mContactPoints[0].mLocalPointA = localPointA;
mContactPoints[0].mLocalPointB = localPointB;
mContactPoints[0].mLocalNormalPen = localNormalPen;
}
return 0;
}
PxU32 PersistentContactManifold::reduceContactsForPCM(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen)
{
bool chosen[5];
PxMemZero(chosen, sizeof(bool)*5);
const FloatV negMax = FNeg(FMax());
PersistentContact tempContacts[5];
for(PxU32 i=0; i<4; ++i)
{
tempContacts[i] = mContactPoints[i];
}
tempContacts[4].mLocalPointA = localPointA;
tempContacts[4].mLocalPointB = localPointB;
tempContacts[4].mLocalNormalPen = localNormalPen;
//ML: we set the start point to be the 4th point
FloatV maxDist = V4GetW(localNormalPen);
PxI32 index = 4;
//Choose deepest point
for(PxI32 i=0; i<4; ++i)
{
const FloatV pen = V4GetW(tempContacts[i].mLocalNormalPen);
if(FAllGrtr(maxDist, pen))
{
maxDist = pen;
index = i;
}
}
chosen[index] = true;
mContactPoints[0] = tempContacts[index];
//ML: we set the start point to be the 0th point
Vec3V dir = V3Sub(tempContacts[0].mLocalPointB, mContactPoints[0].mLocalPointB);
maxDist = V3Dot(dir, dir);
index = 0;
for(PxI32 i=1; i<5; ++i)
{
if(!chosen[i])
{
dir = V3Sub(tempContacts[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(dir, dir);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = i;
}
}
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
mContactPoints[1] = tempContacts[index];
maxDist = negMax;
for(PxI32 i=0; i<5; ++i)
{
if(!chosen[i])
{
const FloatV sqDif = distancePointSegmentSquaredLocal(mContactPoints[0].mLocalPointB, mContactPoints[1].mLocalPointB, tempContacts[i].mLocalPointB);
if(FAllGrtr(sqDif, maxDist))
{
maxDist = sqDif;
index = i;
}
}
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
mContactPoints[2]=tempContacts[index];
//Find point farthest away from segment tempContactPoints[0] - tempContactPoints[1]
maxDist = negMax;
for(PxI32 i=0; i<5; ++i)
{
if(!chosen[i])
{
const FloatV sqDif = distancePointTriangleSquaredLocal( tempContacts[i].mLocalPointB, mContactPoints[0].mLocalPointB, mContactPoints[1].mLocalPointB, mContactPoints[2].mLocalPointB);
if(FAllGrtr(sqDif, maxDist))
{
maxDist= sqDif;
index = i;
}
}
}
//PX_ASSERT(chosen[index] == false);
if(chosen[index] == true)
{
//if we don't have any new contacts, which means the leftover contacts are inside the triangles
mNumContacts = 3;
return 0;
}
else
{
chosen[index] = true;
mContactPoints[3] = tempContacts[index];
}
//Final pass, we work out the index that we didn't choose and bind it to its closest point. We then consider whether we want to swap the point if the
//point we were about to discard is deeper...
PxU32 notChosenIndex = 0;
for(PxU32 a = 0; a < 5; ++a)
{
if(!chosen[a])
{
notChosenIndex = a;
break;
}
}
FloatV closest = FMax();
index = 0;
for(PxI32 a = 0; a < 4; ++a)
{
Vec3V dif = V3Sub(mContactPoints[a].mLocalPointA, tempContacts[notChosenIndex].mLocalPointA);
const FloatV d2 = V3Dot(dif, dif);
if(FAllGrtr(closest, d2))
{
closest = d2;
index = a;
}
}
if(FAllGrtr(V4GetW(mContactPoints[index].mLocalNormalPen), V4GetW(tempContacts[notChosenIndex].mLocalNormalPen)))
{
//Swap
mContactPoints[index] = tempContacts[notChosenIndex];
}
return 0;
}
// This function is for box/convexHull vs box/convexHull.
void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const PxTransformV& transf1, const FloatVArg contactOffset)
{
//add the manifold contacts;
PxU32 contactCount = 0;
for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i)
{
const PersistentContact& p = getContactPoint(i);
const FloatV dist = V4GetW(p.mLocalNormalPen);
//Either the newly created points or the cache points might have dist/penetration larger than contactOffset
if(FAllGrtrOrEq(contactOffset, dist))
{
const Vec3V worldP = transf1.transform(p.mLocalPointB);
outputPCMContact(contactBuffer, contactCount, worldP, normal, dist);
}
}
contactBuffer.count = contactCount;
}
// This function is for direct implementation for box vs box. We don't need to discard the contacts based on whether the contact offset is larger than penetration/dist because
// the direct implementation will guarantee the penetration/dist won't be larger than the contact offset. Also, we won't have points from the cache if the direct implementation
// of box vs box is called.
void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const PxMatTransformV& transf1)
{
//add the manifold contacts;
PxU32 contactCount = 0;
for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i)
{
const PersistentContact& p = getContactPoint(i);
const Vec3V worldP = transf1.transform(p.mLocalPointB);
const FloatV dist = V4GetW(p.mLocalNormalPen);
outputPCMContact(contactBuffer, contactCount, worldP, normal, dist);
}
contactBuffer.count = contactCount;
}
// This function is for sphere/capsule vs other primitives. We treat sphere as a point and capsule as a segment in the contact gen and store the sphere center or a point in the segment for capsule
// in the manifold.
void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const Vec3VArg projectionNormal,
const PxTransformV& transf0, const FloatVArg radius, const FloatVArg contactOffset)
{
//add the manifold contacts;
PxU32 contactCount = 0;
for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i)
{
const PersistentContact& p = getContactPoint(i);
const FloatV dist = FSub(V4GetW(p.mLocalNormalPen), radius);
//The newly created points should have a dist < contactOffset. However, points might come from the PCM contact cache so we might still have points which are
//larger than contactOffset. The reason why we don't want to discard the contacts in the contact cache whose dist > contactOffset is because the contacts may
//only temporarily become separated. The points still project onto roughly the same spot but so, if the bodies move together again, the contacts may be valid again.
//This is important when simulating at large time-steps because GJK can only generate 1 point of contact and missing contacts for just a single frame with large time-steps
//may introduce noticeable instability.
if(FAllGrtrOrEq(contactOffset, dist))
{
const Vec3V worldP = V3NegScaleSub(projectionNormal, radius, transf0.transform(p.mLocalPointA));
outputPCMContact(contactBuffer, contactCount, worldP, normal, dist);
}
}
contactBuffer.count = contactCount;
}
// This function is used in the box/convexhull full manifold contact genenation. We will pass in a list of manifold contacts. If the number of contacts are more than
// GU_MANIFOLD_CACHE_SIZE, we will need to do contact reduction while we are storing the chosen manifold contacts from the manifold contact list to the manifold contact
// buffer.
void PersistentContactManifold::addBatchManifoldContacts(const PersistentContact* manifoldContacts, PxU32 numPoints, PxReal toleranceLength)
{
if(numPoints <= GU_MANIFOLD_CACHE_SIZE)
{
for(PxU32 i=0; i<numPoints; ++i)
{
mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA;
mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB;
mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen;
}
mNumContacts = PxTo8(numPoints);
}
else
{
reduceBatchContacts(manifoldContacts, numPoints, toleranceLength);
mNumContacts = GU_MANIFOLD_CACHE_SIZE;
}
}
// This function is for the plane and box contact gen. If the number of points passed in is more than 4, we need to do contact reduction
void PersistentContactManifold::addBatchManifoldContactsCluster(const PersistentContact* manifoldContacts, PxU32 numPoints)
{
if(numPoints <= GU_MANIFOLD_CACHE_SIZE)
{
for(PxU32 i=0; i<numPoints; ++i)
{
mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA;
mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB;
mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen;
}
mNumContacts = PxTo8(numPoints);
}
else
{
reduceBatchContactsCluster(manifoldContacts, numPoints);
mNumContacts = GU_MANIFOLD_CACHE_SIZE;
}
}
// This function is called by addBatchManifoldContactCluster. The logic in this funtion is:
// (1)get the depest-penetrated contacts and store it in mContactPoints[0]
// (2)get the furthest away point from mContactPoints[0] and store in mContactPoints[1]
// (3)calculate the min and max distance point away the segment (mContactPoints[0] and mContactPoints[1]) and store the max distance point to mContactPoints[2]
// (4)if the min and max distance on the same side of the segment, we need to chose the min distance point again and store this point to mContactPoints[3];
// (5)cluster around that 4 points and chose the deepest points
// (6)reassign contact points
void PersistentContactManifold::reduceBatchContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints)
{
//get the deepest points
bool chosen[64];
PxMemZero(chosen, sizeof(bool)*numPoints);
const FloatV max = FMax();
const FloatV nmax = FNeg(max);
FloatV maxDist = max;
PxU32 index = 0;
PxU32 indices[4];
//get the deepest point
for(PxU32 i=0; i<numPoints; ++i)
{
const FloatV dist = V4GetW(manifoldPoints[i].mLocalNormalPen);
if(FAllGrtr(maxDist, dist))
{
maxDist = dist;
index = i;
}
}
//keep the furthest points in the first position
mContactPoints[0] = manifoldPoints[index];
chosen[index] = true;
indices[0] = index;
//calculate the furthest away points from mContactPoints[0]
Vec3V v = V3Sub(manifoldPoints[0].mLocalPointB, mContactPoints[0].mLocalPointB);
maxDist = V3Dot(v, v);
index = 0;
for(PxU32 i=1; i<numPoints; ++i)
{
v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = i;
}
}
//PX_ASSERT(chosen[index] == false);
mContactPoints[1] = manifoldPoints[index];
chosen[index] = true;
indices[1] = index;
maxDist = nmax;
index = GU_MANIFOLD_INVALID_INDEX;
v = V3Sub(mContactPoints[1].mLocalPointB, mContactPoints[0].mLocalPointB);
const Vec3V cn0 = Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen);
Vec3V norm = V3Cross(v, cn0);
const FloatV sqLen = V3Dot(norm, norm);
norm = V3Sel(FIsGrtr(sqLen, FZero()), V3ScaleInv(norm, FSqrt(sqLen)), cn0);
FloatV minDist = max;
PxU32 index1 = GU_MANIFOLD_INVALID_INDEX;
//calculate the min and max point away from the segment
for(PxU32 i=0; i<numPoints; ++i)
{
if(!chosen[i])
{
v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = i;
}
if(FAllGrtr(minDist, d))
{
minDist = d;
index1 = i;
}
}
}
//PX_ASSERT(chosen[index] == false && chosen[index1] == false);
mContactPoints[2] = manifoldPoints[index];
chosen[index] = true;
indices[2] = index;
//if min and max in the same side, chose again
const FloatV temp = FMul(minDist, maxDist);
if(FAllGrtr(temp, FZero()))
{
//chose again
maxDist = nmax;
for(PxU32 i=0; i<numPoints; ++i)
{
if(!chosen[i])
{
v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index1 = i;
}
}
}
}
mContactPoints[3] = manifoldPoints[index1];
chosen[index1] = true;
indices[3] = index1;
//cluster around that 4 points and chose the deepest points
for(PxU32 i=0; i<numPoints; ++i)
{
if(!chosen[i])
{
maxDist = max;
const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen);
index = 0;
for(PxU32 j=0; j<4; ++j)
{
const Vec3V v1 = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[j].mLocalPointB);
const FloatV dist = V3Dot(v1, v1);
if(FAllGrtr(maxDist, dist))
{
maxDist = dist;
index = j;
}
}
//check to see whether the penetration is deeper than the point in mContactPoints
const FloatV tempPen = V4GetW(manifoldPoints[indices[index]].mLocalNormalPen);
if(FAllGrtr(tempPen, pen))
{
//swap the indices
indices[index] = i;
}
}
}
mContactPoints[0] = manifoldPoints[indices[0]];
mContactPoints[1] = manifoldPoints[indices[1]];
mContactPoints[2] = manifoldPoints[indices[2]];
mContactPoints[3] = manifoldPoints[indices[3]];
}
// This function is for box/convexhull full contact generation. If the numPoints > 4, we will reduce the contact points to 4
void PersistentContactManifold::reduceBatchContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal tolereanceLength)
{
PxU8 chosenIndices[4];
PxU8 candidates[64];
const FloatV zero = FZero();
const FloatV max = FMax();
const FloatV nmax = FNeg(max);
FloatV maxPen = V4GetW(manifoldPoints[0].mLocalNormalPen);
FloatV minPen = maxPen;
PxU32 index = 0;
candidates[0] = 0;
PxU32 candidateIndex = 0;
PxU32 nbCandiates = numPoints;
//keep the deepest point, candidateIndex will be the same as index
for(PxU32 i = 1; i<numPoints; ++i)
{
//at the begining candidates and indices will be the same
candidates[i] = PxU8(i);
const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen);
minPen = FMax(minPen, pen);
if(FAllGrtr(maxPen, pen))
{
maxPen = pen;
index = i;
candidateIndex = i;
}
}
//keep the deepest points in the first position
chosenIndices[0] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
//indices[index] = nbCandiates;
//calculate the furthest away points
Vec3V v = V3Sub(manifoldPoints[candidates[0]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
FloatV maxDist = V3Dot(v, v);
index = candidates[0];
candidateIndex = 0;
for(PxU32 i = 1; i<nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = candidates[i];
candidateIndex = i;
}
}
chosenIndices[1] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
v = V3Sub(manifoldPoints[chosenIndices[1]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
const Vec3V cn0 = Vec3V_From_Vec4V(manifoldPoints[chosenIndices[0]].mLocalNormalPen);
Vec3V norm = V3Cross(v, cn0);
const FloatV sqLen = V3Dot(norm, norm);
norm = V3Sel(FIsGrtr(sqLen, zero), V3ScaleInv(norm, FSqrt(sqLen)), cn0);
//reset maxDist and index
maxDist = nmax;
index = GU_MANIFOLD_INVALID_INDEX;
candidateIndex = GU_MANIFOLD_INVALID_INDEX;
FloatV minDist = max;
PxU32 index1 = GU_MANIFOLD_INVALID_INDEX;
PxU32 candidateIndex1 = GU_MANIFOLD_INVALID_INDEX;
//calculate the min and max point away from the segment
for(PxU32 i = 0; i<nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = candidates[i];
candidateIndex = i;
}
if(FAllGrtr(minDist, d))
{
minDist = d;
index1 = candidates[i];
candidateIndex1 = i;
}
}
chosenIndices[2] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
if(nbCandiates == candidateIndex1)
candidateIndex1 = candidateIndex;
//if min and max in the same side, chose again
const FloatV temp = FMul(minDist, maxDist);
if(FAllGrtr(temp, zero))
{
//chose again
maxDist = nmax;
for(PxU32 i = 0; i < nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index1 = candidates[i];
candidateIndex1 = i;
}
}
}
chosenIndices[3] = PxU8(index1);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex1] = candidates[nbCandiates];
const FloatV eps = FLoad(tolereanceLength * 0.02f);
const BoolV con = BAnd(FIsGrtr(eps, maxPen), FIsGrtr(minPen, eps));
if(BAllEqTTTT(con))
{
//post process
for(PxU32 i = 0; i < 4; ++i)
{
FloatV pen = V4GetW(manifoldPoints[chosenIndices[i]].mLocalNormalPen);
if(FAllGrtr(pen, eps))
{
candidateIndex = GU_MANIFOLD_INVALID_INDEX;
for(PxU32 j = 0; j < nbCandiates; ++j)
{
const FloatV pen1 = V4GetW(manifoldPoints[candidates[j]].mLocalNormalPen);
if(FAllGrtr(pen, pen1) && FAllGrtr(eps, pen1))
{
pen = pen1;
candidateIndex = j;
}
}
if(candidateIndex < nbCandiates)
{
const PxU8 originalIndex = chosenIndices[i];
chosenIndices[i] = candidates[candidateIndex];
candidates[candidateIndex] = originalIndex;
}
}
mContactPoints[i] = manifoldPoints[chosenIndices[i]];
}
}
else
{
for(PxU32 i = 0; i < 4; ++i)
{
mContactPoints[i] = manifoldPoints[chosenIndices[i]];
}
}
}
// This function is for capsule full contact generation. If the numPoints > 2, we will reduce the contact points to 2
void PersistentContactManifold::reduceBatchContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints)
{
PX_ASSERT(numPoints < 64);
bool chosen[64];
PxMemZero(chosen, sizeof(bool)*numPoints);
FloatV maxDis = V4GetW(manifoldPoints[0].mLocalNormalPen);
PxI32 index = 0;
//keep the deepest point
for(PxU32 i=1; i<numPoints; ++i)
{
const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen);
if(FAllGrtr(maxDis, pen))
{
maxDis = pen;
index = PxI32(i);
}
}
//keep the deepest points in the first position
mContactPoints[0] = manifoldPoints[index];
chosen[index] = true;
//calculate the furthest away points
Vec3V v = V3Sub(manifoldPoints[0].mLocalPointB, mContactPoints[0].mLocalPointB);
maxDis = V3Dot(v, v);
index = 0;
for(PxU32 i=1; i<numPoints; ++i)
{
v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxDis))
{
maxDis = d;
index = PxI32(i);
}
}
//PX_ASSERT(chosen[index] == false);
mContactPoints[1] = manifoldPoints[index];
chosen[index] = true;
PxI32 secondIndex = index;
FloatV maxDepth = V4GetW(manifoldPoints[index].mLocalNormalPen);
for(PxU32 i = 0; i < numPoints; ++i)
{
if(!chosen[i])
{
const Vec3V d0 = V3Sub(mContactPoints[0].mLocalPointB, manifoldPoints[i].mLocalPointB);
const Vec3V d1 = V3Sub(mContactPoints[1].mLocalPointB, manifoldPoints[i].mLocalPointB);
const FloatV dd0 = V3Dot(d0, d0);
const FloatV dd1 = V3Dot(d1, d1);
if(FAllGrtr(dd0, dd1))
{
//This clusters to point 1
if(FAllGrtr(maxDepth, V4GetW(manifoldPoints[i].mLocalNormalPen)))
{
secondIndex = PxI32(i);
}
}
}
}
if(secondIndex != index)
{
mContactPoints[1] = manifoldPoints[secondIndex];
}
}
PxU32 PersistentContactManifold::addManifoldPoint(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen, const FloatVArg replaceBreakingThreshold)
{
if(replaceManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold)) //replace the new point with the old one
return 0;
switch(mNumContacts)
{
case 0:
case 1:
case 2:
case 3:
mContactPoints[mNumContacts].mLocalPointA = localPointA;
mContactPoints[mNumContacts].mLocalPointB = localPointB;
mContactPoints[mNumContacts++].mLocalNormalPen = localNormalPen;
return 1;
default:
return reduceContactsForPCM(localPointA, localPointB, localNormalPen);//should be always return zero
};
}
// This function is for capsule vs other primitives. If the manifold originally has contacts and we can incrementally add a point at a time, we will
// use this function to add a point to manifold. If the number of contacts inside the manifold is more than 2, we will reduce contacts to 2 points.
PxU32 PersistentContactManifold::addManifoldPoint2(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen, const FloatVArg replaceBreakingThreshold)
{
if(replaceManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold)) //replace the new point with the old one
return 0;
switch(mNumContacts)
{
case 0:
case 1:
mContactPoints[mNumContacts].mLocalPointA = localPointA;
mContactPoints[mNumContacts].mLocalPointB = localPointB;
mContactPoints[mNumContacts++].mLocalNormalPen = localNormalPen;
return 1;
case 2:
return reduceContactSegment(localPointA, localPointB, localNormalPen);
default:
PX_ASSERT(0);
};
return 0;
}
// This function is used in the capsule full manifold contact genenation. We will pass in a list of manifold contacts. If the number of contacts are more than
// 2, we will need to do contact reduction while we are storing the chosen manifold contacts from the manifold contact list to the manifold contact buffer.
void PersistentContactManifold::addBatchManifoldContacts2(const PersistentContact* manifoldContacts, PxU32 numPoints)
{
if(numPoints <= 2)
{
for(PxU32 i=0; i<numPoints; ++i)
{
mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA;
mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB;
mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen;
}
mNumContacts = PxTo8(numPoints);
}
else
{
reduceBatchContacts2(manifoldContacts, numPoints);
mNumContacts = 2;
}
}
// If the patch total number of manifold contacts are less than or equal to GU_SINGLE_MANIFOLD_CACHE_SIZE, we will add the manifold contacts in the contact stream to the manifold contact buffer
// which is associated to this single persistent contact manifold. Otherwise, we will reduce the manifold contacts to GU_SINGLE_MANIFOLD_CACHE_SIZE.
FloatV SinglePersistentContactManifold::addBatchManifoldContactsConvex(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold)
{
PX_UNUSED(replaceBreakingThreshold);
if(patch.mTotalSize <= GU_SINGLE_MANIFOLD_CACHE_SIZE)
{
PCMContactPatch* currentPatch = &patch;
//this is because we already add the manifold contacts into manifoldContact array
PxU32 tempNumContacts = 0;
while(currentPatch)
{
for(PxU32 j=currentPatch->mStartIndex; j<currentPatch->mEndIndex; ++j)
{
mContactPoints[tempNumContacts++] = manifoldContact[j];
}
currentPatch = currentPatch->mNextPatch;
}
mNumContacts = tempNumContacts;
return patch.mPatchMaxPen;
}
else
{
//contact reduction
const FloatV maxPen = reduceBatchContactsConvex(manifoldContact, numContactExt, patch);
mNumContacts = GU_SINGLE_MANIFOLD_CACHE_SIZE;
return maxPen;
}
}
FloatV SinglePersistentContactManifold::addBatchManifoldContactsSphere(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold)
{
PX_UNUSED(replaceBreakingThreshold);
const FloatV maxPen = reduceBatchContactsSphere(manifoldContact, numContactExt, patch);
mNumContacts = 1;
return maxPen;
}
FloatV SinglePersistentContactManifold::addBatchManifoldContactsCapsule(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold)
{
PX_UNUSED(replaceBreakingThreshold);
if(patch.mTotalSize <=GU_CAPSULE_MANIFOLD_CACHE_SIZE)
{
PCMContactPatch* currentPatch = &patch;
//this is because we already add the manifold contacts into manifoldContact array
PxU32 tempNumContacts = 0;
while(currentPatch)
{
for(PxU32 j=currentPatch->mStartIndex; j<currentPatch->mEndIndex; ++j)
{
mContactPoints[tempNumContacts++] = manifoldContact[j];
}
currentPatch = currentPatch->mNextPatch;
}
mNumContacts = tempNumContacts;
return patch.mPatchMaxPen;
}
else
{
const FloatV maxPen = reduceBatchContactsCapsule(manifoldContact, numContactExt, patch);
mNumContacts = GU_CAPSULE_MANIFOLD_CACHE_SIZE;
return maxPen;
}
}
FloatV SinglePersistentContactManifold::reduceBatchContactsSphere(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch)
{
PX_UNUSED(numContacts);
FloatV max = FMax();
FloatV maxDist = max;
PxI32 index = -1;
PCMContactPatch* currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen);
if(FAllGrtr(maxDist, pen))
{
maxDist = pen;
index = PxI32(i);
}
}
currentPatch = currentPatch->mNextPatch;
}
PX_ASSERT(index!=-1);
mContactPoints[0] = manifoldContactExt[index];
return maxDist;
}
FloatV SinglePersistentContactManifold::reduceBatchContactsCapsule(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch)
{
bool* chosen = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*numContacts));
PxMemZero(chosen, sizeof(bool)*numContacts);
const FloatV max = FMax();
FloatV maxDis = max;
PxI32 index = -1;
FloatV maxPen = max;
PCMContactPatch* currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen);
if(FAllGrtr(maxDis, pen))
{
maxDis = pen;
index = PxI32(i);
}
}
currentPatch = currentPatch->mNextPatch;
}
chosen[index] = true;
mContactPoints[0] = manifoldContactExt[index];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen));
//calculate the furthest away points
Vec3V v = V3Sub(manifoldContactExt[patch.mStartIndex].mLocalPointB, mContactPoints[0].mLocalPointB);
maxDis = V3Dot(v, v);
index = PxI32(patch.mStartIndex);
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
v = V3Sub(manifoldContactExt[i].mLocalPointB, mContactPoints[0].mLocalPointB);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxDis))
{
maxDis = d;
index = PxI32(i);
}
}
currentPatch = currentPatch->mNextPatch;
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
mContactPoints[1] = manifoldContactExt[index];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen));
//keep the second deepest point
maxDis = max;
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
if(!chosen[i])
{
const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen);
//const FloatV v = V3Dot(manifoldContactExt[i].mLocalPointB, manifoldContactExt[i].mLocalPointB);
if(FAllGrtr(maxDis, pen))
{
maxDis = pen;
index = PxI32(i);
}
}
}
currentPatch = currentPatch->mNextPatch;
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
mContactPoints[2] = manifoldContactExt[index];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen));
return maxPen;
}
FloatV SinglePersistentContactManifold::reduceBatchContactsConvex(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch)
{
bool* chosen = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*numContacts));
PxMemZero(chosen, sizeof(bool)*numContacts);
const FloatV max = FMax();
const FloatV nmax = FNeg(max);
FloatV maxDis = nmax;
PxU32 index = GU_MANIFOLD_INVALID_INDEX;
PCMContactPatch* currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
//const FloatV pen = V4GetW(manifoldContactExt[i].localNormalPen);
const FloatV v = V3Dot(manifoldContactExt[i].mLocalPointB, manifoldContactExt[i].mLocalPointB);
if(FAllGrtr(v, maxDis))
{
maxDis = v;
index = i;
}
}
currentPatch = currentPatch->mNextPatch;
}
chosen[index] = true;
const Vec3V contact0 = manifoldContactExt[index].mLocalPointB;
mContactPoints[0] = manifoldContactExt[index];
FloatV maxPen = V4GetW(manifoldContactExt[index].mLocalNormalPen);
//calculate the furthest away points
Vec3V v = V3Sub(manifoldContactExt[patch.mStartIndex].mLocalPointB, contact0);
maxDis = V3Dot(v, v);
index = patch.mStartIndex;
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxDis))
{
maxDis = d;
index = i;
}
}
currentPatch = currentPatch->mNextPatch;
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
const Vec3V contact1 = manifoldContactExt[index].mLocalPointB;
mContactPoints[1] = manifoldContactExt[index];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen));
maxDis = nmax;
index = GU_MANIFOLD_INVALID_INDEX;
v = V3Sub(contact1, contact0);
const Vec3V cn0 = Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen);
Vec3V norm = V3Cross(v, cn0);
const FloatV sqLen = V3Dot(norm, norm);
norm = V3Sel(FIsGrtr(sqLen, FZero()), V3ScaleInv(norm, FSqrt(sqLen)), cn0);
FloatV minDis = max;
PxU32 index1 = GU_MANIFOLD_INVALID_INDEX;
//calculate the point furthest way to the segment
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
if(!chosen[i])
{
v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDis))
{
maxDis = d;
index = i;
}
if(FAllGrtr(minDis, d))
{
minDis = d;
index1 = i;
}
}
}
currentPatch = currentPatch->mNextPatch;
}
//PX_ASSERT(chosen[index] == false);
chosen[index] = true;
mContactPoints[2] = manifoldContactExt[index];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen));
//if min and max in the same side, choose again
const FloatV temp = FMul(minDis, maxDis);
if(FAllGrtr(temp, FZero()))
{
//choose again
maxDis = nmax;
//calculate the point furthest way to the segment
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i)
{
if(!chosen[i])
{
v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDis))
{
maxDis = d;
index1 = i;
}
}
}
currentPatch = currentPatch->mNextPatch;
}
}
//PX_ASSERT(chosen[index1] == false);
chosen[index1] = true;
mContactPoints[3] = manifoldContactExt[index1];
maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index1].mLocalNormalPen));
const PxU32 NB_TO_ADD = GU_SINGLE_MANIFOLD_CACHE_SIZE - 4;
FloatV pens[NB_TO_ADD];
PxU32 inds[NB_TO_ADD];
for(PxU32 a = 0; a < NB_TO_ADD; ++a)
{
pens[a] = FMax();
inds[a] = 0;
}
{
currentPatch = &patch;
while(currentPatch)
{
for(PxU32 i = currentPatch->mStartIndex; i < currentPatch->mEndIndex; ++i)
{
if(!chosen[i])
{
const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen);
for(PxU32 a = 0; a < NB_TO_ADD; ++a)
{
if(FAllGrtr(pens[a], pen))
{
for(PxU32 b = a + 1; b < NB_TO_ADD; ++b)
{
pens[b] = pens[b - 1];
inds[b] = inds[b - 1];
}
pens[a] = pen;
inds[a] = i;
break;
}
}
}
}
currentPatch = currentPatch->mNextPatch;
}
for(PxU32 i = 0; i < NB_TO_ADD; ++i)
{
mContactPoints[i + 4] = manifoldContactExt[inds[i]];
maxPen = FMin(maxPen, pens[i]);
}
}
return maxPen;
}
PxU32 SinglePersistentContactManifold::reduceContacts(MeshPersistentContact* manifoldPoints, PxU32 numPoints)
{
PxU8 chosenIndices[GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE];
PxU8* candidates = reinterpret_cast<PxU8*>(PxAlloca(sizeof(PxU8) * numPoints));
//(1) Remove duplicates...
for(PxU32 i = 0; i < numPoints; ++i)
{
Vec3V localPointB = manifoldPoints[i].mLocalPointB;
for(PxU32 j = i+1; j < numPoints; ++j)
{
if(V3AllGrtr(V3Eps(), V3Abs(V3Sub(localPointB, manifoldPoints[j].mLocalPointB))))
{
manifoldPoints[j] = manifoldPoints[numPoints - 1];
j--;
numPoints--;
}
}
}
if(numPoints <= GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE)
return numPoints;
const FloatV max = FMax();
const FloatV nmax = FNeg(max);
FloatV maxPen = V4GetW(manifoldPoints[0].mLocalNormalPen);
PxU32 index = 0;
candidates[0] = 0;
PxU32 candidateIndex = 0;
PxU32 nbCandiates = numPoints;
MeshPersistentContact newManifold[GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE];
//keep the deepest point
for(PxU32 i = 1; i<numPoints; ++i)
{
//at the begining candidates and indices will be the same
candidates[i] = PxU8(i);
const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen);
if(FAllGrtr(maxPen, pen))
{
maxPen = pen;
index = i;
candidateIndex = i;
}
}
//keep the deepest points in the first position
chosenIndices[0] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
//keep the deepest points in the first position
newManifold[0] = manifoldPoints[chosenIndices[0]];
//calculate the furthest away points
Vec3V v = V3Sub(manifoldPoints[candidates[0]].mLocalPointB, newManifold[0].mLocalPointB);
maxPen = V3Dot(v, v);
index = candidates[0];
candidateIndex = 0;
for(PxU32 i = 1; i<nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB);
const FloatV d = V3Dot(v, v);
if(FAllGrtr(d, maxPen))
{
maxPen = d;
index = candidates[i];
candidateIndex = i;
}
}
chosenIndices[1] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
newManifold[1] = manifoldPoints[chosenIndices[1]];
v = V3Sub(newManifold[1].mLocalPointB, newManifold[0].mLocalPointB);
const Vec3V cn0 = Vec3V_From_Vec4V(newManifold[0].mLocalNormalPen);
Vec3V norm = V3Cross(v, cn0);
FloatV maxDist = nmax;
FloatV minDist = max;
index = GU_MANIFOLD_INVALID_INDEX;
PxU32 index1 = GU_MANIFOLD_INVALID_INDEX;
PxU32 candidateIndex1 = GU_MANIFOLD_INVALID_INDEX;
//calculate the point furthest way to the segment
for(PxU32 i = 0; i<nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, newManifold[0].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index = candidates[i];
candidateIndex = i;
}
if(FAllGrtr(minDist, d))
{
minDist = d;
index1 = candidates[i];
candidateIndex1 = i;
}
}
chosenIndices[2] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
newManifold[2] = manifoldPoints[chosenIndices[2]];
if(nbCandiates == candidateIndex1)
candidateIndex1 = candidateIndex;
const FloatV temp = FMul(minDist, maxDist);
if(FAllGrtr(temp, FZero()))
{
//chose again
maxDist = nmax;
for(PxU32 i = 0; i < nbCandiates; ++i)
{
v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, newManifold[0].mLocalPointB);
const FloatV d = V3Dot(v, norm);
if(FAllGrtr(d, maxDist))
{
maxDist = d;
index1 = candidates[i];
candidateIndex1 = i;
}
}
}
chosenIndices[3] = PxU8(index1);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex1] = candidates[nbCandiates];
newManifold[3] = manifoldPoints[chosenIndices[3]];
maxDist = max;
index = GU_MANIFOLD_INVALID_INDEX;
candidateIndex = GU_MANIFOLD_INVALID_INDEX;
//choose the 5 point, second deepest in the left overlap point
for(PxU32 i = 0; i < nbCandiates; ++i)
{
const FloatV pen = V4GetW(manifoldPoints[candidates[i]].mLocalNormalPen);
if(FAllGrtr(maxDist, pen))
{
maxDist = pen;
index = candidates[i];
candidateIndex = i;
}
}
chosenIndices[4] = PxU8(index);
//move the chosen indices out of the candidates indices
nbCandiates = nbCandiates - 1;
candidates[candidateIndex] = candidates[nbCandiates];
newManifold[4] = manifoldPoints[chosenIndices[4]];
//copy the new manifold back
for(PxU32 i = 0; i<GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; ++i)
{
manifoldPoints[i] = newManifold[i];
}
return GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE;
}
FloatV SinglePersistentContactManifold::refreshContactPoints(const PxMatTransformV& aToB, const FloatVArg projectBreakingThreshold, const FloatVArg /*contactOffset*/)
{
const FloatV sqProjectBreakingThreshold = FMul(projectBreakingThreshold, projectBreakingThreshold);
FloatV maxPen = FZero();
// first refresh worldspace positions and distance
for(PxU32 i=mNumContacts; i > 0; --i)
{
MeshPersistentContact& manifoldPoint = mContactPoints[i-1];
const Vec3V localAInB = aToB.transform( manifoldPoint.mLocalPointA ); // from a to b
const Vec3V localBInB = manifoldPoint.mLocalPointB;
const Vec3V v = V3Sub(localAInB, localBInB);
const Vec3V localNormal = Vec3V_From_Vec4V(manifoldPoint.mLocalNormalPen); // normal in b space
const FloatV dist= V3Dot(v, localNormal);
const Vec3V projectedPoint = V3NegScaleSub(localNormal, dist, localAInB);//manifoldPoint.worldPointA - manifoldPoint.worldPointB * manifoldPoint.m_distance1;
const Vec3V projectedDifference = V3Sub(localBInB, projectedPoint);
const FloatV distance2d = V3Dot(projectedDifference, projectedDifference);
//const BoolV con = BOr(FIsGrtr(dist, contactOffset), FIsGrtr(distance2d, sqProjectBreakingThreshold));
const BoolV con = FIsGrtr(distance2d, sqProjectBreakingThreshold);
if(BAllEqTTTT(con))
{
removeContactPoint(i-1);
}
else
{
manifoldPoint.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), dist);
maxPen = FMin(maxPen, dist);
}
}
return maxPen;
}
void SinglePersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b;
V3StoreU(trA.p, a);
V3StoreU(trB.p, b);
for(PxU32 i = 0; i< mNumContacts; ++i)
{
const MeshPersistentContact& m = mContactPoints[i];
drawManifoldPoint(m, trA, trB, out, gColors[i]);
}
#else
PX_UNUSED(out);
PX_UNUSED(trA);
PX_UNUSED(trB);
#endif
}
void MultiplePersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const
{
for(PxU32 i=0; i<mNumManifolds; ++i)
{
const SinglePersistentContactManifold* manifold = getManifold(i);
manifold->drawManifold(out, trA, trB);
}
}
void MultiplePersistentContactManifold::drawLine(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
PxVec3 a, b;
V3StoreU(p0, a);
V3StoreU(p1, b);
PxMat44 m = PxMat44(PxIdentity);
out << color << m << PxRenderOutput::LINES << a << b;
#else
PX_UNUSED(out);
PX_UNUSED(p0);
PX_UNUSED(p1);
PX_UNUSED(color);
#endif
}
void MultiplePersistentContactManifold::drawLine(PxRenderOutput& out, const PxVec3 p0, const PxVec3 p1, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
PxMat44 m = PxMat44(PxIdentity);
out << color << m << PxRenderOutput::LINES << p0 << p1;
#else
PX_UNUSED(out);
PX_UNUSED(p0);
PX_UNUSED(p1);
PX_UNUSED(color);
#endif
}
void MultiplePersistentContactManifold::drawPoint(PxRenderOutput& out, const Vec3VArg p, const PxF32 size, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
const PxVec3 up(0.f, size, 0.f);
const PxVec3 right(size, 0.f, 0.f);
const PxVec3 forwards(0.f, 0.f, size);
PxVec3 a;
V3StoreU(p, a);
PxMat44 m = PxMat44(PxIdentity);
out << color << m << PxRenderOutput::LINES << a + up << a - up;
out << color << m << PxRenderOutput::LINES << a + right << a - right;
out << color << m << PxRenderOutput::LINES << a + forwards << a - forwards;
#else
PX_UNUSED(out);
PX_UNUSED(p);
PX_UNUSED(size);
PX_UNUSED(color);
#endif
}
void MultiplePersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxTransformV& transform, Vec3V* points, PxU32 numVerts, PxU32 color)
{
#if VISUALIZE_PERSISTENT_CONTACT
for(PxU32 i=0; i<numVerts; ++i)
{
Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1];
Vec3V tempV1 = points[i];
drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color);
}
#else
PX_UNUSED(out);
PX_UNUSED(transform);
PX_UNUSED(points);
PX_UNUSED(numVerts);
PX_UNUSED(color);
#endif
}
static FloatV addBatchManifoldContactsToSingleManifold(SinglePersistentContactManifold* manifold, MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch* patch, const FloatVArg sqReplaceBreakingThreshold, PxU8 maxContactsPerManifold)
{
switch(maxContactsPerManifold)
{
case GU_SPHERE_MANIFOLD_CACHE_SIZE://sphere
return manifold->addBatchManifoldContactsSphere(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold);
case GU_CAPSULE_MANIFOLD_CACHE_SIZE://capsule, need to implement keep two deepest
return manifold->addBatchManifoldContactsCapsule(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold);
default://cache size GU_SINGLE_MANIFOLD_CACHE_SIZE
return manifold->addBatchManifoldContactsConvex(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold);
};
}
// This function adds the manifold contacts with different patches into the corresponding single persistent contact manifold
void MultiplePersistentContactManifold::addManifoldContactPoints(MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch** contactPatch, PxU32 numPatch, const FloatVArg sqReplaceBreakingThreshold, const FloatVArg acceptanceEpsilon, PxU8 maxContactsPerManifold)
{
if(mNumManifolds == 0)
{
for(PxU32 i=0; i<numPatch; ++i)
{
PCMContactPatch* patch = contactPatch[i];
//this mean the patch hasn't been add to the manifold
if(patch->mRoot == patch)
{
SinglePersistentContactManifold* manifold = getEmptyManifold();
if(manifold)
{
const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold);
FStore(_maxPen, &mMaxPen[mManifoldIndices[mNumManifolds]]);
mNumManifolds++;
}
else
{
//We already pre-sorted the patches so we know we can return here
return;
}
}
}
}
else
{
//we do processContacts() when the number of contacts are more than 16, such that, we might call processContacts() multiple times when we have very detailed mesh
//or very large contact offset/objects. In this case, the mNumManifolds will be large than 0.
PCMContactPatch tempPatch;
for(PxU32 i=0; i<numPatch; ++i)
{
bool found = false;
PCMContactPatch* patch = contactPatch[i];
//this mean the patch has't been add to the manifold
if(patch->mRoot == patch)
{
PX_ASSERT(mNumManifolds <= GU_MAX_MANIFOLD_SIZE);
for(PxU32 j=0; j<mNumManifolds; ++j)
{
PX_ASSERT(mManifoldIndices[j] < GU_MAX_MANIFOLD_SIZE);
SinglePersistentContactManifold& manifold = *getManifold(j);
const Vec3V pNor = manifold.getLocalNormal();
const FloatV d = V3Dot(patch->mPatchNormal, pNor);
if(FAllGrtrOrEq(d, acceptanceEpsilon))
{
//appending the existing contacts to the manifold contact stream
for(PxU32 k=0; k< manifold.mNumContacts; ++k)
{
PxU32 index = k + numManifoldContacts;
//not duplicate point
PX_ASSERT(index < 64);
manifoldContact[index] = manifold.mContactPoints[k];
}
//create a new patch for the exiting manifold
tempPatch.mStartIndex = numManifoldContacts;
tempPatch.mEndIndex = numManifoldContacts + manifold.mNumContacts;
tempPatch.mPatchNormal = pNor;//manifold.getLocalNormal();
tempPatch.mRoot = patch;
tempPatch.mNextPatch = NULL;
patch->mEndPatch->mNextPatch = &tempPatch;
//numManifoldContacts += manifold.numContacts;
patch->mTotalSize += manifold.mNumContacts;
patch->mPatchMaxPen = FMin(patch->mPatchMaxPen, FLoad(mMaxPen[mManifoldIndices[j]]));
//manifold.numContacts = 0;
PX_ASSERT((numManifoldContacts+manifold.mNumContacts) <= 64);
const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(&manifold, manifoldContact, numManifoldContacts+manifold.mNumContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold);
FStore(_maxPen, &mMaxPen[mManifoldIndices[j]]);
found = true;
break;
}
}
if(!found)// && numManifolds < 4)
{
SinglePersistentContactManifold* manifold = getEmptyManifold();
//we still have slot to create a new manifold
if(manifold)
{
const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold);
FStore(_maxPen, &mMaxPen[mManifoldIndices[mNumManifolds]]);
mNumManifolds++;
}
else
{
//we can't allocate a new manifold and no existing manifold has the same normal as this patch, we need to find the shallowest penetration manifold. If this manifold is shallower than
//the current patch, replace the manifold with the current patch
PxU32 index = 0;
for(PxU32 j=1; j<mNumManifolds; ++j)
{
//if(FAllGrtr(mMaxPen[mManifoldIndices[i]], mMaxPen[mManifoldIndices[index]]))
if(mMaxPen[mManifoldIndices[j]] > mMaxPen[mManifoldIndices[index]])
{
index = j;
}
}
if(FAllGrtr(FLoad(mMaxPen[mManifoldIndices[index]]), patch->mPatchMaxPen))
{
manifold = getManifold(index);
manifold->mNumContacts = 0;
const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold);
FStore(_maxPen, &mMaxPen[mManifoldIndices[index]]);
}
return;
}
}
}
}
}
}
//This function adds the multi manifold contacts to the contact buffer for box/convexhull
bool MultiplePersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const PxTransformV& meshTransform)
{
PxU32 contactCount = 0;
PxU32 numContacts = 0;
mNumTotalContacts = 0;
//drawManifold(*gRenderOutPut, convexTransform, meshTransform);
for(PxU32 i=0; i < mNumManifolds; ++i)
{
SinglePersistentContactManifold& manifold = *getManifold(i);
numContacts = manifold.getNumContacts();
PX_ASSERT(mNumTotalContacts + numContacts <= 0xFF);
mNumTotalContacts += PxTo8(numContacts);
const Vec3V normal = manifold.getWorldNormal(meshTransform);
for(PxU32 j=0; (j< numContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++j)
{
const MeshPersistentContact& p = manifold.getContactPoint(j);
const Vec3V worldP =meshTransform.transform(p.mLocalPointB);
const FloatV dist = V4GetW(p.mLocalNormalPen);
outputPCMContact(contactBuffer, contactCount, worldP, normal, dist, p.mFaceIndex);
}
}
PX_ASSERT(contactCount <= PxContactBuffer::MAX_CONTACTS);
contactBuffer.count = contactCount;
return contactCount > 0;
}
//This function adds the multi manifold contacts to the contact buffer for sphere and capsule, radius is corresponding to the sphere radius/capsule radius
bool MultiplePersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius)
{
PxU32 contactCount = 0;
PxU32 numContacts = 0;
mNumTotalContacts = 0;
for(PxU32 i=0; i < mNumManifolds; ++i)
{
//get a single manifold
SinglePersistentContactManifold& manifold = *getManifold(i);
numContacts = manifold.getNumContacts();
PX_ASSERT(mNumTotalContacts + numContacts <= 0xFF);
mNumTotalContacts += PxTo8(numContacts);
const Vec3V normal = manifold.getWorldNormal(trB);
//iterate all the contacts in this single manifold and add contacts to the contact buffer
//each manifold contact point store two points which are in each other's local space. In this
//case, mLocalPointA is stored as the center of sphere/a point in the segment for capsule
for(PxU32 j=0; (j< numContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++j)
{
const MeshPersistentContact& p = manifold.getContactPoint(j);
const Vec3V worldP = V3NegScaleSub(normal, radius, trA.transform(p.mLocalPointA));
const FloatV dist = FSub(V4GetW(p.mLocalNormalPen), radius);
outputPCMContact(contactBuffer, contactCount, worldP, normal, dist, p.mFaceIndex);
}
}
PX_ASSERT(contactCount <= PxContactBuffer::MAX_CONTACTS);
contactBuffer.count = contactCount;
return contactCount > 0;
}
// This function copies the mesh persistent contact from compress buffer(NpCacheStreamPair in the PxcNpThreadContext) to the multiple manifold
// PT: function moved to cpp to go around a compiler bug on PS4
void MultiplePersistentContactManifold::fromBuffer(PxU8* PX_RESTRICT buffer)
{
PxU32 numManifolds = 0;
if (buffer != NULL)
{
PX_ASSERT(((uintptr_t(buffer)) & 0xF) == 0);
PxU8* PX_RESTRICT buff = buffer;
MultiPersistentManifoldHeader* PX_RESTRICT header = reinterpret_cast<MultiPersistentManifoldHeader*>(buff);
buff += sizeof(MultiPersistentManifoldHeader);
numManifolds = header->mNumManifolds;
PX_ASSERT(numManifolds <= GU_MAX_MANIFOLD_SIZE);
mRelativeTransform = header->mRelativeTransform;
for (PxU32 a = 0; a < numManifolds; ++a)
{
mManifoldIndices[a] = PxU8(a);
SingleManifoldHeader* PX_RESTRICT manHeader = reinterpret_cast<SingleManifoldHeader*>(buff);
buff += sizeof(SingleManifoldHeader);
PxU32 numContacts = manHeader->mNumContacts;
PX_ASSERT(numContacts <= GU_SINGLE_MANIFOLD_CACHE_SIZE);
SinglePersistentContactManifold& manifold = mManifolds[a];
manifold.mNumContacts = numContacts;
PX_ASSERT((uintptr_t(buff) & 0xf) == 0);
CachedMeshPersistentContact* contacts = reinterpret_cast<CachedMeshPersistentContact*>(buff);
for (PxU32 b = 0; b < manifold.mNumContacts; ++b)
{
manifold.mContactPoints[b].mLocalPointA = Vec3V_From_Vec4V(V4LoadA(&contacts[b].mLocalPointA.x));
manifold.mContactPoints[b].mLocalPointB = Vec3V_From_Vec4V(V4LoadA(&contacts[b].mLocalPointB.x));
manifold.mContactPoints[b].mLocalNormalPen = V4LoadA(&contacts[b].mLocalNormal.x);
manifold.mContactPoints[b].mFaceIndex = contacts[b].mFaceIndex;
}
buff += sizeof(CachedMeshPersistentContact) * numContacts;
}
}
else
{
mRelativeTransform.invalidate();
}
mNumManifolds = PxU8(numManifolds);
for (PxU32 a = numManifolds; a < GU_MAX_MANIFOLD_SIZE; ++a)
{
mManifoldIndices[a] = PxU8(a);
}
}
// This function copies the mesh persistent contact from the multiple manifold to compress buffer(NpCacheStreamPair in the PxcNpThreadContext)
void MultiplePersistentContactManifold::toBuffer(PxU8* PX_RESTRICT buffer) const
{
PxU8* buff = buffer;
PX_ASSERT(((uintptr_t(buff)) & 0xF) == 0);
MultiPersistentManifoldHeader* PX_RESTRICT header = reinterpret_cast<MultiPersistentManifoldHeader*>(buff);
buff += sizeof(MultiPersistentManifoldHeader);
PX_ASSERT(mNumManifolds <= GU_MAX_MANIFOLD_SIZE);
header->mNumManifolds = mNumManifolds;
header->mRelativeTransform = mRelativeTransform;
for(PxU32 a = 0; a < mNumManifolds; ++a)
{
SingleManifoldHeader* manHeader = reinterpret_cast<SingleManifoldHeader*>(buff);
buff += sizeof(SingleManifoldHeader);
const SinglePersistentContactManifold& manifold = *getManifold(a);
manHeader->mNumContacts = manifold.mNumContacts;
PX_ASSERT((uintptr_t(buff) & 0xf) == 0);
CachedMeshPersistentContact* contacts = reinterpret_cast<CachedMeshPersistentContact*>(buff);
//convert the mesh persistent contact to cached mesh persistent contact to save 16 byte memory per contact
for(PxU32 b = 0; b<manifold.mNumContacts; ++b)
{
V4StoreA(Vec4V_From_Vec3V(manifold.mContactPoints[b].mLocalPointA), &contacts[b].mLocalPointA.x);
V4StoreA(Vec4V_From_Vec3V(manifold.mContactPoints[b].mLocalPointB), &contacts[b].mLocalPointB.x);
V4StoreA(manifold.mContactPoints[b].mLocalNormalPen, &contacts[b].mLocalNormal.x);
//Note - this must be written last because we just wrote mLocalPointA to this memory so need to make sure
//that face index is written after that.
contacts[b].mFaceIndex = manifold.mContactPoints[b].mFaceIndex;
}
buff += sizeof(CachedMeshPersistentContact) * manifold.mNumContacts;
}
}
void Gu::addManifoldPoint(PersistentContact* manifoldContacts, PersistentContactManifold& manifold, GjkOutput& output,
const PxMatTransformV& aToB, const FloatV replaceBreakingThreshold)
{
const Vec3V localPointA = aToB.transformInv(output.closestA);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
//Add contact to contact stream
manifoldContacts[0].mLocalPointA = localPointA;
manifoldContacts[0].mLocalPointB = output.closestB;
manifoldContacts[0].mLocalNormalPen = localNormalPen;
//Add contact to manifold
manifold.addManifoldPoint(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold);
}
| 72,749 | C++ | 30.740838 | 287 | 0.71836 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneConvex.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 "GuVecConvexHull.h"
#include "GuContactMethodImpl.h"
#include "GuPersistentContactManifold.h"
using namespace physx;
bool Gu::pcmContactPlaneConvex(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(shape0);
PX_UNUSED(renderOutput);
using namespace aos;
PersistentContactManifold& manifold = cache.getManifold();
PxPrefetchLine(&manifold, 256);
// Get actual shape data
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1);
const PxTransformV transf0 = loadTransformA(transform1);//convex transform
const PxTransformV transf1 = loadTransformA(transform0);//plane transform
//convex to plane
const PxTransformV curTransf(transf1.transformInv(transf0));
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const ConvexHullData* hullData = _getHullData(shapeConvex);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength);
//in world space
const Vec3V planeNormal = V3Normalize(QuatGetBasisVector0(transf1.q));
const Vec3V negPlaneNormal = V3Neg(planeNormal);
const FloatV contactDist = FLoad(params.mContactDistance);
//const FloatV replaceBreakingThreshold = FMul(convexMargin, FLoad(0.001f));
const FloatV projectBreakingThreshold = FMul(convexMargin, FLoad(0.2f));
const PxU32 initialContacts = manifold.mNumContacts;
manifold.refreshContactPoints(curTransf, projectBreakingThreshold, contactDist);
const PxU32 newContacts = manifold.mNumContacts;
const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts));
if(bLostContacts || manifold.invalidate_PrimitivesPlane(curTransf, convexMargin, FLoad(0.2f)))
{
const PxMatTransformV aToB(curTransf);
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const Mat33V vertex2Shape = ConstructVertex2ShapeMatrix(vScale, vQuat);
//ML:localNormal is the local space of plane normal, however, because shape1 is box and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints
//work out the correct pentration for points
const Vec3V localNormal = V3UnitX();
manifold.mNumContacts = 0;
manifold.setRelativeTransform(curTransf);
const PxVec3* PX_RESTRICT verts = hullData->getHullVertices();
const PxU32 nbPolygons = hullData->mNbPolygons;
const Vec3V n = V3Normalize(M33MulV3(vertex2Shape, aToB.rotateInv(localNormal)));
const Vec3V nnormal = V3Neg(n);
const FloatV zero = FZero();
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
PxU32 numContacts = 0;
const PxMatTransformV aToBVertexSpace(aToB.p, M33MulM33(aToB.rot, vertex2Shape));
FloatV minProj = FMax();
PxU32 closestFaceIndex = 0;
PxU32 polyIndex2 = 0xFFFFFFFF;
for (PxU32 i = 0; i < nbPolygons; ++i)
{
const HullPolygonData& polyData = hullData->mPolygons[i];
const Vec3V planeN = V3LoadU_SafeReadW(polyData.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 = hullData->mNbEdges;
const PxU8* const edgeToFace = hullData->getFacesByEdges8();
//Loop through edges
PxU32 closestEdge = 0xffffffff;
//We subtract a small bias to increase the chances of selecting an edge below
minProj = FSub(minProj, FLoad(5e-4f));
FloatV maxDpSq = FMul(minProj, minProj);
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(hullData->mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const Vec3V planeNormal1 = V3LoadU_SafeReadW(hullData->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);
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(hullData->mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class
const Vec3V planeNormal1 = V3LoadU_SafeReadW(hullData->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);
}
}
for (PxU32 index = closestFaceIndex; index != 0xFFFFFFFF; index = polyIndex2, polyIndex2 = 0xFFFFFFFF)
{
const HullPolygonData& face = hullData->mPolygons[closestFaceIndex];
const PxU32 nbFaceVerts = face.mNbVerts;
const PxU8* vertInds = hullData->getVertexData8() + face.mVRef8;
for (PxU32 i = 0; i < nbFaceVerts; ++i)
{
const Vec3V pInVertexSpace = V3LoadU(verts[vertInds[i]]);
//transform p into plane space
const Vec3V pInPlaneSpace = aToBVertexSpace.transform(pInVertexSpace);//V3Add(aToB.p, M33MulV3(temp1, pInVertexSpace));
const FloatV signDist = V3GetX(pInPlaneSpace);
if (FAllGrtr(contactDist, signDist))
{
//transform p into shape space
const Vec3V pInShapeSpace = M33MulV3(vertex2Shape, pInVertexSpace);
//add to manifold
manifoldContacts[numContacts].mLocalPointA = pInShapeSpace;
manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, signDist, pInPlaneSpace);
manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist);
if (numContacts == 64)
{
manifold.reduceBatchContactsCluster(manifoldContacts, numContacts);
numContacts = GU_MANIFOLD_CACHE_SIZE;
for (PxU32 c = 0; c < GU_MANIFOLD_CACHE_SIZE; ++c)
manifoldContacts[c] = manifold.mContactPoints[c];
}
}
}
}
//reduce contacts
//manifold.addBatchManifoldContactsCluster(manifoldContacts, numContacts);
manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength);
}
manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return manifold.getNumContacts() > 0;
}
| 8,992 | C++ | 38.442982 | 216 | 0.739101 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereConvex.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 "GuGJKPenetration.h"
#include "GuEPA.h"
#include "GuVecCapsule.h"
#include "GuVecConvexHull.h"
#include "GuVecConvexHullNoScale.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static void addToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg worldNormal, const Vec3VArg worldPoint, const FloatVArg penDep)
{
outputSimplePCMContact(contactBuffer, worldPoint, worldNormal, penDep);
}
static bool fullContactsGenerationSphereConvex(const CapsuleV& capsule, const ConvexHullV& convexHull, const PxTransformV& transf0, const PxTransformV& transf1,
PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, const bool idtScale, PersistentContactManifold& manifold,
Vec3VArg normal, const FloatVArg contactDist, bool doOverlapTest, PxRenderOutput* renderOutput)
{
PX_UNUSED(renderOutput);
PolygonalData polyData;
getPCMConvexData(convexHull,idtScale, polyData);
PX_ALIGN(16, PxU8 buff[sizeof(SupportLocalImpl<ConvexHullV>)]);
SupportLocal* map = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) :
static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)));
PxU32 numContacts = 0;
if(generateSphereFullContactManifold(capsule, polyData, map, manifoldContacts, numContacts, contactDist, normal, doOverlapTest))
{
if(numContacts > 0)
{
PersistentContact& p = manifold.getContactPoint(0);
p.mLocalPointA = manifoldContacts[0].mLocalPointA;
p.mLocalPointB = manifoldContacts[0].mLocalPointB;
p.mLocalNormalPen = manifoldContacts[0].mLocalNormalPen;
manifold.mNumContacts =1;
//transform normal to world space
const Vec3V worldNormal = transf1.rotate(normal);
const Vec3V worldP = V3NegScaleSub(worldNormal, capsule.radius, transf0.p);
const FloatV penDep = FSub(V4GetW(manifoldContacts[0].mLocalNormalPen), capsule.radius);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius);
#endif
addToContactBuffer(contactBuffer, worldNormal, worldP, penDep);
return true;
}
}
return false;
}
bool Gu::pcmContactSphereConvex(GU_CONTACT_METHOD_ARGS)
{
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1);
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
PersistentContactManifold& manifold = cache.getManifold();
const Vec3V zeroV = V3Zero();
const ConvexHullData* hullData = _getHullData(shapeConvex);
PxPrefetchLine(hullData);
const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const FloatV sphereRadius = FLoad(shapeSphere.radius);
const FloatV contactDist = FLoad(params.mContactDistance);
//Transfer A into the local space of B
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans(transf1.transformInv(transf0));
const PxMatTransformV aToB(curRTrans);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength);
const PxU32 initialContacts = manifold.mNumContacts;
const FloatV minMargin = FMin(convexMargin, sphereRadius);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.05f));
const FloatV refreshDistance = FAdd(sphereRadius, contactDist);
manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDistance);
//ML: after refreshContactPoints, we might lose some contacts
const bool bLostContacts = (manifold.mNumContacts != initialContacts);
if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin))
{
GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT;
manifold.setRelativeTransform(curRTrans);
const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x);
const bool idtScale = shapeConvex.scale.isIdentity();
//use the original shape
const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale);
//transform capsule into the local space of convexHull
const CapsuleV capsule(aToB.p, sphereRadius);
GjkOutput output;
const LocalConvex<CapsuleV> convexA(capsule);
const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), convexHull.getCenter());
if(idtScale)
{
const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull));
status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, initialSearchDir, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull);
status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
}
if(status == GJK_NON_INTERSECT)
{
return false;
}
else if(status == GJK_CONTACT)
{
PersistentContact& p = manifold.getContactPoint(0);
p.mLocalPointA = zeroV;//sphere center
p.mLocalPointB = output.closestB;
p.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
manifold.mNumContacts =1;
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius);
#endif
//transform normal to world space
const Vec3V worldNormal = transf1.rotate(output.normal);
const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p);
const FloatV penDep = FSub(output.penDep, sphereRadius);
addToContactBuffer(contactBuffer, worldNormal, worldP, penDep);
return true;
}
else if(status == GJK_DEGENERATE)
{
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
return fullContactsGenerationSphereConvex(capsule, convexHull, transf0, transf1, manifoldContacts, contactBuffer, idtScale,
manifold, output.normal, contactDist, true, renderOutput);
}
else if (status == EPA_CONTACT)
{
if (idtScale)
{
const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull));
status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull);
status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
}
if (status == EPA_CONTACT)
{
PersistentContact& p = manifold.getContactPoint(0);
p.mLocalPointA = zeroV;//sphere center
p.mLocalPointB = output.closestB;
p.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
manifold.mNumContacts = 1;
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius);
#endif
//transform normal to world space
const Vec3V worldNormal = transf1.rotate(output.normal);
const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p);
const FloatV penDep = FSub(output.penDep, sphereRadius);
addToContactBuffer(contactBuffer, worldNormal, worldP, penDep);
return true;
}
else
{
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
return fullContactsGenerationSphereConvex(capsule, convexHull, transf0, transf1, manifoldContacts, contactBuffer, idtScale,
manifold, output.normal, contactDist, true, renderOutput);
}
}
}
else if(manifold.mNumContacts > 0)
{
//ML:: the manifold originally has contacts
PersistentContact& p = manifold.getContactPoint(0);
const Vec3V worldNormal = transf1.rotate(Vec3V_From_Vec4V(p.mLocalNormalPen));
const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p);
const FloatV penDep = FSub(V4GetW(p.mLocalNormalPen), sphereRadius);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1, sphereRadius);
#endif
addToContactBuffer(contactBuffer, worldNormal, worldP, penDep);
return true;
}
return false;
}
| 10,364 | C++ | 40.963563 | 245 | 0.770069 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleBox.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 "GuVecBox.h"
#include "GuVecCapsule.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGen.h"
#include "GuPCMShapeConvex.h"
#include "GuGJKPenetration.h"
#include "GuEPA.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static bool fullContactsGenerationCapsuleBox(const CapsuleV& capsule, const BoxV& box, const PxVec3& halfExtents, const PxMatTransformV& aToB, const PxTransformV& transf0, const PxTransformV& transf1,
PersistentContact* manifoldContacts, PxU32& numContacts, PxContactBuffer& contactBuffer, PersistentContactManifold& manifold, Vec3V& normal, const Vec3VArg closest,
PxReal boxMargin, const FloatVArg contactDist, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput)
{
PolygonalData polyData;
PCMPolygonalBox polyBox(halfExtents);
polyBox.getPolygonalData(&polyData);
const Mat33V identity = M33Identity();
SupportLocalImpl<BoxV> map(box, transf1, identity, identity);
PxU32 origContacts = numContacts;
if(!generateCapsuleBoxFullContactManifold(capsule, polyData, &map, aToB, manifoldContacts, numContacts, contactDist, normal, closest, boxMargin, doOverlapTest, toleranceScale, renderOutput))
return false;
//EPA has contacts and we have new contacts, we discard the EPA contacts
if(origContacts != 0 && numContacts != origContacts)
{
numContacts--;
manifoldContacts++;
}
manifold.addBatchManifoldContacts2(manifoldContacts, numContacts);
normal = transf1.rotate(normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist);
return true;
}
bool Gu::pcmContactCapsuleBox(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0);
const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1);
PersistentContactManifold& manifold = cache.getManifold();
PxPrefetchLine(&manifold, 256);
const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents);
const FloatV contactDist = FLoad(params.mContactDistance);
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans = transf1.transformInv(transf0);
const PxMatTransformV aToB_(curRTrans);
const FloatV capsuleRadius = FLoad(shapeCapsule.radius);
const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight);
const PxU32 initialContacts = manifold.mNumContacts;
const PxReal toleranceLength = params.mToleranceLength;
const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength);
const FloatV minMargin = FMin(boxMargin, capsuleRadius);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f));
const FloatV refreshDist = FAdd(contactDist, capsuleRadius);
//refreshContactPoints remove invalid contacts from the manifold and update the number correspondingly
manifold.refreshContactPoints(aToB_, projectBreakingThreshold, refreshDist);
const bool bLostContacts = (manifold.mNumContacts != initialContacts);
if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin))
{
GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT;
manifold.setRelativeTransform(curRTrans);
const PxMatTransformV aToB(curRTrans);
const BoxV box(transf1.p, boxExtents);
//transform capsule into the local space of box
const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), capsuleRadius);
const LocalConvex<CapsuleV> convexA(capsule);
const LocalConvex<BoxV> convexB(box);
GjkOutput output;
const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), box.getCenter());
status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
PxU32 numContacts = 0;
bool doOverlapTest = false;
if(status == GJK_NON_INTERSECT)
{
return false;
}
else if(status == GJK_DEGENERATE)
{
return fullContactsGenerationCapsuleBox(capsule, box, shapeBox.halfExtents, aToB, transf0, transf1, manifoldContacts, numContacts, contactBuffer,
manifold, output.normal, output.closestB, box.getMarginF(), contactDist, true, params.mToleranceLength, renderOutput);
}
else
{
if(status == GJK_CONTACT)
{
const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
//Add contact to contact stream
manifoldContacts[numContacts].mLocalPointA = localPointA;
manifoldContacts[numContacts].mLocalPointB = output.closestB;
manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen;
}
else
{
PX_ASSERT(status == EPA_CONTACT);
status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,
true, FLoad(toleranceLength), output);
if(status == EPA_CONTACT)
{
const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
//Add contact to contact stream
manifoldContacts[numContacts].mLocalPointA = localPointA;
manifoldContacts[numContacts].mLocalPointB = output.closestB;
manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen;
}
else
{
doOverlapTest = true;
}
}
if(initialContacts == 0 || bLostContacts || doOverlapTest)
{
return fullContactsGenerationCapsuleBox(capsule, box, shapeBox.halfExtents, aToB, transf0, transf1, manifoldContacts, numContacts, contactBuffer, manifold, output.normal,
output.closestB, box.getMarginF(), contactDist, doOverlapTest, params.mToleranceLength, renderOutput);
}
else
{
//The contacts is either come from GJK or EPA
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.1f));
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep);
manifold.addManifoldPoint2(curRTrans.transformInv(output.closestA), output.closestB, localNormalPen, replaceBreakingThreshold);
const Vec3V normal = transf1.rotate(output.normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist);
return true;
}
}
}
else if(manifold.getNumContacts() > 0)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, worldNormal, transf0, capsuleRadius, contactDist);
return true;
}
return false;
}
| 8,636 | C++ | 41.546798 | 200 | 0.770148 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSpherePlane.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 "foundation/PxVecTransform.h"
#include "GuContactMethodImpl.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
bool Gu::pcmContactSpherePlane(GU_CONTACT_METHOD_ARGS)
{
using namespace aos;
PX_UNUSED(renderOutput);
PX_UNUSED(cache);
PX_UNUSED(shape1);
// Get actual shape data
const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0);
//sphere transform
const Vec3V p0 = V3LoadU_SafeReadW(transform0.p); // PT: safe because 'mRefCount' follows 'mTransform' in PxsTransform
//plane transform
const Vec3V p1 = V3LoadU_SafeReadW(transform1.p); // PT: safe because 'mRefCount' follows 'mTransform' in PxsTransform
const QuatV q1 = QuatVLoadU(&transform1.q.x);
const FloatV radius = FLoad(shapeSphere.radius);
const FloatV contactDist = FLoad(params.mContactDistance);
const PxTransformV transf1(p1, q1);
//Sphere in plane space
const Vec3V sphereCenterInPlaneSpace = transf1.transformInv(p0);
//Separation
const FloatV separation = FSub(V3GetX(sphereCenterInPlaneSpace), radius);
if(FAllGrtrOrEq(contactDist, separation))
{
//get the plane normal
const Vec3V worldNormal = QuatGetBasisVector0(q1);
const Vec3V worldPoint = V3NegScaleSub(worldNormal, radius, p0);
return outputSimplePCMContact(contactBuffer, worldPoint, worldNormal, separation);
}
return false;
}
| 3,074 | C++ | 40.554054 | 119 | 0.770007 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCustomGeometry.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 "GuVecBox.h"
#include "GuBounds.h"
#include "GuContactMethodImpl.h"
#include "GuPCMShapeConvex.h"
#include "GuPCMContactGen.h"
using namespace physx;
using namespace aos;
using namespace Gu;
static bool pcmContactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
const PxCustomGeometry& customGeom = checkedCast<PxCustomGeometry>(shape0);
const PxGeometry& otherGeom = shape1;
float breakingThreshold = 0.01f * params.mToleranceLength;
bool usePCM = customGeom.callbacks->usePersistentContactManifold(customGeom, breakingThreshold);
if (otherGeom.getType() == PxGeometryType::eCUSTOM)
{
float breakingThreshold1 = breakingThreshold;
if (checkedCast<PxCustomGeometry>(shape1).callbacks->usePersistentContactManifold(otherGeom, breakingThreshold1))
{
breakingThreshold = PxMin(breakingThreshold, breakingThreshold1);
usePCM = true;
}
}
else if (otherGeom.getType() > PxGeometryType::eCONVEXMESH)
{
usePCM = true;
}
if (usePCM)
{
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const PxTransformV transf0 = loadTransformA(transform0), transf1 = loadTransformA(transform1);
const PxTransformV curRTrans = transf1.transformInv(transf0);
const FloatV cos5 = FLoad(0.9962f); // Cos of 5 degrees
if (multiManifold.invalidate(curRTrans, FLoad(breakingThreshold)))
{
customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1,
params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength,
contactBuffer);
multiManifold.initialize();
multiManifold.setRelativeTransform(curRTrans);
for (PxU32 ci = 0; ci < contactBuffer.count; ++ci)
{
const PxContactPoint& c = contactBuffer.contacts[ci];
const Vec3V cP = V3LoadU(c.point);
const Vec3V cN = V3LoadU(c.normal);
const FloatV cD = FLoad(c.separation);
SinglePersistentContactManifold* manifold = NULL;
for (PxU8 mi = 0; mi < multiManifold.mNumManifolds; ++mi)
{
const Vec3V mN = multiManifold.mManifolds[mi].getWorldNormal(transf1);
const BoolV cmp = FIsGrtr(V3Dot(cN, mN), cos5);
if (BAllEqTTTT(cmp))
{
manifold = &multiManifold.mManifolds[mi];
break;
}
}
if (!manifold)
{
manifold = multiManifold.getEmptyManifold();
if (manifold) multiManifold.mNumManifolds++;
}
if (manifold)
{
SinglePersistentContactManifold& m = *manifold;
MeshPersistentContact pc;
pc.mLocalPointA = transf0.transformInv(cP);
pc.mLocalPointB = transf1.transformInv(cP);
pc.mLocalNormalPen = V4SetW(transf1.rotateInv(cN), cD);
pc.mFaceIndex = c.internalFaceIndex1;
m.mContactPoints[m.mNumContacts++] = pc;
m.mNumContacts = SinglePersistentContactManifold::reduceContacts(m.mContactPoints, m.mNumContacts);
}
}
contactBuffer.count = 0;
}
#if PCM_LOW_LEVEL_DEBUG
multiManifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, transf1);
}
return customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1,
params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength,
contactBuffer);
}
bool Gu::pcmContactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS)
{
bool res = pcmContactCustomGeometryGeometry(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;
}
| 5,328 | C++ | 36.794326 | 129 | 0.75244 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleCapsule.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 "GuVecCapsule.h"
#include "GuContactMethodImpl.h"
#include "GuDistanceSegmentSegment.h"
#include "GuPCMContactGenUtil.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static Vec4V pcmDistancePointSegmentTValue22( const Vec3VArg a0, const Vec3VArg b0,
const Vec3VArg a1, const Vec3VArg b1,
const Vec3VArg p0, const Vec3VArg p1,
const Vec3VArg p2, const Vec3VArg p3)
{
const Vec4V zero = V4Zero();
const Vec3V ap00 = V3Sub(p0, a0);
const Vec3V ap10 = V3Sub(p1, a0);
const Vec3V ap01 = V3Sub(p2, a1);
const Vec3V ap11 = V3Sub(p3, a1);
const Vec3V ab0 = V3Sub(b0, a0);
const Vec3V ab1 = V3Sub(b1, a1);
/* const FloatV nom00 = V3Dot(ap00, ab0);
const FloatV nom10 = V3Dot(ap10, ab0);
const FloatV nom01 = V3Dot(ap01, ab1);
const FloatV nom11 = V3Dot(ap11, ab1);*/
const Vec4V combinedDot = V3Dot4(ap00, ab0, ap10, ab0, ap01, ab1, ap11, ab1);
const FloatV nom00 = V4GetX(combinedDot);
const FloatV nom10 = V4GetY(combinedDot);
const FloatV nom01 = V4GetZ(combinedDot);
const FloatV nom11 = V4GetW(combinedDot);
const FloatV denom0 = V3Dot(ab0, ab0);
const FloatV denom1 = V3Dot(ab1, ab1);
const Vec4V nom = V4Merge(nom00, nom10, nom01, nom11);
const Vec4V denom = V4Merge(denom0, denom0, denom1, denom1);
const Vec4V tValue = V4Div(nom, denom);
return V4Sel(V4IsEq(denom, zero), zero, tValue);
}
static void storeContact(const Vec3VArg contact, const Vec3VArg normal, const FloatVArg separation, PxContactBuffer& buffer)
{
outputSimplePCMContact(buffer, contact, normal, separation);
}
bool Gu::pcmContactCapsuleCapsule(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
PX_UNUSED(cache);
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
// Get actual shape data
const PxCapsuleGeometry& shapeCapsule0 = checkedCast<PxCapsuleGeometry>(shape0);
const PxCapsuleGeometry& shapeCapsule1 = checkedCast<PxCapsuleGeometry>(shape1);
const Vec3V _p0 = V3LoadA(&transform0.p.x);
const QuatV q0 = QuatVLoadA(&transform0.q.x);
const Vec3V _p1 = V3LoadA(&transform1.p.x);
const QuatV q1 = QuatVLoadA(&transform1.q.x);
/*PsTransformV transf0(p0, q0);
PsTransformV transf1(p1, q1);*/
const FloatV r0 = FLoad(shapeCapsule0.radius);
const FloatV halfHeight0 = FLoad(shapeCapsule0.halfHeight);
const FloatV r1 = FLoad(shapeCapsule1.radius);
const FloatV halfHeight1 = FLoad(shapeCapsule1.halfHeight);
const FloatV cDist = FLoad(params.mContactDistance);
const Vec3V positionOffset = V3Scale(V3Add(_p0, _p1), FHalf());
const Vec3V p0 = V3Sub(_p0, positionOffset);
const Vec3V p1 = V3Sub(_p1, positionOffset);
const FloatV zero = FZero();
//const FloatV one = FOne();
const Vec3V zeroV = V3Zero();
/*const Vec3V positionOffset = V3Scale(V3Add(transf0.p, transf1.p), FloatV_From_F32(0.5f));
transf0.p = V3Sub(transf0.p, positionOffset);
transf1.p = V3Sub(transf1.p, positionOffset);*/
const Vec3V basisVector0 = QuatGetBasisVector0(q0);
const Vec3V tmp0 = V3Scale(basisVector0, halfHeight0);
const Vec3V s0 = V3Add(p0, tmp0);
const Vec3V e0 = V3Sub(p0, tmp0);
const Vec3V d0 = V3Sub(e0, s0);
const Vec3V basisVector1 = QuatGetBasisVector0(q1);
const Vec3V tmp1 = V3Scale(basisVector1, halfHeight1);
const Vec3V s1 = V3Add(p1, tmp1);
const Vec3V e1 = V3Sub(p1, tmp1);
const Vec3V d1 = V3Sub(e1, s1);
const FloatV sumRadius = FAdd(r0, r1);
const FloatV inflatedSum = FAdd(sumRadius, cDist);
const FloatV inflatedSumSquared = FMul(inflatedSum, inflatedSum);
const FloatV a = V3Dot(d0, d0);//squared length of segment1
const FloatV e = V3Dot(d1, d1);//squared length of segment2
const FloatV eps = FLoad(1e-6f);//FEps();
FloatV t0, t1;
const FloatV sqDist0 = distanceSegmentSegmentSquared(s0, d0, s1, d1, t0, t1);
if(FAllGrtrOrEq(inflatedSumSquared, sqDist0))
{
const Vec4V zeroV4 = V4Zero();
const Vec4V oneV4 = V4One();
//check to see whether these two capsule are paralle
const FloatV parallelTolerance = FLoad(0.9998f);
const BoolV con0 = FIsGrtr(eps, a);
const BoolV con1 = FIsGrtr(eps, e);
const Vec3V dir0 = V3Sel(con0, zeroV, V3ScaleInv(d0, FSqrt(a)));
const Vec3V dir1 = V3Sel(con1, zeroV, V3ScaleInv(d1, FSqrt(e)));
const FloatV cos = FAbs(V3Dot(dir0, dir1));
if(FAllGrtr(cos, parallelTolerance))//paralle
{
//project s, e into s1e1
const Vec4V t= pcmDistancePointSegmentTValue22(s0, e0, s1, e1,
s1, e1, s0, e0);
const BoolV con = BAnd(V4IsGrtrOrEq(t, zeroV4), V4IsGrtrOrEq(oneV4, t));
const BoolV con00 = BGetX(con);
const BoolV con01 = BGetY(con);
const BoolV con10 = BGetZ(con);
const BoolV con11 = BGetW(con);
/* PX_ALIGN(16, PxU32 conditions[4]);
F32Array_Aligned_From_Vec4V(con, (PxF32*)conditions);*/
PxU32 numContact=0;
if(BAllEqTTTT(con00))
{
const Vec3V projS1 = V3ScaleAdd(d0, V4GetX(t), s0);
const Vec3V v = V3Sub(projS1, s1);
const FloatV sqDist = V3Dot(v, v);
const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist));
if(BAllEqTTTT(bCon))
{
const FloatV dist = FSqrt(sqDist);
const FloatV pen = FSub(dist, sumRadius);
const Vec3V normal = V3ScaleInv(v, dist);
PX_ASSERT(isFiniteVec3V(normal));
const Vec3V _p = V3NegScaleSub(normal, r0, projS1);
const Vec3V p = V3Add(_p, positionOffset);
storeContact(p, normal, pen, contactBuffer);
numContact++;
}
}
if(BAllEqTTTT(con01))
{
const Vec3V projE1 = V3ScaleAdd(d0, V4GetY(t), s0);
const Vec3V v = V3Sub(projE1, e1);
const FloatV sqDist = V3Dot(v, v);
const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist));
if(BAllEqTTTT(bCon))
{
const FloatV dist = FSqrt(sqDist);
const FloatV pen = FSub(dist, sumRadius);
const Vec3V normal = V3ScaleInv(v, dist);
PX_ASSERT(isFiniteVec3V(normal));
const Vec3V _p = V3NegScaleSub(normal, r0, projE1);
const Vec3V p = V3Add(_p, positionOffset);
storeContact(p, normal, pen, contactBuffer);
numContact++;
}
}
if(BAllEqTTTT(con10))
{
const Vec3V projS0 = V3ScaleAdd(d1, V4GetZ(t), s1);
const Vec3V v = V3Sub(s0, projS0);
const FloatV sqDist = V3Dot(v, v);
const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist));
if(BAllEqTTTT(bCon))
{
const FloatV dist = FSqrt(sqDist);
const FloatV pen = FSub(dist, sumRadius);
const Vec3V normal = V3ScaleInv(v, dist);
PX_ASSERT(isFiniteVec3V(normal));
const Vec3V _p = V3NegScaleSub(normal, r0, s0);
const Vec3V p = V3Add(_p, positionOffset);
//const Vec3V p = V3ScaleAdd(normal, r0, s0);
storeContact(p, normal, pen, contactBuffer);
numContact++;
}
}
if(BAllEqTTTT(con11))
{
const Vec3V projE0 = V3ScaleAdd(d1, V4GetW(t), s1);
const Vec3V v = V3Sub(e0, projE0);
const FloatV sqDist = V3Dot(v, v);
const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist));
if(BAllEqTTTT(bCon))
{
const FloatV dist = FSqrt(sqDist);
const FloatV pen = FSub(dist, sumRadius);
const Vec3V normal = V3ScaleInv(v, dist);
PX_ASSERT(isFiniteVec3V(normal));
const Vec3V _p = V3NegScaleSub(normal, r0, e0);
const Vec3V p = V3Add(_p, positionOffset);
//const Vec3V p = V3ScaleAdd(normal, r0, e0);
storeContact(p, normal, pen, contactBuffer);
numContact++;
}
}
if(numContact)
return true;
}
const Vec3V closestA = V3ScaleAdd(d0, t0, s0);
const Vec3V closestB = V3ScaleAdd(d1, t1, s1);
const BoolV con = FIsGrtr(eps, sqDist0);
//const Vec3V normal = V3Sel(FIsEq(dist, zero), V3Sel(FIsGrtr(a, eps), V3Normalise(d0), V3Scale(V3Sub(closestA, closestB), FRecip(dist)));
const Vec3V _normal = V3Sel(con, V3Sel(FIsGrtr(a, eps), d0, V3UnitX()), V3Sub(closestA, closestB));
const Vec3V normal = V3Normalize(_normal);
PX_ASSERT(isFiniteVec3V(normal));
const Vec3V _point = V3NegScaleSub(normal, r0, closestA);
const Vec3V p = V3Add(_point, positionOffset);
const FloatV dist = FSel(con, zero, FSqrt(sqDist0));
const FloatV pen = FSub(dist, sumRadius);
//PX_ASSERT(FAllGrtrOrEq(zero, pen));
storeContact(p, normal, pen, contactBuffer);
return true;
}
return false;
}
| 10,034 | C++ | 35.358696 | 140 | 0.701216 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexConvex.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 "GuGJKPenetration.h"
#include "GuEPA.h"
#include "GuVecConvexHull.h"
#include "GuVecConvexHullNoScale.h"
#include "GuContactMethodImpl.h"
#include "GuPCMShapeConvex.h"
#include "GuPCMContactGen.h"
using namespace physx;
using namespace Gu;
using namespace aos;
static bool fullContactsGenerationConvexConvex(const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1,
bool idtScale0, bool idtScale1, PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer,
PersistentContactManifold& manifold, Vec3VArg normal, const Vec3VArg closestA, const Vec3VArg closestB,
const FloatVArg contactDist, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength)
{
PolygonalData polyData0, polyData1;
const ConvexHullV& convexHull0 = relativeConvex->getConvex<ConvexHullV>();
const ConvexHullV& convexHull1 = localConvex->getConvex<ConvexHullV>();
getPCMConvexData(convexHull0, idtScale0, polyData0);
getPCMConvexData(convexHull1, idtScale1, polyData1);
PX_ALIGN(16, PxU8 buff0[sizeof(SupportLocalImpl<ConvexHullV>)]);
PX_ALIGN(16, PxU8 buff1[sizeof(SupportLocalImpl<ConvexHullV>)]);
SupportLocal* map0 = (idtScale0 ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff0, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull0), transf0, convexHull0.vertex2Shape, convexHull0.shape2Vertex, idtScale0)) :
static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff0, SupportLocalImpl<ConvexHullV>)(convexHull0, transf0, convexHull0.vertex2Shape, convexHull0.shape2Vertex, idtScale0)));
SupportLocal* map1 = (idtScale1 ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull1), transf1, convexHull1.vertex2Shape, convexHull1.shape2Vertex, idtScale1)) :
static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullV>)(convexHull1, transf1, convexHull1.vertex2Shape, convexHull1.shape2Vertex, idtScale1)));
PxU32 numContacts = 0;
if(generateFullContactManifold(polyData0, polyData1, map0, map1, manifoldContacts, numContacts, contactDist, normal, closestA, closestB, convexHull0.getMarginF(),
convexHull1.getMarginF(), doOverlapTest, renderOutput, toleranceLength))
{
if(numContacts > 0)
{
//reduce contacts
manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength);
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
//add the manifold contacts;
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
}
else
{
//if doOverlapTest is true, which means GJK/EPA degenerate so we won't have any contact in the manifoldContacts array
if(!doOverlapTest)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
}
}
return true;
}
return false;
}
static bool generateOrProcessContactsConvexConvex( const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1,
const PxMatTransformV& aToB, GjkStatus status, GjkOutput& output, PersistentContactManifold& manifold, PxContactBuffer& contactBuffer,
PxU32 initialContacts, const FloatV minMargin, const FloatV contactDist,
bool idtScale0, bool idtScale1, PxReal toleranceLength, PxRenderOutput* renderOutput)
{
if(status == GJK_NON_INTERSECT)
{
return false;
}
else
{
PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts);
const Vec3V localNor = manifold.mNumContacts ? manifold.getLocalNormal() : V3Zero();
const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f));
//addGJKEPAContacts will increase the number of contacts in manifold. If status == EPA_CONTACT, we need to run epa algorithm and generate closest points, normal and
//pentration. If epa doesn't degenerate, we will store the contacts information in the manifold. Otherwise, we will return true to do the fallback test
const bool doOverlapTest = addGJKEPAContacts(relativeConvex, localConvex, aToB, status, manifoldContacts, replaceBreakingThreshold, FLoad(toleranceLength), output, manifold);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
//ML: after we refresh the contacts(newContacts) and generate a GJK/EPA contacts(we will store that in the manifold), if the number of contacts is still less than the original contacts,
//which means we lose too mang contacts and we should regenerate all the contacts in the current configuration
//Also, we need to look at the existing contacts, if the existing contacts has very different normal than the GJK/EPA contacts,
//which means we should throw away the existing contacts and do full contact gen
const bool fullContactGen = FAllGrtr(FLoad(0.707106781f), V3Dot(localNor, output.normal)) || (manifold.mNumContacts < initialContacts);
if(fullContactGen || doOverlapTest)
{
return fullContactsGenerationConvexConvex(relativeConvex, localConvex, transf0, transf1, idtScale0, idtScale1, manifoldContacts, contactBuffer,
manifold, output.normal, output.closestA, output.closestB, contactDist, doOverlapTest, renderOutput, toleranceLength);
}
else
{
const Vec3V newLocalNor = V3Add(localNor, output.normal);
const Vec3V worldNormal = V3Normalize(transf1.rotate(newLocalNor));
//const Vec3V worldNormal = transf1.rotate(normal);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
return true;
}
}
}
static bool convexHullNoScale0( const ConvexHullV& convexHull0, const ConvexHullV& convexHull1, const PxTransformV& transf0, const PxTransformV& transf1,
const PxMatTransformV& aToB, GjkOutput& output, PersistentContactManifold& manifold, PxContactBuffer& contactBuffer,
PxU32 initialContacts, const FloatV minMargin, const FloatV contactDist,
bool idtScale1, PxReal toleranceLength, PxRenderOutput* renderOutput)
{
const RelativeConvex<ConvexHullNoScaleV> convexA(static_cast<const ConvexHullNoScaleV&>(convexHull0), aToB);
if(idtScale1)
{
const LocalConvex<ConvexHullNoScaleV> convexB(static_cast<const ConvexHullNoScaleV&>(convexHull1));
GjkStatus status = gjkPenetration<RelativeConvex<ConvexHullNoScaleV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
return generateOrProcessContactsConvexConvex(&convexA, &convexB, transf0, transf1, aToB, status, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, true, true, toleranceLength, renderOutput);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull1);
GjkStatus status = gjkPenetration<RelativeConvex<ConvexHullNoScaleV>, LocalConvex<ConvexHullV> >(convexA, convexB, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
return generateOrProcessContactsConvexConvex(&convexA, &convexB, transf0, transf1, aToB, status, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, true, false, toleranceLength, renderOutput);
}
}
static bool convexHullHasScale0(const ConvexHullV& convexHull0, const ConvexHullV& convexHull1, const PxTransformV& transf0, const PxTransformV& transf1,
const PxMatTransformV& aToB, GjkOutput& output, PersistentContactManifold& manifold, PxContactBuffer& contactBuffer,
PxU32 initialContacts, const FloatV minMargin, const FloatV contactDist,
bool idtScale1, PxReal toleranceLength, PxRenderOutput* renderOutput)
{
RelativeConvex<ConvexHullV> convexA(convexHull0, aToB);
if(idtScale1)
{
const LocalConvex<ConvexHullNoScaleV> convexB(static_cast<const ConvexHullNoScaleV&>(convexHull1));
GjkStatus status = gjkPenetration<RelativeConvex<ConvexHullV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints,output);
return generateOrProcessContactsConvexConvex(&convexA, &convexB, transf0, transf1, aToB, status, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, false, true, toleranceLength, renderOutput);
}
else
{
const LocalConvex<ConvexHullV> convexB(convexHull1);
GjkStatus status = gjkPenetration<RelativeConvex<ConvexHullV>, LocalConvex<ConvexHullV> >(convexA, convexB, aToB.p, contactDist, true,
manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output);
return generateOrProcessContactsConvexConvex(&convexA, &convexB, transf0, transf1, aToB, status, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, false, false, toleranceLength, renderOutput);
}
}
bool Gu::pcmContactConvexConvex(GU_CONTACT_METHOD_ARGS)
{
const PxConvexMeshGeometry& shapeConvex0 = checkedCast<PxConvexMeshGeometry>(shape0);
const PxConvexMeshGeometry& shapeConvex1 = checkedCast<PxConvexMeshGeometry>(shape1);
PersistentContactManifold& manifold = cache.getManifold();
const ConvexHullData* hullData0 = _getHullData(shapeConvex0);
const ConvexHullData* hullData1 = _getHullData(shapeConvex1);
PxPrefetchLine(hullData0);
PxPrefetchLine(hullData1);
PX_ASSERT(transform1.q.isSane());
PX_ASSERT(transform0.q.isSane());
const Vec3V vScale0 = V3LoadU_SafeReadW(shapeConvex0.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const Vec3V vScale1 = V3LoadU_SafeReadW(shapeConvex1.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale
const FloatV contactDist = FLoad(params.mContactDistance);
//Transfer A into the local space of B
const PxTransformV transf0 = loadTransformA(transform0);
const PxTransformV transf1 = loadTransformA(transform1);
const PxTransformV curRTrans(transf1.transformInv(transf0));
const PxMatTransformV aToB(curRTrans);
const PxReal toleranceLength = params.mToleranceLength;
const FloatV convexMargin0 = CalculatePCMConvexMargin(hullData0, vScale0, toleranceLength);
const FloatV convexMargin1 = CalculatePCMConvexMargin(hullData1, vScale1, toleranceLength);
const PxU32 initialContacts = manifold.mNumContacts;
const FloatV minMargin = FMin(convexMargin0, convexMargin1);
const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f));
manifold.refreshContactPoints(aToB, projectBreakingThreshold, contactDist);
//ML: after refreshContactPoints, we might lose some contacts
const bool bLostContacts = (manifold.mNumContacts != initialContacts);
const Vec3V extent0 = V3Mul(V3LoadU(hullData0->mInternal.mExtents), vScale0);
const Vec3V extent1 = V3Mul(V3LoadU(hullData0->mInternal.mExtents), vScale1);
const FloatV radiusA = V3Length(extent0);
const FloatV radiusB = V3Length(extent1);
if(bLostContacts || manifold.invalidate_BoxConvex(curRTrans, transf0.q, transf1.q, minMargin, radiusA, radiusB))
{
manifold.setRelativeTransform(curRTrans, transf0.q, transf1.q);
const bool idtScale0 = shapeConvex0.scale.isIdentity();
const bool idtScale1 = shapeConvex1.scale.isIdentity();
const QuatV vQuat0 = QuatVLoadU(&shapeConvex0.scale.rotation.x);
const QuatV vQuat1 = QuatVLoadU(&shapeConvex1.scale.rotation.x);
// PT: safe loads because mCenterOfMass isn't the last data in the structure
const ConvexHullV convexHull0(hullData0, V3LoadU_SafeReadW(hullData0->mCenterOfMass), vScale0, vQuat0, idtScale0);
const ConvexHullV convexHull1(hullData1, V3LoadU_SafeReadW(hullData1->mCenterOfMass), vScale1, vQuat1, idtScale1);
GjkOutput output;
if(idtScale0)
{
return convexHullNoScale0(convexHull0, convexHull1, transf0, transf1, aToB, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, idtScale1, toleranceLength, renderOutput);
}
else
{
return convexHullHasScale0(convexHull0, convexHull1, transf0, transf1, aToB, output, manifold,
contactBuffer, initialContacts, minMargin, contactDist, idtScale1, toleranceLength, renderOutput);
}
}
else if(manifold.getNumContacts()> 0)
{
const Vec3V worldNormal = manifold.getWorldNormal(transf1);
manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return true;
}
return false;
}
| 14,360 | C++ | 50.844765 | 252 | 0.786978 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMShapeConvex.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 "GuPCMShapeConvex.h"
#include "GuVecConvexHull.h"
#include "GuPCMContactGen.h"
#include "common/PxRenderOutput.h"
using namespace physx;
using namespace Gu;
using namespace aos;
namespace physx
{
namespace Gu
{
const PxU8 gPCMBoxPolygonData[24] =
{
0, 3, 2, 1,
1, 2, 6, 5,
5, 6, 7, 4,
4, 7, 3, 0,
3, 7, 6, 2,
4, 0, 1, 5,
};
}
}
PCMPolygonalBox::PCMPolygonalBox(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;
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;
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;
PX_ASSERT(mPolygons[2].getMin(mVertices) == -mHalfSide.z);
PX_ASSERT(mPolygons[0].getMin(mVertices) == -mHalfSide.z);
}
void PCMPolygonalBox::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 = gPCMBoxPolygonData;
dst->mFacesByEdges = NULL;
dst->mVerticesByEdges = NULL;
dst->mBigData = NULL;
dst->mInternal.mRadius = 0.0f;
dst->mInternal.mExtents[0] = mHalfSide.x;
dst->mInternal.mExtents[1] = mHalfSide.y;
dst->mInternal.mExtents[2] = mHalfSide.z;
dst->mScale = PxMeshScale();
}
static void getPCMPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const ConvexHullData* PX_RESTRICT src, const Mat33V& vertexToShape)
{
using namespace aos;
const Vec3V vertexSpaceCenterOfMass = V3LoadU(src->mCenterOfMass);
const Vec3V shapeSpaceCenterOfMass = M33MulV3(vertexToShape, vertexSpaceCenterOfMass);
V3StoreU(shapeSpaceCenterOfMass, dst->mCenter);
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();
dst->mVerticesByEdges = src->getVerticesByEdges16();
dst->mBigData = src->mBigConvexRawData;
dst->mInternal = src->mInternal;
dst->mScale = PxMeshScale();
}
static void getPCMPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const ConvexHullData* PX_RESTRICT src,
const Cm::FastVertex2ShapeScaling& scaling, const PxMeshScale& convexScale)
{
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();
dst->mVerticesByEdges = src->getVerticesByEdges16();
dst->mBigData = src->mBigConvexRawData;
dst->mInternal = src->mInternal;
dst->mScale = convexScale;
}
void Gu::getPCMConvexData(const ConvexHullV& convexHull, bool idtScale, PolygonalData& polyData)
{
PX_ASSERT(!convexHull.hullData->mAABB.isEmpty());
//this is used to calculate the convex hull's center of mass
getPCMPolygonalData_Convex(&polyData, convexHull.hullData, convexHull.vertex2Shape);
if(!idtScale)
polyData.mInternal.reset();
}
bool Gu::getPCMConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData)
{
const bool idtScale = shapeConvex.scale.isIdentity();
if(!idtScale)
scaling.init(shapeConvex.scale);
const ConvexHullData* hullData = _getHullData(shapeConvex);
PX_ASSERT(!hullData->mAABB.isEmpty());
bounds = hullData->mAABB.transformFast(scaling.getVertex2ShapeSkew());
getPCMPolygonalData_Convex(&polyData, hullData, scaling, shapeConvex.scale);
return idtScale;
}
| 7,251 | C++ | 33.698564 | 148 | 0.7028 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleHeightField.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 "foundation/PxVecMath.h"
#include "foundation/PxVecTransform.h"
#include "GuVecTriangle.h"
#include "GuContactMethodImpl.h"
#include "GuHeightField.h"
#include "GuPCMContactConvexCommon.h"
#include "GuSegment.h"
#include "GuInternal.h"
#include "GuPCMContactMeshCallback.h"
using namespace physx;
using namespace Gu;
using namespace aos;
struct PCMCapsuleVsHeightfieldContactGenerationCallback : PCMHeightfieldContactGenerationCallback<PCMCapsuleVsHeightfieldContactGenerationCallback>
{
PCMCapsuleVsHeightfieldContactGenerationCallback& operator=(const PCMCapsuleVsHeightfieldContactGenerationCallback&);
PCMCapsuleVsMeshContactGeneration mGeneration;
PCMCapsuleVsHeightfieldContactGenerationCallback(
const CapsuleV& capsule,
const FloatVArg contactDistance,
const FloatVArg replaceBreakingThreshold,
const PxTransformV& capsuleTransform,
const PxTransformV& heightfieldTransform,
const PxTransform& heightfieldTransform1,
MultiplePersistentContactManifold& multiManifold,
PxContactBuffer& contactBuffer,
PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts,
HeightFieldUtil& hfUtil
) :
PCMHeightfieldContactGenerationCallback<PCMCapsuleVsHeightfieldContactGenerationCallback>(hfUtil, heightfieldTransform1),
mGeneration(capsule, contactDistance, replaceBreakingThreshold, capsuleTransform, heightfieldTransform, multiManifold,
contactBuffer, deferredContacts)
{
}
template<PxU32 CacheSize>
void processTriangleCache(TriangleCache<CacheSize>& cache)
{
mGeneration.processTriangleCache<CacheSize, PCMCapsuleVsMeshContactGeneration>(cache);
}
};
bool Gu::pcmContactCapsuleHeightField(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(renderOutput);
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0);
const PxHeightFieldGeometry& shapeHeight = checkedCast<PxHeightFieldGeometry>(shape1);
MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold();
const FloatV capsuleRadius = FLoad(shapeCapsule.radius);
const FloatV contactDist = FLoad(params.mContactDistance);
const PxTransformV capsuleTransform = loadTransformA(transform0);//capsule transform
const PxTransformV heightfieldTransform = loadTransformA(transform1);//height feild
const PxTransformV curTransform = heightfieldTransform.transformInv(capsuleTransform);
const FloatV replaceBreakingThreshold = FMul(capsuleRadius, FLoad(0.001f));
if(multiManifold.invalidate(curTransform, capsuleRadius, FLoad(0.02f)))
{
multiManifold.mNumManifolds = 0;
multiManifold.setRelativeTransform(curTransform);
HeightFieldUtil hfUtil(shapeHeight);
const PxVec3 tmp = getCapsuleHalfHeightVector(transform0, shapeCapsule);
const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance;
const PxVec3 capsuleCenterInMesh = transform1.transformInv(transform0.p);
const PxVec3 capsuleDirInMesh = transform1.rotateInv(tmp);
const CapsuleV capsule(V3LoadU(capsuleCenterInMesh), V3LoadU(capsuleDirInMesh), capsuleRadius);
PCMCapsuleVsHeightfieldContactGenerationCallback callback(
capsule,
contactDist,
replaceBreakingThreshold,
capsuleTransform,
heightfieldTransform,
transform1,
multiManifold,
contactBuffer,
NULL,
hfUtil
);
// PT: TODO: improve these bounds - see computeCapsuleBounds
hfUtil.overlapAABBTriangles(transform0, transform1, getLocalCapsuleBounds(inflatedRadius, shapeCapsule.halfHeight), callback);
callback.mGeneration.processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE, false);
}
else
{
const PxMatTransformV aToB(curTransform);
// We must be in local space to use the cache
const FloatV projectBreakingThreshold = FMul(capsuleRadius, FLoad(0.05f));
const FloatV refereshDistance = FAdd(capsuleRadius, contactDist);
multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance);
}
return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, capsuleTransform, heightfieldTransform, capsuleRadius);
}
| 5,765 | C++ | 40.482014 | 147 | 0.807632 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneCapsule.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 "GuVecCapsule.h"
#include "GuContactMethodImpl.h"
#include "GuPersistentContactManifold.h"
using namespace physx;
bool Gu::pcmContactPlaneCapsule(GU_CONTACT_METHOD_ARGS)
{
PX_UNUSED(shape0);
PX_UNUSED(renderOutput);
using namespace aos;
PersistentContactManifold& manifold = cache.getManifold();
PxPrefetchLine(&manifold, 256);
// Get actual shape data
const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1);
const PxTransformV transf0 = loadTransformA(transform1);//capsule transform
const PxTransformV transf1 = loadTransformA(transform0);//plane transform
//capsule to plane
const PxTransformV aToB(transf1.transformInv(transf0));
//in world space
const Vec3V planeNormal = V3Normalize(QuatGetBasisVector0(transf1.q));
const Vec3V contactNormal = V3Neg(planeNormal);
//ML:localNormal is the local space of plane normal, however, because shape1 is capulse and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints
//work out the correct pentration for points
const Vec3V localNormal = V3UnitX();
const FloatV contactDist = FLoad(params.mContactDistance);
const FloatV radius = FLoad(shapeCapsule.radius);
const FloatV halfHeight = FLoad(shapeCapsule.halfHeight);
//capsule is in the local space of plane(n = (1.f, 0.f, 0.f), d=0.f)
const Vec3V basisVector = QuatGetBasisVector0(aToB.q);
const Vec3V tmp = V3Scale(basisVector, halfHeight);
const Vec3V s = V3Add(aToB.p, tmp);
const Vec3V e = V3Sub(aToB.p, tmp);
const FloatV inflatedRadius = FAdd(radius, contactDist);
const FloatV replaceBreakingThreshold = FMul(radius, FLoad(0.001f));
const FloatV projectBreakingThreshold = FMul(radius, FLoad(0.05f));
const PxU32 initialContacts = manifold.mNumContacts;
//manifold.refreshContactPoints(curRTrans, projectBreakingThreshold, contactDist);
const FloatV refreshDist = FAdd(contactDist, radius);
manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDist);
const PxU32 newContacts = manifold.mNumContacts;
const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts));
if(bLostContacts || manifold.invalidate_PrimitivesPlane(aToB, radius, FLoad(0.02f)))
{
manifold.mNumContacts = 0;
manifold.setRelativeTransform(aToB);
//calculate the distance from s to the plane
const FloatV signDist0 = V3GetX(s);//V3Dot(localNormal, s);
if(FAllGrtr(inflatedRadius, signDist0))
{
const Vec3V localPointA = aToB.transformInv(s);
const Vec3V localPointB = V3NegScaleSub(localNormal, signDist0, s);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist0);
//add to manifold
manifold.addManifoldPoint2(localPointA, localPointB, localNormalPen, replaceBreakingThreshold);
}
const FloatV signDist1 = V3GetX(e);//V3Dot(localNormal, e);
if(FAllGrtr(inflatedRadius, signDist1))
{
const Vec3V localPointA = aToB.transformInv(e);
const Vec3V localPointB = V3NegScaleSub(localNormal, signDist1, e);
const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist1);
//add to manifold
manifold.addManifoldPoint2(localPointA, localPointB, localNormalPen, replaceBreakingThreshold);
}
manifold.addManifoldContactsToContactBuffer(contactBuffer, contactNormal, planeNormal, transf0, radius, contactDist);
#if PCM_LOW_LEVEL_DEBUG
manifold.drawManifold(*renderOutput, transf0, transf1);
#endif
return manifold.getNumContacts() > 0;
}
else
{
manifold.addManifoldContactsToContactBuffer(contactBuffer, contactNormal, planeNormal, transf0, radius, contactDist);
return manifold.getNumContacts() > 0;
}
}
| 5,449 | C++ | 42.951613 | 219 | 0.772619 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.