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/mesh/GuBV4_Internal.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_INTERNAL_H
#define GU_BV4_INTERNAL_H
#include "foundation/PxFPU.h"
// PT: the general structure is that there is a root "process stream" function which is the entry point for the query.
// It then calls "process node" functions for each traversed node, except for the Slabs-based raycast versions that deal
// with 4 nodes at a time within the "process stream" function itself. When a leaf is found, "doLeafTest" functors
// passed to the "process stream" entry point are called.
#ifdef GU_BV4_USE_SLABS
// PT: Linux tries to compile templates even when they're not used so I had to wrap them all with defines to avoid build errors. Blame the only platform that does this.
#ifdef GU_BV4_PROCESS_STREAM_NO_ORDER
template<class LeafTestT, class ParamsT>
PX_FORCE_INLINE PxIntBool processStreamNoOrder(const BV4Tree& tree, ParamsT* PX_RESTRICT params)
{
if(tree.mQuantized)
return BV4_ProcessStreamSwizzledNoOrderQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params);
else
return BV4_ProcessStreamSwizzledNoOrderNQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params);
}
#endif
#ifdef GU_BV4_PROCESS_STREAM_ORDERED
template<class LeafTestT, class ParamsT>
PX_FORCE_INLINE void processStreamOrdered(const BV4Tree& tree, ParamsT* PX_RESTRICT params)
{
if(tree.mQuantized)
BV4_ProcessStreamSwizzledOrderedQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params);
else
BV4_ProcessStreamSwizzledOrderedNQ<LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params);
}
#endif
#ifdef GU_BV4_PROCESS_STREAM_RAY_NO_ORDER
template<int inflateT, class LeafTestT, class ParamsT>
PX_FORCE_INLINE PxIntBool processStreamRayNoOrder(const BV4Tree& tree, ParamsT* PX_RESTRICT params)
{
if(tree.mQuantized)
return BV4_ProcessStreamKajiyaNoOrderQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params);
else
return BV4_ProcessStreamKajiyaNoOrderNQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params);
}
#endif
#ifdef GU_BV4_PROCESS_STREAM_RAY_ORDERED
template<int inflateT, class LeafTestT, class ParamsT>
PX_FORCE_INLINE void processStreamRayOrdered(const BV4Tree& tree, ParamsT* PX_RESTRICT params)
{
if(tree.mQuantized)
BV4_ProcessStreamKajiyaOrderedQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedQ*>(tree.mNodes), tree.mInitData, params);
else
BV4_ProcessStreamKajiyaOrderedNQ<inflateT, LeafTestT, ParamsT>(reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes), tree.mInitData, params);
}
#endif
#else
#define processStreamNoOrder BV4_ProcessStreamNoOrder
#define processStreamOrdered BV4_ProcessStreamOrdered2
#define processStreamRayNoOrder(a, b) BV4_ProcessStreamNoOrder<b>
#define processStreamRayOrdered(a, b) BV4_ProcessStreamOrdered2<b>
#endif
#ifndef GU_BV4_USE_SLABS
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
// PT: see http://www.codercorner.com/blog/?p=734
// PT: TODO: refactor with dup in bucket pruner (TA34704)
PX_FORCE_INLINE PxU32 computeDirMask(const PxVec3& dir)
{
// XYZ
// ---
// --+
// -+-
// -++
// +--
// +-+
// ++-
// +++
const PxU32 X = PX_IR(dir.x)>>31;
const PxU32 Y = PX_IR(dir.y)>>31;
const PxU32 Z = PX_IR(dir.z)>>31;
const PxU32 bitIndex = Z|(Y<<1)|(X<<2);
return 1u<<bitIndex;
}
// 0 0 0 PP PN NP NN 0 1 2 3
// 0 0 1 PP PN NN NP 0 1 3 2
// 0 1 0 PN PP NP NN 1 0 2 3
// 0 1 1 PN PP NN NP 1 0 3 2
// 1 0 0 NP NN PP PN 2 3 0 1
// 1 0 1 NN NP PP PN 3 2 0 1
// 1 1 0 NP NN PN PP 2 3 1 0
// 1 1 1 NN NP PN PP 3 2 1 0
static const PxU8 order[] = {
0,1,2,3,
0,1,3,2,
1,0,2,3,
1,0,3,2,
2,3,0,1,
3,2,0,1,
2,3,1,0,
3,2,1,0,
};
PX_FORCE_INLINE PxU32 decodePNS(const BVDataPacked* PX_RESTRICT node, const PxU32 dirMask)
{
const PxU32 bit0 = (node[0].decodePNSNoShift() & dirMask) ? 1u : 0;
const PxU32 bit1 = (node[1].decodePNSNoShift() & dirMask) ? 1u : 0;
const PxU32 bit2 = (node[2].decodePNSNoShift() & dirMask) ? 1u : 0; //### potentially reads past the end of the stream here!
return bit2|(bit1<<1)|(bit0<<2);
}
#endif // GU_BV4_PRECOMPUTED_NODE_SORT
#define PNS_BLOCK(i, a, b, c, d) \
case i: \
{ \
if(code & (1<<a)) { stack[nb++] = node[a].getChildData(); } \
if(code & (1<<b)) { stack[nb++] = node[b].getChildData(); } \
if(code & (1<<c)) { stack[nb++] = node[c].getChildData(); } \
if(code & (1<<d)) { stack[nb++] = node[d].getChildData(); } \
}break;
#define PNS_BLOCK1(i, a, b, c, d) \
case i: \
{ \
stack[nb] = node[a].getChildData(); nb += (code & (1<<a))?1:0; \
stack[nb] = node[b].getChildData(); nb += (code & (1<<b))?1:0; \
stack[nb] = node[c].getChildData(); nb += (code & (1<<c))?1:0; \
stack[nb] = node[d].getChildData(); nb += (code & (1<<d))?1:0; \
}break;
#define PNS_BLOCK2(a, b, c, d) { \
if(code & (1<<a)) { stack[nb++] = node[a].getChildData(); } \
if(code & (1<<b)) { stack[nb++] = node[b].getChildData(); } \
if(code & (1<<c)) { stack[nb++] = node[c].getChildData(); } \
if(code & (1<<d)) { stack[nb++] = node[d].getChildData(); } } \
template<class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamNoOrder(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU32 nodeType = getChildType(childData);
if(nodeType>1 && BV4_ProcessNodeNoOrder<LeafTestT, 3>(stack, nb, node, params))
return 1;
if(nodeType>0 && BV4_ProcessNodeNoOrder<LeafTestT, 2>(stack, nb, node, params))
return 1;
if(BV4_ProcessNodeNoOrder<LeafTestT, 1>(stack, nb, node, params))
return 1;
if(BV4_ProcessNodeNoOrder<LeafTestT, 0>(stack, nb, node, params))
return 1;
}while(nb);
return 0;
}
template<class LeafTestT, class ParamsT>
static void BV4_ProcessStreamOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
const PxU32 dirMask = computeDirMask(params->mLocalDir)<<3;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU8* PX_RESTRICT ord = order + decodePNS(node, dirMask)*4;
const PxU32 limit = 2 + getChildType(childData);
BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[0], limit);
BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[1], limit);
BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[2], limit);
BV4_ProcessNodeOrdered<LeafTestT>(stack, nb, node, params, ord[3], limit);
}while(Nb);
}
// Alternative, experimental version using PNS
template<class LeafTestT, class ParamsT>
static void BV4_ProcessStreamOrdered2(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU32 nodeType = getChildType(childData);
PxU32 code = 0;
BV4_ProcessNodeOrdered2<LeafTestT, 0>(code, node, params);
BV4_ProcessNodeOrdered2<LeafTestT, 1>(code, node, params);
if(nodeType>0)
BV4_ProcessNodeOrdered2<LeafTestT, 2>(code, node, params);
if(nodeType>1)
BV4_ProcessNodeOrdered2<LeafTestT, 3>(code, node, params);
if(code)
{
// PT: TODO: check which implementation is best on each platform (TA34704)
#define FOURTH_TEST // Version avoids computing the PNS index, and also avoids all non-constant shifts. Full of branches though. Fastest on Win32.
#ifdef FOURTH_TEST
{
if(node[0].decodePNSNoShift() & dirMask) // Bit2
{
if(node[1].decodePNSNoShift() & dirMask) // Bit1
{
if(node[2].decodePNSNoShift() & dirMask) // Bit0
PNS_BLOCK2(3,2,1,0) // 7
else
PNS_BLOCK2(2,3,1,0) // 6
}
else
{
if(node[2].decodePNSNoShift() & dirMask) // Bit0
PNS_BLOCK2(3,2,0,1) // 5
else
PNS_BLOCK2(2,3,0,1) // 4
}
}
else
{
if(node[1].decodePNSNoShift() & dirMask) // Bit1
{
if(node[2].decodePNSNoShift() & dirMask) // Bit0
PNS_BLOCK2(1,0,3,2) // 3
else
PNS_BLOCK2(1,0,2,3) // 2
}
else
{
if(node[2].decodePNSNoShift() & dirMask) // Bit0
PNS_BLOCK2(0,1,3,2) // 1
else
PNS_BLOCK2(0,1,2,3) // 0
}
}
}
#endif
}
}while(nb);
}
#endif // GU_BV4_USE_SLABS
#endif // GU_BV4_INTERNAL_H
| 11,113 | C | 36.170568 | 169 | 0.670206 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuRTree.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_RTREE_H
#define GU_RTREE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxAssert.h"
#include "common/PxSerialFramework.h"
#include "geometry/PxTriangleMesh.h"
#include "foundation/PxUserAllocated.h" // for PxSerializationContext
#include "foundation/PxAlignedMalloc.h"
#include "foundation/PxVecMath.h"
#define RTREE_N 4 // changing this number will affect the mesh format
PX_COMPILE_TIME_ASSERT(RTREE_N == 4 || RTREE_N == 8); // using the low 5 bits for storage of index(childPtr) for dynamic rtree
namespace physx
{
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
namespace Gu {
class Box;
struct RTreePage;
typedef PxF32 RTreeValue;
/////////////////////////////////////////////////////////////////////////
// quantized untransposed RTree node - used for offline build and dynamic insertion
struct RTreeNodeQ
{
RTreeValue minx, miny, minz, maxx, maxy, maxz;
PxU32 ptr; // lowest bit is leaf flag
PX_FORCE_INLINE void setLeaf(bool set) { if (set) ptr |= 1; else ptr &= ~1; }
PX_FORCE_INLINE PxU32 isLeaf() const { return ptr & 1; }
PX_FORCE_INLINE void setEmpty();
PX_FORCE_INLINE void grow(const RTreePage& page, int nodeIndex);
PX_FORCE_INLINE void grow(const RTreeNodeQ& node);
};
/////////////////////////////////////////////////////////////////////////
// RTreePage data structure, holds RTREE_N transposed nodes
// RTreePage data structure, holds 8 transposed nodes
PX_ALIGN_PREFIX(16)
struct RTreePage
{
static const RTreeValue MN, MX;
RTreeValue minx[RTREE_N]; // [min=MX, max=MN] is used as a sentinel range for empty bounds
RTreeValue miny[RTREE_N];
RTreeValue minz[RTREE_N];
RTreeValue maxx[RTREE_N];
RTreeValue maxy[RTREE_N];
RTreeValue maxz[RTREE_N];
PxU32 ptrs[RTREE_N]; // for static rtree this is an offset relative to the first page divided by 16, for dynamics it's an absolute pointer divided by 16
PX_FORCE_INLINE PxU32 nodeCount() const; // returns the number of occupied nodes in this page
PX_FORCE_INLINE void setEmpty(PxU32 startIndex = 0);
PX_FORCE_INLINE bool isEmpty(PxU32 index) const { return minx[index] > maxx[index]; }
PX_FORCE_INLINE void copyNode(PxU32 targetIndex, const RTreePage& sourcePage, PxU32 sourceIndex);
PX_FORCE_INLINE void setNode(PxU32 targetIndex, const RTreeNodeQ& node);
PX_FORCE_INLINE void clearNode(PxU32 nodeIndex);
PX_FORCE_INLINE void getNode(PxU32 nodeIndex, RTreeNodeQ& result) const;
PX_FORCE_INLINE void computeBounds(RTreeNodeQ& bounds);
PX_FORCE_INLINE void adjustChildBounds(PxU32 index, const RTreeNodeQ& adjustedChildBounds);
PX_FORCE_INLINE void growChildBounds(PxU32 index, const RTreeNodeQ& adjustedChildBounds);
PX_FORCE_INLINE PxU32 getNodeHandle(PxU32 index) const;
PX_FORCE_INLINE PxU32 isLeaf(PxU32 index) const { return ptrs[index] & 1; }
} PX_ALIGN_SUFFIX(16);
/////////////////////////////////////////////////////////////////////////
// RTree root data structure
PX_ALIGN_PREFIX(16)
struct RTree
{
// PX_SERIALIZATION
RTree(const PxEMPTY);
void exportExtraData(PxSerializationContext&);
void importExtraData(PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
PX_INLINE RTree(); // offline static rtree constructor used with cooking
~RTree() { release(); }
PX_INLINE void release();
bool load(PxInputStream& stream, PxU32 meshVersion, bool mismatch);
////////////////////////////////////////////////////////////////////////////
// QUERIES
struct Callback
{
// result buffer should have room for at least RTREE_N items
// should return true to continue traversal. If false is returned, traversal is aborted
virtual bool processResults(PxU32 count, PxU32* buf) = 0;
virtual void profile() {}
virtual ~Callback() {}
};
struct CallbackRaycast
{
// result buffer should have room for at least RTREE_N items
// should return true to continue traversal. If false is returned, traversal is aborted
// newMaxT serves as both input and output, as input it's the maxT so far
// set it to a new value (which should be smaller) and it will become the new far clip t
virtual bool processResults(PxU32 count, PxU32* buf, PxF32& newMaxT) = 0;
virtual ~CallbackRaycast() {}
};
// callback will be issued as soon as the buffer overflows maxResultsPerBlock-RTreePage:SIZE entries
// use maxResults = RTreePage:SIZE and return false from callback for "first hit" early out
void traverseAABB(
const PxVec3& boxMin, const PxVec3& boxMax,
const PxU32 maxResultsPerBlock, PxU32* resultsBlockBuf, Callback* processResultsBlockCallback) const;
void traverseOBB(
const Gu::Box& obb,
const PxU32 maxResultsPerBlock, PxU32* resultsBlockBuf, Callback* processResultsBlockCallback) const;
template <int inflate>
void traverseRay(
const PxVec3& rayOrigin, const PxVec3& rayDir, // dir doesn't have to be normalized and is B-A for raySegment
const PxU32 maxResults, PxU32* resultsPtr,
Gu::RTree::CallbackRaycast* callback,
const PxVec3* inflateAABBs, // inflate tree's AABBs by this amount. This function turns into AABB sweep.
PxF32 maxT = PX_MAX_F32 // maximum ray t parameter, p(t)=origin+t*dir; use 1.0f for ray segment
) const;
struct CallbackRefit
{
// In this callback index is the number stored in the RTree, which is a LeafTriangles object for current PhysX mesh
virtual void recomputeBounds(PxU32 index, aos::Vec3V& mn, aos::Vec3V& mx) = 0;
virtual ~CallbackRefit() {}
};
void refitAllStaticTree(CallbackRefit& cb, PxBounds3* resultMeshBounds); // faster version of refit for static RTree only
////////////////////////////////////////////////////////////////////////////
// DEBUG HELPER FUNCTIONS
PX_PHYSX_COMMON_API void validate(CallbackRefit* cb = NULL); // verify that all children are indeed included in parent bounds
void openTextDump();
void closeTextDump();
void textDump(const char* prefix);
void maxscriptExport();
PxU32 computeBottomLevelCount(PxU32 storedToMemMultiplier) const;
////////////////////////////////////////////////////////////////////////////
// DATA
// remember to update save() and load() when adding or removing data
PxVec4 mBoundsMin, mBoundsMax, mInvDiagonal, mDiagonalScaler; // 16
PxU32 mPageSize;
PxU32 mNumRootPages;
PxU32 mNumLevels;
PxU32 mTotalNodes; // 16
PxU32 mTotalPages;
PxU32 mFlags; enum { USER_ALLOCATED = 0x1, IS_EDGE_SET = 0x2 };
RTreePage* mPages;
protected:
typedef PxU32 NodeHandle;
void validateRecursive(PxU32 level, RTreeNodeQ parentBounds, RTreePage* page, CallbackRefit* cb = NULL);
friend struct RTreePage;
} PX_ALIGN_SUFFIX(16);
#if PX_SUPPORT_EXTERN_TEMPLATE
//explicit template instantiation declaration
extern template
void RTree::traverseRay<0>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const;
extern template
void RTree::traverseRay<1>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const;
#endif
#if PX_VC
#pragma warning(pop)
#endif
/////////////////////////////////////////////////////////////////////////
PX_INLINE RTree::RTree()
{
mFlags = 0;
mPages = NULL;
mTotalNodes = 0;
mNumLevels = 0;
mPageSize = RTREE_N;
}
/////////////////////////////////////////////////////////////////////////
PX_INLINE void RTree::release()
{
if ((mFlags & USER_ALLOCATED) == 0 && mPages)
{
physx::PxAlignedAllocator<128>().deallocate(mPages);
mPages = NULL;
}
}
/////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void RTreeNodeQ::setEmpty()
{
minx = miny = minz = RTreePage::MX;
maxx = maxy = maxz = RTreePage::MN;
}
// bit 1 is always expected to be set to differentiate between leaf and non-leaf node
PX_FORCE_INLINE PxU32 LeafGetNbTriangles(PxU32 Data) { return ((Data>>1) & 15)+1; }
PX_FORCE_INLINE PxU32 LeafGetTriangleIndex(PxU32 Data) { return Data>>5; }
PX_FORCE_INLINE PxU32 LeafSetData(PxU32 nb, PxU32 index)
{
PX_ASSERT(nb>0 && nb<=16); PX_ASSERT(index < (1<<27));
return (index<<5)|(((nb-1)&15)<<1) | 1;
}
struct LeafTriangles
{
PxU32 Data;
// Gets number of triangles in the leaf, returns the number of triangles N, with 0 < N <= 16
PX_FORCE_INLINE PxU32 GetNbTriangles() const { return LeafGetNbTriangles(Data); }
// Gets triangle index for this leaf. Indexed model's array of indices retrieved with RTreeMidphase::GetIndices()
PX_FORCE_INLINE PxU32 GetTriangleIndex() const { return LeafGetTriangleIndex(Data); }
PX_FORCE_INLINE void SetData(PxU32 nb, PxU32 index) { Data = LeafSetData(nb, index); }
};
PX_COMPILE_TIME_ASSERT(sizeof(LeafTriangles)==4); // RTree has space for 4 bytes
} // namespace Gu
}
#endif // #ifdef PX_COLLISION_RTREE
| 10,813 | C | 38.611721 | 154 | 0.686026 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxOverlap_Internal.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_BOX_OVERLAP_INTERNAL_H
#define GU_BV4_BOX_OVERLAP_INTERNAL_H
#include "GuBV4_Common.h"
template<class ParamsT>
PX_FORCE_INLINE void precomputeData(ParamsT* PX_RESTRICT dst, PxMat33* PX_RESTRICT absRot, const PxMat33* PX_RESTRICT boxToModelR)
{
// Precompute absolute box-to-model rotation matrix
dst->mPreca0_PaddedAligned.x = boxToModelR->column0.x;
dst->mPreca0_PaddedAligned.y = boxToModelR->column1.y;
dst->mPreca0_PaddedAligned.z = boxToModelR->column2.z;
dst->mPreca1_PaddedAligned.x = boxToModelR->column0.y;
dst->mPreca1_PaddedAligned.y = boxToModelR->column1.z;
dst->mPreca1_PaddedAligned.z = boxToModelR->column2.x;
dst->mPreca2_PaddedAligned.x = boxToModelR->column0.z;
dst->mPreca2_PaddedAligned.y = boxToModelR->column1.x;
dst->mPreca2_PaddedAligned.z = boxToModelR->column2.y;
// Epsilon value prevents floating-point inaccuracies (strategy borrowed from RAPID)
const PxReal epsilon = 1e-6f;
absRot->column0.x = dst->mPreca0b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.x);
absRot->column0.y = dst->mPreca1b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.y);
absRot->column0.z = dst->mPreca2b_PaddedAligned.x = epsilon + fabsf(boxToModelR->column0.z);
absRot->column1.x = dst->mPreca2b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.x);
absRot->column1.y = dst->mPreca0b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.y);
absRot->column1.z = dst->mPreca1b_PaddedAligned.y = epsilon + fabsf(boxToModelR->column1.z);
absRot->column2.x = dst->mPreca1b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.x);
absRot->column2.y = dst->mPreca2b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.y);
absRot->column2.z = dst->mPreca0b_PaddedAligned.z = epsilon + fabsf(boxToModelR->column2.z);
}
template<class ParamsT>
PX_FORCE_INLINE void setupBoxData(ParamsT* PX_RESTRICT dst, const PxVec3& extents, const PxMat33* PX_RESTRICT mAR)
{
dst->mBoxExtents_PaddedAligned = extents;
const float Ex = extents.x;
const float Ey = extents.y;
const float Ez = extents.z;
dst->mBB_PaddedAligned.x = Ex*mAR->column0.x + Ey*mAR->column1.x + Ez*mAR->column2.x;
dst->mBB_PaddedAligned.y = Ex*mAR->column0.y + Ey*mAR->column1.y + Ez*mAR->column2.y;
dst->mBB_PaddedAligned.z = Ex*mAR->column0.z + Ey*mAR->column1.z + Ez*mAR->column2.z;
}
struct OBBTestParams // Data needed to perform the OBB-OBB overlap test
{
BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3p mTBoxToModel_PaddedAligned); //!< Translation from obb space to model space
BV4_ALIGN16(PxVec3p mBB_PaddedAligned);
BV4_ALIGN16(PxVec3p mBoxExtents_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca0_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca1_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca2_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca0b_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca1b_PaddedAligned);
BV4_ALIGN16(PxVec3p mPreca2b_PaddedAligned);
PX_FORCE_INLINE void precomputeBoxData(const PxVec3& extents, const PxMat33* PX_RESTRICT box_to_model)
{
PxMat33 absRot; //!< Absolute rotation matrix
precomputeData(this, &absRot, box_to_model);
setupBoxData(this, extents, &absRot);
}
};
#endif // GU_BV4_BOX_OVERLAP_INTERNAL_H
| 5,017 | C | 47.718446 | 131 | 0.753638 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMesh.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TETRAHEDRONMESH_H
#define GU_TETRAHEDRONMESH_H
#include "foundation/PxIO.h"
#include "geometry/PxTetrahedronMeshGeometry.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxTetrahedron.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "CmRefCountable.h"
#include "common/PxRenderOutput.h"
#include "GuMeshData.h"
#include "GuCenterExtents.h"
#include "GuMeshFactory.h"
namespace physx
{
namespace Gu
{
class MeshFactory;
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class SoftBodyAuxData : public PxSoftBodyAuxData, public PxUserAllocated
{
public:
SoftBodyAuxData(SoftBodySimulationData& d, SoftBodyCollisionData& c, CollisionMeshMappingData& e);
virtual ~SoftBodyAuxData();
virtual const char* getConcreteTypeName() const { return "PxSoftBodyAuxData"; }
virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); }
virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); }
virtual void release() { Cm::RefCountable_decRefCount(*this); }
virtual void onRefCountZero() { PX_DELETE_THIS; }
virtual PxReal* getGridModelInvMass() { return mGridModelInvMass; }
PX_FORCE_INLINE PxU32 getNbTetRemapSizeFast() const { return mTetsRemapSize; }
PX_FORCE_INLINE PxReal* getGridModelInvMassFast() { return mGridModelInvMass; }
PX_FORCE_INLINE PxU32 getNbGMPartitionFast() const { return mGMNbPartitions; }
PX_FORCE_INLINE PxU32 getGMRemapOutputSizeFast() const { return mGMRemapOutputSize; }
PX_FORCE_INLINE PxU32 getGMMaxTetsPerPartitionsFast() const { return mGMMaxMaxTetsPerPartitions; }
PX_FORCE_INLINE PxU32* getCollisionAccumulatedTetrahedronRefs() const { return mCollisionAccumulatedTetrahedronsRef; }
PX_FORCE_INLINE PxU32* getCollisionTetrahedronRefs() const { return mCollisionTetrahedronsReferences; }
PX_FORCE_INLINE PxU32 getCollisionNbTetrahedronRefs() const { return mCollisionNbTetrahedronsReferences; }
PX_FORCE_INLINE PxU32* getCollisionSurfaceVertToTetRemap() const { return mCollisionSurfaceVertToTetRemap; }
PX_FORCE_INLINE PxMat33* getGridModelRestPosesFast() { return mGridModelTetraRestPoses; }
PX_FORCE_INLINE PxMat33* getRestPosesFast() { return mTetraRestPoses; }
float* mGridModelInvMass;
PxMat33* mGridModelTetraRestPoses;
PxU32* mGridModelOrderedTetrahedrons;
PxU32 mGMNbPartitions;
PxU32 mGMMaxMaxTetsPerPartitions;
PxU32 mGMRemapOutputSize;
PxU32* mGMRemapOutputCP;
PxU32* mGMAccumulatedPartitionsCP;
PxU32* mGMAccumulatedCopiesCP;
PxU32* mCollisionAccumulatedTetrahedronsRef;
PxU32* mCollisionTetrahedronsReferences;
PxU32 mCollisionNbTetrahedronsReferences;
PxU8* mCollisionSurfaceVertsHint;
PxU32* mCollisionSurfaceVertToTetRemap;
PxReal* mVertsBarycentricInGridModel;
PxU32* mVertsRemapInGridModel;
PxU32* mTetsRemapColToSim;
PxU32 mTetsRemapSize;
PxU32* mTetsAccumulatedRemapColToSim;
PxU32* mGMPullIndices;
PxMat33* mTetraRestPoses;
PxU32 mNumTetsPerElement;
};
class TetrahedronMesh : public PxTetrahedronMesh, public PxUserAllocated
{
public:
TetrahedronMesh(PxU32 nbVertices, PxVec3* vertices, PxU32 nbTetrahedrons, void* tetrahedrons, PxU8 flags, PxBounds3 aabb, PxReal geomEpsilon);
TetrahedronMesh(TetrahedronMeshData& mesh);
TetrahedronMesh(MeshFactory* meshFactory, TetrahedronMeshData& mesh);
virtual ~TetrahedronMesh();
virtual const char* getConcreteTypeName() const { return "PxTetrahedronMesh"; }
virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); }
virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); }
virtual void release() { Cm::RefCountable_decRefCount(*this); }
virtual void onRefCountZero();
virtual PxU32 getNbVertices() const { return mNbVertices; }
virtual const PxVec3* getVertices() const { return mVertices; }
virtual PxU32 getNbTetrahedrons() const { return mNbTetrahedrons; }
virtual const void* getTetrahedrons() const { return mTetrahedrons; }
virtual PxTetrahedronMeshFlags getTetrahedronMeshFlags() const { return PxTetrahedronMeshFlags(mFlags); }
virtual const PxU32* getTetrahedraRemap() const { return NULL; }
PX_FORCE_INLINE PxU32 getNbVerticesFast() const { return mNbVertices; }
PX_FORCE_INLINE PxVec3* getVerticesFast() const { return mVertices; }
PX_FORCE_INLINE PxU32 getNbTetrahedronsFast() const { return mNbTetrahedrons; }
PX_FORCE_INLINE const void* getTetrahedronsFast() const { return mTetrahedrons; }
PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxMeshFlag::e16_BIT_INDICES) ? true : false; }
PX_FORCE_INLINE bool hasPerTriangleMaterials() const { return mMaterialIndices != NULL; }
PX_FORCE_INLINE const PxU16* getMaterials() const { return mMaterialIndices; }
PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mAABB; }
PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const
{
// PT: see compile-time assert in cpp
return static_cast<const CenterExtentsPadded&>(mAABB);
}
virtual PxBounds3 getLocalBounds() const
{
PX_ASSERT(mAABB.isValid());
return PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents);
}
PxU32 mNbVertices;
PxVec3* mVertices;
PxU32 mNbTetrahedrons;
void* mTetrahedrons;
PxU8 mFlags; //!< Flag whether indices are 16 or 32 bits wide
PxU16* mMaterialIndices; //!< the size of the array is mNbTetrahedrons.
// PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading
CenterExtents mAABB;
PxReal mGeomEpsilon;
MeshFactory* mMeshFactory; // PT: changed to pointer for serialization
};
PX_FORCE_INLINE const Gu::TetrahedronMesh* _getTetraMeshData(const PxTetrahedronMeshGeometry& meshGeom)
{
return static_cast<const Gu::TetrahedronMesh*>(meshGeom.tetrahedronMesh);
}
class BVTetrahedronMesh : public TetrahedronMesh
{
public:
BVTetrahedronMesh(TetrahedronMeshData& mesh, SoftBodyCollisionData& d, MeshFactory* factory = NULL);
virtual ~BVTetrahedronMesh()
{
PX_FREE(mGRB_tetraIndices);
PX_FREE(mGRB_tetraSurfaceHint);
PX_FREE(mGRB_faceRemap);
PX_FREE(mGRB_faceRemapInverse);
PX_DELETE(mGRB_BV32Tree);
PX_FREE(mFaceRemap);
}
//virtual PxBounds3 refitBVH();
PX_FORCE_INLINE const Gu::BV4Tree& getBV4Tree() const { return mBV4Tree; }
PX_FORCE_INLINE Gu::BV4Tree& getBV4Tree() { return mBV4Tree; }
PX_FORCE_INLINE void* getGRBTetraFaceRemap() { return mGRB_faceRemap; }
PX_FORCE_INLINE void* getGRBTetraFaceRemapInverse() { return mGRB_faceRemapInverse; }
virtual const PxU32* getTetrahedraRemap() const { return mFaceRemap; }
PX_FORCE_INLINE bool isTetMeshGPUCompatible() const
{
return mGRB_BV32Tree != NULL;
}
PxU32* mFaceRemap; //!< new faces to old faces mapping (after cleaning, etc). Usage: old = faceRemap[new]
// GRB data -------------------------
void* mGRB_tetraIndices; //!< GRB: GPU-friendly tri indices [uint4]
PxU8* mGRB_tetraSurfaceHint;
PxU32* mGRB_faceRemap;
PxU32* mGRB_faceRemapInverse;
Gu::BV32Tree* mGRB_BV32Tree; //!< GRB: BV32 tree
private:
Gu::TetrahedronSourceMesh mMeshInterface4;
Gu::BV4Tree mBV4Tree;
Gu::TetrahedronSourceMesh mMeshInterface32;
};
// Possible optimization: align the whole struct to cache line
class SoftBodyMesh : public PxSoftBodyMesh, public PxUserAllocated
{
public:
virtual const char* getConcreteTypeName() const { return "PxSoftBodyMesh"; }
// PX_SERIALIZATION
virtual void exportExtraData(PxSerializationContext& ctx);
void importExtraData(PxDeserializationContext&);
//PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
virtual void release();
void resolveReferences(PxDeserializationContext&) {}
virtual void requiresObjects(PxProcessPxBaseCallback&) {}
//~PX_SERIALIZATION
virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); }
virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); }
virtual void onRefCountZero();
//virtual PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH34; }
SoftBodyMesh(MeshFactory* factory, SoftBodyMeshData& data);
virtual ~SoftBodyMesh();
void setMeshFactory(MeshFactory* factory) { mMeshFactory = factory; }
virtual const PxTetrahedronMesh* getCollisionMesh() const { return mCollisionMesh; }
virtual PxTetrahedronMesh* getCollisionMesh() { return mCollisionMesh; }
PX_FORCE_INLINE const BVTetrahedronMesh* getCollisionMeshFast() const { return mCollisionMesh; }
PX_FORCE_INLINE BVTetrahedronMesh* getCollisionMeshFast() { return mCollisionMesh; }
virtual const PxTetrahedronMesh* getSimulationMesh() const { return mSimulationMesh; }
virtual PxTetrahedronMesh* getSimulationMesh() { return mSimulationMesh; }
PX_FORCE_INLINE const TetrahedronMesh* getSimulationMeshFast() const { return mSimulationMesh; }
PX_FORCE_INLINE TetrahedronMesh* getSimulationMeshFast() { return mSimulationMesh; }
virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const { return mSoftBodyAuxData; }
virtual PxSoftBodyAuxData* getSoftBodyAuxData() { return mSoftBodyAuxData; }
PX_FORCE_INLINE const SoftBodyAuxData* getSoftBodyAuxDataFast() const { return mSoftBodyAuxData; }
PX_FORCE_INLINE SoftBodyAuxData* getSoftBodyAuxDataFast() { return mSoftBodyAuxData; }
protected:
TetrahedronMesh* mSimulationMesh;
BVTetrahedronMesh* mCollisionMesh;
SoftBodyAuxData* mSoftBodyAuxData;
MeshFactory* mMeshFactory; // PT: changed to pointer for serialization
};
#if PX_VC
#pragma warning(pop)
#endif
} // namespace Gu
}
#endif
| 12,247 | C | 40.518644 | 153 | 0.716829 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Settings.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SETTINGS_H
#define GU_BV4_SETTINGS_H
// PT: "BV4" ported from "Opcode 2.0". Available compile-time options are:
#define GU_BV4_STACK_SIZE 256 // Default size of local stacks for non-recursive traversals.
#define GU_BV4_PRECOMPUTED_NODE_SORT // Use node sorting or not. This should probably always be enabled.
// #define GU_BV4_QUANTIZED_TREE // Use AABB quantization/compression or not.
#define GU_BV4_USE_SLABS // Use swizzled data format or not. Swizzled = faster raycasts, but slower overlaps & larger trees.
// #define GU_BV4_COMPILE_NON_QUANTIZED_TREE //
#define GU_BV4_FILL_GAPS
//#define PROFILE_MESH_COOKING
#ifdef PROFILE_MESH_COOKING
#include <intrin.h>
#include <stdio.h>
struct LocalProfileZone
{
LocalProfileZone(const char* name)
{
mName = name;
mTime = __rdtsc();
}
~LocalProfileZone()
{
mTime = __rdtsc() - mTime;
printf("%s: %d\n", mName, unsigned int(mTime/1024));
}
const char* mName;
unsigned long long mTime;
};
#define GU_PROFILE_ZONE(name) LocalProfileZone zone(name);
#else
#define GU_PROFILE_ZONE(name)
#endif
#endif // GU_BV4_SETTINGS_H
| 2,833 | C | 41.298507 | 129 | 0.740205 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_INFLATED_H
#define GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_INFLATED_H
#ifndef GU_BV4_USE_SLABS
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_SegmentAABBOverlap(node+i, params->mOriginalExtents_Padded, params))
#else
if(BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params->mOriginalExtents_Padded, params))
#endif
{
if(node[i].isLeaf())
{
if(LeafTestT::doLeafTest(params, node[i].getPrimitive()))
return 1;
}
else
Stack[Nb++] = node[i].getChildData();
}
return 0;
}
#endif
#endif // GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_INFLATED_H
| 2,550 | C | 45.381817 | 153 | 0.75451 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshBV4.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TRIANGLEMESH_BV4_H
#define GU_TRIANGLEMESH_BV4_H
#include "GuTriangleMesh.h"
namespace physx
{
namespace Gu
{
class MeshFactory;
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class BV4TriangleMesh : public TriangleMesh
{
public:
virtual const char* getConcreteTypeName() const { return "PxBVH34TriangleMesh"; }
// PX_SERIALIZATION
BV4TriangleMesh(PxBaseFlags baseFlags) : TriangleMesh(baseFlags), mMeshInterface(PxEmpty), mBV4Tree(PxEmpty) {}
PX_PHYSX_COMMON_API virtual void exportExtraData(PxSerializationContext& ctx);
void importExtraData(PxDeserializationContext&);
PX_PHYSX_COMMON_API static TriangleMesh* createObject(PxU8*& address, PxDeserializationContext& context);
PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
BV4TriangleMesh(MeshFactory* factory, TriangleMeshData& data);
virtual ~BV4TriangleMesh(){}
virtual PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH34; }
virtual PxVec3* getVerticesForModification();
virtual PxBounds3 refitBVH();
PX_PHYSX_COMMON_API BV4TriangleMesh(const PxTriangleMeshInternalData& data);
virtual bool getInternalData(PxTriangleMeshInternalData&, bool) const;
PX_FORCE_INLINE const Gu::BV4Tree& getBV4Tree() const { return mBV4Tree; }
private:
Gu::SourceMesh mMeshInterface;
Gu::BV4Tree mBV4Tree;
};
#if PX_VC
#pragma warning(pop)
#endif
} // namespace Gu
}
#endif
| 3,362 | C | 40.012195 | 125 | 0.7442 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TRIANGLE_CACHE_H
#define GU_TRIANGLE_CACHE_H
#include "foundation/PxHash.h"
#include "foundation/PxUtilities.h"
namespace physx
{
namespace Gu
{
struct CachedEdge
{
protected:
PxU32 mId0, mId1;
public:
CachedEdge(PxU32 i0, PxU32 i1)
{
mId0 = PxMin(i0, i1);
mId1 = PxMax(i0, i1);
}
CachedEdge()
{
}
PxU32 getId0() const { return mId0; }
PxU32 getId1() const { return mId1; }
bool operator == (const CachedEdge& other) const
{
return mId0 == other.mId0 && mId1 == other.mId1;
}
PxU32 getHashCode() const
{
return PxComputeHash(mId0 << 16 | mId1);
}
};
struct CachedVertex
{
private:
PxU32 mId;
public:
CachedVertex(PxU32 id)
{
mId = id;
}
CachedVertex()
{
}
PxU32 getId() const { return mId; }
PxU32 getHashCode() const
{
return mId;
}
bool operator == (const CachedVertex& other) const
{
return mId == other.mId;
}
};
template <typename Elem, PxU32 MaxCount>
struct CacheMap
{
PX_COMPILE_TIME_ASSERT(MaxCount < 0xFF);
Elem mCache[MaxCount];
PxU8 mNextInd[MaxCount];
PxU8 mIndex[MaxCount];
PxU32 mSize;
CacheMap() : mSize(0)
{
for(PxU32 a = 0; a < MaxCount; ++a)
{
mIndex[a] = 0xFF;
}
}
bool addData(const Elem& data)
{
if(mSize == MaxCount)
return false;
const PxU8 hash = PxU8(data.getHashCode() % MaxCount);
PxU8 index = hash;
PxU8 nextInd = mIndex[hash];
while(nextInd != 0xFF)
{
index = nextInd;
if(mCache[index] == data)
return false;
nextInd = mNextInd[nextInd];
}
if(mIndex[hash] == 0xFF)
{
mIndex[hash] = PxTo8(mSize);
}
else
{
mNextInd[index] = PxTo8(mSize);
}
mNextInd[mSize] = 0xFF;
mCache[mSize++] = data;
return true;
}
bool contains(const Elem& data) const
{
PxU32 hash = (data.getHashCode() % MaxCount);
PxU8 index = mIndex[hash];
while(index != 0xFF)
{
if(mCache[index] == data)
return true;
index = mNextInd[index];
}
return false;
}
const Elem* get(const Elem& data) const
{
PxU32 hash = (data.getHashCode() % MaxCount);
PxU8 index = mIndex[hash];
while(index != 0xFF)
{
if(mCache[index] == data)
return &mCache[index];
index = mNextInd[index];
}
return NULL;
}
};
template <PxU32 MaxTriangles>
struct TriangleCache
{
PxVec3 mVertices[3*MaxTriangles];
PxU32 mIndices[3*MaxTriangles];
PxU32 mTriangleIndex[MaxTriangles];
PxU8 mEdgeFlags[MaxTriangles];
PxU32 mNumTriangles;
TriangleCache() : mNumTriangles(0)
{
}
PX_FORCE_INLINE bool isEmpty() const { return mNumTriangles == 0; }
PX_FORCE_INLINE bool isFull() const { return mNumTriangles == MaxTriangles; }
PX_FORCE_INLINE void reset() { mNumTriangles = 0; }
void addTriangle(const PxVec3* verts, const PxU32* indices, PxU32 triangleIndex, PxU8 edgeFlag)
{
PX_ASSERT(mNumTriangles < MaxTriangles);
PxU32 triInd = mNumTriangles++;
PxU32 triIndMul3 = triInd*3;
mVertices[triIndMul3] = verts[0];
mVertices[triIndMul3+1] = verts[1];
mVertices[triIndMul3+2] = verts[2];
mIndices[triIndMul3] = indices[0];
mIndices[triIndMul3+1] = indices[1];
mIndices[triIndMul3+2] = indices[2];
mTriangleIndex[triInd] = triangleIndex;
mEdgeFlags[triInd] = edgeFlag;
}
};
template <PxU32 MaxTetrahedrons>
struct TetrahedronCache
{
PxVec3 mVertices[4 * MaxTetrahedrons];
PxU32 mTetVertIndices[4 * MaxTetrahedrons];
PxU32 mTetrahedronIndices[MaxTetrahedrons];
PxU32 mNumTetrahedrons;
TetrahedronCache() : mNumTetrahedrons(0)
{
}
PX_FORCE_INLINE bool isEmpty() const { return mNumTetrahedrons == 0; }
PX_FORCE_INLINE bool isFull() const { return mNumTetrahedrons == MaxTetrahedrons; }
PX_FORCE_INLINE void reset() { mNumTetrahedrons = 0; }
void addTetrahedrons(const PxVec3* verts, const PxU32* indices, PxU32 tetIndex)
{
PX_ASSERT(mNumTetrahedrons < MaxTetrahedrons);
PxU32 tetInd = mNumTetrahedrons++;
PxU32 tetIndMul4 = tetInd * 4;
mVertices[tetIndMul4] = verts[0];
mVertices[tetIndMul4 + 1] = verts[1];
mVertices[tetIndMul4 + 2] = verts[2];
mVertices[tetIndMul4 + 3] = verts[3];
mTetVertIndices[tetIndMul4] = indices[0];
mTetVertIndices[tetIndMul4 + 1] = indices[1];
mTetVertIndices[tetIndMul4 + 2] = indices[2];
mTetVertIndices[tetIndMul4 + 3] = indices[3];
mTetrahedronIndices[tetInd] = tetIndex;
}
};
}
}
#endif
| 6,284 | C | 25.1875 | 98 | 0.667887 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Build.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxVec4.h"
#include "foundation/PxMemory.h"
#include "GuAABBTreeBuildStats.h"
#include "GuAABBTree.h"
#include "GuSAH.h"
#include "GuBounds.h"
#include "GuBV4Build.h"
#include "GuBV4.h"
#include <stdio.h>
using namespace physx;
using namespace Gu;
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#define GU_BV4_USE_NODE_POOLS
static PX_FORCE_INLINE PxU32 largestAxis(const PxVec4& v)
{
const float* Vals = &v.x;
PxU32 m = 0;
if(Vals[1] > Vals[m]) m = 1;
if(Vals[2] > Vals[m]) m = 2;
return m;
}
BV4_AABBTree::BV4_AABBTree() : mIndices(NULL), mPool(NULL), mTotalNbNodes(0)
{
}
BV4_AABBTree::~BV4_AABBTree()
{
release();
}
void BV4_AABBTree::release()
{
PX_DELETE_ARRAY(mPool);
PX_FREE(mIndices);
}
namespace
{
struct BuildParams
{
PX_FORCE_INLINE BuildParams(const PxBounds3* boxes, const PxVec3* centers, const AABBTreeNode* const node_base, const PxU32 limit, const SourceMesh* mesh) :
mBoxes(boxes), mCenters(centers), mNodeBase(node_base), mLimit(limit), mMesh(mesh) {}
const PxBounds3* mBoxes;
const PxVec3* mCenters;
const AABBTreeNode* const mNodeBase;
const PxU32 mLimit;
const SourceMesh* mMesh;
PX_NOCOPY(BuildParams)
};
}
static PxU32 local_Split(const AABBTreeNode* PX_RESTRICT node, const PxBounds3* PX_RESTRICT /*Boxes*/, const PxVec3* PX_RESTRICT centers, PxU32 axis, const BuildParams& params)
{
const PxU32 nb = node->mNbPrimitives;
PxU32* PX_RESTRICT prims = node->mNodePrimitives;
// Get node split value
float splitValue = 0.0f;
if(params.mMesh)
{
VertexPointers VP;
for(PxU32 i=0;i<nb;i++)
{
params.mMesh->getTriangle(VP, prims[i]);
splitValue += (*VP.Vertex[0])[axis];
splitValue += (*VP.Vertex[1])[axis];
splitValue += (*VP.Vertex[2])[axis];
}
splitValue /= float(nb*3);
}
else
splitValue = node->mBV.getCenter(axis);
return reshuffle(nb, prims, centers, splitValue, axis);
}
static bool local_Subdivide(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params)
{
const PxU32* PX_RESTRICT prims = node->mNodePrimitives;
const PxU32 nb = node->mNbPrimitives;
const PxBounds3* PX_RESTRICT boxes = params.mBoxes;
const PxVec3* PX_RESTRICT centers = params.mCenters;
// Compute bv & means at the same time
Vec4V meansV;
{
Vec4V minV = V4LoadU(&boxes[prims[0]].minimum.x);
Vec4V maxV = V4LoadU(&boxes[prims[0]].maximum.x);
meansV = V4LoadU(¢ers[prims[0]].x);
for(PxU32 i=1;i<nb;i++)
{
const PxU32 index = prims[i];
minV = V4Min(minV, V4LoadU(&boxes[index].minimum.x));
maxV = V4Max(maxV, V4LoadU(&boxes[index].maximum.x));
meansV = V4Add(meansV, V4LoadU(¢ers[index].x));
}
const float coeffNb = 1.0f/float(nb);
meansV = V4Scale(meansV, FLoad(coeffNb));
// BV4_ALIGN16(PxVec4 mergedMin);
// BV4_ALIGN16(PxVec4 mergedMax);
PX_ALIGN_PREFIX(16) PxVec4 mergedMin PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16) PxVec4 mergedMax PX_ALIGN_SUFFIX(16);
V4StoreA_Safe(minV, &mergedMin.x);
V4StoreA_Safe(maxV, &mergedMax.x);
node->mBV.minimum = PxVec3(mergedMin.x, mergedMin.y, mergedMin.z);
node->mBV.maximum = PxVec3(mergedMax.x, mergedMax.y, mergedMax.z);
}
#ifndef GU_BV4_FILL_GAPS
// // Stop subdividing if we reach a leaf node. This is always performed here,
// // else we could end in trouble if user overrides this.
// if(nb==1)
// return false;
if(nb<=params.mLimit)
return false;
#endif
bool validSplit = true;
PxU32 nbPos;
{
// Compute variances
Vec4V varsV = V4Zero();
for(PxU32 i=0;i<nb;i++)
{
const PxU32 index = prims[i];
Vec4V centerV = V4LoadU(¢ers[index].x);
centerV = V4Sub(centerV, meansV);
centerV = V4Mul(centerV, centerV);
varsV = V4Add(varsV, centerV);
}
const float coeffNb1 = 1.0f/float(nb-1);
varsV = V4Scale(varsV, FLoad(coeffNb1));
// BV4_ALIGN16(PxVec4 vars);
PX_ALIGN_PREFIX(16) PxVec4 vars PX_ALIGN_SUFFIX(16);
V4StoreA_Safe(varsV, &vars.x);
// Choose axis with greatest variance
const PxU32 axis = largestAxis(vars);
// Split along the axis
nbPos = local_Split(node, boxes, centers, axis, params);
// Check split validity
if(!nbPos || nbPos==nb)
validSplit = false;
}
// Check the subdivision has been successful
if(!validSplit)
{
// Here, all boxes lie in the same sub-space. Two strategies:
// - if the tree *must* be complete, make an arbitrary 50-50 split
// - else stop subdividing
// if(nb>limit)
{
nbPos = node->mNbPrimitives>>1;
if(1)
{
// Test 3 axes, take the best
float results[3];
nbPos = local_Split(node, boxes, centers, 0, params); results[0] = float(nbPos)/float(node->mNbPrimitives);
nbPos = local_Split(node, boxes, centers, 1, params); results[1] = float(nbPos)/float(node->mNbPrimitives);
nbPos = local_Split(node, boxes, centers, 2, params); results[2] = float(nbPos)/float(node->mNbPrimitives);
results[0]-=0.5f; results[0]*=results[0];
results[1]-=0.5f; results[1]*=results[1];
results[2]-=0.5f; results[2]*=results[2];
PxU32 Min=0;
if(results[1]<results[Min]) Min = 1;
if(results[2]<results[Min]) Min = 2;
// Split along the axis
nbPos = local_Split(node, boxes, centers, Min, params);
// Check split validity
if(!nbPos || nbPos==node->mNbPrimitives)
nbPos = node->mNbPrimitives>>1;
}
}
//else return
}
#ifdef GU_BV4_FILL_GAPS
// We split the node a last time before returning when we're below the limit, for the "fill the gaps" strategy
if(nb<=params.mLimit)
{
node->mNextSplit = nbPos;
return false;
}
#endif
// Now create children and assign their pointers.
// We use a pre-allocated linear pool for complete trees [Opcode 1.3]
const PxU32 count = stats.getCount();
node->mPos = size_t(params.mNodeBase + count);
// Update stats
stats.increaseCount(2);
// Assign children
AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos());
AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg());
pos->mNodePrimitives = node->mNodePrimitives;
pos->mNbPrimitives = nbPos;
neg->mNodePrimitives = node->mNodePrimitives + nbPos;
neg->mNbPrimitives = node->mNbPrimitives - nbPos;
return true;
}
static bool local_Subdivide_SAH(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params, SAH_Buffers& buffers)
{
const PxU32* prims = node->mNodePrimitives;
const PxU32 nb = node->mNbPrimitives;
const PxBounds3* PX_RESTRICT boxes = params.mBoxes;
const PxVec3* PX_RESTRICT centers = params.mCenters;
// Compute bv
computeGlobalBox(node->mBV, nb, boxes, prims);
#ifndef GU_BV4_FILL_GAPS
// // Stop subdividing if we reach a leaf node. This is always performed here,
// // else we could end in trouble if user overrides this.
// if(nb==1)
// return false;
if(nb<=params.mLimit)
return false;
#endif
PxU32 leftCount;
if(!buffers.split(leftCount, nb, prims, boxes, centers))
{
// Invalid split => fallback to previous strategy
return local_Subdivide(node, stats, params);
}
#ifdef GU_BV4_FILL_GAPS
// We split the node a last time before returning when we're below the limit, for the "fill the gaps" strategy
if(nb<=params.mLimit)
{
node->mNextSplit = leftCount;
return false;
}
#endif
// Now create children and assign their pointers.
// We use a pre-allocated linear pool for complete trees [Opcode 1.3]
const PxU32 count = stats.getCount();
node->mPos = size_t(params.mNodeBase + count);
// Update stats
stats.increaseCount(2);
// Assign children
AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos());
AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg());
pos->mNodePrimitives = node->mNodePrimitives;
pos->mNbPrimitives = leftCount;
neg->mNodePrimitives = node->mNodePrimitives + leftCount;
neg->mNbPrimitives = node->mNbPrimitives - leftCount;
return true;
}
// PT: TODO: consider local_BuildHierarchy & local_BuildHierarchy_SAH
static void local_BuildHierarchy(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params)
{
if(local_Subdivide(node, stats, params))
{
AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos());
AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg());
local_BuildHierarchy(pos, stats, params);
local_BuildHierarchy(neg, stats, params);
}
}
static void local_BuildHierarchy_SAH(AABBTreeNode* PX_RESTRICT node, BuildStats& stats, const BuildParams& params, SAH_Buffers& buffers)
{
if(local_Subdivide_SAH(node, stats, params, buffers))
{
AABBTreeNode* pos = const_cast<AABBTreeNode*>(node->getPos());
AABBTreeNode* neg = const_cast<AABBTreeNode*>(node->getNeg());
local_BuildHierarchy_SAH(pos, stats, params, buffers);
local_BuildHierarchy_SAH(neg, stats, params, buffers);
}
}
bool BV4_AABBTree::buildFromMesh(SourceMeshBase& mesh, PxU32 limit, BV4_BuildStrategy strategy)
{
const PxU32 nbBoxes = mesh.getNbPrimitives();
if(!nbBoxes)
return false;
PxBounds3* boxes = PX_ALLOCATE(PxBounds3, (nbBoxes + 1), "BV4"); // PT: +1 to safely V4Load/V4Store the last element
PxVec3* centers = PX_ALLOCATE(PxVec3, (nbBoxes + 1), "BV4"); // PT: +1 to safely V4Load/V4Store the last element
const FloatV halfV = FLoad(0.5f);
for (PxU32 i = 0; i<nbBoxes; i++)
{
Vec4V minV, maxV;
mesh.getPrimitiveBox(i, minV, maxV);
V4StoreU_Safe(minV, &boxes[i].minimum.x); // PT: safe because 'maximum' follows 'minimum'
V4StoreU_Safe(maxV, &boxes[i].maximum.x); // PT: safe because we allocated one more box
const Vec4V centerV = V4Scale(V4Add(maxV, minV), halfV);
V4StoreU_Safe(centerV, ¢ers[i].x); // PT: safe because we allocated one more PxVec3
}
{
// Release previous tree
release();
// Init stats
BuildStats Stats;
Stats.setCount(1);
// Initialize indices. This list will be modified during build.
mIndices = PX_ALLOCATE(PxU32, nbBoxes, "BV4 indices");
// Identity permutation
for (PxU32 i = 0; i<nbBoxes; i++)
mIndices[i] = i;
// Use a linear array for complete trees (since we can predict the final number of nodes) [Opcode 1.3]
// Allocate a pool of nodes
// PT: TODO: optimize memory here (TA34704)
mPool = PX_NEW(AABBTreeNode)[nbBoxes * 2 - 1];
// Setup initial node. Here we have a complete permutation of the app's primitives.
mPool->mNodePrimitives = mIndices;
mPool->mNbPrimitives = nbBoxes;
// Build the hierarchy
if(strategy==BV4_SPLATTER_POINTS||strategy==BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER)
{
// PT: not sure what the equivalent would be for tet-meshes here
SourceMesh* triMesh = NULL;
if(strategy==BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER)
{
if(mesh.getMeshType()==SourceMeshBase::TRI_MESH)
triMesh = static_cast<SourceMesh*>(&mesh);
}
local_BuildHierarchy(mPool, Stats, BuildParams(boxes, centers, mPool, limit, triMesh));
}
else if(strategy==BV4_SAH)
{
SAH_Buffers sah(nbBoxes);
local_BuildHierarchy_SAH(mPool, Stats, BuildParams(boxes, centers, mPool, limit, NULL), sah);
}
else
return false;
// Get back total number of nodes
mTotalNbNodes = Stats.getCount();
}
PX_FREE(centers);
PX_FREE(boxes);
if(0)
printf("Tree depth: %d\n", walk(NULL, NULL));
return true;
}
PxU32 BV4_AABBTree::walk(WalkingCallback cb, void* userData) const
{
// Call it without callback to compute max depth
PxU32 maxDepth = 0;
PxU32 currentDepth = 0;
struct Local
{
static void _walk(const AABBTreeNode* current_node, PxU32& max_depth, PxU32& current_depth, WalkingCallback callback, void* userData_)
{
// Checkings
if(!current_node)
return;
// Entering a new node => increase depth
current_depth++;
// Keep track of max depth
if(current_depth>max_depth)
max_depth = current_depth;
// Callback
if(callback && !(callback)(current_node, current_depth, userData_))
return;
// Recurse
if(current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, userData_); current_depth--; }
if(current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, userData_); current_depth--; }
}
};
Local::_walk(mPool, maxDepth, currentDepth, cb, userData);
return maxDepth;
}
PxU32 BV4_AABBTree::walkDistance(WalkingCallback cb, WalkingDistanceCallback cb2, void* userData) const
{
// Call it without callback to compute max depth
PxU32 maxDepth = 0;
PxU32 currentDepth = 0;
struct Local
{
static void _walk(const AABBTreeNode* current_node, PxU32& max_depth, PxU32& current_depth, WalkingCallback callback, WalkingDistanceCallback distanceCheck, void* userData_)
{
// Checkings
if (!current_node)
return;
// Entering a new node => increase depth
current_depth++;
// Keep track of max depth
if (current_depth > max_depth)
max_depth = current_depth;
// Callback
if (callback && !(callback)(current_node, current_depth, userData_))
return;
// Recurse
bool posHint = distanceCheck && (distanceCheck)(current_node, userData_);
if (posHint)
{
if (current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; }
if (current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; }
}
else
{
if (current_node->getNeg()) { _walk(current_node->getNeg(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; }
if (current_node->getPos()) { _walk(current_node->getPos(), max_depth, current_depth, callback, distanceCheck, userData_); current_depth--; }
}
}
};
Local::_walk(mPool, maxDepth, currentDepth, cb, cb2, userData);
return maxDepth;
}
#include "GuBV4_Internal.h"
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
// PT: see http://www.codercorner.com/blog/?p=734
static PxU32 precomputeNodeSorting(const PxBounds3& box0, const PxBounds3& box1)
{
const PxVec3 C0 = box0.getCenter();
const PxVec3 C1 = box1.getCenter();
PxVec3 dirPPP(1.0f, 1.0f, 1.0f); dirPPP.normalize();
PxVec3 dirPPN(1.0f, 1.0f, -1.0f); dirPPN.normalize();
PxVec3 dirPNP(1.0f, -1.0f, 1.0f); dirPNP.normalize();
PxVec3 dirPNN(1.0f, -1.0f, -1.0f); dirPNN.normalize();
PxVec3 dirNPP(-1.0f, 1.0f, 1.0f); dirNPP.normalize();
PxVec3 dirNPN(-1.0f, 1.0f, -1.0f); dirNPN.normalize();
PxVec3 dirNNP(-1.0f, -1.0f, 1.0f); dirNNP.normalize();
PxVec3 dirNNN(-1.0f, -1.0f, -1.0f); dirNNN.normalize();
const PxVec3 deltaC = C0 - C1;
const bool bPPP = deltaC.dot(dirPPP)<0.0f;
const bool bPPN = deltaC.dot(dirPPN)<0.0f;
const bool bPNP = deltaC.dot(dirPNP)<0.0f;
const bool bPNN = deltaC.dot(dirPNN)<0.0f;
const bool bNPP = deltaC.dot(dirNPP)<0.0f;
const bool bNPN = deltaC.dot(dirNPN)<0.0f;
const bool bNNP = deltaC.dot(dirNNP)<0.0f;
const bool bNNN = deltaC.dot(dirNNN)<0.0f;
PxU32 code = 0;
if(!bPPP)
code |= (1<<7); // Bit 0: PPP
if(!bPPN)
code |= (1<<6); // Bit 1: PPN
if(!bPNP)
code |= (1<<5); // Bit 2: PNP
if(!bPNN)
code |= (1<<4); // Bit 3: PNN
if(!bNPP)
code |= (1<<3); // Bit 4: NPP
if(!bNPN)
code |= (1<<2); // Bit 5: NPN
if(!bNNP)
code |= (1<<1); // Bit 6: NNP
if(!bNNN)
code |= (1<<0); // Bit 7: NNN
return code;
}
#endif
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Common.h"
#endif
// PT: warning, not the same as CenterExtents::setEmpty()
static void setEmpty(CenterExtents& box)
{
box.mCenter = PxVec3(0.0f, 0.0f, 0.0f);
box.mExtents = PxVec3(-1.0f, -1.0f, -1.0f);
}
#define PX_INVALID_U64 0xffffffffffffffff
// Data:
// 1 bit for leaf/no leaf
// 2 bits for child-node type
// 8 bits for PNS
// => 32 - 1 - 2 - 8 = 21 bits left for encoding triangle index or node *offset*
// => limited to 2.097.152 triangles
// => and 2Mb-large trees (this one may not work out well in practice)
// ==> lines marked with //* have been changed to address this. Now we don't store offsets in bytes directly
// but in BVData indices. There's more work at runtime calculating addresses, but now the format can support
// 2 million single nodes.
//
// That being said we only need 3*8 = 24 bits in total, so that could be only 6 bits in each BVData.
// For type0: we have 2 nodes, we need 8 bits => 6 bits/node = 12 bits available, ok
// For type1: we have 3 nodes, we need 8*2 = 16 bits => 6 bits/node = 18 bits available, ok
// For type2: we have 4 nodes, we need 8*3 = 24 bits => 6 bits/node = 24 bits available, ok
//#pragma pack(1)
struct BVData : public physx::PxUserAllocated
{
BVData();
CenterExtents mAABB;
size_t mData64;
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
PxU32 mTempPNS;
#endif
};
//#pragma pack()
BVData::BVData() : mData64(PX_INVALID_U64)
{
setEmpty(mAABB);
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
mTempPNS = 0;
#endif
}
struct BV4Node : public physx::PxUserAllocated
{
PX_FORCE_INLINE BV4Node() {}
PX_FORCE_INLINE ~BV4Node() {}
BVData mBVData[4];
PX_FORCE_INLINE size_t isLeaf(PxU32 i) const { return mBVData[i].mData64 & 1; }
PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return PxU32(mBVData[i].mData64 >> 1); }
PX_FORCE_INLINE const BV4Node* getChild(PxU32 i) const { return reinterpret_cast<BV4Node*>(mBVData[i].mData64); }
PxU32 getType() const
{
PxU32 Nb=0;
for(PxU32 i=0;i<4;i++)
{
if(mBVData[i].mData64!=PX_INVALID_U64)
Nb++;
}
return Nb;
}
PxU32 getSize() const
{
const PxU32 type = getType();
return sizeof(BVData)*type;
}
};
#define NB_NODES_PER_SLAB 256
struct BV4BuildParams
{
PX_FORCE_INLINE BV4BuildParams(const BV4_AABBTree& source, const SourceMesh* mesh, float epsilon) : mSource(source), mMesh(mesh), mEpsilon(epsilon)
#ifdef GU_BV4_USE_NODE_POOLS
,mTop(NULL)
#endif
{}
~BV4BuildParams();
const BV4_AABBTree& mSource;
const SourceMesh* mMesh;
// Stats
PxU32 mNbNodes;
PxU32 mStats[4];
//
float mEpsilon;
#ifdef GU_BV4_USE_NODE_POOLS
//
struct Slab : public physx::PxUserAllocated
{
BV4Node mNodes[NB_NODES_PER_SLAB];
PxU32 mNbUsedNodes;
Slab* mNext;
};
Slab* mTop;
BV4Node* allocateNode();
void releaseNodes();
#endif
PX_NOCOPY(BV4BuildParams)
};
BV4BuildParams::~BV4BuildParams()
{
#ifdef GU_BV4_USE_NODE_POOLS
releaseNodes();
#endif
}
#ifdef GU_BV4_USE_NODE_POOLS
BV4Node* BV4BuildParams::allocateNode()
{
if(!mTop || mTop->mNbUsedNodes==NB_NODES_PER_SLAB)
{
Slab* newSlab = PX_NEW(Slab);
newSlab->mNbUsedNodes = 0;
newSlab->mNext = mTop;
mTop = newSlab;
}
return &mTop->mNodes[mTop->mNbUsedNodes++];
}
void BV4BuildParams::releaseNodes()
{
Slab* current = mTop;
while(current)
{
Slab* next = current->mNext;
PX_DELETE(current);
current = next;
}
mTop = NULL;
}
#endif
static PX_FORCE_INLINE void setupBounds(BV4Node* node4, PxU32 i, const AABBTreeNode* node, float epsilon)
{
node4->mBVData[i].mAABB = node->getAABB();
if(epsilon!=0.0f)
node4->mBVData[i].mAABB.mExtents += PxVec3(epsilon);
}
static void setPrimitive(const BV4_AABBTree& source, BV4Node* node4, PxU32 i, const AABBTreeNode* node, float epsilon)
{
const PxU32 nbPrims = node->getNbPrimitives();
PX_ASSERT(nbPrims<16);
const PxU32* indexBase = source.getIndices();
const PxU32* prims = node->getPrimitives();
const PxU64 offset = PxU64(prims - indexBase);
for(PxU32 j=0;j<nbPrims;j++)
{
PX_ASSERT(prims[j] == offset+j);
}
const PxU64 primitiveIndex = (offset<<4)|(nbPrims&15);
setupBounds(node4, i, node, epsilon);
node4->mBVData[i].mData64 = (primitiveIndex<<1)|1;
}
#ifdef GU_BV4_FILL_GAPS
static bool splitPrimitives(const BV4BuildParams& params, BV4Node* node4, PxU32 i, const AABBTreeNode* node)
{
if(!params.mMesh)
return false;
const PxU32 nbPrims = node->getNbPrimitives();
PX_ASSERT(nbPrims<16);
if(nbPrims<2)
return false;
const PxU32* indexBase = params.mSource.getIndices();
const PxU32* prims = node->getPrimitives();
PxU64 offset = PxU64(prims - indexBase);
// In theory we should reshuffle the list but it would mean updating the remap table again.
// A way to avoid that would be to virtually split & sort the triangles directly in the BV2
// source tree, before the initial remap table is created.
//const PxU32 splitPrims = NbPrims/2; // ### actually should be the number in the last split in bv2
const PxU32 splitPrims = node->mNextSplit;
PxU32 j=0;
for(PxU32 ii=0;ii<2;ii++)
{
const PxU32 currentNb = ii==0 ? splitPrims : (nbPrims-splitPrims);
PxBounds3 bounds = PxBounds3::empty();
for(PxU32 k=0;k<currentNb;k++)
{
PX_ASSERT(prims[j] == offset+k);
PxU32 vref0, vref1, vref2;
getVertexReferences(vref0, vref1, vref2, prims[j], params.mMesh->getTris32(), params.mMesh->getTris16());
// PT: TODO: SIMD
const PxVec3* verts = params.mMesh->getVerts();
bounds.include(verts[vref0]);
bounds.include(verts[vref1]);
bounds.include(verts[vref2]);
j++;
}
PX_ASSERT(bounds.isInside(node->mBV));
const PxU64 primitiveIndex = (offset<<4)|(currentNb&15);
// SetupBounds(node4, i, node, context.mEpsilon);
node4->mBVData[i+ii].mAABB = bounds;
if(params.mEpsilon!=0.0f)
node4->mBVData[i+ii].mAABB.mExtents += PxVec3(params.mEpsilon);
node4->mBVData[i+ii].mData64 = (primitiveIndex<<1)|1;
offset += currentNb;
}
return true;
}
#endif
static BV4Node* setNode(const BV4_AABBTree& source, BV4Node* node4, PxU32 i, const AABBTreeNode* node, BV4BuildParams& params)
{
BV4Node* child = NULL;
if(node->isLeaf())
{
setPrimitive(source, node4, i, node, params.mEpsilon);
}
else
{
setupBounds(node4, i, node, params.mEpsilon);
params.mNbNodes++;
#ifdef GU_BV4_USE_NODE_POOLS
child = params.allocateNode();
#else
child = PX_NEW(BV4Node);
#endif
node4->mBVData[i].mData64 = size_t(child);
}
return child;
}
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
static inline PxBounds3 getMinMaxBox(const CenterExtents& box)
{
if(box.mExtents.x>=0.0f && box.mExtents.y>=0.0f && box.mExtents.z>=0.0f)
// if(!box.isEmpty()) // ### asserts!
return PxBounds3::centerExtents(box.mCenter, box.mExtents);
else
return PxBounds3::empty();
}
static void FigureOutPNS(BV4Node* node)
{
// ____A____
// P N
// __|__ __|__
// PP PN NP NN
const CenterExtents& box0 = node->mBVData[0].mAABB;
const CenterExtents& box1 = node->mBVData[1].mAABB;
const CenterExtents& box2 = node->mBVData[2].mAABB;
const CenterExtents& box3 = node->mBVData[3].mAABB;
// PT: TODO: SIMD, optimize
const PxBounds3 boxPP = getMinMaxBox(box0);
const PxBounds3 boxPN = getMinMaxBox(box1);
const PxBounds3 boxNP = getMinMaxBox(box2);
const PxBounds3 boxNN = getMinMaxBox(box3);
PxBounds3 boxP = boxPP; boxP.include(boxPN);
PxBounds3 boxN = boxNP; boxN.include(boxNN);
node->mBVData[0].mTempPNS = precomputeNodeSorting(boxP, boxN);
node->mBVData[1].mTempPNS = precomputeNodeSorting(boxPP, boxPN);
node->mBVData[2].mTempPNS = precomputeNodeSorting(boxNP, boxNN);
}
#endif
/*static bool hasTwoLeafChildren(const AABBTreeNode* current_node)
{
if(current_node->isLeaf())
return false;
const AABBTreeNode* P = current_node->getPos();
const AABBTreeNode* N = current_node->getNeg();
return P->isLeaf() && N->isLeaf();
}*/
static void buildBV4(const BV4_AABBTree& source, BV4Node* tmp, const AABBTreeNode* current_node, BV4BuildParams& params)
{
PX_ASSERT(!current_node->isLeaf());
// In the regular tree we have current node A, and:
// ____A____
// P N
// __|__ __|__
// PP PN NP NN
//
// For PNS we have:
// bit0 to sort P|N
// bit1 to sort PP|PN
// bit2 to sort NP|NN
//
// As much as possible we need to preserve the original order in BV4, if we want to reuse the same PNS bits.
//
// bit0|bit1|bit2 Order 8bits code
// 0 0 0 PP PN NP NN 0 1 2 3
// 0 0 1 PP PN NN NP 0 1 3 2
// 0 1 0 PN PP NP NN 1 0 2 3
// 0 1 1 PN PP NN NP 1 0 3 2
// 1 0 0 NP NN PP PN 2 3 0 1
// 1 0 1 NN NP PP PN 3 2 0 1
// 1 1 0 NP NN PN PP 2 3 1 0
// 1 1 1 NN NP PN PP 3 2 1 0
//
// So we can fetch/compute the sequence from the bits, combine it with limitations from the node type, and process the nodes in order. In theory.
// 8*8bits => the whole thing fits in a single 64bit register, so we could potentially use a "register LUT" here.
const AABBTreeNode* P = current_node->getPos();
const AABBTreeNode* N = current_node->getNeg();
const bool PLeaf = P->isLeaf();
const bool NLeaf = N->isLeaf();
if(PLeaf)
{
if(NLeaf)
{
// Case 1: P and N are both leaves:
// ____A____
// P N
// => store as (P,N) and keep bit0
#ifndef GU_BV4_FILL_GAPS
params.mStats[0]++;
// PN leaves => store 2 triangle pointers, lose 50% of node space
setPrimitive(source, tmp, 0, P, params.mEpsilon);
setPrimitive(source, tmp, 1, N, params.mEpsilon);
#else
{
PxU32 nextIndex = 2;
if(!splitPrimitives(params, tmp, 0, P))
{
setPrimitive(source, tmp, 0, P, params.mEpsilon);
nextIndex = 1;
}
if(!splitPrimitives(params, tmp, nextIndex, N))
setPrimitive(source, tmp, nextIndex, N, params.mEpsilon);
const PxU32 statIndex = tmp->getType();
if(statIndex==4)
params.mStats[3]++;
else if(statIndex==3)
params.mStats[1]++;
else if(statIndex==2)
params.mStats[0]++;
else
PX_ASSERT(0);
}
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT0
tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV);
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
FigureOutPNS(tmp);
#endif
}
else
{
// Case 2: P leaf, N no leaf
// ____A____
// P N
// __|__
// NP NN
// => store as (P,NP,NN), keep bit0 and bit2
//#define NODE_FUSION
#ifdef NODE_FUSION
// P leaf => store 1 triangle pointers and 2 node pointers
// => 3 slots used, 25% wasted
const AABBTreeNode* NP = N->getPos();
const AABBTreeNode* NN = N->getNeg();
BV4Node* ChildNP;
BV4Node* ChildNN;
#ifdef GU_BV4_FILL_GAPS
if(splitPrimitives(params, tmp, 0, P))
{
// We used up the empty slot, continue as usual in slot 2
ChildNP = setNode(source, tmp, 2, NP, params);
ChildNN = setNode(source, tmp, 3, NN, params);
}
else
#endif
{
// We oouldn't split the prims, continue searching for a way to use the empty slot
setPrimitive(source, tmp, 0, P, params.mEpsilon);
PxU32 c=0;
if(hasTwoLeafChildren(NP))
{
// Drag the terminal leaves directly into this BV4 node, drop internal node NP
setPrimitive(source, tmp, 1, NP->getPos(), params.mEpsilon);
setPrimitive(source, tmp, 2, NP->getNeg(), params.mEpsilon);
ChildNP = NULL;
c=1;
}
else
{
ChildNP = setNode(source, tmp, 1, NP, params);
}
if(c==0 && hasTwoLeafChildren(NN))
{
// Drag the terminal leaves directly into this BV4 node, drop internal node NN
setPrimitive(source, tmp, 2, NN->getPos(), params.mEpsilon);
setPrimitive(source, tmp, 3, NN->getNeg(), params.mEpsilon);
ChildNN = NULL;
}
else
{
#ifdef GU_BV4_FILL_GAPS
if(c==0 && NN->isLeaf())
{
ChildNN = NULL;
if(!splitPrimitives(params, tmp, 2, NN))
setPrimitive(source, tmp, 2, NN, params.mEpsilon);
}
else
#endif
{
ChildNN = setNode(source, tmp, 2+c, NN, params);
}
}
}
const PxU32 statIndex = tmp->getType();
if(statIndex==4)
params.mStats[3]++;
else if(statIndex==3)
params.mStats[1]++;
else if(statIndex==2)
params.mStats[0]++;
else
PX_ASSERT(0);
#else
params.mStats[1]++;
// P leaf => store 1 triangle pointers and 2 node pointers
// => 3 slots used, 25% wasted
setPrimitive(source, tmp, 0, P, params.mEpsilon);
const AABBTreeNode* NP = N->getPos();
const AABBTreeNode* NN = N->getNeg();
BV4Node* ChildNP = setNode(source, tmp, 1, NP, params);
BV4Node* ChildNN = setNode(source, tmp, 2, NN, params);
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT0
tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV);
tmp->mBVData[2].mTempPNS = precomputeNodeSorting(NP->mBV, NN->mBV);
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
FigureOutPNS(tmp);
#endif
if(ChildNP)
buildBV4(source, ChildNP, NP, params);
if(ChildNN)
buildBV4(source, ChildNN, NN, params);
}
}
else
{
if(NLeaf)
{
// Note: this case doesn't exist anymore because of the node reorganizing for shadow rays
// Case 3: P no leaf, N leaf
// ____A____
// P N
// __|__
// PP PN
// => store as (PP,PN,N), keep bit0 and bit1
params.mStats[2]++;
// N leaf => store 1 triangle pointers and 2 node pointers
// => 3 slots used, 25% wasted
setPrimitive(source, tmp, 2, N, params.mEpsilon);
//
const AABBTreeNode* PP = P->getPos();
const AABBTreeNode* PN = P->getNeg();
BV4Node* ChildPP = setNode(source, tmp, 0, PP, params);
BV4Node* ChildPN = setNode(source, tmp, 1, PN, params);
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT0
tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV);
tmp->mBVData[1].mTempPNS = precomputeNodeSorting(PP->mBV, PN->mBV);
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
FigureOutPNS(tmp);
#endif
if(ChildPP)
buildBV4(source, ChildPP, PP, params);
if(ChildPN)
buildBV4(source, ChildPN, PN, params);
}
else
{
// Case 4: P and N are no leaves:
// => store as (PP,PN,NP,NN), keep bit0/bit1/bit2
params.mStats[3]++;
// No leaves => store 4 node pointers
const AABBTreeNode* PP = P->getPos();
const AABBTreeNode* PN = P->getNeg();
const AABBTreeNode* NP = N->getPos();
const AABBTreeNode* NN = N->getNeg();
BV4Node* ChildPP = setNode(source, tmp, 0, PP, params);
BV4Node* ChildPN = setNode(source, tmp, 1, PN, params);
BV4Node* ChildNP = setNode(source, tmp, 2, NP, params);
BV4Node* ChildNN = setNode(source, tmp, 3, NN, params);
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT0
tmp->mBVData[0].mTempPNS = precomputeNodeSorting(P->mBV, N->mBV);
tmp->mBVData[1].mTempPNS = precomputeNodeSorting(PP->mBV, PN->mBV);
tmp->mBVData[2].mTempPNS = precomputeNodeSorting(NP->mBV, NN->mBV);
#endif
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
FigureOutPNS(tmp);
#endif
if(ChildPP)
buildBV4(source, ChildPP, PP, params);
if(ChildPN)
buildBV4(source, ChildPN, PN, params);
if(ChildNP)
buildBV4(source, ChildNP, NP, params);
if(ChildNN)
buildBV4(source, ChildNN, NN, params);
}
}
}
#ifdef GU_BV4_USE_SLABS
static void computeMaxValues(const BV4Node* current, PxVec3& MinMax, PxVec3& MaxMax)
#else
static void computeMaxValues(const BV4Node* current, PxVec3& CMax, PxVec3& EMax)
#endif
{
for(PxU32 i=0; i<4; i++)
{
if(current->mBVData[i].mData64 != PX_INVALID_U64)
{
const CenterExtents& Box = current->mBVData[i].mAABB;
#ifdef GU_BV4_USE_SLABS
const PxVec3 Min = Box.mCenter - Box.mExtents;
const PxVec3 Max = Box.mCenter + Box.mExtents;
if(fabsf(Min.x)>MinMax.x) MinMax.x = fabsf(Min.x);
if(fabsf(Min.y)>MinMax.y) MinMax.y = fabsf(Min.y);
if(fabsf(Min.z)>MinMax.z) MinMax.z = fabsf(Min.z);
if(fabsf(Max.x)>MaxMax.x) MaxMax.x = fabsf(Max.x);
if(fabsf(Max.y)>MaxMax.y) MaxMax.y = fabsf(Max.y);
if(fabsf(Max.z)>MaxMax.z) MaxMax.z = fabsf(Max.z);
#else
if(fabsf(Box.mCenter.x)>CMax.x) CMax.x = fabsf(Box.mCenter.x);
if(fabsf(Box.mCenter.y)>CMax.y) CMax.y = fabsf(Box.mCenter.y);
if(fabsf(Box.mCenter.z)>CMax.z) CMax.z = fabsf(Box.mCenter.z);
if(fabsf(Box.mExtents.x)>EMax.x) EMax.x = fabsf(Box.mExtents.x);
if(fabsf(Box.mExtents.y)>EMax.y) EMax.y = fabsf(Box.mExtents.y);
if(fabsf(Box.mExtents.z)>EMax.z) EMax.z = fabsf(Box.mExtents.z);
#endif
if(!current->isLeaf(i))
{
const BV4Node* ChildNode = current->getChild(i);
#ifdef GU_BV4_USE_SLABS
computeMaxValues(ChildNode, MinMax, MaxMax);
#else
computeMaxValues(ChildNode, CMax, EMax);
#endif
}
}
}
}
template<class T>
static PX_FORCE_INLINE bool copyData(T* PX_RESTRICT dst, const BV4Node* PX_RESTRICT src, PxU32 i)
{
if(src->isLeaf(i))
{
if(src->mBVData[i].mData64 > 0xffffffff)
return false;
}
dst->mData = PxU32(src->mBVData[i].mData64);
//dst->mData = PxTo32(src->mBVData[i].mData);
// dst->mData = PxU32(src->mBVData[i].mData);
// dst->encodePNS(src->mBVData[i].mTempPNS);
return true;
}
namespace
{
struct flattenQParams
{
PxVec3 mCQuantCoeff;
PxVec3 mEQuantCoeff;
PxVec3 mCenterCoeff;
PxVec3 mExtentsCoeff;
};
}
template<class T>
static PX_FORCE_INLINE bool processNode(T* PX_RESTRICT data, const BV4Node* PX_RESTRICT current, PxU64* PX_RESTRICT nextIDs, const BV4Node** PX_RESTRICT childNodes, PxU32 i, PxU64& current_id, PxU32& nbToGo)
{
const BV4Node* childNode = current->getChild(i);
const PxU64 nextID = current_id;
#ifdef GU_BV4_USE_SLABS
current_id += 4;
#else
const PxU32 childSize = childNode->getType();
current_id += childSize;
#endif
const PxU32 childType = (childNode->getType() - 2) << 1;
const PxU64 data64 = size_t(childType + (nextID << GU_BV4_CHILD_OFFSET_SHIFT_COUNT));
if(data64 <= 0xffffffff)
data[i].mData = PxU32(data64);
else
return false;
//PX_ASSERT(data[i].mData == size_t(childType+(nextID<<3)));
nextIDs[nbToGo] = nextID;
childNodes[nbToGo] = childNode;
nbToGo++;
#ifdef GU_BV4_PRECOMPUTED_NODE_SORT
data[i].encodePNS(current->mBVData[i].mTempPNS);
#endif
return true;
}
static bool flattenQ(const flattenQParams& params, BVDataPackedQ* const dest, const PxU64 box_id, PxU64& current_id, const BV4Node* current, PxU32& max_depth, PxU32& current_depth)
{
// Entering a new node => increase depth
current_depth++;
// Keep track of max depth
if(current_depth>max_depth)
max_depth = current_depth;
// dest[box_id] = *current;
const PxU32 CurrentType = current->getType();
for(PxU32 i=0; i<CurrentType; i++)
{
const CenterExtents& Box = current->mBVData[i].mAABB;
#ifdef GU_BV4_USE_SLABS
const PxVec3 m = Box.mCenter - Box.mExtents;
const PxVec3 M = Box.mCenter + Box.mExtents;
dest[box_id + i].mAABB.mData[0].mCenter = PxI16(m.x * params.mCQuantCoeff.x);
dest[box_id + i].mAABB.mData[1].mCenter = PxI16(m.y * params.mCQuantCoeff.y);
dest[box_id + i].mAABB.mData[2].mCenter = PxI16(m.z * params.mCQuantCoeff.z);
dest[box_id + i].mAABB.mData[0].mExtents = PxU16(PxI16(M.x * params.mEQuantCoeff.x));
dest[box_id + i].mAABB.mData[1].mExtents = PxU16(PxI16(M.y * params.mEQuantCoeff.y));
dest[box_id + i].mAABB.mData[2].mExtents = PxU16(PxI16(M.z * params.mEQuantCoeff.z));
if (1)
{
for (PxU32 j = 0; j<3; j++)
{
// Dequantize the min/max
// const float qmin = float(dest[box_id+i].mAABB.mData[j].mCenter) * mCenterCoeff[j];
// const float qmax = float(PxI16(dest[box_id+i].mAABB.mData[j].mExtents)) * mExtentsCoeff[j];
// Compare real & dequantized values
/* if(qmax<M[j] || qmin>m[j])
{
int stop=1;
}*/
bool CanLeave;
do
{
CanLeave = true;
const float qmin = float(dest[box_id + i].mAABB.mData[j].mCenter) * params.mCenterCoeff[j];
const float qmax = float(PxI16(dest[box_id + i].mAABB.mData[j].mExtents)) * params.mExtentsCoeff[j];
if (qmax<M[j])
{
// if(dest[box_id+i].mAABB.mData[j].mExtents!=0xffff)
if (dest[box_id + i].mAABB.mData[j].mExtents != 0x7fff)
{
dest[box_id + i].mAABB.mData[j].mExtents++;
CanLeave = false;
}
}
if (qmin>m[j])
{
if (dest[box_id + i].mAABB.mData[j].mCenter)
{
dest[box_id + i].mAABB.mData[j].mCenter--;
CanLeave = false;
}
}
} while (!CanLeave);
}
}
#else // GU_BV4_USE_SLABS
dest[box_id + i].mAABB.mData[0].mCenter = PxI16(Box.mCenter.x * CQuantCoeff.x);
dest[box_id + i].mAABB.mData[1].mCenter = PxI16(Box.mCenter.y * CQuantCoeff.y);
dest[box_id + i].mAABB.mData[2].mCenter = PxI16(Box.mCenter.z * CQuantCoeff.z);
dest[box_id + i].mAABB.mData[0].mExtents = PxU16(Box.mExtents.x * EQuantCoeff.x);
dest[box_id + i].mAABB.mData[1].mExtents = PxU16(Box.mExtents.y * EQuantCoeff.y);
dest[box_id + i].mAABB.mData[2].mExtents = PxU16(Box.mExtents.z * EQuantCoeff.z);
// Fix quantized boxes
if (1)
{
// Make sure the quantized box is still valid
const PxVec3 Max = Box.mCenter + Box.mExtents;
const PxVec3 Min = Box.mCenter - Box.mExtents;
// For each axis
for (PxU32 j = 0; j<3; j++)
{ // Dequantize the box center
const float qc = float(dest[box_id + i].mAABB.mData[j].mCenter) * mCenterCoeff[j];
bool FixMe = true;
do
{ // Dequantize the box extent
const float qe = float(dest[box_id + i].mAABB.mData[j].mExtents) * mExtentsCoeff[j];
// Compare real & dequantized values
if (qc + qe<Max[j] || qc - qe>Min[j]) dest[box_id + i].mAABB.mData[j].mExtents++;
else FixMe = false;
// Prevent wrapping
if (!dest[box_id + i].mAABB.mData[j].mExtents)
{
dest[box_id + i].mAABB.mData[j].mExtents = 0xffff;
FixMe = false;
}
} while (FixMe);
}
}
#endif // GU_BV4_USE_SLABS
if(!copyData(&dest[box_id + i], current, i))
return false;
}
PxU32 NbToGo = 0;
PxU64 NextIDs[4] = { PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64 };
const BV4Node* ChildNodes[4] = { NULL, NULL, NULL, NULL };
BVDataPackedQ* data = dest + box_id;
for(PxU32 i=0; i<4; i++)
{
if(current->mBVData[i].mData64 != PX_INVALID_U64 && !current->isLeaf(i))
{
if(!processNode(data, current, NextIDs, ChildNodes, i, current_id, NbToGo))
return false;
//#define DEPTH_FIRST
#ifdef DEPTH_FIRST
if(!flattenQ(params, dest, NextID, current_id, ChildNode, max_depth, current_depth, CQuantCoeff, EQuantCoeff, mCenterCoeff, mExtentsCoeff))
return false;
current_depth--;
#endif
}
#ifdef GU_BV4_USE_SLABS
if (current->mBVData[i].mData64 == PX_INVALID_U64)
{
data[i].mAABB.mData[0].mExtents = 0;
data[i].mAABB.mData[1].mExtents = 0;
data[i].mAABB.mData[2].mExtents = 0;
data[i].mAABB.mData[0].mCenter = 0;
data[i].mAABB.mData[1].mCenter = 0;
data[i].mAABB.mData[2].mCenter = 0;
data[i].mData = PX_INVALID_U32;
}
#endif
}
#ifndef DEPTH_FIRST
for(PxU32 i=0; i<NbToGo; i++)
{
if(!flattenQ(params, dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth))
return false;
current_depth--;
}
#endif
#ifndef GU_BV4_USE_NODE_POOLS
PX_DELETE(current);
#endif
return true;
}
static bool flattenNQ(BVDataPackedNQ* const dest, const PxU64 box_id, PxU64& current_id, const BV4Node* current, PxU32& max_depth, PxU32& current_depth)
{
// Entering a new node => increase depth
current_depth++;
// Keep track of max depth
if(current_depth>max_depth)
max_depth = current_depth;
// dest[box_id] = *current;
const PxU32 CurrentType = current->getType();
for(PxU32 i=0; i<CurrentType; i++)
{
#ifdef GU_BV4_USE_SLABS
// Compute min & max right here. Store temp as Center/Extents = Min/Max
const CenterExtents& Box = current->mBVData[i].mAABB;
dest[box_id + i].mAABB.mCenter = Box.mCenter - Box.mExtents;
dest[box_id + i].mAABB.mExtents = Box.mCenter + Box.mExtents;
#else // GU_BV4_USE_SLABS
dest[box_id + i].mAABB = current->mBVData[i].mAABB;
#endif // GU_BV4_USE_SLABS
if(!copyData(&dest[box_id + i], current, i))
return false;
}
PxU32 NbToGo = 0;
PxU64 NextIDs[4] = { PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64, PX_INVALID_U64 };
const BV4Node* ChildNodes[4] = { NULL, NULL, NULL, NULL };
BVDataPackedNQ* data = dest + box_id;
for(PxU32 i=0; i<4; i++)
{
if(current->mBVData[i].mData64 != PX_INVALID_U64 && !current->isLeaf(i))
{
if(!processNode(data, current, NextIDs, ChildNodes, i, current_id, NbToGo))
return false;
//#define DEPTH_FIRST
#ifdef DEPTH_FIRST
if(!flattenNQ(dest, NextID, current_id, ChildNode, max_depth, current_depth))
return false;
current_depth--;
#endif
}
#ifdef GU_BV4_USE_SLABS
if (current->mBVData[i].mData64 == PX_INVALID_U64)
{
data[i].mAABB.mCenter = PxVec3(0.0f);
data[i].mAABB.mExtents = PxVec3(0.0f);
data[i].mData = PX_INVALID_U32;
}
#endif
}
#ifndef DEPTH_FIRST
for(PxU32 i=0; i<NbToGo; i++)
{
if(!flattenNQ(dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth))
return false;
current_depth--;
}
#endif
#ifndef GU_BV4_USE_NODE_POOLS
PX_DELETE(current);
#endif
return true;
}
static bool BuildBV4FromRoot(BV4Tree& tree, BV4Node* Root, BV4BuildParams& Params, bool quantized, float epsilon)
{
GU_PROFILE_ZONE("....BuildBV4FromRoot")
BV4Tree* T = &tree;
T->mQuantized = quantized;
// Version with variable-sized nodes in single stream
{
const PxU32 NbSingleNodes = Params.mStats[0] * 2 + (Params.mStats[1] + Params.mStats[2]) * 3 + Params.mStats[3] * 4;
PxU64 CurID = Root->getType();
PxU32 InitData = PX_INVALID_U32;
#ifdef GU_BV4_USE_SLABS
PX_UNUSED(NbSingleNodes);
const PxU32 NbNeeded = (Params.mStats[0] + Params.mStats[1] + Params.mStats[2] + Params.mStats[3]) * 4;
// PT: TODO: refactor with code in BV4Tree::load
// BVDataPacked* Nodes = reinterpret_cast<BVDataPacked*>(PX_ALLOC(sizeof(BVDataPacked)*NbNeeded, "BV4 nodes")); // PT: PX_NEW breaks alignment here
// BVDataPacked* Nodes = PX_NEW(BVDataPacked)[NbNeeded];
void* nodes;
{
const PxU32 nodeSize = T->mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
const PxU32 dataSize = nodeSize*NbNeeded;
nodes = PX_ALLOC(dataSize, "BV4 nodes"); // PT: PX_NEW breaks alignment here
}
if (CurID == 2)
{
InitData = 0;
}
else if (CurID == 3)
{
InitData = 2;
}
else if (CurID == 4)
{
InitData = 4;
}
CurID = 4;
// PxU32 CurID = 4;
// PxU32 InitData = 4;
#else
BVDataPacked* Nodes = PX_NEW(BVDataPacked)[NbSingleNodes];
if (CurID == 2)
{
InitData = 0;
}
else if (CurID == 3)
{
InitData = 2;
}
else if (CurID == 4)
{
InitData = 4;
}
#endif
T->mInitData = InitData;
PxU32 MaxDepth = 0;
PxU32 CurrentDepth = 0;
bool buildStatus;
if(T->mQuantized)
{
flattenQParams params;
#ifdef GU_BV4_USE_SLABS
PxVec3 MinQuantCoeff, MaxQuantCoeff;
// Get max values
PxVec3 MinMax(-FLT_MAX);
PxVec3 MaxMax(-FLT_MAX);
computeMaxValues(Root, MinMax, MaxMax);
const PxU32 nbm = 15;
// Compute quantization coeffs
const float MinCoeff = float((1 << nbm) - 1);
const float MaxCoeff = float((1 << nbm) - 1);
MinQuantCoeff.x = MinMax.x != 0.0f ? MinCoeff / MinMax.x : 0.0f;
MinQuantCoeff.y = MinMax.y != 0.0f ? MinCoeff / MinMax.y : 0.0f;
MinQuantCoeff.z = MinMax.z != 0.0f ? MinCoeff / MinMax.z : 0.0f;
MaxQuantCoeff.x = MaxMax.x != 0.0f ? MaxCoeff / MaxMax.x : 0.0f;
MaxQuantCoeff.y = MaxMax.y != 0.0f ? MaxCoeff / MaxMax.y : 0.0f;
MaxQuantCoeff.z = MaxMax.z != 0.0f ? MaxCoeff / MaxMax.z : 0.0f;
// Compute and save dequantization coeffs
T->mCenterOrMinCoeff.x = MinMax.x / MinCoeff;
T->mCenterOrMinCoeff.y = MinMax.y / MinCoeff;
T->mCenterOrMinCoeff.z = MinMax.z / MinCoeff;
T->mExtentsOrMaxCoeff.x = MaxMax.x / MaxCoeff;
T->mExtentsOrMaxCoeff.y = MaxMax.y / MaxCoeff;
T->mExtentsOrMaxCoeff.z = MaxMax.z / MaxCoeff;
params.mCQuantCoeff = MinQuantCoeff;
params.mEQuantCoeff = MaxQuantCoeff;
#else
// Get max values
PxVec3 CMax(-FLT_MAX);
PxVec3 EMax(-FLT_MAX);
computeMaxValues(Root, CMax, EMax);
const PxU32 nbc = 15;
const PxU32 nbe = 16;
// const PxU32 nbc=7;
// const PxU32 nbe=8;
const float UnitQuantError = 2.0f / 65535.0f;
EMax.x += CMax.x*UnitQuantError;
EMax.y += CMax.y*UnitQuantError;
EMax.z += CMax.z*UnitQuantError;
// Compute quantization coeffs
const float CCoeff = float((1 << nbc) - 1);
CQuantCoeff.x = CMax.x != 0.0f ? CCoeff / CMax.x : 0.0f;
CQuantCoeff.y = CMax.y != 0.0f ? CCoeff / CMax.y : 0.0f;
CQuantCoeff.z = CMax.z != 0.0f ? CCoeff / CMax.z : 0.0f;
const float ECoeff = float((1 << nbe) - 32);
EQuantCoeff.x = EMax.x != 0.0f ? ECoeff / EMax.x : 0.0f;
EQuantCoeff.y = EMax.y != 0.0f ? ECoeff / EMax.y : 0.0f;
EQuantCoeff.z = EMax.z != 0.0f ? ECoeff / EMax.z : 0.0f;
// Compute and save dequantization coeffs
T->mCenterOrMinCoeff.x = CMax.x / CCoeff;
T->mCenterOrMinCoeff.y = CMax.y / CCoeff;
T->mCenterOrMinCoeff.z = CMax.z / CCoeff;
T->mExtentsOrMaxCoeff.x = EMax.x / ECoeff;
T->mExtentsOrMaxCoeff.y = EMax.y / ECoeff;
T->mExtentsOrMaxCoeff.z = EMax.z / ECoeff;
params.mCQuantCoeff = CQuantCoeff;
params.mEQuantCoeff = EQuantCoeff;
#endif
params.mCenterCoeff = T->mCenterOrMinCoeff;
params.mExtentsCoeff = T->mExtentsOrMaxCoeff;
buildStatus = flattenQ(params, reinterpret_cast<BVDataPackedQ*>(nodes), 0, CurID, Root, MaxDepth, CurrentDepth);
}
else
{
buildStatus = flattenNQ(reinterpret_cast<BVDataPackedNQ*>(nodes), 0, CurID, Root, MaxDepth, CurrentDepth);
}
#ifdef GU_BV4_USE_NODE_POOLS
Params.releaseNodes();
#endif
if(!buildStatus)
{
T->mNodes = nodes;
return false;
}
#ifdef GU_BV4_USE_SLABS
// PT: TODO: revisit this, don't duplicate everything
if(T->mQuantized)
{
BVDataPackedQ* _nodes = reinterpret_cast<BVDataPackedQ*>(nodes);
PX_COMPILE_TIME_ASSERT(sizeof(BVDataSwizzledQ) == sizeof(BVDataPackedQ) * 4);
BVDataPackedQ* Copy = PX_ALLOCATE(BVDataPackedQ, NbNeeded, "BVDataPackedQ");
PxMemCopy(Copy, nodes, sizeof(BVDataPackedQ)*NbNeeded);
for (PxU32 i = 0; i<NbNeeded / 4; i++)
{
const BVDataPackedQ* Src = Copy + i * 4;
BVDataSwizzledQ* Dst = reinterpret_cast<BVDataSwizzledQ*>(_nodes + i * 4);
for (PxU32 j = 0; j<4; j++)
{
// We previously stored m/M within c/e so we just need to swizzle now
const QuantizedAABB& Box = Src[j].mAABB;
Dst->mX[j].mMin = Box.mData[0].mCenter;
Dst->mY[j].mMin = Box.mData[1].mCenter;
Dst->mZ[j].mMin = Box.mData[2].mCenter;
Dst->mX[j].mMax = PxI16(Box.mData[0].mExtents);
Dst->mY[j].mMax = PxI16(Box.mData[1].mExtents);
Dst->mZ[j].mMax = PxI16(Box.mData[2].mExtents);
Dst->mData[j] = Src[j].mData;
}
}
PX_FREE(Copy);
}
else
{
BVDataPackedNQ* _nodes = reinterpret_cast<BVDataPackedNQ*>(nodes);
PX_COMPILE_TIME_ASSERT(sizeof(BVDataSwizzledNQ) == sizeof(BVDataPackedNQ) * 4);
BVDataPackedNQ* Copy = PX_ALLOCATE(BVDataPackedNQ, NbNeeded, "BVDataPackedNQ");
PxMemCopy(Copy, nodes, sizeof(BVDataPackedNQ)*NbNeeded);
for (PxU32 i = 0; i<NbNeeded / 4; i++)
{
const BVDataPackedNQ* Src = Copy + i * 4;
BVDataSwizzledNQ* Dst = reinterpret_cast<BVDataSwizzledNQ*>(_nodes + i * 4);
for (PxU32 j = 0; j<4; j++)
{
// We previously stored m/M within c/e so we just need to swizzle now
const CenterExtents& Box = Src[j].mAABB;
Dst->mMinX[j] = Box.mCenter.x;
Dst->mMinY[j] = Box.mCenter.y;
Dst->mMinZ[j] = Box.mCenter.z;
Dst->mMaxX[j] = Box.mExtents.x;
Dst->mMaxY[j] = Box.mExtents.y;
Dst->mMaxZ[j] = Box.mExtents.z;
Dst->mData[j] = Src[j].mData;
}
}
PX_FREE(Copy);
if(0)
{
const PxVec3 eps(epsilon);
float maxError = 0.0f;
PxU32 nb = NbNeeded/4;
BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(nodes);
while(nb--)
{
BVDataSwizzledNQ* current = data + nb;
for(PxU32 j=0;j<4;j++)
{
if(current->getChildData(j)==PX_INVALID_U32)
continue;
const PxBounds3 localBox( PxVec3(current->mMinX[j], current->mMinY[j], current->mMinZ[j]),
PxVec3(current->mMaxX[j], current->mMaxY[j], current->mMaxZ[j]));
PxBounds3 refitBox;
refitBox.setEmpty();
if(current->isLeaf(j))
{
PxU32 primIndex = current->getPrimitive(j);
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PX_ASSERT(primIndex<T->mMeshInterface->getNbPrimitives());
T->mMeshInterface->refit(primIndex, refitBox);
primIndex++;
}while(nbToGo--);
}
else
{
PxU32 childOffset = current->getChildOffset(j);
PX_ASSERT(!(childOffset&3));
childOffset>>=2;
PX_ASSERT(childOffset>nb);
const PxU32 childType = current->getChildType(j);
const BVDataSwizzledNQ* next = data + childOffset;
{
if(childType>1)
{
const PxBounds3 childBox( PxVec3(next->mMinX[3], next->mMinY[3], next->mMinZ[3]),
PxVec3(next->mMaxX[3], next->mMaxY[3], next->mMaxZ[3]));
refitBox.include(childBox);
}
if(childType>0)
{
const PxBounds3 childBox( PxVec3(next->mMinX[2], next->mMinY[2], next->mMinZ[2]),
PxVec3(next->mMaxX[2], next->mMaxY[2], next->mMaxZ[2]));
refitBox.include(childBox);
}
{
const PxBounds3 childBox( PxVec3(next->mMinX[1], next->mMinY[1], next->mMinZ[1]),
PxVec3(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1]));
refitBox.include(childBox);
}
{
const PxBounds3 childBox( PxVec3(next->mMinX[0], next->mMinY[0], next->mMinZ[0]),
PxVec3(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0]));
refitBox.include(childBox);
}
}
}
refitBox.minimum -= eps;
refitBox.maximum += eps;
{
float error = (refitBox.minimum - localBox.minimum).magnitude();
if(error>maxError)
maxError = error;
}
{
float error = (refitBox.maximum - localBox.maximum).magnitude();
if(error>maxError)
maxError = error;
}
}
}
printf("maxError: %f\n", double(maxError));
}
}
PX_ASSERT(CurID == NbNeeded);
T->mNbNodes = NbNeeded;
#else
PX_ASSERT(CurID == NbSingleNodes);
T->mNbNodes = NbSingleNodes;
#endif
T->mNodes = nodes;
}
return true;
}
static bool BuildBV4Internal(BV4Tree& tree, const BV4_AABBTree& source, SourceMeshBase* mesh, float epsilon, bool quantized)
{
GU_PROFILE_ZONE("..BuildBV4Internal")
if(mesh->getNbPrimitives()<=4)
return tree.init(mesh, source.getBV());
{
GU_PROFILE_ZONE("....CheckMD")
struct Local
{
static void _checkMD(const AABBTreeNode* current_node, PxU32& md, PxU32& cd)
{
cd++;
md = PxMax(md, cd);
if(current_node->getPos()) { _checkMD(current_node->getPos(), md, cd); cd--; }
if(current_node->getNeg()) { _checkMD(current_node->getNeg(), md, cd); cd--; }
}
static void _check(AABBTreeNode* current_node)
{
if(current_node->isLeaf())
return;
AABBTreeNode* P = const_cast<AABBTreeNode*>(current_node->getPos());
AABBTreeNode* N = const_cast<AABBTreeNode*>(current_node->getNeg());
{
PxU32 MDP = 0; PxU32 CDP = 0; _checkMD(P, MDP, CDP);
PxU32 MDN = 0; PxU32 CDN = 0; _checkMD(N, MDN, CDN);
if(MDP>MDN)
// if(MDP<MDN)
{
PxSwap(*P, *N);
PxSwap(P, N);
}
}
_check(P);
_check(N);
}
};
Local::_check(const_cast<AABBTreeNode*>(source.getNodes()));
}
// PT: not sure what the equivalent would be for tet-meshes here
SourceMesh* triMesh = NULL;
if(mesh->getMeshType()==SourceMeshBase::TRI_MESH)
triMesh = static_cast<SourceMesh*>(mesh);
BV4BuildParams Params(source, triMesh, epsilon);
Params.mNbNodes=1; // Root node
Params.mStats[0]=0;
Params.mStats[1]=0;
Params.mStats[2]=0;
Params.mStats[3]=0;
#ifdef GU_BV4_USE_NODE_POOLS
BV4Node* Root = Params.allocateNode();
#else
BV4Node* Root = PX_NEW(BV4Node);
#endif
{
GU_PROFILE_ZONE("....buildBV4")
buildBV4(source, Root, source.getNodes(), Params);
}
if(!tree.init(mesh, source.getBV()))
return false;
return BuildBV4FromRoot(tree, Root, Params, quantized, epsilon);
}
/////
#define REORDER_STATS_SIZE 16
struct ReorderData
{
public:
PxU32* mOrder;
PxU32 mNbPrimsPerLeaf;
PxU32 mIndex;
PxU32 mNbPrims;
PxU32 mStats[REORDER_STATS_SIZE];
const SourceMeshBase* mMesh;
};
static bool gReorderCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData)
{
ReorderData* Data = reinterpret_cast<ReorderData*>(userData);
if(current->isLeaf())
{
const PxU32 n = current->getNbPrimitives();
PX_ASSERT(n<=Data->mNbPrimsPerLeaf);
Data->mStats[n]++;
PxU32* Prims = const_cast<PxU32*>(current->getPrimitives());
for(PxU32 i=0;i<n;i++)
{
PX_ASSERT(Prims[i]<Data->mNbPrims);
Data->mOrder[Data->mIndex] = Prims[i];
PX_ASSERT(Data->mIndex<Data->mNbPrims);
Prims[i] = Data->mIndex;
Data->mIndex++;
}
}
return true;
}
bool physx::Gu::BuildBV4Ex(BV4Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivePerLeaf, bool quantized, BV4_BuildStrategy strategy)
{
//either number of triangle or number of tetrahedron
const PxU32 nbPrimitives = mesh.getNbPrimitives();
BV4_AABBTree Source;
{
GU_PROFILE_ZONE("..BuildBV4Ex_buildFromMesh")
if(!Source.buildFromMesh(mesh, nbPrimitivePerLeaf, strategy))
return false;
}
{
GU_PROFILE_ZONE("..BuildBV4Ex_remap")
PxU32* orderArray = PX_ALLOCATE(PxU32, nbPrimitives, "BV4");
ReorderData RD;
RD.mMesh = &mesh;
RD.mOrder = orderArray;
RD.mNbPrimsPerLeaf = nbPrimitivePerLeaf;
RD.mIndex = 0;
RD.mNbPrims = nbPrimitives;
for(PxU32 i=0;i<REORDER_STATS_SIZE;i++)
RD.mStats[i] = 0;
Source.walk(gReorderCallback, &RD);
PX_ASSERT(RD.mIndex== nbPrimitives);
mesh.remapTopology(orderArray);
PX_FREE(orderArray);
// for(PxU32 i=0;i<16;i++)
// printf("%d: %d\n", i, RD.mStats[i]);
}
if(mesh.getNbPrimitives() <= nbPrimitivePerLeaf)
return tree.init(&mesh, Source.getBV());
return BuildBV4Internal(tree, Source, &mesh, epsilon, quantized);
}
| 54,942 | C++ | 28.539247 | 207 | 0.662753 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "GuBV4.h"
#include "GuBV4_Common.h"
#include "CmSerialize.h"
#include "foundation/PxVecMath.h"
#include "common/PxSerialFramework.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
using namespace physx::aos;
SourceMeshBase::SourceMeshBase(MeshType meshType) : mNbVerts(0), mVerts(NULL), mType(meshType), mRemap(NULL)
{
}
SourceMeshBase::~SourceMeshBase()
{
PX_FREE(mRemap);
}
///////////////////////////////////////////////////////////////////////////////
TetrahedronSourceMesh::TetrahedronSourceMesh() : SourceMeshBase(MeshType::TET_MESH)
{
reset();
}
TetrahedronSourceMesh::~TetrahedronSourceMesh()
{
}
void TetrahedronSourceMesh::reset()
{
mNbVerts = 0;
mVerts = NULL;
mNbTetrahedrons = 0;
mTetrahedrons32 = NULL;
mTetrahedrons16 = NULL;
mRemap = NULL;
}
void TetrahedronSourceMesh::operator=(TetrahedronSourceMesh& v)
{
mNbVerts = v.mNbVerts;
mVerts = v.mVerts;
mNbTetrahedrons = v.mNbTetrahedrons;
mTetrahedrons32 = v.mTetrahedrons32;
mTetrahedrons16 = v.mTetrahedrons16;
v.reset();
}
void TetrahedronSourceMesh::remapTopology(const PxU32* order)
{
if(!mNbTetrahedrons)
return;
if(mTetrahedrons32)
{
IndTetrahedron32* newTopo = PX_NEW(IndTetrahedron32)[mNbTetrahedrons];
for(PxU32 i = 0; i<mNbTetrahedrons; i++)
newTopo[i] = mTetrahedrons32[order[i]];
PxMemCopy(mTetrahedrons32, newTopo, sizeof(IndTetrahedron32)*mNbTetrahedrons);
PX_DELETE_ARRAY(newTopo);
}
else
{
PX_ASSERT(mTetrahedrons16);
IndTetrahedron16* newTopo = PX_NEW(IndTetrahedron16)[mNbTetrahedrons];
for(PxU32 i = 0; i<mNbTetrahedrons; i++)
newTopo[i] = mTetrahedrons16[order[i]];
PxMemCopy(mTetrahedrons16, newTopo, sizeof(IndTetrahedron16)*mNbTetrahedrons);
PX_DELETE_ARRAY(newTopo);
}
{
PxU32* newMap = PX_ALLOCATE(PxU32, mNbTetrahedrons, "newMap");
for(PxU32 i = 0; i<mNbTetrahedrons; i++)
newMap[i] = mRemap ? mRemap[order[i]] : order[i];
PX_FREE(mRemap);
mRemap = newMap;
}
}
void TetrahedronSourceMesh::getPrimitiveBox(const PxU32 primitiveInd, Vec4V& minV, Vec4V& maxV)
{
TetrahedronPointers VP;
getTetrahedron(VP, primitiveInd);
const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x);
const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x);
const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x);
const Vec4V v3V = V4LoadU(&VP.Vertex[3]->x);
minV = V4Min(v0V, v1V);
minV = V4Min(minV, v2V);
minV = V4Min(minV, v3V);
maxV = V4Max(v0V, v1V);
maxV = V4Max(maxV, v2V);
maxV = V4Max(maxV, v3V);
}
void TetrahedronSourceMesh::refit(const PxU32 primitiveInd, PxBounds3& refitBox)
{
TetrahedronPointers VP;
getTetrahedron(VP, primitiveInd);
refitBox.include(*VP.Vertex[0]);
refitBox.include(*VP.Vertex[1]);
refitBox.include(*VP.Vertex[2]);
refitBox.include(*VP.Vertex[3]);
}
///////////////////////////////////////////////////////////////////////////////
SourceMesh::SourceMesh() : SourceMeshBase(MeshType::TRI_MESH)
{
reset();
}
SourceMesh::~SourceMesh()
{
}
void SourceMesh::reset()
{
mNbVerts = 0;
mVerts = NULL;
mNbTris = 0;
mTriangles32 = NULL;
mTriangles16 = NULL;
mRemap = NULL;
}
void SourceMesh::operator=(SourceMesh& v)
{
mNbVerts = v.mNbVerts;
mVerts = v.mVerts;
mNbTris = v.mNbTris;
mTriangles32 = v.mTriangles32;
mTriangles16 = v.mTriangles16;
mRemap = v.mRemap;
v.reset();
}
void SourceMesh::remapTopology(const PxU32* order)
{
if(!mNbTris)
return;
if(mTriangles32)
{
IndTri32* newTopo = PX_NEW(IndTri32)[mNbTris];
for(PxU32 i=0;i<mNbTris;i++)
newTopo[i] = mTriangles32[order[i]];
PxMemCopy(mTriangles32, newTopo, sizeof(IndTri32)*mNbTris);
PX_DELETE_ARRAY(newTopo);
}
else
{
PX_ASSERT(mTriangles16);
IndTri16* newTopo = PX_NEW(IndTri16)[mNbTris];
for(PxU32 i=0;i<mNbTris;i++)
newTopo[i] = mTriangles16[order[i]];
PxMemCopy(mTriangles16, newTopo, sizeof(IndTri16)*mNbTris);
PX_DELETE_ARRAY(newTopo);
}
{
PxU32* newMap = PX_ALLOCATE(PxU32, mNbTris, "newMap");
for(PxU32 i=0;i<mNbTris;i++)
newMap[i] = mRemap ? mRemap[order[i]] : order[i];
PX_FREE(mRemap);
mRemap = newMap;
}
}
void SourceMesh::getPrimitiveBox(const PxU32 primitiveInd, Vec4V& minV, Vec4V& maxV)
{
VertexPointers VP;
getTriangle(VP, primitiveInd);
const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x);
const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x);
const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x);
minV = V4Min(v0V, v1V);
minV = V4Min(minV, v2V);
maxV = V4Max(v0V, v1V);
maxV = V4Max(maxV, v2V);
}
void SourceMesh::refit(const PxU32 primitiveInd, PxBounds3& refitBox)
{
VertexPointers VP;
getTriangle(VP, primitiveInd);
refitBox.include(*VP.Vertex[0]);
refitBox.include(*VP.Vertex[1]);
refitBox.include(*VP.Vertex[2]);
}
bool SourceMesh::isValid() const
{
if(!mNbTris || !mNbVerts) return false;
if(!mVerts) return false;
if(!mTriangles32 && !mTriangles16) return false;
return true;
}
/////
BV4Tree::BV4Tree(SourceMesh* meshInterface, const PxBounds3& localBounds)
{
reset();
init(meshInterface, localBounds);
}
BV4Tree::BV4Tree()
{
reset();
}
void BV4Tree::release()
{
if(!mUserAllocated)
{
#ifdef GU_BV4_USE_SLABS
PX_FREE(mNodes);
// PX_DELETE(mNodes);
#else
PX_DELETE_ARRAY(mNodes);
#endif
}
mNodes = NULL;
mNbNodes = 0;
reset();
}
BV4Tree::~BV4Tree()
{
release();
}
void BV4Tree::reset()
{
mMeshInterface = NULL;
//mTetrahedronMeshInterface = NULL;
mNbNodes = 0;
mNodes = NULL;
mInitData = 0;
mCenterOrMinCoeff = PxVec3(0.0f);
mExtentsOrMaxCoeff = PxVec3(0.0f);
mUserAllocated = false;
mQuantized = false;
mIsEdgeSet = false;
}
void BV4Tree::operator=(BV4Tree& v)
{
mMeshInterface = v.mMeshInterface;
//mTetrahedronMeshInterface = v.mTetrahedronMeshInterface;
mLocalBounds = v.mLocalBounds;
mNbNodes = v.mNbNodes;
mNodes = v.mNodes;
mInitData = v.mInitData;
mCenterOrMinCoeff = v.mCenterOrMinCoeff;
mExtentsOrMaxCoeff = v.mExtentsOrMaxCoeff;
mUserAllocated = v.mUserAllocated;
mQuantized = v.mQuantized;
mIsEdgeSet = false;
v.reset();
}
bool BV4Tree::init(SourceMeshBase* meshInterface, const PxBounds3& localBounds)
{
mMeshInterface = meshInterface;
mLocalBounds.init(localBounds);
return true;
}
//bool BV4Tree::init(TetrahedronSourceMesh* meshInterface, const PxBounds3& localBounds)
//{
// mTetrahedronMeshInterface = meshInterface;
// mLocalBounds.init(localBounds);
// return true;
//}
// PX_SERIALIZATION
BV4Tree::BV4Tree(const PxEMPTY) : mLocalBounds(PxEmpty)
{
mUserAllocated = true;
mIsEdgeSet = false;
}
void BV4Tree::exportExtraData(PxSerializationContext& stream)
{
if(mNbNodes)
{
stream.alignData(16);
const PxU32 nodeSize = mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
stream.writeData(mNodes, mNbNodes*nodeSize);
}
}
void BV4Tree::importExtraData(PxDeserializationContext& context)
{
if(mNbNodes)
{
context.alignExtraData(16);
if(mQuantized)
mNodes = context.readExtraData<BVDataPackedQ>(mNbNodes);
else
mNodes = context.readExtraData<BVDataPackedNQ>(mNbNodes);
}
}
//~PX_SERIALIZATION
bool BV4Tree::load(PxInputStream& stream, bool mismatch_)
{
PX_ASSERT(!mUserAllocated);
release();
PxI8 a, b, c, d;
readChunk(a, b, c, d, stream);
if(a!='B' || b!='V' || c!='4' || d!=' ')
return false;
bool mismatch;
PxU32 fileVersion;
if(!readBigEndianVersionNumber(stream, mismatch_, fileVersion, mismatch))
return false;
readFloatBuffer(&mLocalBounds.mCenter.x, 3, mismatch, stream);
mLocalBounds.mExtentsMagnitude = readFloat(mismatch, stream);
mInitData = readDword(mismatch, stream);
readFloatBuffer(&mCenterOrMinCoeff.x, 3, mismatch, stream);
readFloatBuffer(&mExtentsOrMaxCoeff.x, 3, mismatch, stream);
// PT: version 3
if(fileVersion>=3)
{
const PxU32 Quantized = readDword(mismatch, stream);
mQuantized = Quantized!=0;
}
else
mQuantized = true;
const PxU32 nbNodes = readDword(mismatch, stream);
mNbNodes = nbNodes;
if(nbNodes)
{
PxU32 dataSize = 0;
#ifdef GU_BV4_USE_SLABS
const PxU32 nodeSize = mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
dataSize = nodeSize*nbNodes;
void* nodes = PX_ALLOC(dataSize, "BV4 nodes"); // PT: PX_NEW breaks alignment here
// BVDataPacked* nodes = reinterpret_cast<BVDataPacked*>(PX_ALLOC(sizeof(BVDataPacked)*nbNodes, "BV4 nodes")); // PT: PX_NEW breaks alignment here
mNodes = nodes;
#else
BVDataPacked* nodes = PX_NEW(BVDataPacked)[nbNodes];
mNodes = nodes;
#endif
// PxMarkSerializedMemory(nodes, dataSize);
stream.read(nodes, dataSize);
PX_ASSERT(!mismatch);
}
else mNodes = NULL;
mIsEdgeSet = false;
return true;
}
#define VERSION2
#ifdef VERSION1
bool BV4Tree::refit(PxBounds3& globalBounds, float epsilon)
{
if(mQuantized)
if(!mNodes)
{
PxBounds3 bounds;
bounds.setEmpty();
if(mMeshInterface)
{
PxU32 nbVerts = mMeshInterface->getNbVertices();
const PxVec3* verts = mMeshInterface->getVerts();
while(nbVerts--)
bounds.include(*verts++);
mLocalBounds.init(bounds);
}
if(mTetrahedronMeshInterface)
{
PX_ASSERT(0);
}
return true;
}
class PxBounds3Padded : public PxBounds3
{
public:
PX_FORCE_INLINE PxBounds3Padded() {}
PX_FORCE_INLINE ~PxBounds3Padded() {}
PxU32 padding;
};
PX_ASSERT(!(mNbNodes&3));
PxU32 nb = mNbNodes/4;
BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(mNodes);
while(nb--)
{
BVDataSwizzledNQ* PX_RESTRICT current = data + nb;
for(PxU32 j=0;j<4;j++)
{
if(current->getChildData(j)==PX_INVALID_U32)
continue;
Vec4V minV = V4Load(FLT_MAX);
Vec4V maxV = V4Load(-FLT_MAX);
if(current->isLeaf(j))
{
PxU32 primIndex = current->getPrimitive(j);
PxU32 nbToGo = getNbPrimitives(primIndex);
VertexPointers VP;
do
{
PX_ASSERT(primIndex<mMeshInterface->getNbTriangles());
mMeshInterface->getTriangle(VP, primIndex);
const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x);
const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x);
const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x);
minV = V4Min(minV, v0V);
minV = V4Min(minV, v1V);
minV = V4Min(minV, v2V);
maxV = V4Max(maxV, v0V);
maxV = V4Max(maxV, v1V);
maxV = V4Max(maxV, v2V);
primIndex++;
}while(nbToGo--);
const Vec4V epsilonV = V4Load(epsilon);
minV = V4Sub(minV, epsilonV);
maxV = V4Add(maxV, epsilonV);
}
else
{
PxU32 childOffset = current->getChildOffset(j);
PX_ASSERT(!(childOffset&3));
childOffset>>=2;
PX_ASSERT(childOffset>nb);
const PxU32 childType = current->getChildType(j);
// PT: TODO: revisit SIMD here, not great
const BVDataSwizzledNQ* PX_RESTRICT next = data + childOffset;
{
{
const Vec4V childMinV = V4LoadXYZW(next->mMinX[0], next->mMinY[0], next->mMinZ[0], 0.0f);
const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0], 0.0f);
// minV = V4Min(minV, childMinV);
// maxV = V4Max(maxV, childMaxV);
minV = childMinV;
maxV = childMaxV;
}
{
const Vec4V childMinV = V4LoadXYZW(next->mMinX[1], next->mMinY[1], next->mMinZ[1], 0.0f);
const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1], 0.0f);
minV = V4Min(minV, childMinV);
maxV = V4Max(maxV, childMaxV);
}
/* {
const Vec4V childMinV0 = V4LoadXYZW(next->mMinX[0], next->mMinY[0], next->mMinZ[0], 0.0f);
const Vec4V childMaxV0 = V4LoadXYZW(next->mMaxX[0], next->mMaxY[0], next->mMaxZ[0], 0.0f);
const Vec4V childMinV1 = V4LoadXYZW(next->mMinX[1], next->mMinY[1], next->mMinZ[1], 0.0f);
const Vec4V childMaxV1 = V4LoadXYZW(next->mMaxX[1], next->mMaxY[1], next->mMaxZ[1], 0.0f);
minV = V4Min(childMinV0, childMinV1);
maxV = V4Max(childMaxV0, childMaxV1);
}*/
if(childType>0)
{
const Vec4V childMinV = V4LoadXYZW(next->mMinX[2], next->mMinY[2], next->mMinZ[2], 0.0f);
const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[2], next->mMaxY[2], next->mMaxZ[2], 0.0f);
minV = V4Min(minV, childMinV);
maxV = V4Max(maxV, childMaxV);
}
if(childType>1)
{
const Vec4V childMinV = V4LoadXYZW(next->mMinX[3], next->mMinY[3], next->mMinZ[3], 0.0f);
const Vec4V childMaxV = V4LoadXYZW(next->mMaxX[3], next->mMaxY[3], next->mMaxZ[3], 0.0f);
minV = V4Min(minV, childMinV);
maxV = V4Max(maxV, childMaxV);
}
}
}
PxBounds3Padded refitBox;
V4StoreU_Safe(minV, &refitBox.minimum.x);
V4StoreU_Safe(maxV, &refitBox.maximum.x);
current->mMinX[j] = refitBox.minimum.x;
current->mMinY[j] = refitBox.minimum.y;
current->mMinZ[j] = refitBox.minimum.z;
current->mMaxX[j] = refitBox.maximum.x;
current->mMaxY[j] = refitBox.maximum.y;
current->mMaxZ[j] = refitBox.maximum.z;
}
}
BVDataSwizzledNQ* root = reinterpret_cast<BVDataSwizzledNQ*>(mNodes);
{
globalBounds.setEmpty();
for(PxU32 j=0;j<4;j++)
{
if(root->getChildData(j)==PX_INVALID_U32)
continue;
PxBounds3 refitBox;
refitBox.minimum.x = root->mMinX[j];
refitBox.minimum.y = root->mMinY[j];
refitBox.minimum.z = root->mMinZ[j];
refitBox.maximum.x = root->mMaxX[j];
refitBox.maximum.y = root->mMaxY[j];
refitBox.maximum.z = root->mMaxZ[j];
globalBounds.include(refitBox);
}
mLocalBounds.init(globalBounds);
}
return true;
}
#endif
#ifdef VERSION2
bool BV4Tree::refit(PxBounds3& globalBounds, float epsilon)
{
if(mQuantized)
return false;
if(!mNodes)
{
globalBounds.setEmpty();
if(mMeshInterface)
{
PxU32 nbVerts = mMeshInterface->getNbVertices();
const PxVec3* verts = mMeshInterface->getVerts();
while(nbVerts--)
globalBounds.include(*verts++);
mLocalBounds.init(globalBounds);
}
return true;
}
class PxBounds3Padded : public PxBounds3
{
public:
PX_FORCE_INLINE PxBounds3Padded() {}
PX_FORCE_INLINE ~PxBounds3Padded() {}
PxU32 padding;
};
PX_ASSERT(!(mNbNodes&3));
PxU32 nb = mNbNodes/4;
BVDataSwizzledNQ* data = reinterpret_cast<BVDataSwizzledNQ*>(mNodes);
while(nb--)
{
BVDataSwizzledNQ* PX_RESTRICT current = data + nb;
for(PxU32 j=0;j<4;j++)
{
if(current->getChildData(j)==PX_INVALID_U32)
continue;
if(current->isLeaf(j))
{
PxU32 primIndex = current->getPrimitive(j);
Vec4V minV = V4Load(FLT_MAX);
Vec4V maxV = V4Load(-FLT_MAX);
PxU32 nbToGo = getNbPrimitives(primIndex);
//VertexPointers VP;
do
{
PX_ASSERT(primIndex< mMeshInterface->getNbPrimitives());
//meshInterface->getTriangle(VP, primIndex);
Vec4V tMin, tMax;
mMeshInterface->getPrimitiveBox(primIndex, tMin, tMax);
minV = V4Min(minV, tMin);
maxV = V4Max(maxV, tMax);
/* const Vec4V v0V = V4LoadU(&VP.Vertex[0]->x);
const Vec4V v1V = V4LoadU(&VP.Vertex[1]->x);
const Vec4V v2V = V4LoadU(&VP.Vertex[2]->x);
minV = V4Min(minV, v0V);
minV = V4Min(minV, v1V);
minV = V4Min(minV, v2V);
maxV = V4Max(maxV, v0V);
maxV = V4Max(maxV, v1V);
maxV = V4Max(maxV, v2V);*/
primIndex++;
}while(nbToGo--);
const Vec4V epsilonV = V4Load(epsilon);
minV = V4Sub(minV, epsilonV);
maxV = V4Add(maxV, epsilonV);
PxBounds3Padded refitBox;
V4StoreU_Safe(minV, &refitBox.minimum.x);
V4StoreU_Safe(maxV, &refitBox.maximum.x);
current->mMinX[j] = refitBox.minimum.x;
current->mMinY[j] = refitBox.minimum.y;
current->mMinZ[j] = refitBox.minimum.z;
current->mMaxX[j] = refitBox.maximum.x;
current->mMaxY[j] = refitBox.maximum.y;
current->mMaxZ[j] = refitBox.maximum.z;
}
else
{
PxU32 childOffset = current->getChildOffset(j);
PX_ASSERT(!(childOffset&3));
childOffset>>=2;
PX_ASSERT(childOffset>nb);
const PxU32 childType = current->getChildType(j);
const BVDataSwizzledNQ* PX_RESTRICT next = data + childOffset;
{
current->mMinX[j] = PxMin(next->mMinX[0], next->mMinX[1]);
current->mMinY[j] = PxMin(next->mMinY[0], next->mMinY[1]);
current->mMinZ[j] = PxMin(next->mMinZ[0], next->mMinZ[1]);
current->mMaxX[j] = PxMax(next->mMaxX[0], next->mMaxX[1]);
current->mMaxY[j] = PxMax(next->mMaxY[0], next->mMaxY[1]);
current->mMaxZ[j] = PxMax(next->mMaxZ[0], next->mMaxZ[1]);
if(childType>0)
{
current->mMinX[j] = PxMin(current->mMinX[j], next->mMinX[2]);
current->mMinY[j] = PxMin(current->mMinY[j], next->mMinY[2]);
current->mMinZ[j] = PxMin(current->mMinZ[j], next->mMinZ[2]);
current->mMaxX[j] = PxMax(current->mMaxX[j], next->mMaxX[2]);
current->mMaxY[j] = PxMax(current->mMaxY[j], next->mMaxY[2]);
current->mMaxZ[j] = PxMax(current->mMaxZ[j], next->mMaxZ[2]);
}
if(childType>1)
{
current->mMinX[j] = PxMin(current->mMinX[j], next->mMinX[3]);
current->mMinY[j] = PxMin(current->mMinY[j], next->mMinY[3]);
current->mMinZ[j] = PxMin(current->mMinZ[j], next->mMinZ[3]);
current->mMaxX[j] = PxMax(current->mMaxX[j], next->mMaxX[3]);
current->mMaxY[j] = PxMax(current->mMaxY[j], next->mMaxY[3]);
current->mMaxZ[j] = PxMax(current->mMaxZ[j], next->mMaxZ[3]);
}
}
}
}
}
BVDataSwizzledNQ* root = reinterpret_cast<BVDataSwizzledNQ*>(mNodes);
{
globalBounds.setEmpty();
for(PxU32 j=0;j<4;j++)
{
if(root->getChildData(j)==PX_INVALID_U32)
continue;
PxBounds3 refitBox;
refitBox.minimum.x = root->mMinX[j];
refitBox.minimum.y = root->mMinY[j];
refitBox.minimum.z = root->mMinZ[j];
refitBox.maximum.x = root->mMaxX[j];
refitBox.maximum.y = root->mMaxY[j];
refitBox.maximum.z = root->mMaxZ[j];
globalBounds.include(refitBox);
}
mLocalBounds.init(globalBounds);
}
return true;
}
#endif
| 19,356 | C++ | 25.228997 | 147 | 0.672711 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TRIANGLE_H
#define GU_TRIANGLE_H
#include "foundation/PxVec3.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Gu
{
// PT: I'm taking back control of these files and re-introducing the "ICE" naming conventions:
// - "Triangle" is for actual triangles (like the PxTriangle class)
// - If it contains vertex indices, it's "IndexedTriangle".
// - "v" is too ambiguous (it could be either an actual vertex or a vertex reference) so use "ref" instead.
// Plus we sometimes reference edges, not vertices, so "v" is too restrictive.
template <class T>
struct IndexedTriangleT : public PxUserAllocated
{
PX_INLINE IndexedTriangleT () {}
PX_INLINE IndexedTriangleT (T a, T b, T c) { mRef[0] = a; mRef[1] = b; mRef[2] = c; }
template <class TX>
PX_INLINE IndexedTriangleT (const IndexedTriangleT <TX>& other) { mRef[0] = other[0]; mRef[1] = other[1]; mRef[2] = other[2]; }
PX_INLINE T& operator[](T i) { return mRef[i]; }
PX_INLINE const T& operator[](T i) const { return mRef[i]; }
template<class TX>//any type of IndexedTriangleT <>, possibly with different T
PX_INLINE IndexedTriangleT <T>& operator=(const IndexedTriangleT <TX>& i) { mRef[0]=i[0]; mRef[1]=i[1]; mRef[2]=i[2]; return *this; }
void flip()
{
PxSwap(mRef[1], mRef[2]);
}
PX_INLINE bool contains(T id) const
{
return mRef[0] == id || mRef[1] == id || mRef[2] == id;
}
PX_INLINE void center(const PxVec3* verts, PxVec3& center) const
{
const PxVec3& p0 = verts[mRef[0]];
const PxVec3& p1 = verts[mRef[1]];
const PxVec3& p2 = verts[mRef[2]];
center = (p0+p1+p2)*0.33333333333333333333f;
}
float area(const PxVec3* verts) const
{
const PxVec3& p0 = verts[mRef[0]];
const PxVec3& p1 = verts[mRef[1]];
const PxVec3& p2 = verts[mRef[2]];
return ((p0-p1).cross(p0-p2)).magnitude() * 0.5f;
}
PxU8 findEdge(T vref0, T vref1) const
{
if(mRef[0]==vref0 && mRef[1]==vref1) return 0;
else if(mRef[0]==vref1 && mRef[1]==vref0) return 0;
else if(mRef[0]==vref0 && mRef[2]==vref1) return 1;
else if(mRef[0]==vref1 && mRef[2]==vref0) return 1;
else if(mRef[1]==vref0 && mRef[2]==vref1) return 2;
else if(mRef[1]==vref1 && mRef[2]==vref0) return 2;
return 0xff;
}
// counter clock wise order
PxU8 findEdgeCCW(T vref0, T vref1) const
{
if(mRef[0]==vref0 && mRef[1]==vref1) return 0;
else if(mRef[0]==vref1 && mRef[1]==vref0) return 0;
else if(mRef[0]==vref0 && mRef[2]==vref1) return 2;
else if(mRef[0]==vref1 && mRef[2]==vref0) return 2;
else if(mRef[1]==vref0 && mRef[2]==vref1) return 1;
else if(mRef[1]==vref1 && mRef[2]==vref0) return 1;
return 0xff;
}
bool replaceVertex(T oldref, T newref)
{
if(mRef[0]==oldref) { mRef[0] = newref; return true; }
else if(mRef[1]==oldref) { mRef[1] = newref; return true; }
else if(mRef[2]==oldref) { mRef[2] = newref; return true; }
return false;
}
bool isDegenerate() const
{
if(mRef[0]==mRef[1]) return true;
if(mRef[1]==mRef[2]) return true;
if(mRef[2]==mRef[0]) return true;
return false;
}
PX_INLINE void denormalizedNormal(const PxVec3* verts, PxVec3& normal) const
{
const PxVec3& p0 = verts[mRef[0]];
const PxVec3& p1 = verts[mRef[1]];
const PxVec3& p2 = verts[mRef[2]];
normal = ((p2 - p1).cross(p0 - p1));
}
T mRef[3]; //vertex indices
};
typedef IndexedTriangleT<PxU32> IndexedTriangle32;
typedef IndexedTriangleT<PxU16> IndexedTriangle16;
PX_COMPILE_TIME_ASSERT(sizeof(IndexedTriangle32)==12);
PX_COMPILE_TIME_ASSERT(sizeof(IndexedTriangle16)==6);
}
}
#endif
| 5,358 | C | 35.95862 | 135 | 0.681411 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamNoOrder_SphereAABB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_NOORDER_SPHERE_AABB_H
#define GU_BV4_PROCESS_STREAM_NOORDER_SPHERE_AABB_H
#ifdef GU_BV4_USE_SLABS
/* template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_Swizzled(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzled* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
// OPC_SLABS_GET_CE(i)
OPC_SLABS_GET_CE2(i)
if(BV4_SphereAABBOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}*/
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_SwizzledQ(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CE2Q(i)
if(BV4_SphereAABBOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_SwizzledNQ(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledNQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CE2NQ(i)
if(BV4_SphereAABBOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}
#else
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_SphereAABBOverlap(node+i, params))
#else
if(BV4_SphereAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params))
#endif
{
if(node[i].isLeaf())
{
if(LeafTestT::doLeafTest(params, node[i].getPrimitive()))
return 1;
}
else
Stack[Nb++] = node[i].getChildData();
}
return 0;
}
#endif
#endif // GU_BV4_PROCESS_STREAM_NOORDER_SPHERE_AABB_H
| 3,928 | C | 34.396396 | 168 | 0.726069 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_AABBAABBSweepTest.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_AABB_AABB_SWEEP_TEST_H
#define GU_BV4_AABB_AABB_SWEEP_TEST_H
#ifndef GU_BV4_USE_SLABS
PX_FORCE_INLINE PxIntBool BV4_SegmentAABBOverlap(const PxVec3& center, const PxVec3& extents, const PxVec3& extents2, const RayParams* PX_RESTRICT params)
{
const Vec4V fdirV = V4LoadA_Safe(¶ms->mFDir_PaddedAligned.x);
const Vec4V extentsV = V4Add(V4LoadU(&extents.x), V4LoadU(&extents2.x));
const Vec4V DV = V4Sub(V4LoadA_Safe(¶ms->mData2_PaddedAligned.x), V4LoadU(¢er.x));
const Vec4V absDV = V4Abs(DV);
const BoolV resDV = V4IsGrtr(absDV, V4Add(extentsV, fdirV));
const PxU32 test = BGetBitMask(resDV);
if(test&7)
return 0;
if(1)
{
const Vec4V dataZYX_V = V4LoadA_Safe(¶ms->mData_PaddedAligned.x);
const Vec4V dataXZY_V = V4Perm<1, 2, 0, 3>(dataZYX_V);
const Vec4V DXZY_V = V4Perm<1, 2, 0, 3>(DV);
const Vec4V fV = V4Sub(V4Mul(dataZYX_V, DXZY_V), V4Mul(dataXZY_V, DV));
const Vec4V fdirZYX_V = V4LoadA_Safe(¶ms->mFDir_PaddedAligned.x);
const Vec4V fdirXZY_V = V4Perm<1, 2, 0, 3>(fdirZYX_V);
const Vec4V extentsXZY_V = V4Perm<1, 2, 0, 3>(extentsV);
// PT: TODO: use V4MulAdd here (TA34704)
const Vec4V fg = V4Add(V4Mul(extentsV, fdirXZY_V), V4Mul(extentsXZY_V, fdirZYX_V));
const Vec4V absfV = V4Abs(fV);
const BoolV resAbsfV = V4IsGrtr(absfV, fg);
const PxU32 test2 = BGetBitMask(resAbsfV);
if(test2&7)
return 0;
return 1;
}
}
#ifdef GU_BV4_QUANTIZED_TREE
template<class T>
PX_FORCE_INLINE PxIntBool BV4_SegmentAABBOverlap(const T* PX_RESTRICT node, const PxVec3& extents2, const RayParams* PX_RESTRICT params)
{
const VecI32V testV = I4LoadA((PxI32*)node->mAABB.mData);
const VecI32V qextentsV = VecI32V_And(testV, I4Load(0x0000ffff));
const VecI32V qcenterV = VecI32V_RightShift(testV, 16);
const Vec4V centerV0 = V4Mul(Vec4V_From_VecI32V(qcenterV), V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x));
const Vec4V extentsV0 = V4Mul(Vec4V_From_VecI32V(qextentsV), V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x));
const Vec4V fdirV = V4LoadA_Safe(¶ms->mFDir_PaddedAligned.x);
const Vec4V extentsV = V4Add(extentsV0, V4LoadU(&extents2.x));
const Vec4V DV = V4Sub(V4LoadA_Safe(¶ms->mData2_PaddedAligned.x), centerV0);
const Vec4V absDV = V4Abs(DV);
const BoolV res = V4IsGrtr(absDV, V4Add(extentsV, fdirV));
const PxU32 test = BGetBitMask(res);
if(test&7)
return 0;
if(1)
{
const Vec4V dataZYX_V = V4LoadA_Safe(¶ms->mData_PaddedAligned.x);
const Vec4V dataXZY_V = V4Perm<1, 2, 0, 3>(dataZYX_V);
const Vec4V DXZY_V = V4Perm<1, 2, 0, 3>(DV);
const Vec4V fV = V4Sub(V4Mul(dataZYX_V, DXZY_V), V4Mul(dataXZY_V, DV));
const Vec4V fdirZYX_V = V4LoadA_Safe(¶ms->mFDir_PaddedAligned.x);
const Vec4V fdirXZY_V = V4Perm<1, 2, 0, 3>(fdirZYX_V);
const Vec4V extentsXZY_V = V4Perm<1, 2, 0, 3>(extentsV);
// PT: TODO: use V4MulAdd here (TA34704)
const Vec4V fg = V4Add(V4Mul(extentsV, fdirXZY_V), V4Mul(extentsXZY_V, fdirZYX_V));
const Vec4V absfV = V4Abs(fV);
const BoolV res2 = V4IsGrtr(absfV, fg);
const PxU32 test2 = BGetBitMask(res2);
if(test2&7)
return 0;
return 1;
}
}
#endif
#endif
#endif // GU_BV4_AABB_AABB_SWEEP_TEST_H
| 4,953 | C | 43.63063 | 155 | 0.720775 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshRTree.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TRIANGLEMESH_RTREE_H
#define GU_TRIANGLEMESH_RTREE_H
#include "GuTriangleMesh.h"
namespace physx
{
namespace Gu
{
class MeshFactory;
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class RTreeTriangleMesh : public TriangleMesh
{
public:
virtual const char* getConcreteTypeName() const { return "PxBVH33TriangleMesh"; }
// PX_SERIALIZATION
RTreeTriangleMesh(PxBaseFlags baseFlags) : TriangleMesh(baseFlags), mRTree(PxEmpty) {}
PX_PHYSX_COMMON_API virtual void exportExtraData(PxSerializationContext& ctx);
void importExtraData(PxDeserializationContext&);
PX_PHYSX_COMMON_API static TriangleMesh* createObject(PxU8*& address, PxDeserializationContext& context);
PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
RTreeTriangleMesh(MeshFactory* factory, TriangleMeshData& data);
virtual ~RTreeTriangleMesh(){}
virtual PxMeshMidPhase::Enum getMidphaseID() const { return PxMeshMidPhase::eBVH33; }
virtual PxVec3* getVerticesForModification();
virtual PxBounds3 refitBVH();
PX_FORCE_INLINE const Gu::RTree& getRTree() const { return mRTree; }
private:
Gu::RTree mRTree;
};
#if PX_VC
#pragma warning(pop)
#endif
} // namespace Gu
}
#endif
| 3,134 | C | 39.192307 | 115 | 0.742821 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuSweepConvexTri.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_CONVEX_TRI
#define GU_SWEEP_CONVEX_TRI
#include "geometry/PxConvexMeshGeometry.h"
#include "GuVecTriangle.h"
#include "GuVecConvexHull.h"
#include "GuConvexMesh.h"
#include "GuGJKRaycast.h"
// return true if hit, false if no hit
static PX_FORCE_INLINE bool sweepConvexVsTriangle(
const PxVec3& v0, const PxVec3& v1, const PxVec3& v2,
ConvexHullV& convexHull, const aos::PxMatTransformV& meshToConvex, const aos::PxTransformV& convexTransfV,
const aos::Vec3VArg convexSpaceDir, const PxVec3& unitDir, const PxVec3& meshSpaceUnitDir,
const aos::FloatVArg fullDistance, PxReal shrunkDistance,
PxGeomSweepHit& hit, bool isDoubleSided, const PxReal inflation, bool& initialOverlap, PxU32 faceIndex)
{
using namespace aos;
if(!isDoubleSided)
{
// Create triangle normal
const PxVec3 denormalizedNormal = (v1 - v0).cross(v2 - v1);
// Backface culling
// PT: WARNING, the test is reversed compared to usual because we pass -unitDir to this function
const bool culled = denormalizedNormal.dot(meshSpaceUnitDir) <= 0.0f;
if(culled)
return false;
}
const Vec3V zeroV = V3Zero();
const FloatV zero = FZero();
const Vec3V p0 = V3LoadU(v0); // in mesh local space
const Vec3V p1 = V3LoadU(v1);
const Vec3V p2 = V3LoadU(v2);
// transform triangle verts from mesh local to convex local space
TriangleV triangleV(meshToConvex.transform(p0), meshToConvex.transform(p1), meshToConvex.transform(p2));
FloatV toi;
Vec3V closestA,normal;
const LocalConvex<TriangleV> convexA(triangleV);
const LocalConvex<ConvexHullV> convexB(convexHull);
const Vec3V initialSearchDir = V3Sub(triangleV.getCenter(), convexHull.getCenter());
// run GJK raycast
// sweep triangle in convex local space vs convex, closestA will be the impact point in convex local space
const bool gjkHit = gjkRaycastPenetration<LocalConvex<TriangleV>, LocalConvex<ConvexHullV> >(
convexA, convexB, initialSearchDir, zero, zeroV, convexSpaceDir, toi, normal, closestA, inflation, false);
if(!gjkHit)
return false;
if(FAllGrtrOrEq(zero, toi))
{
initialOverlap = true; // PT: TODO: redundant with hit distance, consider removing
return setInitialOverlapResults(hit, unitDir, faceIndex);
}
const FloatV minDist = FLoad(shrunkDistance);
const FloatV dist = FMul(toi, fullDistance); // scale the toi to original full sweep distance
if(FAllGrtr(minDist, dist)) // is current dist < minDist?
{
hit.faceIndex = faceIndex;
hit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
const Vec3V destWorldPointA = convexTransfV.transform(closestA);
const Vec3V destNormal = V3Normalize(convexTransfV.rotate(normal));
V3StoreU(destWorldPointA, hit.position);
V3StoreU(destNormal, hit.normal);
FStore(dist, &hit.distance);
return true; // report a hit
}
return false; // report no hit
}
#endif
| 4,543 | C | 42.27619 | 108 | 0.761171 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMidphaseRTree.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "GuSweepMesh.h"
#include "GuIntersectionRayTriangle.h"
#include "GuIntersectionCapsuleTriangle.h"
#include "GuIntersectionRayBox.h"
#include "GuSphere.h"
#include "GuBoxConversion.h"
#include "GuConvexUtilsInternal.h"
#include "GuVecTriangle.h"
#include "GuIntersectionTriangleBox.h"
#include "GuRTree.h"
#include "GuTriangleMeshRTree.h"
#include "GuInternal.h"
#include "CmMatrix34.h"
// This file contains code specific to the RTree midphase.
using namespace physx;
using namespace Cm;
using namespace Gu;
using namespace physx::aos;
struct MeshRayCollider
{
template <int tInflate, int tRayTest>
PX_PHYSX_COMMON_API static void collide(
const PxVec3& orig, const PxVec3& dir, // dir is not normalized (full length), both in mesh space (unless meshWorld is non-zero)
PxReal maxT, // maxT is from [0,1], if maxT is 0.0f, AABB traversal will be used
bool bothTriangleSidesCollide, const RTreeTriangleMesh* mesh, MeshHitCallback<PxGeomRaycastHit>& callback,
const PxVec3* inflate = NULL);
PX_PHYSX_COMMON_API static void collideOBB(
const Box& obb, bool bothTriangleSidesCollide, const RTreeTriangleMesh* mesh, MeshHitCallback<PxGeomRaycastHit>& callback,
bool checkObbIsAligned = true); // perf hint, pass false if obb is rarely axis aligned
};
class SimpleRayTriOverlap
{
public:
PX_FORCE_INLINE SimpleRayTriOverlap(const PxVec3& origin, const PxVec3& dir, bool bothSides, PxReal geomEpsilon)
: mOrigin(origin), mDir(dir), mBothSides(bothSides), mGeomEpsilon(geomEpsilon)
{
}
PX_FORCE_INLINE PxIntBool overlap(const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2, PxGeomRaycastHit& hit) const
{
if(!intersectRayTriangle(mOrigin, mDir, vert0, vert1, vert2, hit.distance, hit.u, hit.v, !mBothSides, mGeomEpsilon))
return false;
if(hit.distance< 0.0f) // test if the ray intersection t is negative
return false;
return true;
}
PxVec3 mOrigin;
PxVec3 mDir;
bool mBothSides;
PxReal mGeomEpsilon;
};
using Gu::RTree;
// This callback comes from RTree and decodes LeafTriangle indices stored in rtree into actual triangles
// This callback is needed because RTree doesn't know that it stores triangles since it's a general purpose spatial index
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
template <int tInflate, bool tRayTest>
struct RayRTreeCallback : RTree::CallbackRaycast, RTree::Callback
{
MeshHitCallback<PxGeomRaycastHit>& outerCallback;
PxI32 has16BitIndices;
const void* mTris;
const PxVec3* mVerts;
const PxVec3* mInflate;
const SimpleRayTriOverlap rayCollider;
PxReal maxT;
PxGeomRaycastHit closestHit; // recorded closest hit over the whole traversal (only for callback mode eCLOSEST)
PxVec3 cv0, cv1, cv2; // PT: make sure these aren't last in the class, to safely V4Load them
PxU32 cis[3];
bool hadClosestHit;
const bool closestMode;
Vec3V inflateV, rayOriginV, rayDirV;
RayRTreeCallback(
PxReal geomEpsilon, MeshHitCallback<PxGeomRaycastHit>& callback,
PxI32 has16BitIndices_, const void* tris, const PxVec3* verts,
const PxVec3& origin, const PxVec3& dir, PxReal maxT_, bool bothSides, const PxVec3* inflate)
: outerCallback(callback), has16BitIndices(has16BitIndices_),
mTris(tris), mVerts(verts), mInflate(inflate), rayCollider(origin, dir, bothSides, geomEpsilon),
maxT(maxT_), closestMode(callback.inClosestMode())
{
PX_ASSERT(closestHit.distance == PX_MAX_REAL);
hadClosestHit = false;
if (tInflate)
inflateV = V3LoadU(*mInflate);
rayOriginV = V3LoadU(rayCollider.mOrigin);
rayDirV = V3LoadU(rayCollider.mDir);
}
PX_FORCE_INLINE void getVertIndices(PxU32 triIndex, PxU32& i0, PxU32 &i1, PxU32 &i2)
{
if(has16BitIndices)
{
const PxU16* p = reinterpret_cast<const PxU16*>(mTris) + triIndex*3;
i0 = p[0]; i1 = p[1]; i2 = p[2];
}
else
{
const PxU32* p = reinterpret_cast<const PxU32*>(mTris) + triIndex*3;
i0 = p[0]; i1 = p[1]; i2 = p[2];
}
}
virtual PX_FORCE_INLINE bool processResults(PxU32 NumTouched, PxU32* Touched, PxF32& newMaxT)
{
PX_ASSERT(NumTouched > 0);
// Loop through touched leaves
PxGeomRaycastHit tempHit;
for(PxU32 leaf = 0; leaf<NumTouched; leaf++)
{
// Each leaf box has a set of triangles
LeafTriangles currentLeaf;
currentLeaf.Data = Touched[leaf];
PxU32 nbLeafTris = currentLeaf.GetNbTriangles();
PxU32 baseLeafTriIndex = currentLeaf.GetTriangleIndex();
for(PxU32 i = 0; i < nbLeafTris; i++)
{
PxU32 i0, i1, i2;
const PxU32 triangleIndex = baseLeafTriIndex+i;
getVertIndices(triangleIndex, i0, i1, i2);
const PxVec3& v0 = mVerts[i0], &v1 = mVerts[i1], &v2 = mVerts[i2];
const PxU32 vinds[3] = { i0, i1, i2 };
if (tRayTest)
{
PxIntBool overlap;
if (tInflate)
{
// AP: mesh skew is already included here (ray is pre-transformed)
Vec3V v0v = V3LoadU(v0), v1v = V3LoadU(v1), v2v = V3LoadU(v2);
Vec3V minB = V3Min(V3Min(v0v, v1v), v2v), maxB = V3Max(V3Max(v0v, v1v), v2v);
// PT: we add an epsilon to max distance, to make sure we don't reject triangles that are just at the same
// distance as best triangle so far. We need to keep all of these to make sure we return the one with the
// best normal.
const float relativeEpsilon = GU_EPSILON_SAME_DISTANCE * PxMax(1.0f, maxT);
FloatV tNear, tFar;
overlap = intersectRayAABB2(
V3Sub(minB, inflateV), V3Add(maxB, inflateV), rayOriginV, rayDirV, FLoad(maxT+relativeEpsilon), tNear, tFar);
if (overlap)
{
// can't clip to tFar here because hitting the AABB doesn't guarantee that we can clip
// (since we can still miss the actual tri)
tempHit.distance = maxT;
tempHit.faceIndex = triangleIndex;
tempHit.u = tempHit.v = 0.0f;
}
} else
overlap = rayCollider.overlap(v0, v1, v2, tempHit) && tempHit.distance <= maxT;
if(!overlap)
continue;
}
tempHit.faceIndex = triangleIndex;
tempHit.flags = PxHitFlag::ePOSITION;
// Intersection point is valid if dist < segment's length
// We know dist>0 so we can use integers
if (closestMode)
{
if(tempHit.distance < closestHit.distance)
{
closestHit = tempHit;
newMaxT = PxMin(tempHit.distance, newMaxT);
cv0 = v0; cv1 = v1; cv2 = v2;
cis[0] = vinds[0]; cis[1] = vinds[1]; cis[2] = vinds[2];
hadClosestHit = true;
}
} else
{
PxReal shrunkMaxT = newMaxT;
PxAgain again = outerCallback.processHit(tempHit, v0, v1, v2, shrunkMaxT, vinds);
if (!again)
return false;
if (shrunkMaxT < newMaxT)
{
newMaxT = shrunkMaxT;
maxT = shrunkMaxT;
}
}
if (outerCallback.inAnyMode()) // early out if in ANY mode
return false;
}
} // for(PxU32 leaf = 0; leaf<NumTouched; leaf++)
return true;
}
virtual bool processResults(PxU32 numTouched, PxU32* touched)
{
PxF32 dummy;
return RayRTreeCallback::processResults(numTouched, touched, dummy);
}
virtual ~RayRTreeCallback()
{
if (hadClosestHit)
{
PX_ASSERT(outerCallback.inClosestMode());
outerCallback.processHit(closestHit, cv0, cv1, cv2, maxT, cis);
}
}
private:
RayRTreeCallback& operator=(const RayRTreeCallback&);
};
#if PX_VC
#pragma warning(pop)
#endif
void MeshRayCollider::collideOBB(
const Box& obb, bool bothTriangleSidesCollide, const RTreeTriangleMesh* mi, MeshHitCallback<PxGeomRaycastHit>& callback,
bool checkObbIsAligned)
{
const PxU32 maxResults = RTREE_N; // maxResults=rtree page size for more efficient early out
PxU32 buf[maxResults];
RayRTreeCallback<false, false> rTreeCallback(
mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(),
PxVec3(0), PxVec3(0), 0.0f, bothTriangleSidesCollide, NULL);
if (checkObbIsAligned && PxAbs(PxQuat(obb.rot).w) > 0.9999f)
{
PxVec3 aabbExtents = obb.computeAABBExtent();
mi->getRTree().traverseAABB(obb.center - aabbExtents, obb.center + aabbExtents, maxResults, buf, &rTreeCallback);
} else
mi->getRTree().traverseOBB(obb, maxResults, buf, &rTreeCallback);
}
template <int tInflate, int tRayTest>
void MeshRayCollider::collide(
const PxVec3& orig, const PxVec3& dir, PxReal maxT, bool bothSides,
const RTreeTriangleMesh* mi, MeshHitCallback<PxGeomRaycastHit>& callback,
const PxVec3* inflate)
{
const PxU32 maxResults = RTREE_N; // maxResults=rtree page size for more efficient early out
PxU32 buf[maxResults];
if (maxT == 0.0f) // AABB traversal path
{
RayRTreeCallback<tInflate, false> rTreeCallback(
mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(),
orig, dir, maxT, bothSides, inflate);
PxVec3 inflate1 = tInflate ? *inflate : PxVec3(0); // both maxT and inflate can be zero, so need to check tInflate
mi->getRTree().traverseAABB(orig-inflate1, orig+inflate1, maxResults, buf, &rTreeCallback);
}
else // ray traversal path
{
RayRTreeCallback<tInflate, tRayTest> rTreeCallback(
mi->getGeomEpsilon(), callback, mi->has16BitIndices(), mi->getTrianglesFast(), mi->getVerticesFast(),
orig, dir, maxT, bothSides, inflate);
mi->getRTree().traverseRay<tInflate>(orig, dir, maxResults, buf, &rTreeCallback, inflate, maxT);
}
}
#define TINST(a,b) \
template void MeshRayCollider::collide<a,b>( \
const PxVec3& orig, const PxVec3& dir, PxReal maxT, bool bothSides, const RTreeTriangleMesh* mesh, \
MeshHitCallback<PxGeomRaycastHit>& callback, const PxVec3* inflate);
TINST(0,0)
TINST(1,0)
TINST(0,1)
TINST(1,1)
#undef TINST
#include "GuRaycastTests.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "GuTriangleMesh.h"
#include "CmScaling.h"
struct RayMeshColliderCallback : public MeshHitCallback<PxGeomRaycastHit>
{
PxU8* mDstBase;
PxU32 mHitNum;
const PxU32 mMaxHits;
const PxU32 mStride;
const PxMeshScale* mScale;
const PxTransform* mPose;
const PxMat34* mWorld2vertexSkew;
PxU32 mHitFlags;
const PxVec3& mRayDir;
bool mIsDoubleSided;
float mDistCoeff;
RayMeshColliderCallback(
CallbackMode::Enum mode_, PxGeomRaycastHit* hits, PxU32 maxHits, PxU32 stride, const PxMeshScale* scale, const PxTransform* pose,
const PxMat34* world2vertexSkew, PxU32 hitFlags, const PxVec3& rayDir, bool isDoubleSided, float distCoeff) :
MeshHitCallback<PxGeomRaycastHit> (mode_),
mDstBase (reinterpret_cast<PxU8*>(hits)),
mHitNum (0),
mMaxHits (maxHits),
mStride (stride),
mScale (scale),
mPose (pose),
mWorld2vertexSkew (world2vertexSkew),
mHitFlags (hitFlags),
mRayDir (rayDir),
mIsDoubleSided (isDoubleSided),
mDistCoeff (distCoeff)
{
}
// return false for early out
virtual bool processHit(
const PxGeomRaycastHit& lHit, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxReal&, const PxU32*)
{
if(mHitNum == mMaxHits)
return false;
const PxReal u = lHit.u, v = lHit.v;
const PxVec3 localImpact = (1.0f - u - v)*lp0 + u*lp1 + v*lp2;
//not worth concatenating to do 1 transform: PxMat34Legacy vertex2worldSkew = scaling.getVertex2WorldSkew(absPose);
// PT: TODO: revisit this for N hits
PxGeomRaycastHit& hit = *reinterpret_cast<PxGeomRaycastHit*>(mDstBase);
hit = lHit;
hit.position = mPose->transform(mScale->transform(localImpact));
hit.flags = PxHitFlag::ePOSITION|PxHitFlag::eUV|PxHitFlag::eFACE_INDEX;
hit.normal = PxVec3(0.0f);
hit.distance *= mDistCoeff;
// Compute additional information if needed
if(mHitFlags & PxHitFlag::eNORMAL)
{
// User requested impact normal
const PxVec3 localNormal = (lp1 - lp0).cross(lp2 - lp0);
if(mWorld2vertexSkew)
{
hit.normal = mWorld2vertexSkew->rotateTranspose(localNormal);
if (mScale->hasNegativeDeterminant())
PxSwap<PxReal>(hit.u, hit.v); // have to swap the UVs though since they were computed in mesh local space
}
else
hit.normal = mPose->rotate(localNormal);
hit.normal.normalize();
// PT: figure out correct normal orientation (DE7458)
// - if the mesh is single-sided the normal should be the regular triangle normal N, regardless of eMESH_BOTH_SIDES.
// - if the mesh is double-sided the correct normal can be either N or -N. We take the one opposed to ray direction.
if(mIsDoubleSided && hit.normal.dot(mRayDir) > 0.0f)
hit.normal = -hit.normal;
hit.flags |= PxHitFlag::eNORMAL;
}
mHitNum++;
mDstBase += mStride;
return true;
}
private:
RayMeshColliderCallback& operator=(const RayMeshColliderCallback&);
};
PxU32 physx::Gu::raycast_triangleMesh_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose,
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist,
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride)
{
PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33);
const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh);
//scaling: transform the ray to vertex space
PxVec3 orig, dir;
PxMat34 world2vertexSkew;
PxMat34* world2vertexSkewP = NULL;
PxReal distCoeff = 1.0f;
if(meshGeom.scale.isIdentity())
{
orig = pose.transformInv(rayOrigin);
dir = pose.rotateInv(rayDir);
}
else
{
world2vertexSkew = meshGeom.scale.getInverse() * pose.getInverse();
world2vertexSkewP = &world2vertexSkew;
orig = world2vertexSkew.transform(rayOrigin);
dir = world2vertexSkew.rotate(rayDir);
{
distCoeff = dir.normalize();
maxDist *= distCoeff;
maxDist += 1e-3f;
distCoeff = 1.0f / distCoeff;
}
}
const bool isDoubleSided = meshGeom.meshFlags.isSet(PxMeshGeometryFlag::eDOUBLE_SIDED);
const bool bothSides = isDoubleSided || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES);
const bool multipleHits = hitFlags & PxHitFlag::eMESH_MULTIPLE;
RayMeshColliderCallback callback(
multipleHits ? CallbackMode::eMULTIPLE : (hitFlags & PxHitFlag::eMESH_ANY ? CallbackMode::eANY : CallbackMode::eCLOSEST),
hits, maxHits, stride, &meshGeom.scale, &pose, world2vertexSkewP, hitFlags, rayDir, isDoubleSided, distCoeff);
MeshRayCollider::collide<0, 1>(orig, dir, maxDist, bothSides, static_cast<const RTreeTriangleMesh*>(meshData), callback, NULL);
return callback.mHitNum;
}
/**
\brief returns indices for the largest axis and 2 other axii
*/
PX_FORCE_INLINE PxU32 largestAxis(const PxVec3& v, PxU32& other1, PxU32& other2)
{
if (v.x >= PxMax(v.y, v.z))
{
other1 = 1;
other2 = 2;
return 0;
}
else if (v.y >= v.z)
{
other1 = 0;
other2 = 2;
return 1;
}
else
{
other1 = 0;
other2 = 1;
return 2;
}
}
static PX_INLINE void computeSweptAABBAroundOBB(
const Box& obb, PxVec3& sweepOrigin, PxVec3& sweepExtents, PxVec3& sweepDir, PxReal& sweepLen)
{
PxU32 other1, other2;
// largest axis of the OBB is the sweep direction, sum of abs of two other is the swept AABB extents
PxU32 lai = largestAxis(obb.extents, other1, other2);
PxVec3 longestAxis = obb.rot[lai]*obb.extents[lai];
PxVec3 absOther1 = obb.rot[other1].abs()*obb.extents[other1];
PxVec3 absOther2 = obb.rot[other2].abs()*obb.extents[other2];
sweepOrigin = obb.center - longestAxis;
sweepExtents = absOther1 + absOther2 + PxVec3(GU_MIN_AABB_EXTENT); // see comments for GU_MIN_AABB_EXTENT
sweepLen = 2.0f; // length is already included in longestAxis
sweepDir = longestAxis;
}
enum { eSPHERE, eCAPSULE, eBOX }; // values for tSCB
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#pragma warning( disable : 4512 ) // assignment operator could not be generated
#endif
namespace
{
struct IntersectShapeVsMeshCallback : MeshHitCallback<PxGeomRaycastHit>
{
PX_NOCOPY(IntersectShapeVsMeshCallback)
public:
IntersectShapeVsMeshCallback(const PxMat33& vertexToShapeSkew, LimitedResults* results, bool flipNormal)
: MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE),
mVertexToShapeSkew (vertexToShapeSkew),
mResults (results),
mAnyHits (false),
mFlipNormal (flipNormal)
{
}
virtual ~IntersectShapeVsMeshCallback(){}
const PxMat33& mVertexToShapeSkew; // vertex to box without translation for boxes
LimitedResults* mResults;
bool mAnyHits;
bool mFlipNormal;
PX_FORCE_INLINE bool recordHit(const PxGeomRaycastHit& aHit, PxIntBool hit)
{
if(hit)
{
mAnyHits = true;
if(mResults)
mResults->add(aHit.faceIndex);
else
return false; // abort traversal if we are only interested in firstContact (mResults is NULL)
}
return true; // if we are here, either no triangles were hit or multiple results are expected => continue traversal
}
};
template<bool tScaleIsIdentity>
struct IntersectSphereVsMeshCallback : IntersectShapeVsMeshCallback
{
IntersectSphereVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {}
virtual ~IntersectSphereVsMeshCallback(){}
PxF32 mMinDist2;
PxVec3 mLocalCenter; // PT: sphere center in local/mesh space
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*)
{
const Vec3V v0 = V3LoadU(tScaleIsIdentity ? av0 : mVertexToShapeSkew * av0);
const Vec3V v1 = V3LoadU(tScaleIsIdentity ? av1 : mVertexToShapeSkew * (mFlipNormal ? av2 : av1));
const Vec3V v2 = V3LoadU(tScaleIsIdentity ? av2 : mVertexToShapeSkew * (mFlipNormal ? av1 : av2));
FloatV dummy1, dummy2;
Vec3V closestP;
PxReal dist2;
FStore(distancePointTriangleSquared(V3LoadU(mLocalCenter), v0, v1, v2, dummy1, dummy2, closestP), &dist2);
return recordHit(aHit, dist2 <= mMinDist2);
}
};
template<bool tScaleIsIdentity>
struct IntersectCapsuleVsMeshCallback : IntersectShapeVsMeshCallback
{
IntersectCapsuleVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {}
virtual ~IntersectCapsuleVsMeshCallback(){}
Capsule mLocalCapsule; // PT: capsule in mesh/local space
CapsuleTriangleOverlapData mParams;
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*)
{
bool hit;
if(tScaleIsIdentity)
{
const PxVec3 normal = (av0 - av1).cross(av0 - av2);
hit = intersectCapsuleTriangle(normal, av0, av1, av2, mLocalCapsule, mParams);
}
else
{
const PxVec3 v0 = mVertexToShapeSkew * av0;
const PxVec3 v1 = mVertexToShapeSkew * (mFlipNormal ? av2 : av1);
const PxVec3 v2 = mVertexToShapeSkew * (mFlipNormal ? av1 : av2);
const PxVec3 normal = (v0 - v1).cross(v0 - v2);
hit = intersectCapsuleTriangle(normal, v0, v1, v2, mLocalCapsule, mParams);
}
return recordHit(aHit, hit);
}
};
template<bool tScaleIsIdentity>
struct IntersectBoxVsMeshCallback : IntersectShapeVsMeshCallback
{
IntersectBoxVsMeshCallback(const PxMat33& m, LimitedResults* r, bool flipNormal) : IntersectShapeVsMeshCallback(m, r, flipNormal) {}
virtual ~IntersectBoxVsMeshCallback(){}
PxMat34 mVertexToBox;
PxVec3p mBoxExtents, mBoxCenter;
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const PxGeomRaycastHit& aHit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal&, const PxU32*)
{
PxVec3p v0, v1, v2;
if(tScaleIsIdentity)
{
v0 = mVertexToShapeSkew * av0; // transform from skewed mesh vertex to box space,
v1 = mVertexToShapeSkew * av1; // this includes inverse skew, inverse mesh shape transform and inverse box basis
v2 = mVertexToShapeSkew * av2;
}
else
{
v0 = mVertexToBox.transform(av0);
v1 = mVertexToBox.transform(mFlipNormal ? av2 : av1);
v2 = mVertexToBox.transform(mFlipNormal ? av1 : av2);
}
// PT: this one is safe because we're using PxVec3p for all parameters
const PxIntBool hit = intersectTriangleBox_Unsafe(mBoxCenter, mBoxExtents, v0, v1, v2);
return recordHit(aHit, hit);
}
};
}
#if PX_VC
#pragma warning(pop)
#endif
template<int tSCB, bool idtMeshScale>
static bool intersectAnyVsMeshT(
const Sphere* worldSphere, const Capsule* worldCapsule, const Box* worldOBB,
const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale,
LimitedResults* results)
{
const bool flipNormal = meshScale.hasNegativeDeterminant();
PxMat33 shapeToVertexSkew, vertexToShapeSkew;
if (!idtMeshScale && tSCB != eBOX)
{
vertexToShapeSkew = toMat33(meshScale);
shapeToVertexSkew = vertexToShapeSkew.getInverse();
}
if (tSCB == eSPHERE)
{
IntersectSphereVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal);
// transform sphere center from world to mesh shape space
const PxVec3 center = meshTransform.transformInv(worldSphere->center);
// callback will transform verts
callback.mLocalCenter = center;
callback.mMinDist2 = worldSphere->radius*worldSphere->radius;
PxVec3 sweepOrigin, sweepDir, sweepExtents;
PxReal sweepLen;
if (!idtMeshScale)
{
// AP: compute a swept AABB around an OBB around a skewed sphere
// TODO: we could do better than an AABB around OBB actually because we can slice off the corners..
const Box worldOBB_(worldSphere->center, PxVec3(worldSphere->radius), PxMat33(PxIdentity));
Box vertexOBB;
computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale);
computeSweptAABBAroundOBB(vertexOBB, sweepOrigin, sweepExtents, sweepDir, sweepLen);
} else
{
sweepOrigin = center;
sweepDir = PxVec3(1.0f,0,0);
sweepLen = 0.0f;
sweepExtents = PxVec3(PxMax(worldSphere->radius, GU_MIN_AABB_EXTENT));
}
MeshRayCollider::collide<1, 1>(sweepOrigin, sweepDir, sweepLen, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback, &sweepExtents);
return callback.mAnyHits;
}
else if (tSCB == eCAPSULE)
{
IntersectCapsuleVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal);
const PxF32 radius = worldCapsule->radius;
// transform world capsule to mesh shape space
callback.mLocalCapsule.p0 = meshTransform.transformInv(worldCapsule->p0);
callback.mLocalCapsule.p1 = meshTransform.transformInv(worldCapsule->p1);
callback.mLocalCapsule.radius = radius;
callback.mParams.init(callback.mLocalCapsule);
if (idtMeshScale)
{
// traverse a sweptAABB around the capsule
const PxVec3 radius3(radius);
MeshRayCollider::collide<1, 0>(callback.mLocalCapsule.p0, callback.mLocalCapsule.p1-callback.mLocalCapsule.p0, 1.0f, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback, &radius3);
}
else
{
// make vertex space OBB
Box vertexOBB;
Box worldOBB_;
worldOBB_.create(*worldCapsule); // AP: potential optimization (meshTransform.inverse is already in callback.mCapsule)
computeVertexSpaceOBB(vertexOBB, worldOBB_, meshTransform, meshScale);
MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback);
}
return callback.mAnyHits;
}
else if (tSCB == eBOX)
{
Box vertexOBB; // query box in vertex space
if (idtMeshScale)
{
// mesh scale is identity - just inverse transform the box without optimization
vertexOBB = transformBoxOrthonormal(*worldOBB, meshTransform.getInverse());
// mesh vertices will be transformed from skewed vertex space directly to box AABB space
// box inverse rotation is baked into the vertexToShapeSkew transform
// if meshScale is not identity, vertexOBB already effectively includes meshScale transform
PxVec3 boxCenter;
getInverse(vertexToShapeSkew, boxCenter, vertexOBB.rot, vertexOBB.center);
IntersectBoxVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal);
callback.mBoxCenter = -boxCenter;
callback.mBoxExtents = worldOBB->extents; // extents do not change
MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback);
return callback.mAnyHits;
} else
{
computeVertexSpaceOBB(vertexOBB, *worldOBB, meshTransform, meshScale);
// mesh scale needs to be included - inverse transform and optimize the box
const PxMat33 vertexToWorldSkew_Rot = PxMat33Padded(meshTransform.q) * toMat33(meshScale);
const PxVec3& vertexToWorldSkew_Trans = meshTransform.p;
PxMat34 tmp;
buildMatrixFromBox(tmp, *worldOBB);
const PxMat34 inv = tmp.getInverseRT();
const PxMat34 _vertexToWorldSkew(vertexToWorldSkew_Rot, vertexToWorldSkew_Trans);
IntersectBoxVsMeshCallback<idtMeshScale> callback(vertexToShapeSkew, results, flipNormal);
callback.mVertexToBox = inv * _vertexToWorldSkew;
callback.mBoxCenter = PxVec3(0.0f);
callback.mBoxExtents = worldOBB->extents; // extents do not change
MeshRayCollider::collideOBB(vertexOBB, true, static_cast<const RTreeTriangleMesh*>(&triMesh), callback);
return callback.mAnyHits;
}
}
else
{
PX_ASSERT(0);
return false;
}
}
template<int tSCB>
static bool intersectAnyVsMesh(
const Sphere* worldSphere, const Capsule* worldCapsule, const Box* worldOBB,
const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale,
LimitedResults* results)
{
PX_ASSERT(triMesh.getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33);
if (meshScale.isIdentity())
return intersectAnyVsMeshT<tSCB, true>(worldSphere, worldCapsule, worldOBB, triMesh, meshTransform, meshScale, results);
else
return intersectAnyVsMeshT<tSCB, false>(worldSphere, worldCapsule, worldOBB, triMesh, meshTransform, meshScale, results);
}
bool physx::Gu::intersectSphereVsMesh_RTREE(const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
return intersectAnyVsMesh<eSPHERE>(&sphere, NULL, NULL, triMesh, meshTransform, meshScale, results);
}
bool physx::Gu::intersectBoxVsMesh_RTREE(const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
return intersectAnyVsMesh<eBOX>(NULL, NULL, &box, triMesh, meshTransform, meshScale, results);
}
bool physx::Gu::intersectCapsuleVsMesh_RTREE(const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
return intersectAnyVsMesh<eCAPSULE>(NULL, &capsule, NULL, triMesh, meshTransform, meshScale, results);
}
void physx::Gu::intersectOBB_RTREE(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned)
{
MeshRayCollider::collideOBB(obb, bothTriangleSidesCollide, static_cast<const RTreeTriangleMesh*>(mesh), callback, checkObbIsAligned);
}
// PT: TODO: refactor/share bits of this
bool physx::Gu::sweepCapsule_MeshGeom_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Capsule& lss, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation)
{
PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33);
const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh);
const Capsule inflatedCapsule(lss.p0, lss.p1, lss.radius + inflation);
const bool isIdentity = triMeshGeom.scale.isIdentity();
bool isDoubleSided = (triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED);
const PxU32 meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES;
// compute sweptAABB
const PxVec3 localP0 = pose.transformInv(inflatedCapsule.p0);
const PxVec3 localP1 = pose.transformInv(inflatedCapsule.p1);
PxVec3 sweepOrigin = (localP0+localP1)*0.5f;
PxVec3 sweepDir = pose.rotateInv(unitDir);
PxVec3 sweepExtents = PxVec3(inflatedCapsule.radius) + (localP0-localP1).abs()*0.5f;
PxReal distance1 = distance;
PxReal distCoeff = 1.0f;
PxMat34 poseWithScale;
if(!isIdentity)
{
poseWithScale = pose * triMeshGeom.scale;
distance1 = computeSweepData(triMeshGeom, sweepOrigin, sweepExtents, sweepDir, distance);
distCoeff = distance1 / distance;
} else
poseWithScale = Matrix34FromTransform(pose);
SweepCapsuleMeshHitCallback callback(sweepHit, poseWithScale, distance, isDoubleSided, inflatedCapsule, unitDir, hitFlags, triMeshGeom.scale.hasNegativeDeterminant(), distCoeff);
MeshRayCollider::collide<1, 1>(sweepOrigin, sweepDir, distance1, true, meshData, callback, &sweepExtents);
if(meshBothSides)
isDoubleSided = true;
return callback.finalizeHit(sweepHit, inflatedCapsule, triMeshGeom, pose, isDoubleSided);
}
#include "GuSweepSharedTests.h"
// PT: TODO: refactor/share bits of this
bool physx::Gu::sweepBox_MeshGeom_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Box& box, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation)
{
PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33);
const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh);
const bool isIdentity = triMeshGeom.scale.isIdentity();
const bool meshBothSides = hitFlags & PxHitFlag::eMESH_BOTH_SIDES;
const bool isDoubleSided = triMeshGeom.meshFlags & PxMeshGeometryFlag::eDOUBLE_SIDED;
PxMat34 meshToWorldSkew;
PxVec3 sweptAABBMeshSpaceExtents, meshSpaceOrigin, meshSpaceDir;
// Input sweep params: geom, pose, box, unitDir, distance
// We convert the origin from world space to mesh local space
// and convert the box+pose to mesh space AABB
if(isIdentity)
{
meshToWorldSkew = Matrix34FromTransform(pose);
const PxMat33Padded worldToMeshRot(pose.q.getConjugate()); // extract rotation matrix from pose.q
meshSpaceOrigin = worldToMeshRot.transform(box.center - pose.p);
meshSpaceDir = worldToMeshRot.transform(unitDir) * distance;
PxMat33 boxToMeshRot = worldToMeshRot * box.rot;
sweptAABBMeshSpaceExtents = boxToMeshRot.column0.abs() * box.extents.x +
boxToMeshRot.column1.abs() * box.extents.y +
boxToMeshRot.column2.abs() * box.extents.z;
}
else
{
meshToWorldSkew = pose * triMeshGeom.scale;
const PxMat33 meshToWorldSkew_Rot = PxMat33Padded(pose.q) * toMat33(triMeshGeom.scale);
const PxVec3& meshToWorldSkew_Trans = pose.p;
PxMat33 worldToVertexSkew_Rot;
PxVec3 worldToVertexSkew_Trans;
getInverse(worldToVertexSkew_Rot, worldToVertexSkew_Trans, meshToWorldSkew_Rot, meshToWorldSkew_Trans);
//make vertex space OBB
Box vertexSpaceBox1;
const PxMat34 worldToVertexSkew(worldToVertexSkew_Rot, worldToVertexSkew_Trans);
vertexSpaceBox1 = transform(worldToVertexSkew, box);
// compute swept aabb
sweptAABBMeshSpaceExtents = vertexSpaceBox1.computeAABBExtent();
meshSpaceOrigin = worldToVertexSkew.transform(box.center);
meshSpaceDir = worldToVertexSkew.rotate(unitDir*distance); // also applies scale to direction/length
}
sweptAABBMeshSpaceExtents += PxVec3(inflation); // inflate the bounds with additive inflation
sweptAABBMeshSpaceExtents *= 1.01f; // fatten the bounds to account for numerical discrepancies
PxReal dirLen = PxMax(meshSpaceDir.magnitude(), 1e-5f);
PxReal distCoeff = 1.0f;
if (!isIdentity)
distCoeff = dirLen / distance;
// Move to AABB space
PxMat34 worldToBox;
computeWorldToBoxMatrix(worldToBox, box);
const bool bothTriangleSidesCollide = isDoubleSided || meshBothSides;
const PxMat34Padded meshToBox = worldToBox*meshToWorldSkew;
const PxTransform boxTransform = box.getTransform();
const PxVec3 localDir = worldToBox.rotate(unitDir);
const PxVec3 localDirDist = localDir*distance;
SweepBoxMeshHitCallback callback( // using eMULTIPLE with shrinkMaxT
CallbackMode::eMULTIPLE, meshToBox, distance, bothTriangleSidesCollide, box, localDirDist, localDir, unitDir, hitFlags, inflation, triMeshGeom.scale.hasNegativeDeterminant(), distCoeff);
MeshRayCollider::collide<1, 1>(meshSpaceOrigin, meshSpaceDir/dirLen, dirLen, bothTriangleSidesCollide, meshData, callback, &sweptAABBMeshSpaceExtents);
return callback.finalizeHit(sweepHit, triMeshGeom, pose, boxTransform, localDir, meshBothSides, isDoubleSided);
}
#include "GuInternal.h"
void physx::Gu::sweepConvex_MeshGeom_RTREE(const TriangleMesh* mesh, const Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool)
{
PX_ASSERT(mesh->getConcreteType()==PxConcreteType::eTRIANGLE_MESH_BVH33);
const RTreeTriangleMesh* meshData = static_cast<const RTreeTriangleMesh*>(mesh);
// create temporal bounds
Box querySweptBox;
computeSweptBox(querySweptBox, hullBox.extents, hullBox.center, hullBox.rot, localDir, distance);
MeshRayCollider::collideOBB(querySweptBox, true, meshData, callback);
}
void physx::Gu::pointMeshDistance_RTREE(const TriangleMesh*, const PxTriangleMeshGeometry&, const PxTransform&, const PxVec3&, float, PxU32&, float&, PxVec3&)
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Point-mesh distance query not supported for BVH33. Please use a BVH34 mesh.\n");
}
| 35,196 | C++ | 37.216069 | 199 | 0.739743 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMeshQuery.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxProfileZone.h"
#include "geometry/PxMeshQuery.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxGeometryQuery.h"
#include "GuInternal.h"
#include "GuEntityReport.h"
#include "GuHeightFieldUtil.h"
#include "GuBoxConversion.h"
#include "GuIntersectionTriangleBox.h"
#include "CmScaling.h"
#include "GuSweepTests.h"
#include "GuMidphaseInterface.h"
#include "foundation/PxFPU.h"
using namespace physx;
using namespace Gu;
namespace {
class HfTrianglesEntityReport2 : public OverlapReport, public LimitedResults
{
public:
HfTrianglesEntityReport2(
PxU32* results, PxU32 maxResults, PxU32 startIndex,
HeightFieldUtil& hfUtil,
const PxVec3& boxCenter, const PxVec3& boxExtents, const PxQuat& boxRot,
bool aabbOverlap) :
LimitedResults (results, maxResults, startIndex),
mHfUtil (hfUtil),
mAABBOverlap (aabbOverlap)
{
buildFrom(mBox2Hf, boxCenter, boxExtents, boxRot);
}
virtual bool reportTouchedTris(PxU32 nbEntities, const PxU32* entities)
{
if(mAABBOverlap)
{
while(nbEntities--)
if(!add(*entities++))
return false;
}
else
{
const PxTransform idt(PxIdentity);
for(PxU32 i=0; i<nbEntities; i++)
{
PxTrianglePadded tri;
mHfUtil.getTriangle(idt, tri, NULL, NULL, entities[i], false, false); // First parameter not needed if local space triangle is enough
// PT: this one is safe because triangle class is padded
if(intersectTriangleBox(mBox2Hf, tri.verts[0], tri.verts[1], tri.verts[2]))
{
if(!add(entities[i]))
return false;
}
}
}
return true;
}
HeightFieldUtil& mHfUtil;
BoxPadded mBox2Hf;
bool mAABBOverlap;
private:
HfTrianglesEntityReport2& operator=(const HfTrianglesEntityReport2&);
};
} // namespace
void physx::PxMeshQuery::getTriangle(const PxTriangleMeshGeometry& triGeom, const PxTransform& globalPose, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices, PxU32* adjacencyIndices)
{
const TriangleMesh* tm = static_cast<const TriangleMesh*>(triGeom.triangleMesh);
PX_CHECK_AND_RETURN(triangleIndex<tm->getNbTriangles(), "PxMeshQuery::getTriangle: triangle index is out of bounds");
if(adjacencyIndices && !tm->getAdjacencies())
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Adjacency information not created. Set buildTriangleAdjacencies on Cooking params.");
const PxMat34 vertex2worldSkew = globalPose * triGeom.scale;
tm->computeWorldTriangle(triangle, triangleIndex, vertex2worldSkew, triGeom.scale.hasNegativeDeterminant(), vertexIndices, adjacencyIndices);
}
///////////////////////////////////////////////////////////////////////////////
void physx::PxMeshQuery::getTriangle(const PxHeightFieldGeometry& hfGeom, const PxTransform& globalPose, PxTriangleID triangleIndex, PxTriangle& triangle, PxU32* vertexIndices, PxU32* adjacencyIndices)
{
HeightFieldUtil hfUtil(hfGeom);
hfUtil.getTriangle(globalPose, triangle, vertexIndices, adjacencyIndices, triangleIndex, true, true);
}
///////////////////////////////////////////////////////////////////////////////
PxU32 physx::PxMeshQuery::findOverlapTriangleMesh(
const PxGeometry& geom, const PxTransform& geomPose,
const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose,
PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, PxGeometryQueryFlags queryFlags)
{
PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD)
LimitedResults limitedResults(results, maxResults, startIndex);
const TriangleMesh* tm = static_cast<const TriangleMesh*>(meshGeom.triangleMesh);
switch(geom.getType())
{
case PxGeometryType::eBOX:
{
const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom);
Box box;
buildFrom(box, geomPose.p, boxGeom.halfExtents, geomPose.q);
Midphase::intersectBoxVsMesh(box, *tm, meshPose, meshGeom.scale, &limitedResults);
break;
}
case PxGeometryType::eCAPSULE:
{
const PxCapsuleGeometry& capsGeom = static_cast<const PxCapsuleGeometry&>(geom);
Capsule capsule;
getCapsule(capsule, capsGeom, geomPose);
Midphase::intersectCapsuleVsMesh(capsule, *tm, meshPose, meshGeom.scale, &limitedResults);
break;
}
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom);
Midphase::intersectSphereVsMesh(Sphere(geomPose.p, sphereGeom.radius), *tm, meshPose, meshGeom.scale, &limitedResults);
break;
}
default:
{
PX_CHECK_MSG(false, "findOverlapTriangleMesh: Only box, capsule and sphere geometries are supported.");
}
}
overflow = limitedResults.mOverflow;
return limitedResults.mNbResults;
}
///////////////////////////////////////////////////////////////////////////////
bool physx::PxMeshQuery::findOverlapTriangleMesh( PxReportCallback<PxGeomIndexPair>& callback,
const PxTriangleMeshGeometry& meshGeom0, const PxTransform& meshPose0,
const PxTriangleMeshGeometry& meshGeom1, const PxTransform& meshPose1,
PxGeometryQueryFlags queryFlags, PxMeshMeshQueryFlags meshMeshFlags, float tolerance)
{
PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD)
const TriangleMesh* tm0 = static_cast<const TriangleMesh*>(meshGeom0.triangleMesh);
const TriangleMesh* tm1 = static_cast<const TriangleMesh*>(meshGeom1.triangleMesh);
// PT: only implemented for BV4
if(!tm0 || !tm1 || tm0->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34 || tm1->getConcreteType()!=PxConcreteType::eTRIANGLE_MESH_BVH34)
return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMeshQuery::findOverlapTriangleMesh(): only available between two BVH34 triangles meshes.");
// PT: ...so we don't need a table like for the other ops, just go straight to BV4
return intersectMeshVsMesh_BV4(callback, *tm0, meshPose0, meshGeom0.scale, *tm1, meshPose1, meshGeom1.scale, meshMeshFlags, tolerance);
}
///////////////////////////////////////////////////////////////////////////////
PxU32 physx::PxMeshQuery::findOverlapHeightField( const PxGeometry& geom, const PxTransform& geomPose,
const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose,
PxU32* results, PxU32 maxResults, PxU32 startIndex, bool& overflow, PxGeometryQueryFlags queryFlags)
{
PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD)
const PxTransform localPose0 = hfPose.transformInv(geomPose);
PxBoxGeometry boxGeom;
switch(geom.getType())
{
case PxGeometryType::eCAPSULE:
{
const PxCapsuleGeometry& cap = static_cast<const PxCapsuleGeometry&>(geom);
boxGeom.halfExtents = PxVec3(cap.halfHeight+cap.radius, cap.radius, cap.radius);
// PT: TODO: improve these bounds - see computeCapsuleBounds
}
break;
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& sph = static_cast<const PxSphereGeometry&>(geom);
boxGeom.halfExtents = PxVec3(sph.radius);
// PT: TODO: could this codepath be improved using the following?
//PxBounds3 localBounds;
//const PxVec3 localSphereCenter = getLocalSphereData(localBounds, pose0, pose1, sphereGeom.radius);
}
break;
case PxGeometryType::eBOX:
boxGeom = static_cast<const PxBoxGeometry&>(geom);
break;
default:
{
overflow = false;
PX_CHECK_AND_RETURN_VAL(false, "findOverlapHeightField: Only box, sphere and capsule queries are supported.", false);
}
}
const bool isAABB = ((localPose0.q.x == 0.0f) && (localPose0.q.y == 0.0f) && (localPose0.q.z == 0.0f));
PxBounds3 bounds;
if (isAABB)
bounds = PxBounds3::centerExtents(localPose0.p, boxGeom.halfExtents);
else
bounds = PxBounds3::poseExtent(localPose0, boxGeom.halfExtents); // box.halfExtents is really extent
HeightFieldUtil hfUtil(hfGeom);
HfTrianglesEntityReport2 entityReport(results, maxResults, startIndex, hfUtil, localPose0.p, boxGeom.halfExtents, localPose0.q, isAABB);
hfUtil.overlapAABBTriangles(bounds, entityReport);
overflow = entityReport.mOverflow;
return entityReport.mNbResults;
}
///////////////////////////////////////////////////////////////////////////////
bool physx::PxMeshQuery::sweep( const PxVec3& unitDir, const PxReal maxDistance,
const PxGeometry& geom, const PxTransform& pose,
PxU32 triangleCount, const PxTriangle* triangles,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags,
const PxU32* cachedIndex, const PxReal inflation, bool doubleSided, PxGeometryQueryFlags queryFlags)
{
PX_SIMD_GUARD_CNDT(queryFlags & PxGeometryQueryFlag::eSIMD_GUARD)
PX_CHECK_AND_RETURN_VAL(pose.isValid(), "PxMeshQuery::sweep(): pose is not valid.", false);
PX_CHECK_AND_RETURN_VAL(unitDir.isFinite(), "PxMeshQuery::sweep(): unitDir is not valid.", false);
PX_CHECK_AND_RETURN_VAL(PxIsFinite(maxDistance), "PxMeshQuery::sweep(): distance is not valid.", false);
PX_CHECK_AND_RETURN_VAL(maxDistance > 0, "PxMeshQuery::sweep(): sweep distance must be greater than 0.", false);
PX_PROFILE_ZONE("MeshQuery.sweep", 0);
const PxReal distance = PxMin(maxDistance, PX_MAX_SWEEP_DISTANCE);
switch(geom.getType())
{
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom);
const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f);
return sweepCapsuleTriangles( triangleCount, triangles, doubleSided, capsuleGeom, pose, unitDir, distance,
sweepHit, cachedIndex, inflation, hitFlags);
}
case PxGeometryType::eCAPSULE:
{
const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom);
return sweepCapsuleTriangles( triangleCount, triangles, doubleSided, capsuleGeom, pose, unitDir, distance,
sweepHit, cachedIndex, inflation, hitFlags);
}
case PxGeometryType::eBOX:
{
const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom);
if(hitFlags & PxHitFlag::ePRECISE_SWEEP)
{
return sweepBoxTriangles_Precise( triangleCount, triangles, doubleSided, boxGeom, pose, unitDir, distance, sweepHit, cachedIndex,
inflation, hitFlags);
}
else
{
return sweepBoxTriangles( triangleCount, triangles, doubleSided, boxGeom, pose, unitDir, distance, sweepHit, cachedIndex,
inflation, hitFlags);
}
}
default:
PX_CHECK_MSG(false, "PxMeshQuery::sweep(): geometry object parameter must be sphere, capsule or box geometry.");
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
| 12,194 | C++ | 37.837579 | 203 | 0.720026 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMesh.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_TRIANGLEMESH_H
#define GU_TRIANGLEMESH_H
#include "foundation/PxIO.h"
#include "geometry/PxTriangle.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "geometry/PxTriangleMesh.h"
#include "GuMeshData.h"
#include "GuCenterExtents.h"
#include "CmScaling.h"
#include "CmRefCountable.h"
#include "common/PxRenderOutput.h"
namespace physx
{
class PxMeshScale;
struct PxTriangleMeshInternalData;
namespace Gu
{
PX_FORCE_INLINE void getVertexRefs(PxU32 triangleIndex, PxU32& vref0, PxU32& vref1, PxU32& vref2, const void* indices, bool has16BitIndices)
{
if(has16BitIndices)
{
const PxU16* inds = reinterpret_cast<const PxU16*>(indices) + triangleIndex*3;
vref0 = inds[0];
vref1 = inds[1];
vref2 = inds[2];
}
else
{
const PxU32* inds = reinterpret_cast<const PxU32*>(indices) + triangleIndex*3;
vref0 = inds[0];
vref1 = inds[1];
vref2 = inds[2];
}
}
class MeshFactory;
#if PX_VC
#pragma warning(push)
#pragma warning(disable: 4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class EdgeList;
class TriangleMesh : public PxTriangleMesh, public PxUserAllocated
{
public:
// PX_SERIALIZATION
TriangleMesh(PxBaseFlags baseFlags) : PxTriangleMesh(baseFlags), mSdfData(PxEmpty) {}
void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); }
virtual void exportExtraData(PxSerializationContext& context);
void importExtraData(PxDeserializationContext& context);
PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream);
virtual void release();
virtual void requiresObjects(PxProcessPxBaseCallback&){}
//~PX_SERIALIZATION
TriangleMesh(MeshFactory* factory, TriangleMeshData& data);
TriangleMesh(const PxTriangleMeshInternalData& data);
virtual ~TriangleMesh();
// PxBase
virtual void onRefCountZero();
//~PxBase
// PxRefCounted
virtual void acquireReference() { Cm::RefCountable_incRefCount(*this); }
virtual PxU32 getReferenceCount() const { return Cm::RefCountable_getRefCount(*this); }
//~PxRefCounted
// PxTriangleMesh
virtual PxU32 getNbVertices() const { return mNbVertices;}
virtual const PxVec3* getVertices() const { return mVertices; }
virtual PxVec3* getVerticesForModification();
virtual PxBounds3 refitBVH();
virtual PxU32 getNbTriangles() const { return mNbTriangles; }
virtual const void* getTriangles() const { return mTriangles; }
virtual PxTriangleMeshFlags getTriangleMeshFlags() const { return PxTriangleMeshFlags(mFlags); }
virtual const PxU32* getTrianglesRemap() const { return mFaceRemap; }
virtual void setPreferSDFProjection(bool preferProjection)
{
if (preferProjection)
mFlags &= PxU8(~PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ);
else
mFlags |= PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ;
}
virtual bool getPreferSDFProjection() const { return !(mFlags & PxTriangleMeshFlag::ePREFER_NO_SDF_PROJ); }
virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const
{
return hasPerTriangleMaterials() ? getMaterials()[triangleIndex] : PxMaterialTableIndex(0xffff);
}
virtual PxBounds3 getLocalBounds() const
{
PX_ASSERT(mAABB.isValid());
return PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents);
}
virtual const PxReal* getSDF() const
{
return mSdfData.mSdf;
}
virtual void getSDFDimensions(PxU32& numX, PxU32& numY, PxU32& numZ) const
{
if(mSdfData.mSdf)
{
numX = mSdfData.mDims.x;
numY = mSdfData.mDims.y;
numZ = mSdfData.mDims.z;
}
else
numX = numY = numZ = 0;
}
virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const
{
mass = mMass; localInertia = mInertia; localCenterOfMass = mLocalCenterOfMass;
}
//~PxTriangleMesh
virtual bool getInternalData(PxTriangleMeshInternalData&, bool) const { return false; }
// PT: this one is just to prevent instancing Gu::TriangleMesh.
// But you should use PxBase::getConcreteType() instead to avoid the virtual call.
virtual PxMeshMidPhase::Enum getMidphaseID() const = 0;
PX_FORCE_INLINE const PxU32* getFaceRemap() const { return mFaceRemap; }
PX_FORCE_INLINE bool has16BitIndices() const { return (mFlags & PxMeshFlag::e16_BIT_INDICES) ? true : false; }
PX_FORCE_INLINE bool hasPerTriangleMaterials() const { return mMaterialIndices != NULL; }
PX_FORCE_INLINE PxU32 getNbVerticesFast() const { return mNbVertices; }
PX_FORCE_INLINE PxU32 getNbTrianglesFast() const { return mNbTriangles; }
PX_FORCE_INLINE const void* getTrianglesFast() const { return mTriangles; }
PX_FORCE_INLINE const PxVec3* getVerticesFast() const { return mVertices; }
PX_FORCE_INLINE const PxU32* getAdjacencies() const { return mAdjacencies; }
PX_FORCE_INLINE PxReal getGeomEpsilon() const { return mGeomEpsilon; }
PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mAABB; }
PX_FORCE_INLINE const PxU16* getMaterials() const { return mMaterialIndices; }
PX_FORCE_INLINE const PxU8* getExtraTrigData() const { return mExtraTrigData; }
PX_FORCE_INLINE const PxU32* getAccumulatedTriangleRef() const { return mAccumulatedTrianglesRef; }
PX_FORCE_INLINE const PxU32* getTriangleReferences() const { return mTrianglesReferences; }
PX_FORCE_INLINE PxU32 getNbTriangleReferences() const { return mNbTrianglesReferences; }
PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const
{
// PT: see compile-time assert in cpp
return static_cast<const CenterExtentsPadded&>(mAABB);
}
PX_FORCE_INLINE void computeWorldTriangle(
PxTriangle& worldTri, PxTriangleID triangleIndex, const PxMat34& worldMatrix, bool flipNormal = false,
PxU32* PX_RESTRICT vertexIndices=NULL, PxU32* PX_RESTRICT adjacencyIndices=NULL) const;
PX_FORCE_INLINE void getLocalTriangle(PxTriangle& localTri, PxTriangleID triangleIndex, bool flipNormal = false) const;
void setMeshFactory(MeshFactory* factory) { mMeshFactory = factory; }
// SDF methods
PX_FORCE_INLINE const SDF& getSdfDataFast() const { return mSdfData; }
//~SDF methods
PX_FORCE_INLINE PxReal getMass() const { return mMass; }
// PT: for debug viz
PX_PHYSX_COMMON_API const Gu::EdgeList* requestEdgeList() const;
protected:
PxU32 mNbVertices;
PxU32 mNbTriangles;
PxVec3* mVertices;
void* mTriangles; //!< 16 (<= 0xffff #vertices) or 32 bit trig indices (mNbTriangles * 3)
// 16 bytes block
// PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading
CenterExtents mAABB;
PxU8* mExtraTrigData; //one per trig
PxReal mGeomEpsilon; //!< see comments in cooking code referencing this variable
// 16 bytes block
/*
low 3 bits (mask: 7) are the edge flags:
b001 = 1 = ignore edge 0 = edge v0-->v1
b010 = 2 = ignore edge 1 = edge v0-->v2
b100 = 4 = ignore edge 2 = edge v1-->v2
*/
PxU8 mFlags; //!< Flag whether indices are 16 or 32 bits wide
//!< Flag whether triangle adajacencies are build
PxU16* mMaterialIndices; //!< the size of the array is numTriangles.
PxU32* mFaceRemap; //!< new faces to old faces mapping (after cleaning, etc). Usage: old = faceRemap[new]
PxU32* mAdjacencies; //!< Adjacency information for each face - 3 adjacent faces
//!< Set to 0xFFFFffff if no adjacent face
MeshFactory* mMeshFactory; // PT: changed to pointer for serialization
mutable Gu::EdgeList* mEdgeList; // PT: for debug viz
PxReal mMass; //this is mass assuming a unit density that can be scaled by instances!
PxMat33 mInertia; //in local space of mesh!
PxVec3 mLocalCenterOfMass; //local space com
public:
// GRB data -------------------------
void* mGRB_triIndices; //!< GRB: GPU-friendly tri indices
// TODO avoroshilov: cooking - adjacency info - duplicated, remove it and use 'mAdjacencies' and 'mExtraTrigData' see GuTriangleMesh.cpp:325
void* mGRB_triAdjacencies; //!< GRB: adjacency data, with BOUNDARY and NONCONVEX flags (flags replace adj indices where applicable)
PxU32* mGRB_faceRemap; //!< GRB : gpu to cpu triangle indice remap
PxU32* mGRB_faceRemapInverse;
Gu::BV32Tree* mGRB_BV32Tree; //!< GRB: BV32 tree
// End of GRB data ------------------
// SDF data -------------------------
SDF mSdfData;
// End of SDF data ------------------
void setAllEdgesActive();
//Vertex mapping data
PxU32* mAccumulatedTrianglesRef;//runsum
PxU32* mTrianglesReferences;
PxU32 mNbTrianglesReferences;
//End of vertex mapping data
};
#if PX_VC
#pragma warning(pop)
#endif
} // namespace Gu
PX_FORCE_INLINE void Gu::TriangleMesh::computeWorldTriangle(PxTriangle& worldTri, PxTriangleID triangleIndex, const PxMat34& worldMatrix, bool flipNormal,
PxU32* PX_RESTRICT vertexIndices, PxU32* PX_RESTRICT adjacencyIndices) const
{
PxU32 vref0, vref1, vref2;
getVertexRefs(triangleIndex, vref0, vref1, vref2, mTriangles, has16BitIndices());
if(flipNormal)
PxSwap<PxU32>(vref1, vref2);
const PxVec3* PX_RESTRICT vertices = getVerticesFast();
worldTri.verts[0] = worldMatrix.transform(vertices[vref0]);
worldTri.verts[1] = worldMatrix.transform(vertices[vref1]);
worldTri.verts[2] = worldMatrix.transform(vertices[vref2]);
if(vertexIndices)
{
vertexIndices[0] = vref0;
vertexIndices[1] = vref1;
vertexIndices[2] = vref2;
}
if(adjacencyIndices)
{
if(mAdjacencies)
{
// PT: TODO: is this correct?
adjacencyIndices[0] = flipNormal ? mAdjacencies[triangleIndex*3 + 2] : mAdjacencies[triangleIndex*3 + 0];
adjacencyIndices[1] = mAdjacencies[triangleIndex*3 + 1];
adjacencyIndices[2] = flipNormal ? mAdjacencies[triangleIndex*3 + 0] : mAdjacencies[triangleIndex*3 + 2];
}
else
{
adjacencyIndices[0] = 0xffffffff;
adjacencyIndices[1] = 0xffffffff;
adjacencyIndices[2] = 0xffffffff;
}
}
}
PX_FORCE_INLINE void Gu::TriangleMesh::getLocalTriangle(PxTriangle& localTri, PxTriangleID triangleIndex, bool flipNormal) const
{
PxU32 vref0, vref1, vref2;
getVertexRefs(triangleIndex, vref0, vref1, vref2, mTriangles, has16BitIndices());
if(flipNormal)
PxSwap<PxU32>(vref1, vref2);
const PxVec3* PX_RESTRICT vertices = getVerticesFast();
localTri.verts[0] = vertices[vref0];
localTri.verts[1] = vertices[vref1];
localTri.verts[2] = vertices[vref2];
}
PX_INLINE float computeSweepData(const PxTriangleMeshGeometry& triMeshGeom, /*const Cm::FastVertex2ShapeScaling& scaling,*/ PxVec3& sweepOrigin, PxVec3& sweepExtents, PxVec3& sweepDir, float distance)
{
PX_ASSERT(!Cm::isEmpty(sweepOrigin, sweepExtents));
const PxVec3 endPt = sweepOrigin + sweepDir*distance;
PX_ASSERT(!Cm::isEmpty(endPt, sweepExtents));
const Cm::FastVertex2ShapeScaling meshScaling(triMeshGeom.scale.getInverse()); // shape to vertex transform
const PxMat33& vertex2ShapeSkew = meshScaling.getVertex2ShapeSkew();
const PxVec3 originBoundsCenter = vertex2ShapeSkew * sweepOrigin;
const PxVec3 originBoundsExtents = Cm::basisExtent(vertex2ShapeSkew.column0, vertex2ShapeSkew.column1, vertex2ShapeSkew.column2, sweepExtents);
sweepOrigin = originBoundsCenter;
sweepExtents = originBoundsExtents;
sweepDir = (vertex2ShapeSkew * endPt) - originBoundsCenter;
return sweepDir.normalizeSafe();
}
PX_FORCE_INLINE const Gu::TriangleMesh* _getMeshData(const PxTriangleMeshGeometry& meshGeom)
{
return static_cast<const Gu::TriangleMesh*>(meshGeom.triangleMesh);
}
}
#endif
| 14,286 | C | 40.054598 | 200 | 0.682066 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_H
#define GU_BV4_H
#include "foundation/PxBounds3.h"
#include "GuBV4Settings.h"
#include "GuCenterExtents.h"
#include "GuTriangle.h"
#include "foundation/PxVecMath.h"
#include "common/PxPhysXCommonConfig.h"
#define V4LoadU_Safe physx::aos::V4LoadU // PT: prefix needed on Linux. Sigh.
#define V4LoadA_Safe V4LoadA
#define V4StoreA_Safe V4StoreA
#define V4StoreU_Safe V4StoreU
namespace physx
{
class PxSerializationContext;
class PxDeserializationContext;
namespace Gu
{
struct VertexPointers
{
const PxVec3* Vertex[3];
};
struct TetrahedronPointers
{
const PxVec3* Vertex[4];
};
// PT: TODO: make this more generic, rename to IndQuad32, refactor with GRB's int4
class IndTetrahedron32 : public physx::PxUserAllocated
{
public:
public:
PX_FORCE_INLINE IndTetrahedron32() {}
PX_FORCE_INLINE IndTetrahedron32(PxU32 r0, PxU32 r1, PxU32 r2, PxU32 r3) { mRef[0] = r0; mRef[1] = r1; mRef[2] = r2; mRef[3] = r3; }
PX_FORCE_INLINE IndTetrahedron32(const IndTetrahedron32& tetrahedron)
{
mRef[0] = tetrahedron.mRef[0];
mRef[1] = tetrahedron.mRef[1];
mRef[2] = tetrahedron.mRef[2];
mRef[3] = tetrahedron.mRef[3];
}
PX_FORCE_INLINE ~IndTetrahedron32() {}
PxU32 mRef[4];
};
PX_COMPILE_TIME_ASSERT(sizeof(IndTetrahedron32) == 16);
// PT: TODO: make this more generic, rename to IndQuad16
class IndTetrahedron16 : public physx::PxUserAllocated
{
public:
public:
PX_FORCE_INLINE IndTetrahedron16() {}
PX_FORCE_INLINE IndTetrahedron16(PxU16 r0, PxU16 r1, PxU16 r2, PxU16 r3) { mRef[0] = r0; mRef[1] = r1; mRef[2] = r2; mRef[3] = r3; }
PX_FORCE_INLINE IndTetrahedron16(const IndTetrahedron16& tetrahedron)
{
mRef[0] = tetrahedron.mRef[0];
mRef[1] = tetrahedron.mRef[1];
mRef[2] = tetrahedron.mRef[2];
mRef[3] = tetrahedron.mRef[3];
}
PX_FORCE_INLINE ~IndTetrahedron16() {}
PxU16 mRef[4];
};
PX_COMPILE_TIME_ASSERT(sizeof(IndTetrahedron16) == 8);
typedef IndexedTriangle32 IndTri32;
typedef IndexedTriangle16 IndTri16;
PX_FORCE_INLINE void getVertexReferences(PxU32& vref0, PxU32& vref1, PxU32& vref2, PxU32 index, const IndTri32* T32, const IndTri16* T16)
{
if(T32)
{
const IndTri32* PX_RESTRICT tri = T32 + index;
vref0 = tri->mRef[0];
vref1 = tri->mRef[1];
vref2 = tri->mRef[2];
}
else
{
const IndTri16* PX_RESTRICT tri = T16 + index;
vref0 = tri->mRef[0];
vref1 = tri->mRef[1];
vref2 = tri->mRef[2];
}
}
PX_FORCE_INLINE void getVertexReferences(PxU32& vref0, PxU32& vref1, PxU32& vref2, PxU32& vref3, PxU32 index, const IndTetrahedron32* T32, const IndTetrahedron16* T16)
{
if(T32)
{
const IndTetrahedron32* PX_RESTRICT tet = T32 + index;
vref0 = tet->mRef[0];
vref1 = tet->mRef[1];
vref2 = tet->mRef[2];
vref3 = tet->mRef[3];
}
else
{
const IndTetrahedron16* PX_RESTRICT tet = T16 + index;
vref0 = tet->mRef[0];
vref1 = tet->mRef[1];
vref2 = tet->mRef[2];
vref3 = tet->mRef[3];
}
}
class SourceMeshBase : public physx::PxUserAllocated
{
public:
enum MeshType
{
TRI_MESH,
TET_MESH,
FORCE_DWORD = 0x7fffffff
};
SourceMeshBase(MeshType meshType);
virtual ~SourceMeshBase();
SourceMeshBase(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
PxU32 mNbVerts;
const PxVec3* mVerts;
PX_FORCE_INLINE PxU32 getNbVertices() const { return mNbVerts; }
PX_FORCE_INLINE const PxVec3* getVerts() const { return mVerts; }
PX_FORCE_INLINE void setNbVertices(PxU32 nb) { mNbVerts = nb; }
PX_FORCE_INLINE void initRemap() { mRemap = NULL; }
PX_FORCE_INLINE const PxU32* getRemap() const { return mRemap; }
PX_FORCE_INLINE void releaseRemap() { PX_FREE(mRemap); }
PX_FORCE_INLINE MeshType getMeshType() const { return mType; }
// PT: TODO: check whether adding these vcalls affected build & runtime performance
virtual PxU32 getNbPrimitives() const = 0;
virtual void remapTopology(const PxU32* order) = 0;
virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV) = 0;
virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox) = 0;
protected:
MeshType mType;
PxU32* mRemap;
};
class SourceMesh : public SourceMeshBase
{
public:
SourceMesh();
virtual ~SourceMesh();
// PX_SERIALIZATION
SourceMesh(const PxEMPTY) : SourceMeshBase(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
void reset();
void operator = (SourceMesh& v);
PxU32 mNbTris;
IndTri32* mTriangles32;
IndTri16* mTriangles16;
PX_FORCE_INLINE PxU32 getNbTriangles() const { return mNbTris; }
PX_FORCE_INLINE const IndTri32* getTris32() const { return mTriangles32; }
PX_FORCE_INLINE const IndTri16* getTris16() const { return mTriangles16; }
PX_FORCE_INLINE void setNbTriangles(PxU32 nb) { mNbTris = nb; }
// SourceMeshBase
virtual PxU32 getNbPrimitives() const { return getNbTriangles(); }
virtual void remapTopology(const PxU32* order);
virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV);
virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox);
//~SourceMeshBase
PX_FORCE_INLINE void setPointers(IndTri32* tris32, IndTri16* tris16, const PxVec3* verts)
{
mTriangles32 = tris32;
mTriangles16 = tris16;
mVerts = verts;
}
bool isValid() const;
PX_FORCE_INLINE void getTriangle(VertexPointers& vp, PxU32 index) const
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, index, mTriangles32, mTriangles16);
vp.Vertex[0] = mVerts + VRef0;
vp.Vertex[1] = mVerts + VRef1;
vp.Vertex[2] = mVerts + VRef2;
}
};
class TetrahedronSourceMesh : public SourceMeshBase
{
public:
TetrahedronSourceMesh();
virtual ~TetrahedronSourceMesh();
// PX_SERIALIZATION
TetrahedronSourceMesh(const PxEMPTY) : SourceMeshBase(TET_MESH) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
void reset();
void operator = (TetrahedronSourceMesh& v);
PxU32 mNbTetrahedrons;
IndTetrahedron32* mTetrahedrons32;
IndTetrahedron16* mTetrahedrons16;
PX_FORCE_INLINE PxU32 getNbTetrahedrons() const { return mNbTetrahedrons; }
PX_FORCE_INLINE const IndTetrahedron32* getTetrahedrons32() const { return mTetrahedrons32; }
PX_FORCE_INLINE const IndTetrahedron16* getTetrahedrons16() const { return mTetrahedrons16; }
PX_FORCE_INLINE void setNbTetrahedrons(PxU32 nb) { mNbTetrahedrons = nb; }
// SourceMeshBase
virtual PxU32 getNbPrimitives() const { return getNbTetrahedrons(); }
virtual void remapTopology(const PxU32* order);
virtual void getPrimitiveBox(const PxU32 primitiveInd, physx::aos::Vec4V& minV, physx::aos::Vec4V& maxV);
virtual void refit(const PxU32 primitiveInd, PxBounds3& refitBox);
//~SourceMeshBase
PX_FORCE_INLINE void setPointers(IndTetrahedron32* tets32, IndTetrahedron16* tets16, const PxVec3* verts)
{
mTetrahedrons32 = tets32;
mTetrahedrons16 = tets16;
mVerts = verts;
}
bool isValid() const;
PX_FORCE_INLINE void getTetrahedron(TetrahedronPointers& vp, PxU32 index) const
{
PxU32 VRef0, VRef1, VRef2, VRef3;
getVertexReferences(VRef0, VRef1, VRef2, VRef3, index, mTetrahedrons32, mTetrahedrons16);
vp.Vertex[0] = mVerts + VRef0;
vp.Vertex[1] = mVerts + VRef1;
vp.Vertex[2] = mVerts + VRef2;
vp.Vertex[3] = mVerts + VRef3;
}
};
struct LocalBounds
{
// PX_SERIALIZATION
LocalBounds(const PxEMPTY) {}
//~PX_SERIALIZATION
LocalBounds() : mCenter(PxVec3(0.0f)), mExtentsMagnitude(0.0f) {}
PxVec3 mCenter;
float mExtentsMagnitude;
PX_FORCE_INLINE void init(const PxBounds3& bounds)
{
mCenter = bounds.getCenter();
// PT: TODO: compute mag first, then multiplies by 0.5f (TA34704)
mExtentsMagnitude = bounds.getExtents().magnitude();
}
};
class QuantizedAABB
{
public:
struct Data
{
PxU16 mExtents; //!< Quantized extents
PxI16 mCenter; //!< Quantized center
};
Data mData[3];
};
PX_COMPILE_TIME_ASSERT(sizeof(QuantizedAABB)==12);
/////
#define GU_BV4_CHILD_OFFSET_SHIFT_COUNT 11
static PX_FORCE_INLINE PxU32 getChildOffset(PxU32 data) { return data>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; }
static PX_FORCE_INLINE PxU32 getChildType(PxU32 data) { return (data>>1)&3; }
template<class BoxType>
struct BVDataPackedT
{
BoxType mAABB;
PxU32 mData;
PX_FORCE_INLINE PxU32 isLeaf() const { return mData&1; }
PX_FORCE_INLINE PxU32 getPrimitive() const { return mData>>1; }
PX_FORCE_INLINE PxU32 getChildOffset() const { return mData>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT;}
PX_FORCE_INLINE PxU32 getChildType() const { return (mData>>1)&3; }
PX_FORCE_INLINE PxU32 getChildData() const { return mData; }
PX_FORCE_INLINE void encodePNS(PxU32 code)
{
PX_ASSERT(code<256);
mData |= code<<3;
}
PX_FORCE_INLINE PxU32 decodePNSNoShift() const { return mData; }
};
typedef BVDataPackedT<QuantizedAABB> BVDataPackedQ;
typedef BVDataPackedT<CenterExtents> BVDataPackedNQ;
// PT: TODO: align class to 16? (TA34704)
class BV4Tree : public physx::PxUserAllocated
{
public:
// PX_SERIALIZATION
BV4Tree(const PxEMPTY);
void exportExtraData(PxSerializationContext&);
void importExtraData(PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
BV4Tree();
BV4Tree(SourceMesh* meshInterface, const PxBounds3& localBounds);
~BV4Tree();
bool refit(PxBounds3& globalBounds, float epsilon);
bool load(PxInputStream& stream, bool mismatch);
void reset();
void operator = (BV4Tree& v);
bool init(SourceMeshBase* meshInterface, const PxBounds3& localBounds);
void release();
SourceMeshBase* mMeshInterface;
LocalBounds mLocalBounds;
PxU32 mNbNodes;
void* mNodes; // PT: BVDataPacked / BVDataSwizzled
PxU32 mInitData;
// PT: the dequantization coeffs are only used for quantized trees
PxVec3 mCenterOrMinCoeff; // PT: dequantization coeff, either for Center or Min (depending on AABB format)
PxVec3 mExtentsOrMaxCoeff; // PT: dequantization coeff, either for Extents or Max (depending on AABB format)
bool mUserAllocated; // PT: please keep these 4 bytes right after mCenterOrMinCoeff/mExtentsOrMaxCoeff for safe V4 loading
bool mQuantized; // PT: true for quantized trees
bool mIsEdgeSet; // PT: equivalent to RTree::IS_EDGE_SET
bool mPadding;
};
} // namespace Gu
}
#endif // GU_BV4_H
| 13,036 | C | 33.039164 | 168 | 0.67375 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuSweepMesh.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_SWEEP_MESH_H
#define GU_SWEEP_MESH_H
#include "GuMidphaseInterface.h"
#include "GuVecConvexHull.h"
namespace physx
{
namespace Gu
{
// PT: intermediate class containing shared bits of code & members
struct SweepShapeMeshHitCallback : MeshHitCallback<PxGeomRaycastHit>
{
SweepShapeMeshHitCallback(CallbackMode::Enum mode, const PxHitFlags& hitFlags, bool flipNormal, float distCoef);
const PxHitFlags mHitFlags;
bool mStatus; // Default is false, set to true if a valid hit is found. Stays true once true.
bool mInitialOverlap; // Default is false, set to true if an initial overlap hit is found. Reset for each hit.
bool mFlipNormal; // If negative scale is used we need to flip normal
PxReal mDistCoeff; // dist coeff from unscaled to scaled distance
void operator=(const SweepShapeMeshHitCallback&) {}
};
struct SweepCapsuleMeshHitCallback : SweepShapeMeshHitCallback
{
PxGeomSweepHit& mSweepHit;
const PxMat34& mVertexToWorldSkew;
const PxReal mTrueSweepDistance; // max sweep distance that can be used
PxReal mBestAlignmentValue; // best alignment value for triangle normal
PxReal mBestDist; // best distance, not the same as sweepHit.distance, can be shorter by epsilon
const Capsule& mCapsule;
const PxVec3& mUnitDir;
const bool mMeshDoubleSided; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED
const bool mIsSphere;
SweepCapsuleMeshHitCallback(PxGeomSweepHit& sweepHit, const PxMat34& worldMatrix, PxReal distance, bool meshDoubleSided,
const Capsule& capsule, const PxVec3& unitDir, const PxHitFlags& hitFlags, bool flipNormal, float distCoef);
virtual PxAgain processHit(const PxGeomRaycastHit& aHit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal& shrunkMaxT, const PxU32*);
// PT: TODO: unify these operators
void operator=(const SweepCapsuleMeshHitCallback&) {}
bool finalizeHit( PxGeomSweepHit& sweepHit, const Capsule& lss, const PxTriangleMeshGeometry& triMeshGeom,
const PxTransform& pose, bool isDoubleSided) const;
};
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
struct SweepBoxMeshHitCallback : SweepShapeMeshHitCallback
{
const PxMat34Padded& mMeshToBox;
PxReal mDist, mDist0;
physx::aos::FloatV mDistV;
const Box& mBox;
const PxVec3& mLocalDir;
const PxVec3& mWorldUnitDir;
PxReal mInflation;
PxTriangle mHitTriangle;
physx::aos::Vec3V mMinClosestA;
physx::aos::Vec3V mMinNormal;
physx::aos::Vec3V mLocalMotionV;
PxU32 mMinTriangleIndex;
PxVec3 mOneOverDir;
const bool mBothTriangleSidesCollide; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED || PxHitFlag::eMESH_BOTH_SIDES
SweepBoxMeshHitCallback(CallbackMode::Enum mode_, const PxMat34Padded& meshToBox, PxReal distance, bool bothTriangleSidesCollide,
const Box& box, const PxVec3& localMotion, const PxVec3& localDir, const PxVec3& unitDir,
const PxHitFlags& hitFlags, const PxReal inflation, bool flipNormal, float distCoef);
virtual ~SweepBoxMeshHitCallback() {}
virtual PxAgain processHit(const PxGeomRaycastHit& meshHit, const PxVec3& lp0, const PxVec3& lp1, const PxVec3& lp2, PxReal& shrinkMaxT, const PxU32*);
bool finalizeHit( PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const PxTransform& boxTransform, const PxVec3& localDir,
bool meshBothSides, bool isDoubleSided) const;
private:
SweepBoxMeshHitCallback& operator=(const SweepBoxMeshHitCallback&);
};
struct SweepConvexMeshHitCallback : SweepShapeMeshHitCallback
{
PxTriangle mHitTriangle;
ConvexHullV mConvexHull;
physx::aos::PxMatTransformV mMeshToConvex;
physx::aos::PxTransformV mConvexPoseV;
const Cm::FastVertex2ShapeScaling& mMeshScale;
PxGeomSweepHit mSweepHit; // stores either the closest or any hit depending on value of mAnyHit
physx::aos::FloatV mInitialDistance;
physx::aos::Vec3V mConvexSpaceDir; // convexPose.rotateInv(-unit*distance)
PxVec3 mUnitDir;
PxVec3 mMeshSpaceUnitDir;
PxReal mInflation;
const bool mAnyHit;
const bool mBothTriangleSidesCollide; // PT: true if PxMeshGeometryFlag::eDOUBLE_SIDED || PxHitFlag::eMESH_BOTH_SIDES
SweepConvexMeshHitCallback( const ConvexHullData& hull, const PxMeshScale& convexScale, const Cm::FastVertex2ShapeScaling& meshScale,
const PxTransform& convexPose, const PxTransform& meshPose,
const PxVec3& unitDir, const PxReal distance, PxHitFlags hitFlags, const bool bothTriangleSidesCollide, const PxReal inflation,
const bool anyHit, float distCoef);
virtual ~SweepConvexMeshHitCallback() {}
virtual PxAgain processHit(const PxGeomRaycastHit& hit, const PxVec3& av0, const PxVec3& av1, const PxVec3& av2, PxReal& shrunkMaxT, const PxU32*);
bool finalizeHit(PxGeomSweepHit& sweepHit, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose,
const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose,
const PxVec3& unitDir, PxReal inflation,
bool isMtd, bool meshBothSides, bool isDoubleSided, bool bothTriangleSidesCollide);
private:
SweepConvexMeshHitCallback& operator=(const SweepConvexMeshHitCallback&);
};
#if PX_VC
#pragma warning(pop)
#endif
}
}
#endif
| 7,172 | C | 44.398734 | 153 | 0.755159 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_SphereSweep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxMat44.h"
#include "GuBV4.h"
#include "GuBox.h"
#include "GuSphere.h"
#include "GuSweepSphereTriangle.h"
using namespace physx;
using namespace Gu;
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#include "GuBV4_Common.h"
// PT: for sphere-sweeps we use method 3 in %SDKRoot%\InternalDocumentation\GU\Sweep strategies.ppt
namespace
{
// PT: TODO: refactor structure (TA34704)
struct RayParams
{
BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned);
#ifndef GU_BV4_USE_SLABS
BV4_ALIGN16(PxVec3p mData2_PaddedAligned);
BV4_ALIGN16(PxVec3p mFDir_PaddedAligned);
BV4_ALIGN16(PxVec3p mData_PaddedAligned);
#endif
BV4_ALIGN16(PxVec3p mLocalDir_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704)
BV4_ALIGN16(PxVec3p mOrigin_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704)
};
struct SphereSweepParams : RayParams
{
const IndTri32* PX_RESTRICT mTris32;
const IndTri16* PX_RESTRICT mTris16;
const PxVec3* PX_RESTRICT mVerts;
PxVec3 mOriginalExtents_Padded;
RaycastHitInternal mStabbedFace;
PxU32 mBackfaceCulling;
PxU32 mEarlyExit;
PxVec3 mP0, mP1, mP2;
PxVec3 mBestTriNormal;
float mBestAlignmentValue;
float mBestDistance;
float mMaxDist;
// PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; }
PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; }
};
}
#include "GuBV4_AABBAABBSweepTest.h"
// PT: TODO: __fastcall removed to make it compile everywhere. Revisit.
static bool /*__fastcall*/ triSphereSweep(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex, bool nodeSorting=true)
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
const PxVec3& p0 = params->mVerts[VRef0];
const PxVec3& p1 = params->mVerts[VRef1];
const PxVec3& p2 = params->mVerts[VRef2];
PxVec3 normal = (p1 - p0).cross(p2 - p0);
// Backface culling
const bool culled = params->mBackfaceCulling && normal.dot(params->mLocalDir_Padded) > 0.0f;
if(culled)
return false;
const PxTriangle T(p0, p1, p2); // PT: TODO: check potential bad ctor/dtor here (TA34704) <= or avoid creating the tri, not needed anymore
normal.normalize();
// PT: TODO: we lost some perf when switching to PhysX version. Revisit/investigate. (TA34704)
float dist;
bool directHit;
if(!sweepSphereVSTri(T.verts, normal, params->mOrigin_Padded, params->mOriginalExtents_Padded.x, params->mLocalDir_Padded, dist, directHit, true))
return false;
const PxReal alignmentValue = computeAlignmentValue(normal, params->mLocalDir_Padded);
if(keepTriangle(dist, alignmentValue, params->mBestDistance, params->mBestAlignmentValue, params->mMaxDist))
{
params->mStabbedFace.mDistance = dist;
params->mStabbedFace.mTriangleID = primIndex;
params->mP0 = p0;
params->mP1 = p1;
params->mP2 = p2;
params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound
params->mBestAlignmentValue = alignmentValue;
params->mBestTriNormal = normal;
if(nodeSorting)
{
#ifndef GU_BV4_USE_SLABS
setupRayData(params, params->mBestDistance, params->mOrigin_Padded, params->mLocalDir_Padded);
//setupRayData(params, dist, params->mOrigin_Padded, params->mLocalDir_Padded);
#endif
}
return true;
}
//
else if(keepTriangleBasic(dist, params->mBestDistance, params->mMaxDist))
{
params->mStabbedFace.mDistance = dist;
params->mBestDistance = PxMin(params->mBestDistance, dist); // exact lower bound
}
//
return false;
}
namespace
{
class LeafFunction_SphereSweepClosest
{
public:
static PX_FORCE_INLINE void doLeafTest(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
triSphereSweep(params, primIndex);
primIndex++;
}while(nbToGo--);
}
};
class LeafFunction_SphereSweepAny
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(SphereSweepParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(triSphereSweep(params, primIndex))
return 1;
primIndex++;
}while(nbToGo--);
return 0;
}
};
class ImpactFunctionSphere
{
public:
static PX_FORCE_INLINE void computeImpact(PxVec3& impactPos, PxVec3& impactNormal, const Sphere& sphere, const PxVec3& dir, const PxReal t, const PxTrianglePadded& triangle)
{
computeSphereTriImpactData(impactPos, impactNormal, sphere.center, dir, t, triangle);
}
};
}
template<class ParamsT>
static PX_FORCE_INLINE void setupSphereParams(ParamsT* PX_RESTRICT params, const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh, PxU32 flags)
{
params->mOriginalExtents_Padded = PxVec3(sphere.radius);
params->mStabbedFace.mTriangleID = PX_INVALID_U32;
params->mStabbedFace.mDistance = maxDist;
params->mBestDistance = PX_MAX_REAL;
params->mBestAlignmentValue = 2.0f;
params->mMaxDist = maxDist;
setupParamsFlags(params, flags);
setupMeshPointersAndQuantizedCoeffs(params, mesh, tree);
computeLocalRay(params->mLocalDir_Padded, params->mOrigin_Padded, dir, sphere.center, worldm_Aligned);
#ifndef GU_BV4_USE_SLABS
setupRayData(params, maxDist, params->mOrigin_Padded, params->mLocalDir_Padded);
#endif
}
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
#endif
#include "GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h"
#include "GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_KajiyaNoOrder.h"
#include "GuBV4_Slabs_KajiyaOrdered.h"
#endif
#define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER
#define GU_BV4_PROCESS_STREAM_RAY_ORDERED
#include "GuBV4_Internal.h"
PxIntBool BV4_SphereSweepSingle(const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepHit* PX_RESTRICT hit, PxU32 flags)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
SphereSweepParams Params;
setupSphereParams(&Params, sphere, dir, maxDist, &tree, worldm_Aligned, mesh, flags);
if(tree.mNodes)
{
if(Params.mEarlyExit)
processStreamRayNoOrder<1, LeafFunction_SphereSweepAny>(tree, &Params);
else
processStreamRayOrdered<1, LeafFunction_SphereSweepClosest>(tree, &Params);
}
else
doBruteForceTests<LeafFunction_SphereSweepAny, LeafFunction_SphereSweepClosest>(mesh->getNbTriangles(), &Params);
return computeImpactDataT<ImpactFunctionSphere>(sphere, dir, hit, &Params, worldm_Aligned, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0);
}
// PT: sphere sweep callback version - currently not used
namespace
{
struct SphereSweepParamsCB : SphereSweepParams
{
// PT: these new members are only here to call computeImpactDataT during traversal :(
// PT: TODO: most of them may not be needed if we just move sphere to local space before traversal
Sphere mSphere; // Sphere in original space (maybe not local/mesh space)
PxVec3 mDir; // Dir in original space (maybe not local/mesh space)
const PxMat44* mWorldm_Aligned;
PxU32 mFlags;
SweepUnlimitedCallback mCallback;
void* mUserData;
bool mNodeSorting;
};
class LeafFunction_SphereSweepCB
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(SphereSweepParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(triSphereSweep(params, primIndex, params->mNodeSorting))
{
// PT: TODO: in this version we must compute the impact data immediately,
// which is a terrible idea in general, but I'm not sure what else I can do.
SweepHit hit;
const bool b = computeImpactDataT<ImpactFunctionSphere>(params->mSphere, params->mDir, &hit, params, params->mWorldm_Aligned, (params->mFlags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (params->mFlags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0);
PX_ASSERT(b);
PX_UNUSED(b);
reportUnlimitedCallbackHit(params, hit);
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
// PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB().
void BV4_SphereSweepCB(const Sphere& sphere, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
SphereSweepParamsCB Params;
Params.mSphere = sphere;
Params.mDir = dir;
Params.mWorldm_Aligned = worldm_Aligned;
Params.mFlags = flags;
Params.mCallback = callback;
Params.mUserData = userData;
Params.mMaxDist = maxDist;
Params.mNodeSorting = nodeSorting;
setupSphereParams(&Params, sphere, dir, maxDist, &tree, worldm_Aligned, mesh, flags);
PX_ASSERT(!Params.mEarlyExit);
if(tree.mNodes)
{
if(nodeSorting)
processStreamRayOrdered<1, LeafFunction_SphereSweepCB>(tree, &Params);
else
processStreamRayNoOrder<1, LeafFunction_SphereSweepCB>(tree, &Params);
}
else
doBruteForceTests<LeafFunction_SphereSweepCB, LeafFunction_SphereSweepCB>(mesh->getNbTriangles(), &Params);
}
// Old box sweep callback version, using sphere code
namespace
{
struct BoxSweepParamsCB : SphereSweepParams
{
MeshSweepCallback mCallback;
void* mUserData;
};
class ExLeafTestSweepCB
{
public:
static PX_FORCE_INLINE void doLeafTest(BoxSweepParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
{
// const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 };
float dist = params->mStabbedFace.mDistance;
if((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], primIndex, /*vrefs,*/ dist))
return;
if(dist<params->mStabbedFace.mDistance)
{
params->mStabbedFace.mDistance = dist;
#ifndef GU_BV4_USE_SLABS
setupRayData(params, dist, params->mOrigin_Padded, params->mLocalDir_Padded);
#endif
}
}
primIndex++;
}while(nbToGo--);
}
};
}
void BV4_GenericSweepCB_Old(const PxVec3& origin, const PxVec3& extents, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshSweepCallback callback, void* userData)
{
BoxSweepParamsCB Params;
Params.mCallback = callback;
Params.mUserData = userData;
Params.mOriginalExtents_Padded = extents;
Params.mStabbedFace.mTriangleID = PX_INVALID_U32;
Params.mStabbedFace.mDistance = maxDist;
computeLocalRay(Params.mLocalDir_Padded, Params.mOrigin_Padded, dir, origin, worldm_Aligned);
#ifndef GU_BV4_USE_SLABS
setupRayData(&Params, maxDist, Params.mOrigin_Padded, Params.mLocalDir_Padded);
#endif
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
setupMeshPointersAndQuantizedCoeffs(&Params, mesh, &tree);
if(tree.mNodes)
processStreamRayOrdered<1, ExLeafTestSweepCB>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
ExLeafTestSweepCB::doLeafTest(&Params, nbTris);
}
}
| 13,115 | C++ | 32.459184 | 255 | 0.749523 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_KajiyaOrdered.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SLABS_KAJIYA_ORDERED_H
#define GU_BV4_SLABS_KAJIYA_ORDERED_H
#include "GuBVConstants.h"
#ifdef REMOVED
// Kajiya + PNS
template<const int inflateT, class LeafTestT, class ParamsT>
static void BV4_ProcessStreamKajiyaOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
#ifdef BV4_SLABS_SORT
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
#endif
#ifdef BV4_SLABS_FIX
BV4_ALIGN16(float distances4[4]);
#endif
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
#ifdef GU_BV4_QUANTIZED_TREE
const Vec4V minCoeffV = V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x);
const Vec4V maxCoeffV = V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV);
const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV);
const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV);
const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV);
const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV);
const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV);
#endif
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node);
#ifdef GU_BV4_QUANTIZED_TREE
Vec4V minx4a;
Vec4V maxx4a;
OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV)
Vec4V miny4a;
Vec4V maxy4a;
OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV)
Vec4V minz4a;
Vec4V maxz4a;
OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV)
#else
Vec4V minx4a = V4LoadA(tn->mMinX);
Vec4V miny4a = V4LoadA(tn->mMinY);
Vec4V minz4a = V4LoadA(tn->mMinZ);
Vec4V maxx4a = V4LoadA(tn->mMaxX);
Vec4V maxy4a = V4LoadA(tn->mMaxY);
Vec4V maxz4a = V4LoadA(tn->mMaxZ);
#endif
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
#ifdef BV4_SLABS_FIX
if(inflateT)
V4StoreA(maxOfNeasa, &distances4[0]);
#endif
SLABS_TEST2
#ifdef BV4_SLABS_SORT
#ifdef BV4_SLABS_FIX
// PT: for some unknown reason the Linux/OSX compilers fail to understand this version
/* #define DO_LEAF_TEST(x) \
{ \
if(!inflateT) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
} \
else \
{ \
if(distances4[x]<params->mStabbedFace.mDistance) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
} \
} \
}*/
// PT: TODO: check that this version compiles to the same code as above. Redo benchmarks.
#define DO_LEAF_TEST(x) \
{ \
if(!inflateT || distances4[x]<params->mStabbedFace.mDistance + GU_EPSILON_SAME_DISTANCE) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
} \
}
#else
#define DO_LEAF_TEST(x) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
}
#endif
PxU32 code2 = 0;
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
SLABS_PNS
#else
#define DO_LEAF_TEST(x) \
{if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
stack[nb++] = tn->getChildData(x); \
}}
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
#endif
}while(nb);
}
#undef DO_LEAF_TEST
#endif
#ifdef BV4_SLABS_SORT
#ifdef BV4_SLABS_FIX
// PT: for some unknown reason the Linux/OSX compilers fail to understand this version
/* #define DO_LEAF_TEST(x) \
{ \
if(!inflateT) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
} \
else \
{ \
if(distances4[x]<params->mStabbedFace.mDistance) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; \
} \
} \
} \
}*/
// PT: TODO: check that this version compiles to the same code as above. Redo benchmarks.
#define DO_LEAF_TEST(x) \
{ \
if(!inflateT || distances4[x]<params->mStabbedFace.mDistance + GU_EPSILON_SAME_DISTANCE) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; nbHits++; \
} \
} \
}
#else
#define DO_LEAF_TEST(x) \
{ \
if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
code2 |= 1<<x; nbHits++; \
} \
}
#endif
#else
#define DO_LEAF_TEST(x) \
{if(tn->isLeaf(x)) \
{ \
LeafTestT::doLeafTest(params, tn->getPrimitive(x)); \
maxT4 = V4Load(params->mStabbedFace.mDistance); \
} \
else \
{ \
stack[nb++] = tn->getChildData(x); \
}}
#endif
// Kajiya + PNS
template<const int inflateT, class LeafTestT, class ParamsT>
static void BV4_ProcessStreamKajiyaOrderedQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
#ifdef BV4_SLABS_SORT
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
#endif
#ifdef BV4_SLABS_FIX
BV4_ALIGN16(float distances4[4]);
#endif
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
const Vec4V minCoeffV = V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x);
const Vec4V maxCoeffV = V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV);
const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV);
const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV);
const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV);
const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV);
const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV);
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node);
Vec4V minx4a;
Vec4V maxx4a;
OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV)
Vec4V miny4a;
Vec4V maxy4a;
OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV)
Vec4V minz4a;
Vec4V maxz4a;
OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV)
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
#ifdef BV4_SLABS_FIX
if(inflateT)
V4StoreA(maxOfNeasa, &distances4[0]);
#endif
SLABS_TEST2
#ifdef BV4_SLABS_SORT
PxU32 code2 = 0;
PxU32 nbHits = 0;
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
//SLABS_PNS
if(nbHits==1)
{
PNS_BLOCK3(0,1,2,3)
}
else
{
SLABS_PNS
}
#else
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
#endif
}while(nb);
}
// Kajiya + PNS
template<const int inflateT, class LeafTestT, class ParamsT>
static void BV4_ProcessStreamKajiyaOrderedNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedNQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
#ifdef BV4_SLABS_SORT
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
#endif
#ifdef BV4_SLABS_FIX
BV4_ALIGN16(float distances4[4]);
#endif
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node);
Vec4V minx4a = V4LoadA(tn->mMinX);
Vec4V miny4a = V4LoadA(tn->mMinY);
Vec4V minz4a = V4LoadA(tn->mMinZ);
Vec4V maxx4a = V4LoadA(tn->mMaxX);
Vec4V maxy4a = V4LoadA(tn->mMaxY);
Vec4V maxz4a = V4LoadA(tn->mMaxZ);
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
#ifdef BV4_SLABS_FIX
if(inflateT)
V4StoreA(maxOfNeasa, &distances4[0]);
#endif
SLABS_TEST2
#ifdef BV4_SLABS_SORT
PxU32 code2 = 0;
PxU32 nbHits = 0;
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
//SLABS_PNS
if(nbHits==1)
{
PNS_BLOCK3(0,1,2,3)
}
else
{
SLABS_PNS
}
#else
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
#endif
}while(nb);
}
#undef DO_LEAF_TEST
#endif // GU_BV4_SLABS_KAJIYA_ORDERED_H
| 16,434 | C | 27.782837 | 142 | 0.592552 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_SwizzledOrdered.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SLABS_SWIZZLED_ORDERED_H
#define GU_BV4_SLABS_SWIZZLED_ORDERED_H
// Generic + PNS
/* template<class LeafTestT, class ParamsT>
static void BV4_ProcessStreamSwizzledOrdered(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU32 nodeType = getChildType(childData);
const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node);
PxU32 code2 = 0;
BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 0>(code2, tn, params);
BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 1>(code2, tn, params);
if(nodeType>0)
BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 2>(code2, tn, params);
if(nodeType>1)
BV4_ProcessNodeOrdered2_Swizzled<LeafTestT, 3>(code2, tn, params);
SLABS_PNS
}while(nb);
}*/
// Generic + PNS
template<class LeafTestT, class ParamsT>
static void BV4_ProcessStreamSwizzledOrderedQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU32 nodeType = getChildType(childData);
const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node);
PxU32 code2 = 0;
BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 0>(code2, tn, params);
BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 1>(code2, tn, params);
if(nodeType>0)
BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 2>(code2, tn, params);
if(nodeType>1)
BV4_ProcessNodeOrdered2_SwizzledQ<LeafTestT, 3>(code2, tn, params);
SLABS_PNS
}while(nb);
}
// Generic + PNS
template<class LeafTestT, class ParamsT>
static void BV4_ProcessStreamSwizzledOrderedNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedNQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
const PxU32* tmp = reinterpret_cast<const PxU32*>(¶ms->mLocalDir_Padded);
const PxU32 X = tmp[0]>>31;
const PxU32 Y = tmp[1]>>31;
const PxU32 Z = tmp[2]>>31;
// const PxU32 X = PX_IR(params->mLocalDir_Padded.x)>>31;
// const PxU32 Y = PX_IR(params->mLocalDir_Padded.y)>>31;
// const PxU32 Z = PX_IR(params->mLocalDir_Padded.z)>>31;
const PxU32 bitIndex = 3+(Z|(Y<<1)|(X<<2));
const PxU32 dirMask = 1u<<bitIndex;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const PxU32 nodeType = getChildType(childData);
const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node);
PxU32 code2 = 0;
BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 0>(code2, tn, params);
BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 1>(code2, tn, params);
if(nodeType>0)
BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 2>(code2, tn, params);
if(nodeType>1)
BV4_ProcessNodeOrdered2_SwizzledNQ<LeafTestT, 3>(code2, tn, params);
SLABS_PNS
}while(nb);
}
#endif // GU_BV4_SLABS_SWIZZLED_ORDERED_H
| 5,831 | C | 36.146497 | 132 | 0.716344 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxOverlap.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
using namespace physx;
using namespace Gu;
using namespace physx::aos;
#include "GuInternal.h"
#include "GuDistancePointSegment.h"
#include "GuIntersectionCapsuleTriangle.h"
#include "GuBV4_BoxOverlap_Internal.h"
#include "GuBV4_BoxBoxOverlapTest.h"
// Box overlap any
struct OBBParams : OBBTestParams
{
const IndTri32* PX_RESTRICT mTris32;
const IndTri16* PX_RESTRICT mTris16;
const PxVec3* PX_RESTRICT mVerts;
PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space
PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space
};
struct OBBTetParams : OBBTestParams
{
const IndTetrahedron32* PX_RESTRICT mTets32;
const IndTetrahedron16* PX_RESTRICT mTets16;
const PxVec3* PX_RESTRICT mVerts;
PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space
PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space
};
// PT: TODO: this used to be inlined so we lost some perf by moving to PhysX's version. Revisit. (TA34704)
PxIntBool intersectTriangleBoxBV4(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents);
namespace
{
class LeafFunction_BoxOverlapAny
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
if(intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
return 1;
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
template<class ParamsT>
static PX_FORCE_INLINE void setupBoxParams(ParamsT* PX_RESTRICT params, const Box& localBox, const BV4Tree* PX_RESTRICT tree, const SourceMesh* PX_RESTRICT mesh)
{
invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox);
params->mTBoxToModel_PaddedAligned = localBox.center;
setupMeshPointersAndQuantizedCoeffs(params, mesh, tree);
params->precomputeBoxData(localBox.extents, &localBox.rot);
}
template<class ParamsT>
static PX_FORCE_INLINE void setupBoxParams(ParamsT* PX_RESTRICT params, const Box& localBox, const BV4Tree* PX_RESTRICT tree, const TetrahedronSourceMesh* PX_RESTRICT mesh)
{
invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox);
params->mTBoxToModel_PaddedAligned = localBox.center;
setupMeshPointersAndQuantizedCoeffs(params, mesh, tree);
params->precomputeBoxData(localBox.extents, &localBox.rot);
}
///////////////////////////////////////////////////////////////////////////////
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
#endif
#include "GuBV4_ProcessStreamNoOrder_OBBOBB.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_SwizzledNoOrder.h"
#endif
#define GU_BV4_PROCESS_STREAM_NO_ORDER
#include "GuBV4_Internal.h"
PxIntBool BV4_OverlapBoxAny(const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned)
{
const SourceMesh* PX_RESTRICT mesh =static_cast<const SourceMesh*>(tree.mMeshInterface);
Box localBox;
computeLocalBox(localBox, box, worldm_Aligned);
OBBParams Params;
setupBoxParams(&Params, localBox, &tree, mesh);
if(tree.mNodes)
return processStreamNoOrder<LeafFunction_BoxOverlapAny>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbPrimitives();
PX_ASSERT(nbTris<16);
return LeafFunction_BoxOverlapAny::doLeafTest(&Params, nbTris);
}
}
// Box overlap all
struct OBBParamsAll : OBBParams
{
PxU32 mNbHits;
PxU32 mMaxNbHits;
PxU32* mHits;
};
namespace
{
class LeafFunction_BoxOverlapAll
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(OBBParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
if(intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
OBBParamsAll* ParamsAll = static_cast<OBBParamsAll*>(params);
if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits)
return 1;
ParamsAll->mHits[ParamsAll->mNbHits] = primIndex;
ParamsAll->mNbHits++;
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
PxU32 BV4_OverlapBoxAll(const Box& box, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
Box localBox;
computeLocalBox(localBox, box, worldm_Aligned);
OBBParamsAll Params;
Params.mNbHits = 0;
Params.mMaxNbHits = size;
Params.mHits = results;
setupBoxParams(&Params, localBox, &tree, mesh);
if(tree.mNodes)
overflow = processStreamNoOrder<LeafFunction_BoxOverlapAll>(tree, &Params)!=0;
else
{
const PxU32 nbTris = mesh->getNbPrimitives();
PX_ASSERT(nbTris<16);
overflow = LeafFunction_BoxOverlapAll::doLeafTest(&Params, nbTris)!=0;
}
return Params.mNbHits;
}
// Box overlap - callback version
struct OBBParamsCB : OBBParams
{
MeshOverlapCallback mCallback;
void* mUserData;
};
struct OBBTetParamsCB : OBBTetParams
{
TetMeshOverlapCallback mCallback;
void* mUserData;
};
namespace
{
class LeafFunction_BoxOverlapCB
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 };
if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], primIndex, vrefs))
return 1;
}
primIndex++;
}while(nbToGo--);
return 0;
}
static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBTetParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2, VRef3;
getVertexReferences(VRef0, VRef1, VRef2, VRef3, primIndex, params->mTets32, params->mTets16);
if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3};
if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs))
return 1;
}
if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef3], params->mVerts[VRef1], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 };
if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs))
return 1;
}
if (intersectTriangleBoxBV4(params->mVerts[VRef1], params->mVerts[VRef3], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 };
if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs))
return 1;
}
if (intersectTriangleBoxBV4(params->mVerts[VRef0], params->mVerts[VRef3], params->mVerts[VRef2], params->mRModelToBox_Padded, params->mTModelToBox_Padded, params->mBoxExtents_PaddedAligned))
{
const PxU32 vrefs[4] = { VRef0, VRef1, VRef2, VRef3 };
if ((params->mCallback)(params->mUserData, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params->mVerts[VRef3], primIndex, vrefs))
return 1;
}
primIndex++;
} while (nbToGo--);
return 0;
}
};
}
void BV4_OverlapBoxCB(const Box& localBox, const BV4Tree& tree, MeshOverlapCallback callback, void* userData)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
OBBParamsCB Params;
Params.mCallback = callback;
Params.mUserData = userData;
setupBoxParams(&Params, localBox, &tree, mesh);
if(tree.mNodes)
processStreamNoOrder<LeafFunction_BoxOverlapCB>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbPrimitives();
PX_ASSERT(nbTris<16);
LeafFunction_BoxOverlapCB::doLeafTest(&Params, nbTris);
}
}
void BV4_OverlapBoxCB(const Box& localBox, const BV4Tree& tree, TetMeshOverlapCallback callback, void* userData)
{
const TetrahedronSourceMesh* PX_RESTRICT mesh = static_cast<TetrahedronSourceMesh*>(tree.mMeshInterface);
OBBTetParamsCB Params;
Params.mCallback = callback;
Params.mUserData = userData;
setupBoxParams(&Params, localBox, &tree, mesh);
if (tree.mNodes)
processStreamNoOrder<LeafFunction_BoxOverlapCB>(tree, &Params);
else
{
const PxU32 nbTetrahedrons = mesh->getNbTetrahedrons();
PX_ASSERT(nbTetrahedrons<16);
LeafFunction_BoxOverlapCB::doLeafTest(&Params, nbTetrahedrons);
}
}
// Capsule overlap any
struct CapsuleParamsAny : OBBParams
{
Capsule mLocalCapsule; // Capsule in mesh space
CapsuleTriangleOverlapData mData;
};
// PT: TODO: try to refactor this one with the PhysX version (TA34704)
static bool CapsuleVsTriangle_SAT(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const CapsuleParamsAny* PX_RESTRICT params)
{
// PX_ASSERT(capsule.p0!=capsule.p1);
{
const PxReal d2 = distancePointSegmentSquaredInternal(params->mLocalCapsule.p0, params->mData.mCapsuleDir, p0);
if(d2<=params->mLocalCapsule.radius*params->mLocalCapsule.radius)
return 1;
}
const PxVec3 N = (p0 - p1).cross(p0 - p2);
if(!testAxis(p0, p1, p2, params->mLocalCapsule, N))
return 0;
const float BDotB = params->mData.mBDotB;
const float oneOverBDotB = params->mData.mOneOverBDotB;
const PxVec3& capP0 = params->mLocalCapsule.p0;
const PxVec3& capDir = params->mData.mCapsuleDir;
if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p0, p1 - p0, capP0, capDir, BDotB, oneOverBDotB)))
return 0;
if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p1, p2 - p1, capP0, capDir, BDotB, oneOverBDotB)))
return 0;
if(!testAxis(p0, p1, p2, params->mLocalCapsule, computeEdgeAxis(p2, p0 - p2, capP0, capDir, BDotB, oneOverBDotB)))
return 0;
return 1;
}
static PxIntBool PX_FORCE_INLINE capsuleTriangle(const CapsuleParamsAny* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
return CapsuleVsTriangle_SAT(params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2], params);
}
namespace
{
class LeafFunction_CapsuleOverlapAny
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const OBBParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(capsuleTriangle(static_cast<const CapsuleParamsAny*>(params), primIndex))
return 1;
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
template<class ParamsT>
static PX_FORCE_INLINE void setupCapsuleParams(ParamsT* PX_RESTRICT params, const Capsule& capsule, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh)
{
computeLocalCapsule(params->mLocalCapsule, capsule, worldm_Aligned);
params->mData.init(params->mLocalCapsule);
Box localBox;
computeBoxAroundCapsule(params->mLocalCapsule, localBox);
setupBoxParams(params, localBox, tree, mesh);
}
PxIntBool BV4_OverlapCapsuleAny(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface);
CapsuleParamsAny Params;
setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
return processStreamNoOrder<LeafFunction_CapsuleOverlapAny>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
return LeafFunction_CapsuleOverlapAny::doLeafTest(&Params, nbTris);
}
}
// Capsule overlap all
struct CapsuleParamsAll : CapsuleParamsAny
{
PxU32 mNbHits;
PxU32 mMaxNbHits;
PxU32* mHits;
};
namespace
{
class LeafFunction_CapsuleOverlapAll
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(OBBParams* PX_RESTRICT params, PxU32 primIndex)
{
CapsuleParamsAll* ParamsAll = static_cast<CapsuleParamsAll*>(params);
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(capsuleTriangle(ParamsAll, primIndex))
{
if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits)
return 1;
ParamsAll->mHits[ParamsAll->mNbHits] = primIndex;
ParamsAll->mNbHits++;
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
PxU32 BV4_OverlapCapsuleAll(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface);
CapsuleParamsAll Params;
Params.mNbHits = 0;
Params.mMaxNbHits = size;
Params.mHits = results;
setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
overflow = processStreamNoOrder<LeafFunction_CapsuleOverlapAll>(tree, &Params)!=0;
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
overflow = LeafFunction_CapsuleOverlapAll::doLeafTest(&Params, nbTris)!=0;
}
return Params.mNbHits;
}
// Capsule overlap - callback version
struct CapsuleParamsCB : CapsuleParamsAny
{
MeshOverlapCallback mCallback;
void* mUserData;
};
namespace
{
class LeafFunction_CapsuleOverlapCB
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const CapsuleParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
const PxVec3& p0 = params->mVerts[VRef0];
const PxVec3& p1 = params->mVerts[VRef1];
const PxVec3& p2 = params->mVerts[VRef2];
if(CapsuleVsTriangle_SAT(p0, p1, p2, params))
{
const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 };
if((params->mCallback)(params->mUserData, p0, p1, p2, primIndex, vrefs))
return 1;
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
// PT: this one is currently not used
void BV4_OverlapCapsuleCB(const Capsule& capsule, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
CapsuleParamsCB Params;
Params.mCallback = callback;
Params.mUserData = userData;
setupCapsuleParams(&Params, capsule, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
processStreamNoOrder<LeafFunction_CapsuleOverlapCB>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
LeafFunction_CapsuleOverlapCB::doLeafTest(&Params, nbTris);
}
}
| 17,269 | C++ | 30.688073 | 211 | 0.742487 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Common.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_COMMON_H
#define GU_BV4_COMMON_H
#include "foundation/PxMat44.h"
#include "geometry/PxTriangle.h"
#include "GuBox.h"
#include "GuSphere.h"
#include "GuCapsule.h"
#include "GuBV4.h"
#define BV4_ALIGN16(x) PX_ALIGN_PREFIX(16) x PX_ALIGN_SUFFIX(16)
namespace physx
{
namespace Gu
{
enum QueryModifierFlag
{
QUERY_MODIFIER_ANY_HIT = (1<<0),
QUERY_MODIFIER_DOUBLE_SIDED = (1<<1),
QUERY_MODIFIER_MESH_BOTH_SIDES = (1<<2)
};
template<class ParamsT>
PX_FORCE_INLINE void setupParamsFlags(ParamsT* PX_RESTRICT params, PxU32 flags)
{
params->mBackfaceCulling = (flags & (QUERY_MODIFIER_DOUBLE_SIDED|QUERY_MODIFIER_MESH_BOTH_SIDES)) ? 0 : 1u;
params->mEarlyExit = flags & QUERY_MODIFIER_ANY_HIT;
}
enum HitCode
{
HIT_NONE = 0, //!< No hit
HIT_CONTINUE = 1, //!< Hit found, but keep looking for closer one
HIT_EXIT = 2 //!< Hit found, you can early-exit (raycast any)
};
class RaycastHitInternal : public physx::PxUserAllocated
{
public:
PX_FORCE_INLINE RaycastHitInternal() {}
PX_FORCE_INLINE ~RaycastHitInternal() {}
float mDistance;
PxU32 mTriangleID;
};
class SweepHit : public physx::PxUserAllocated
{
public:
PX_FORCE_INLINE SweepHit() {}
PX_FORCE_INLINE ~SweepHit() {}
PxU32 mTriangleID; //!< Index of touched face
float mDistance; //!< Impact distance
PxVec3 mPos;
PxVec3 mNormal;
};
typedef HitCode (*MeshRayCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, float dist, float u, float v);
typedef bool (*MeshOverlapCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, const PxU32* vertexIndices);
typedef bool (*TetMeshOverlapCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxVec3& p3, PxU32 tetIndex, const PxU32* vertexIndices);
typedef bool (*MeshSweepCallback) (void* userData, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxU32 triangleIndex, /*const PxU32* vertexIndices,*/ float& dist);
typedef bool (*SweepUnlimitedCallback) (void* userData, const SweepHit& hit);
template<class ParamsT>
PX_FORCE_INLINE void reportUnlimitedCallbackHit(ParamsT* PX_RESTRICT params, const SweepHit& hit)
{
// PT: we can't reuse the MeshSweepCallback here since it's designed for doing the sweep test inside the callback
// (in the user's code) rather than inside the traversal code. So we use the SweepUnlimitedCallback instead to
// report the already fully computed hit to users.
// PT: TODO: this may not be very efficient, since computing the full hit is expensive. If we use this codepath
// to implement the Epic Tweak, the resulting code will not be optimal.
(params->mCallback)(params->mUserData, hit);
// PT: the existing traversal code already shrunk the ray. For real "sweep all" calls we must undo that by reseting the max dist.
// (params->mStabbedFace.mDistance is used in computeImpactDataX code, so we need it before that point - we can't simply avoid
// modifying this value before this point).
if(!params->mNodeSorting)
params->mStabbedFace.mDistance = params->mMaxDist;
}
PX_FORCE_INLINE void invertPRMatrix(PxMat44* PX_RESTRICT dest, const PxMat44* PX_RESTRICT src)
{
const float m30 = src->column3.x;
const float m31 = src->column3.y;
const float m32 = src->column3.z;
const float m00 = src->column0.x;
const float m01 = src->column0.y;
const float m02 = src->column0.z;
dest->column0.x = m00;
dest->column1.x = m01;
dest->column2.x = m02;
dest->column3.x = -(m30*m00 + m31*m01 + m32*m02);
const float m10 = src->column1.x;
const float m11 = src->column1.y;
const float m12 = src->column1.z;
dest->column0.y = m10;
dest->column1.y = m11;
dest->column2.y = m12;
dest->column3.y = -(m30*m10 + m31*m11 + m32*m12);
const float m20 = src->column2.x;
const float m21 = src->column2.y;
const float m22 = src->column2.z;
dest->column0.z = m20;
dest->column1.z = m21;
dest->column2.z = m22;
dest->column3.z = -(m30*m20 + m31*m21 + m32*m22);
dest->column0.w = 0.0f;
dest->column1.w = 0.0f;
dest->column2.w = 0.0f;
dest->column3.w = 1.0f;
}
PX_FORCE_INLINE void invertBoxMatrix(PxMat33& m, PxVec3& t, const Gu::Box& box)
{
const float m30 = box.center.x;
const float m31 = box.center.y;
const float m32 = box.center.z;
const float m00 = box.rot.column0.x;
const float m01 = box.rot.column0.y;
const float m02 = box.rot.column0.z;
m.column0.x = m00;
m.column1.x = m01;
m.column2.x = m02;
t.x = -(m30*m00 + m31*m01 + m32*m02);
const float m10 = box.rot.column1.x;
const float m11 = box.rot.column1.y;
const float m12 = box.rot.column1.z;
m.column0.y = m10;
m.column1.y = m11;
m.column2.y = m12;
t.y = -(m30*m10 + m31*m11 + m32*m12);
const float m20 = box.rot.column2.x;
const float m21 = box.rot.column2.y;
const float m22 = box.rot.column2.z;
m.column0.z = m20;
m.column1.z = m21;
m.column2.z = m22;
t.z = -(m30*m20 + m31*m21 + m32*m22);
}
#ifdef GU_BV4_USE_SLABS
// PT: this class moved here to make things compile with pedantic compilers.
// PT: now duplicated because not easy to do otherwise
struct BVDataSwizzledQ : public physx::PxUserAllocated
{
struct Data
{
PxI16 mMin; //!< Quantized min
PxI16 mMax; //!< Quantized max
};
Data mX[4];
Data mY[4];
Data mZ[4];
PxU32 mData[4];
PX_FORCE_INLINE PxU32 isLeaf(PxU32 i) const { return mData[i]&1; }
PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return mData[i]>>1; }
PX_FORCE_INLINE PxU32 getChildOffset(PxU32 i) const { return mData[i]>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; }
PX_FORCE_INLINE PxU32 getChildType(PxU32 i) const { return (mData[i]>>1)&3; }
PX_FORCE_INLINE PxU32 getChildData(PxU32 i) const { return mData[i]; }
PX_FORCE_INLINE PxU32 decodePNSNoShift(PxU32 i) const { return mData[i]; }
};
struct BVDataSwizzledNQ : public physx::PxUserAllocated
{
float mMinX[4];
float mMinY[4];
float mMinZ[4];
float mMaxX[4];
float mMaxY[4];
float mMaxZ[4];
PxU32 mData[4];
PX_FORCE_INLINE PxU32 isLeaf(PxU32 i) const { return mData[i]&1; }
PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return mData[i]>>1; }
PX_FORCE_INLINE PxU32 getChildOffset(PxU32 i) const { return mData[i]>>GU_BV4_CHILD_OFFSET_SHIFT_COUNT; }
PX_FORCE_INLINE PxU32 getChildType(PxU32 i) const { return (mData[i]>>1)&3; }
PX_FORCE_INLINE PxU32 getChildData(PxU32 i) const { return mData[i]; }
PX_FORCE_INLINE PxU32 decodePNSNoShift(PxU32 i) const { return mData[i]; }
};
#else
#define SSE_CONST4(name, val) static const __declspec(align(16)) PxU32 name[4] = { (val), (val), (val), (val) }
#define SSE_CONST(name) *(const __m128i *)&name
#define SSE_CONSTF(name) *(const __m128 *)&name
#endif
PX_FORCE_INLINE PxU32 getNbPrimitives(PxU32& primIndex)
{
PxU32 NbToGo = (primIndex & 15)-1;
primIndex>>=4;
return NbToGo;
}
template<class ParamsT>
PX_FORCE_INLINE void setupMeshPointersAndQuantizedCoeffs(ParamsT* PX_RESTRICT params, const SourceMesh* PX_RESTRICT mesh, const BV4Tree* PX_RESTRICT tree)
{
using namespace physx::aos;
params->mTris32 = mesh->getTris32();
params->mTris16 = mesh->getTris16();
params->mVerts = mesh->getVerts();
V4StoreA_Safe(V4LoadU_Safe(&tree->mCenterOrMinCoeff.x), ¶ms->mCenterOrMinCoeff_PaddedAligned.x);
V4StoreA_Safe(V4LoadU_Safe(&tree->mExtentsOrMaxCoeff.x), ¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
}
template<class ParamsT>
PX_FORCE_INLINE void setupMeshPointersAndQuantizedCoeffs(ParamsT* PX_RESTRICT params, const TetrahedronSourceMesh* PX_RESTRICT mesh, const BV4Tree* PX_RESTRICT tree)
{
params->mTets32 = mesh->getTetrahedrons32();
params->mTets16 = mesh->getTetrahedrons16();
params->mVerts = mesh->getVerts();
V4StoreA_Safe(V4LoadU_Safe(&tree->mCenterOrMinCoeff.x), ¶ms->mCenterOrMinCoeff_PaddedAligned.x);
V4StoreA_Safe(V4LoadU_Safe(&tree->mExtentsOrMaxCoeff.x), ¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
}
PX_FORCE_INLINE void rotateBox(Gu::Box& dst, const PxMat44& m, const Gu::Box& src)
{
// The extents remain constant
dst.extents = src.extents;
// The center gets x-formed
dst.center = m.transform(src.center);
// Combine rotations
// PT: TODO: revisit.. this is awkward... grab 3x3 part of 4x4 matrix (TA34704)
const PxMat33 tmp( PxVec3(m.column0.x, m.column0.y, m.column0.z),
PxVec3(m.column1.x, m.column1.y, m.column1.z),
PxVec3(m.column2.x, m.column2.y, m.column2.z));
dst.rot = tmp * src.rot;
}
PX_FORCE_INLINE PxVec3 inverseRotate(const PxMat44* PX_RESTRICT src, const PxVec3& p)
{
const float m00 = src->column0.x;
const float m01 = src->column0.y;
const float m02 = src->column0.z;
const float m10 = src->column1.x;
const float m11 = src->column1.y;
const float m12 = src->column1.z;
const float m20 = src->column2.x;
const float m21 = src->column2.y;
const float m22 = src->column2.z;
return PxVec3( m00*p.x + m01*p.y + m02*p.z,
m10*p.x + m11*p.y + m12*p.z,
m20*p.x + m21*p.y + m22*p.z);
}
PX_FORCE_INLINE PxVec3 inverseTransform(const PxMat44* PX_RESTRICT src, const PxVec3& p)
{
const float m30 = src->column3.x;
const float m31 = src->column3.y;
const float m32 = src->column3.z;
const float m00 = src->column0.x;
const float m01 = src->column0.y;
const float m02 = src->column0.z;
const float m10 = src->column1.x;
const float m11 = src->column1.y;
const float m12 = src->column1.z;
const float m20 = src->column2.x;
const float m21 = src->column2.y;
const float m22 = src->column2.z;
return PxVec3( m00*p.x + m01*p.y + m02*p.z -(m30*m00 + m31*m01 + m32*m02),
m10*p.x + m11*p.y + m12*p.z -(m30*m10 + m31*m11 + m32*m12),
m20*p.x + m21*p.y + m22*p.z -(m30*m20 + m31*m21 + m32*m22));
}
PX_FORCE_INLINE void computeLocalRay(PxVec3& localDir, PxVec3& localOrigin, const PxVec3& dir, const PxVec3& origin, const PxMat44* PX_RESTRICT worldm_Aligned)
{
if(worldm_Aligned)
{
localDir = inverseRotate(worldm_Aligned, dir);
localOrigin = inverseTransform(worldm_Aligned, origin);
}
else
{
localDir = dir;
localOrigin = origin;
}
}
PX_FORCE_INLINE void computeLocalSphere(float& radius2, PxVec3& local_center, const Sphere& sphere, const PxMat44* PX_RESTRICT worldm_Aligned)
{
radius2 = sphere.radius * sphere.radius;
if(worldm_Aligned)
{
local_center = inverseTransform(worldm_Aligned, sphere.center);
}
else
{
local_center = sphere.center;
}
}
PX_FORCE_INLINE void computeLocalCapsule(Capsule& localCapsule, const Capsule& capsule, const PxMat44* PX_RESTRICT worldm_Aligned)
{
localCapsule.radius = capsule.radius;
if(worldm_Aligned)
{
localCapsule.p0 = inverseTransform(worldm_Aligned, capsule.p0);
localCapsule.p1 = inverseTransform(worldm_Aligned, capsule.p1);
}
else
{
localCapsule.p0 = capsule.p0;
localCapsule.p1 = capsule.p1;
}
}
PX_FORCE_INLINE void computeLocalBox(Gu::Box& dst, const Gu::Box& src, const PxMat44* PX_RESTRICT worldm_Aligned)
{
if(worldm_Aligned)
{
PxMat44 invWorldM;
invertPRMatrix(&invWorldM, worldm_Aligned);
rotateBox(dst, invWorldM, src);
}
else
{
dst = src; // PT: TODO: check asm for operator= (TA34704)
}
}
template<class ImpactFunctionT, class ShapeT, class ParamsT>
static PX_FORCE_INLINE bool computeImpactDataT(const ShapeT& shape, const PxVec3& dir, SweepHit* PX_RESTRICT hit, const ParamsT* PX_RESTRICT params, const PxMat44* PX_RESTRICT worldm, bool isDoubleSided, bool meshBothSides)
{
if(params->mStabbedFace.mTriangleID==PX_INVALID_U32)
return false; // We didn't touch any triangle
if(hit)
{
const float t = params->getReportDistance();
hit->mTriangleID = params->mStabbedFace.mTriangleID;
hit->mDistance = t;
if(t==0.0f)
{
hit->mPos = PxVec3(0.0f);
hit->mNormal = -dir;
}
else
{
// PT: TODO: we shouldn't compute impact in world space, and in fact moving this to local space is necessary if we want to reuse this for box-sweeps (TA34704)
PxTrianglePadded WP;
if(worldm)
{
WP.verts[0] = worldm->transform(params->mP0);
WP.verts[1] = worldm->transform(params->mP1);
WP.verts[2] = worldm->transform(params->mP2);
}
else
{
WP.verts[0] = params->mP0;
WP.verts[1] = params->mP1;
WP.verts[2] = params->mP2;
}
PxVec3 impactNormal;
ImpactFunctionT::computeImpact(hit->mPos, impactNormal, shape, dir, t, WP);
// PT: by design, returned normal is opposed to the sweep direction.
if(shouldFlipNormal(impactNormal, meshBothSides, isDoubleSided, params->mBestTriNormal, dir))
impactNormal = -impactNormal;
hit->mNormal = impactNormal;
}
}
return true;
}
// PT: we don't create a structure for small meshes with just a few triangles. We use brute-force tests on these.
template<class LeafFunction_AnyT, class LeafFunction_ClosestT, class ParamsT>
void doBruteForceTests(PxU32 nbTris, ParamsT* PX_RESTRICT params)
{
PX_ASSERT(nbTris<16);
if(params->mEarlyExit)
LeafFunction_AnyT::doLeafTest(params, nbTris);
else
LeafFunction_ClosestT::doLeafTest(params, nbTris);
}
#ifndef GU_BV4_USE_SLABS
template<class ParamsT>
PX_FORCE_INLINE void setupRayData(ParamsT* PX_RESTRICT params, float max_dist, const PxVec3& origin, const PxVec3& dir)
{
const float Half = 0.5f*max_dist;
const FloatV HalfV = FLoad(Half);
const Vec4V DataV = V4Scale(V4LoadU(&dir.x), HalfV);
const Vec4V Data2V = V4Add(V4LoadU(&origin.x), DataV);
const Vec4V FDirV = V4Abs(DataV);
V4StoreA_Safe(DataV, ¶ms->mData_PaddedAligned.x);
V4StoreA_Safe(Data2V, ¶ms->mData2_PaddedAligned.x);
V4StoreA_Safe(FDirV, ¶ms->mFDir_PaddedAligned.x);
}
#endif
}
}
#endif // GU_BV4_COMMON_H
| 15,649 | C | 33.170306 | 224 | 0.695891 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4Build.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_BUILD_H
#define GU_BV4_BUILD_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBounds3.h"
#include "GuBV4Settings.h"
namespace physx
{
namespace Gu
{
class BV4Tree;
class SourceMeshBase;
// PT: TODO: refactor with SQ version (TA34704)
class AABBTreeNode : public physx::PxUserAllocated
{
public:
PX_FORCE_INLINE AABBTreeNode() : mPos(0), mNodePrimitives(NULL), mNbPrimitives(0)
#ifdef GU_BV4_FILL_GAPS
, mNextSplit(0)
#endif
{
}
PX_FORCE_INLINE ~AABBTreeNode()
{
mPos = 0;
mNodePrimitives = NULL; // This was just a shortcut to the global list => no release
mNbPrimitives = 0;
}
// Data access
PX_FORCE_INLINE const PxBounds3& getAABB() const { return mBV; }
PX_FORCE_INLINE const AABBTreeNode* getPos() const { return reinterpret_cast<const AABBTreeNode*>(mPos); }
PX_FORCE_INLINE const AABBTreeNode* getNeg() const { const AABBTreeNode* P = getPos(); return P ? P+1 : NULL; }
PX_FORCE_INLINE bool isLeaf() const { return !getPos(); }
PxBounds3 mBV; // Global bounding-volume enclosing all the node-related primitives
size_t mPos; // "Positive" & "Negative" children
// Data access
PX_FORCE_INLINE const PxU32* getPrimitives() const { return mNodePrimitives; }
PX_FORCE_INLINE PxU32 getNbPrimitives() const { return mNbPrimitives; }
PxU32* mNodePrimitives; //!< Node-related primitives (shortcut to a position in mIndices below)
PxU32 mNbPrimitives; //!< Number of primitives for this node
#ifdef GU_BV4_FILL_GAPS
PxU32 mNextSplit;
#endif
};
typedef bool (*WalkingCallback) (const AABBTreeNode* current, PxU32 depth, void* userData);
typedef bool (*WalkingDistanceCallback) (const AABBTreeNode* current, void* userData);
enum BV4_BuildStrategy
{
BV4_SPLATTER_POINTS,
BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER,
BV4_SAH
};
// PT: TODO: refactor with SQ version (TA34704)
class BV4_AABBTree : public physx::PxUserAllocated
{
public:
BV4_AABBTree();
~BV4_AABBTree();
bool buildFromMesh(SourceMeshBase& mesh, PxU32 limit, BV4_BuildStrategy strategy=BV4_SPLATTER_POINTS);
void release();
PX_FORCE_INLINE const PxU32* getIndices() const { return mIndices; } //!< Catch the indices
PX_FORCE_INLINE PxU32 getNbNodes() const { return mTotalNbNodes; } //!< Catch the number of nodes
PX_FORCE_INLINE const PxU32* getPrimitives() const { return mPool->mNodePrimitives; }
PX_FORCE_INLINE PxU32 getNbPrimitives() const { return mPool->mNbPrimitives; }
PX_FORCE_INLINE const AABBTreeNode* getNodes() const { return mPool; }
PX_FORCE_INLINE const PxBounds3& getBV() const { return mPool->mBV; }
PxU32 walk(WalkingCallback callback, void* userData) const;
PxU32 walkDistance(WalkingCallback callback, WalkingDistanceCallback distancCallback, void* userData) const;
private:
PxU32* mIndices; //!< Indices in the app list. Indices are reorganized during build (permutation).
AABBTreeNode* mPool; //!< Linear pool of nodes for complete trees. Null otherwise. [Opcode 1.3]
PxU32 mTotalNbNodes; //!< Number of nodes in the tree.
};
bool BuildBV4Ex(BV4Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivePerLeaf, bool quantized, BV4_BuildStrategy strategy=BV4_SPLATTER_POINTS);
} // namespace Gu
}
#endif // GU_BV4_BUILD_H
| 5,236 | C | 41.233871 | 159 | 0.711803 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SLABS_H
#define GU_BV4_SLABS_H
#include "foundation/PxFPU.h"
#include "GuBV4_Common.h"
#ifdef GU_BV4_USE_SLABS
// PT: contains code for tree-traversal using the swizzled format.
// PT: ray traversal based on Kay & Kajiya's slab intersection code, but using SIMD to do 4 ray-vs-AABB tests at a time.
// PT: other (ordered or unordered) traversals just process one node at a time, similar to the non-swizzled format.
#define BV4_SLABS_FIX
#define BV4_SLABS_SORT
#define PNS_BLOCK3(a, b, c, d) { \
if(code2 & (1<<a)) { stack[nb++] = tn->getChildData(a); } \
if(code2 & (1<<b)) { stack[nb++] = tn->getChildData(b); } \
if(code2 & (1<<c)) { stack[nb++] = tn->getChildData(c); } \
if(code2 & (1<<d)) { stack[nb++] = tn->getChildData(d); } } \
#define OPC_SLABS_GET_MIN_MAX(i) \
const VecI32V minVi = I4LoadXYZW(node->mX[i].mMin, node->mY[i].mMin, node->mZ[i].mMin, 0); \
const Vec4V minCoeffV = V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x); \
Vec4V minV = V4Mul(Vec4V_From_VecI32V(minVi), minCoeffV); \
const VecI32V maxVi = I4LoadXYZW(node->mX[i].mMax, node->mY[i].mMax, node->mZ[i].mMax, 0); \
const Vec4V maxCoeffV = V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x); \
Vec4V maxV = V4Mul(Vec4V_From_VecI32V(maxVi), maxCoeffV); \
#define OPC_SLABS_GET_CEQ(i) \
OPC_SLABS_GET_MIN_MAX(i) \
const FloatV HalfV = FLoad(0.5f); \
const Vec4V centerV = V4Scale(V4Add(maxV, minV), HalfV); \
const Vec4V extentsV = V4Scale(V4Sub(maxV, minV), HalfV);
#define OPC_SLABS_GET_CE2Q(i) \
OPC_SLABS_GET_MIN_MAX(i) \
const Vec4V centerV = V4Add(maxV, minV); \
const Vec4V extentsV = V4Sub(maxV, minV);
#define OPC_SLABS_GET_CENQ(i) \
const FloatV HalfV = FLoad(0.5f); \
const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f); \
const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f); \
const Vec4V centerV = V4Scale(V4Add(maxV, minV), HalfV); \
const Vec4V extentsV = V4Scale(V4Sub(maxV, minV), HalfV);
#define OPC_SLABS_GET_CE2NQ(i) \
const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f); \
const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f); \
const Vec4V centerV = V4Add(maxV, minV); \
const Vec4V extentsV = V4Sub(maxV, minV);
#define OPC_DEQ4(part2xV, part1xV, mMember, minCoeff, maxCoeff) \
{ \
part2xV = V4LoadA(reinterpret_cast<const float*>(tn->mMember)); \
part1xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_And(VecI32V_ReinterpretFrom_Vec4V(part2xV), I4Load(0x0000ffff))); \
part1xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_RightShift(VecI32V_LeftShift(VecI32V_ReinterpretFrom_Vec4V(part1xV),16), 16)); \
part1xV = V4Mul(Vec4V_From_VecI32V(VecI32V_ReinterpretFrom_Vec4V(part1xV)), minCoeff); \
part2xV = Vec4V_ReinterpretFrom_VecI32V(VecI32V_RightShift(VecI32V_ReinterpretFrom_Vec4V(part2xV), 16)); \
part2xV = V4Mul(Vec4V_From_VecI32V(VecI32V_ReinterpretFrom_Vec4V(part2xV)), maxCoeff); \
}
#define SLABS_INIT\
Vec4V maxT4 = V4Load(params->mStabbedFace.mDistance);\
const Vec4V rayP = V4LoadU_Safe(¶ms->mOrigin_Padded.x);\
Vec4V rayD = V4LoadU_Safe(¶ms->mLocalDir_Padded.x);\
const VecU32V raySign = V4U32and(VecU32V_ReinterpretFrom_Vec4V(rayD), signMask);\
const Vec4V rayDAbs = V4Abs(rayD);\
Vec4V rayInvD = Vec4V_ReinterpretFrom_VecU32V(V4U32or(raySign, VecU32V_ReinterpretFrom_Vec4V(V4Max(rayDAbs, epsFloat4))));\
rayD = rayInvD;\
rayInvD = V4RecipFast(rayInvD);\
rayInvD = V4Mul(rayInvD, V4NegMulSub(rayD, rayInvD, twos));\
const Vec4V rayPinvD = V4NegMulSub(rayInvD, rayP, zeroes);\
const Vec4V rayInvDsplatX = V4SplatElement<0>(rayInvD);\
const Vec4V rayInvDsplatY = V4SplatElement<1>(rayInvD);\
const Vec4V rayInvDsplatZ = V4SplatElement<2>(rayInvD);\
const Vec4V rayPinvDsplatX = V4SplatElement<0>(rayPinvD);\
const Vec4V rayPinvDsplatY = V4SplatElement<1>(rayPinvD);\
const Vec4V rayPinvDsplatZ = V4SplatElement<2>(rayPinvD);
#define SLABS_TEST\
const Vec4V tminxa0 = V4MulAdd(minx4a, rayInvDsplatX, rayPinvDsplatX);\
const Vec4V tminya0 = V4MulAdd(miny4a, rayInvDsplatY, rayPinvDsplatY);\
const Vec4V tminza0 = V4MulAdd(minz4a, rayInvDsplatZ, rayPinvDsplatZ);\
const Vec4V tmaxxa0 = V4MulAdd(maxx4a, rayInvDsplatX, rayPinvDsplatX);\
const Vec4V tmaxya0 = V4MulAdd(maxy4a, rayInvDsplatY, rayPinvDsplatY);\
const Vec4V tmaxza0 = V4MulAdd(maxz4a, rayInvDsplatZ, rayPinvDsplatZ);\
const Vec4V tminxa = V4Min(tminxa0, tmaxxa0);\
const Vec4V tmaxxa = V4Max(tminxa0, tmaxxa0);\
const Vec4V tminya = V4Min(tminya0, tmaxya0);\
const Vec4V tmaxya = V4Max(tminya0, tmaxya0);\
const Vec4V tminza = V4Min(tminza0, tmaxza0);\
const Vec4V tmaxza = V4Max(tminza0, tmaxza0);\
const Vec4V maxOfNeasa = V4Max(V4Max(tminxa, tminya), tminza);\
const Vec4V minOfFarsa = V4Min(V4Min(tmaxxa, tmaxya), tmaxza);\
#define SLABS_TEST2\
BoolV ignore4a = V4IsGrtr(epsFloat4, minOfFarsa); /* if tfar is negative, ignore since its a ray, not a line */\
ignore4a = BOr(ignore4a, V4IsGrtr(maxOfNeasa, maxT4)); /* if tnear is over maxT, ignore this result */\
BoolV resa4 = V4IsGrtr(maxOfNeasa, minOfFarsa); /* if 1 => fail */\
resa4 = BOr(resa4, ignore4a);\
const PxU32 code = BGetBitMask(resa4);\
if(code==15)\
continue;
#define SLABS_PNS \
if(code2) \
{ \
if(tn->decodePNSNoShift(0) & dirMask) \
{ \
if(tn->decodePNSNoShift(1) & dirMask) \
{ \
if(tn->decodePNSNoShift(2) & dirMask) \
PNS_BLOCK3(3,2,1,0) \
else \
PNS_BLOCK3(2,3,1,0) \
} \
else \
{ \
if(tn->decodePNSNoShift(2) & dirMask) \
PNS_BLOCK3(3,2,0,1) \
else \
PNS_BLOCK3(2,3,0,1) \
} \
} \
else \
{ \
if(tn->decodePNSNoShift(1) & dirMask) \
{ \
if(tn->decodePNSNoShift(2) & dirMask) \
PNS_BLOCK3(1,0,3,2) \
else \
PNS_BLOCK3(1,0,2,3) \
} \
else \
{ \
if(tn->decodePNSNoShift(2) & dirMask) \
PNS_BLOCK3(0,1,3,2) \
else \
PNS_BLOCK3(0,1,2,3) \
} \
} \
}
#endif // GU_BV4_USE_SLABS
#endif // GU_BV4_SLABS_H
| 8,239 | C | 45.553672 | 129 | 0.66343 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_MeshMeshOverlap.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
using namespace physx;
using namespace Gu;
using namespace physx::aos;
#include "GuBV4_BoxOverlap_Internal.h"
#include "GuBV4_BoxBoxOverlapTest.h"
#define USE_GU_TRI_TRI_OVERLAP_FUNCTION
#ifdef USE_GU_TRI_TRI_OVERLAP_FUNCTION
#include "GuIntersectionTriangleTriangle.h"
#endif
#include "GuDistanceTriangleTriangle.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
#endif
#include "GuBV4_ProcessStreamNoOrder_OBBOBB.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_SwizzledNoOrder.h"
#endif
//#include <stdio.h>
#include "geometry/PxMeshQuery.h"
//#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION
//! if OPC_TRITRI_EPSILON_TEST is true then we do a check (if |dv|<EPSILON then dv=0.0;) else no check is done (which is less robust, but faster)
#define LOCAL_EPSILON 0.000001f
//! Use epsilon value in tri-tri overlap test
#define OPC_TRITRI_EPSILON_TEST
//! sort so that a<=b
#define SORT(a,b) \
if(a>b) \
{ \
const float _c=a; \
a=b; \
b=_c; \
}
//! Edge to edge test based on Franlin Antonio's gem: "Faster Line Segment Intersection", in Graphics Gems III, pp. 199-202
#define EDGE_EDGE_TEST(V0, U0, U1) \
Bx = U0[i0] - U1[i0]; \
By = U0[i1] - U1[i1]; \
Cx = V0[i0] - U0[i0]; \
Cy = V0[i1] - U0[i1]; \
f = Ay*Bx - Ax*By; \
d = By*Cx - Bx*Cy; \
if((f>0.0f && d>=0.0f && d<=f) || (f<0.0f && d<=0.0f && d>=f)) \
{ \
const float e=Ax*Cy - Ay*Cx; \
if(f>0.0f) \
{ \
if(e>=0.0f && e<=f) return 1; \
} \
else \
{ \
if(e<=0.0f && e>=f) return 1; \
} \
}
//! TO BE DOCUMENTED
#define EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2) \
{ \
float Bx,By,Cx,Cy,d,f; \
const float Ax = V1[i0] - V0[i0]; \
const float Ay = V1[i1] - V0[i1]; \
/* test edge U0,U1 against V0,V1 */ \
EDGE_EDGE_TEST(V0, U0, U1); \
/* test edge U1,U2 against V0,V1 */ \
EDGE_EDGE_TEST(V0, U1, U2); \
/* test edge U2,U1 against V0,V1 */ \
EDGE_EDGE_TEST(V0, U2, U0); \
}
//! TO BE DOCUMENTED
#define POINT_IN_TRI(V0, U0, U1, U2) \
{ \
/* is T1 completly inside T2? */ \
/* check if V0 is inside tri(U0,U1,U2) */ \
float a = U1[i1] - U0[i1]; \
float b = -(U1[i0] - U0[i0]); \
float c = -a*U0[i0] - b*U0[i1]; \
float d0 = a*V0[i0] + b*V0[i1] + c; \
\
a = U2[i1] - U1[i1]; \
b = -(U2[i0] - U1[i0]); \
c = -a*U1[i0] - b*U1[i1]; \
const float d1 = a*V0[i0] + b*V0[i1] + c; \
\
a = U0[i1] - U2[i1]; \
b = -(U0[i0] - U2[i0]); \
c = -a*U2[i0] - b*U2[i1]; \
const float d2 = a*V0[i0] + b*V0[i1] + c; \
if(d0*d1>0.0f) \
{ \
if(d0*d2>0.0f) return 1; \
} \
}
static PxU32 CoplanarTriTri(const PxVec3& n, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& u0, const PxVec3& u1, const PxVec3& u2)
{
int i0,i1;
{
float A[3];
/* first project onto an axis-aligned plane, that maximizes the area */
/* of the triangles, compute indices: i0,i1. */
A[0] = fabsf(n.x);
A[1] = fabsf(n.y);
A[2] = fabsf(n.z);
if(A[0]>A[1])
{
if(A[0]>A[2])
{
i0=1; /* A[0] is greatest */
i1=2;
}
else
{
i0=0; /* A[2] is greatest */
i1=1;
}
}
else /* A[0]<=A[1] */
{
if(A[2]>A[1])
{
i0=0; /* A[2] is greatest */
i1=1;
}
else
{
i0=0; /* A[1] is greatest */
i1=2;
}
}
}
/* test all edges of triangle 1 against the edges of triangle 2 */
EDGE_AGAINST_TRI_EDGES(v0, v1, u0, u1, u2);
EDGE_AGAINST_TRI_EDGES(v1, v2, u0, u1, u2);
EDGE_AGAINST_TRI_EDGES(v2, v0, u0, u1, u2);
/* finally, test if tri1 is totally contained in tri2 or vice versa */
POINT_IN_TRI(v0, u0, u1, u2);
POINT_IN_TRI(u0, v0, v1, v2);
return 0;
}
//! TO BE DOCUMENTED
#define NEWCOMPUTE_INTERVALS(VV0, VV1, VV2, D0, D1, D2, D0D1, D0D2, A, B, C, X0, X1) \
{ \
if(D0D1>0.0f) \
{ \
/* here we know that D0D2<=0.0 */ \
/* that is D0, D1 are on the same side, D2 on the other or on the plane */ \
A=VV2; B=(VV0 - VV2)*D2; C=(VV1 - VV2)*D2; X0=D2 - D0; X1=D2 - D1; \
} \
else if(D0D2>0.0f) \
{ \
/* here we know that d0d1<=0.0 */ \
A=VV1; B=(VV0 - VV1)*D1; C=(VV2 - VV1)*D1; X0=D1 - D0; X1=D1 - D2; \
} \
else if(D1*D2>0.0f || D0!=0.0f) \
{ \
/* here we know that d0d1<=0.0 or that D0!=0.0 */ \
A=VV0; B=(VV1 - VV0)*D0; C=(VV2 - VV0)*D0; X0=D0 - D1; X1=D0 - D2; \
} \
else if(D1!=0.0f) \
{ \
A=VV1; B=(VV0 - VV1)*D1; C=(VV2 - VV1)*D1; X0=D1 - D0; X1=D1 - D2; \
} \
else if(D2!=0.0f) \
{ \
A=VV2; B=(VV0 - VV2)*D2; C=(VV1 - VV2)*D2; X0=D2 - D0; X1=D2 - D1; \
} \
else \
{ \
/* triangles are coplanar */ \
return ignoreCoplanar ? 0 : CoplanarTriTri(N1, V0, V1, V2, U0, U1, U2); \
} \
}
//#endif
namespace
{
PX_ALIGN_PREFIX(16)
struct TriangleData
{
PxVec3p mV0, mV1, mV2;
PxVec3p mXXX, mYYY, mZZZ;
//#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION
PxVec3 mNormal;
float mD;
//#endif
PX_FORCE_INLINE void init(const PxVec3& V0, const PxVec3& V1, const PxVec3& V2)
{
// 45 lines of asm (x64)
const Vec4V V0V = V4LoadU(&V0.x);
const Vec4V V1V = V4LoadU(&V1.x);
const Vec4V V2V = V4LoadU(&V2.x);
//#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION
const Vec4V E1V = V4Sub(V1V, V0V);
const Vec4V E2V = V4Sub(V2V, V0V);
const Vec4V NV = V4Cross(E1V, E2V);
const FloatV dV = FNeg(V4Dot3(NV, V0V));
//#endif
V4StoreA(V0V, &mV0.x);
V4StoreA(V1V, &mV1.x);
V4StoreA(V2V, &mV2.x);
//#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION
V4StoreA(NV, &mNormal.x);
FStore(dV, &mD);
//#endif
// 62 lines of asm (x64)
// const PxVec3 E1 = V1 - V0;
// const PxVec3 E2 = V2 - V0;
// const PxVec3 N = E1.cross(E2);
// mV0 = V0;
// mV1 = V1;
// mV2 = V2;
// mNormal = N;
// mD = -N.dot(V0);
const Vec4V tri_xs = V4LoadXYZW(V0.x, V1.x, V2.x, 0.0f);
const Vec4V tri_ys = V4LoadXYZW(V0.y, V1.y, V2.y, 0.0f);
const Vec4V tri_zs = V4LoadXYZW(V0.z, V1.z, V2.z, 0.0f);
V4StoreA(tri_xs, &mXXX.x);
V4StoreA(tri_ys, &mYYY.x);
V4StoreA(tri_zs, &mZZZ.x);
}
}PX_ALIGN_SUFFIX(16);
}
//#ifndef USE_GU_TRI_TRI_OVERLAP_FUNCTION
static PxU32 TriTriOverlap(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar)
{
const PxVec3& V0 = data0.mV0;
const PxVec3& V1 = data0.mV1;
const PxVec3& V2 = data0.mV2;
const PxVec3& U0 = data1.mV0;
const PxVec3& U1 = data1.mV1;
const PxVec3& U2 = data1.mV2;
const PxVec3& N1 = data0.mNormal;
float du0, du1, du2, du0du1, du0du2;
{
const float d1 = data0.mD;
// Put U0,U1,U2 into plane equation 1 to compute signed distances to the plane
du0 = N1.dot(U0) + d1;
du1 = N1.dot(U1) + d1;
du2 = N1.dot(U2) + d1;
// Coplanarity robustness check
#ifdef OPC_TRITRI_EPSILON_TEST
if(fabsf(du0)<LOCAL_EPSILON) du0 = 0.0f;
if(fabsf(du1)<LOCAL_EPSILON) du1 = 0.0f;
if(fabsf(du2)<LOCAL_EPSILON) du2 = 0.0f;
#endif
du0du1 = du0 * du1;
du0du2 = du0 * du2;
if(du0du1>0.0f && du0du2>0.0f) // same sign on all of them + not equal 0 ?
return 0; // no intersection occurs
}
const PxVec3& N2 = data1.mNormal;
float dv0, dv1, dv2, dv0dv1, dv0dv2;
{
const float d2 = data1.mD;
// put V0,V1,V2 into plane equation 2
dv0 = N2.dot(V0) + d2;
dv1 = N2.dot(V1) + d2;
dv2 = N2.dot(V2) + d2;
#ifdef OPC_TRITRI_EPSILON_TEST
if(fabsf(dv0)<LOCAL_EPSILON) dv0 = 0.0f;
if(fabsf(dv1)<LOCAL_EPSILON) dv1 = 0.0f;
if(fabsf(dv2)<LOCAL_EPSILON) dv2 = 0.0f;
#endif
dv0dv1 = dv0 * dv1;
dv0dv2 = dv0 * dv2;
if(dv0dv1>0.0f && dv0dv2>0.0f) // same sign on all of them + not equal 0 ?
return 0; // no intersection occurs
}
// Compute direction of intersection line
// Compute and index to the largest component of D
short index = 0;
{
const PxVec3 D = N1.cross(N2);
float max = fabsf(D[0]);
const float bb = fabsf(D[1]);
const float cc = fabsf(D[2]);
if(bb>max)
{
max=bb;
index=1;
}
if(cc>max)
{
max=cc;
index=2;
}
}
// This is the simplified projection onto L
const float vp0 = V0[index];
const float vp1 = V1[index];
const float vp2 = V2[index];
const float up0 = U0[index];
const float up1 = U1[index];
const float up2 = U2[index];
// Compute interval for triangle 1
float a,b,c,x0,x1;
NEWCOMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,a,b,c,x0,x1);
// Compute interval for triangle 2
float d,e,f,y0,y1;
NEWCOMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,d,e,f,y0,y1);
const float xx=x0*x1;
const float yy=y0*y1;
const float xxyy=xx*yy;
float isect1[2], isect2[2];
float tmp=a*xxyy;
isect1[0]=tmp+b*x1*yy;
isect1[1]=tmp+c*x0*yy;
tmp=d*xxyy;
isect2[0]=tmp+e*xx*y1;
isect2[1]=tmp+f*xx*y0;
SORT(isect1[0],isect1[1]);
SORT(isect2[0],isect2[1]);
if(isect1[1]<isect2[0] || isect2[1]<isect1[0])
return 0;
return 1;
}
//#endif
//////////
static PX_FORCE_INLINE void projectTriangle4(
const TriangleData& data,
const Vec4V& axesX, // axis0x axis1x axis2x axis3x
const Vec4V& axesY, // axis0y axis1y axis2y axis3y
const Vec4V& axesZ, // axis0z axis1z axis2z axis3z
Vec4V& min4,
Vec4V& max4
)
{
Vec4V dp0_4 = V4Mul(V4Load(data.mV0.x), axesX);
dp0_4 = V4MulAdd(V4Load(data.mV0.y), axesY, dp0_4); //dp0_4 = V4Add(dp0_4, V4Mul(V4Load(data.mV0.y), axesY));
dp0_4 = V4MulAdd(V4Load(data.mV0.z), axesZ, dp0_4); //dp0_4 = V4Add(dp0_4, V4Mul(V4Load(data.mV0.z), axesZ));
Vec4V dp1_4 = V4Mul(V4Load(data.mV1.x), axesX);
dp1_4 = V4MulAdd(V4Load(data.mV1.y), axesY, dp1_4); //dp1_4 = V4Add(dp1_4, V4Mul(V4Load(data.mV1.y), axesY));
dp1_4 = V4MulAdd(V4Load(data.mV1.z), axesZ, dp1_4); //dp1_4 = V4Add(dp1_4, V4Mul(V4Load(data.mV1.z), axesZ));
Vec4V dp2_4 = V4Mul(V4Load(data.mV2.x), axesX);
dp2_4 = V4MulAdd(V4Load(data.mV2.y), axesY, dp2_4); //dp2_4 = V4Add(dp2_4, V4Mul(V4Load(data.mV2.y), axesY));
dp2_4 = V4MulAdd(V4Load(data.mV2.z), axesZ, dp2_4); //dp2_4 = V4Add(dp2_4, V4Mul(V4Load(data.mV2.z), axesZ));
min4 = V4Min(V4Min(dp0_4, dp1_4), dp2_4);
max4 = V4Max(V4Max(dp0_4, dp1_4), dp2_4);
}
static PX_FORCE_INLINE PxU32 V4AnyGrtrX(const Vec4V a, const Vec4V b, PxU32 mask)
{
const PxU32 moveMask = BGetBitMask(V4IsGrtr(a, b));
return moveMask & mask;
}
static PX_FORCE_INLINE bool testSepAxis(
const TriangleData& data0,
const TriangleData& data1,
const Vec4V& axesX, // axis0x axis1x axis2x axis3x
const Vec4V& axesY, // axis0y axis1y axis2y axis3y
const Vec4V& axesZ, // axis0z axis1z axis2z axis3z
PxU32 mask
)
{
Vec4V min0, max0;
projectTriangle4(data0, axesX, axesY, axesZ, min0, max0);
Vec4V min1, max1;
projectTriangle4(data1, axesX, axesY, axesZ, min1, max1);
if( V4AnyGrtrX(min1, max0, mask)
|| V4AnyGrtrX(min0, max1, mask))
return false;
return true;
}
static PX_FORCE_INLINE bool testEdges4( const TriangleData& data0, const TriangleData& data1,
const FloatV& edge0_x,
const FloatV& edge0_y,
const FloatV& edge0_z,
const Vec4V& edge1_xs,
const Vec4V& edge1_ys,
const Vec4V& edge1_zs
)
{
const Vec4V axis_xs = V4Sub(V4Scale(edge1_zs, edge0_y), V4Scale(edge1_ys, edge0_z));
const Vec4V axis_ys = V4Sub(V4Scale(edge1_xs, edge0_z), V4Scale(edge1_zs, edge0_x));
const Vec4V axis_zs = V4Sub(V4Scale(edge1_ys, edge0_x), V4Scale(edge1_xs, edge0_y));
const Vec4V eps = V4Load(1e-6f);
Vec4V maxV = V4Max(axis_ys, axis_xs);
maxV = V4Max(axis_zs, maxV);
Vec4V minV = V4Min(axis_ys, axis_xs);
minV = V4Min(axis_zs, minV);
maxV = V4Max(V4Neg(minV), maxV);
BoolV cmpV = V4IsGrtr(maxV, eps);
const PxU32 mask = BGetBitMask(cmpV) & 0x7;
return testSepAxis(data0, data1, axis_xs, axis_ys, axis_zs, mask);
}
//////////
static PX_FORCE_INLINE void projectTriangle(const PxVec3& axis, const TriangleData& triangle, float& min, float& max)
{
const float dp0 = triangle.mV0.dot(axis);
const float dp1 = triangle.mV1.dot(axis);
min = PxMin(dp0, dp1);
max = PxMax(dp0, dp1);
const float dp2 = triangle.mV2.dot(axis);
min = PxMin(min, dp2);
max = PxMax(max, dp2);
}
static PX_FORCE_INLINE bool testSepAxis(const PxVec3& axis, const TriangleData& triangle0, const TriangleData& triangle1)
{
float min0, max0;
projectTriangle(axis, triangle0, min0, max0);
float min1, max1;
projectTriangle(axis, triangle1, min1, max1);
if(max0<min1 || max1<min0)
return false;
return true;
}
static PX_FORCE_INLINE bool isAlmostZero(const PxVec3& v)
{
if(PxAbs(v.x)>1e-6f || PxAbs(v.y)>1e-6f || PxAbs(v.z)>1e-6f)
return false;
return true;
}
static PX_FORCE_INLINE bool testEdges( const TriangleData& tri0, const TriangleData& tri1,
const PxVec3& edge0, const PxVec3& edge1)
{
PxVec3 cp = edge0.cross(edge1);
if(!isAlmostZero(cp))
{
if(!testSepAxis(cp, tri0, tri1))
return false;
}
return true;
}
static bool TriTriSAT(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar)
{
{
const PxReal data1_v0_dot_N0 = data1.mV0.dot(data0.mNormal);
const PxReal data1_v1_dot_N0 = data1.mV1.dot(data0.mNormal);
const PxReal data1_v2_dot_N0 = data1.mV2.dot(data0.mNormal);
const PxReal p1ToA = data1_v0_dot_N0 + data0.mD;
const PxReal p1ToB = data1_v1_dot_N0 + data0.mD;
const PxReal p1ToC = data1_v2_dot_N0 + data0.mD;
const PxReal tolerance = 1e-8f;
if(PxAbs(p1ToA) < tolerance && PxAbs(p1ToB) < tolerance && PxAbs(p1ToC) < tolerance)
{
return ignoreCoplanar ? false : CoplanarTriTri(data0.mNormal, data0.mV0, data0.mV1, data0.mV2,
data1.mV0, data1.mV1, data1.mV2)!=0;
}
if ((p1ToA > 0) == (p1ToB > 0) && (p1ToA > 0) == (p1ToC > 0))
{
return false; //All points of triangle 2 on same side of triangle 1 -> no intersection
}
}
{
const PxReal data0_v0_dot_N1 = data0.mV0.dot(data1.mNormal);
const PxReal data0_v1_dot_N1 = data0.mV1.dot(data1.mNormal);
const PxReal data0_v2_dot_N1 = data0.mV2.dot(data1.mNormal);
const PxReal p2ToA = data0_v0_dot_N1 + data1.mD;
const PxReal p2ToB = data0_v1_dot_N1 + data1.mD;
const PxReal p2ToC = data0_v2_dot_N1 + data1.mD;
if ((p2ToA > 0) == (p2ToB > 0) && (p2ToA > 0) == (p2ToC > 0))
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
}
{
const PxVec3 edge1_01 = data1.mV0 - data1.mV1;
const PxVec3 edge1_12 = data1.mV1 - data1.mV2;
const PxVec3 edge1_20 = data1.mV2 - data1.mV0;
{
const PxVec3 edge0_01 = data0.mV0 - data0.mV1;
if(!testEdges(data0, data1, edge0_01, edge1_01))
return false;
if(!testEdges(data0, data1, edge0_01, edge1_12))
return false;
if(!testEdges(data0, data1, edge0_01, edge1_20))
return false;
}
{
const PxVec3 edge0_12 = data0.mV1 - data0.mV2;
if(!testEdges(data0, data1, edge0_12, edge1_01))
return false;
if(!testEdges(data0, data1, edge0_12, edge1_12))
return false;
if(!testEdges(data0, data1, edge0_12, edge1_20))
return false;
}
{
const PxVec3 edge0_20 = data0.mV2 - data0.mV0;
if(!testEdges(data0, data1, edge0_20, edge1_01))
return false;
if(!testEdges(data0, data1, edge0_20, edge1_12))
return false;
if(!testEdges(data0, data1, edge0_20, edge1_20))
return false;
}
}
return true;
}
static bool TriTriSAT_SIMD(const TriangleData& data0, const TriangleData& data1, bool ignoreCoplanar)
{
const Vec4V tri1_xs = V4LoadA(&data1.mXXX.x);
const Vec4V tri1_ys = V4LoadA(&data1.mYYY.x);
const Vec4V tri1_zs = V4LoadA(&data1.mZZZ.x);
{
const Vec4V tri0_normal_x = V4Load(data0.mNormal.x);
const Vec4V tri0_normal_y = V4Load(data0.mNormal.y);
const Vec4V tri0_normal_z = V4Load(data0.mNormal.z);
Vec4V tri1_dot_N0 = V4Mul(tri1_xs, tri0_normal_x);
// PT: TODO: V4MulAdd
tri1_dot_N0 = V4Add(tri1_dot_N0, V4Mul(tri1_ys, tri0_normal_y));
tri1_dot_N0 = V4Add(tri1_dot_N0, V4Mul(tri1_zs, tri0_normal_z));
const Vec4V p1ToABC = V4Add(tri1_dot_N0, V4Load(data0.mD));
if(V4AllGrtrOrEq3(V4Load(1e-8f), V4Abs(p1ToABC)))
{
return ignoreCoplanar ? false : CoplanarTriTri(data0.mNormal, data0.mV0, data0.mV1, data0.mV2,
data1.mV0, data1.mV1, data1.mV2)!=0;
}
PxU32 mm = BGetBitMask(V4IsGrtr(p1ToABC, V4Zero()));
if((mm & 0x7) == 0x7)
return false;
mm = BGetBitMask(V4IsGrtrOrEq(V4Zero(), p1ToABC));
if((mm & 0x7) == 0x7)
return false;
}
{
const Vec4V tri0_xs = V4LoadA(&data0.mXXX.x);
const Vec4V tri0_ys = V4LoadA(&data0.mYYY.x);
const Vec4V tri0_zs = V4LoadA(&data0.mZZZ.x);
const Vec4V tri1_normal_x = V4Load(data1.mNormal.x);
const Vec4V tri1_normal_y = V4Load(data1.mNormal.y);
const Vec4V tri1_normal_z = V4Load(data1.mNormal.z);
Vec4V tri0_dot_N1 = V4Mul(tri0_xs, tri1_normal_x);
// PT: TODO: V4MulAdd
tri0_dot_N1 = V4Add(tri0_dot_N1, V4Mul(tri0_ys, tri1_normal_y));
tri0_dot_N1 = V4Add(tri0_dot_N1, V4Mul(tri0_zs, tri1_normal_z));
const Vec4V p2ToABC = V4Add(tri0_dot_N1, V4Load(data1.mD));
PxU32 mm = BGetBitMask(V4IsGrtr(p2ToABC, V4Zero()));
if((mm & 0x7) == 0x7)
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
mm = BGetBitMask(V4IsGrtrOrEq(V4Zero(), p2ToABC));
if((mm & 0x7) == 0x7)
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
}
{
const Vec4V tri1_xs_shuffled = V4PermYZXW(tri1_xs);
const Vec4V tri1_ys_shuffled = V4PermYZXW(tri1_ys);
const Vec4V tri1_zs_shuffled = V4PermYZXW(tri1_zs);
const Vec4V edge1_xs = V4Sub(tri1_xs, tri1_xs_shuffled);
const Vec4V edge1_ys = V4Sub(tri1_ys, tri1_ys_shuffled);
const Vec4V edge1_zs = V4Sub(tri1_zs, tri1_zs_shuffled);
const Vec4V data0_V0 = V4LoadA(&data0.mV0.x);
const Vec4V data0_V1 = V4LoadA(&data0.mV1.x);
const Vec4V data0_V2 = V4LoadA(&data0.mV2.x);
const Vec4V edge0_01 = V4Sub(data0_V0, data0_V1);
if(!testEdges4(data0, data1,
V4GetX(edge0_01), V4GetY(edge0_01), V4GetZ(edge0_01),
edge1_xs, edge1_ys, edge1_zs))
return false;
const Vec4V edge0_12 = V4Sub(data0_V1, data0_V2);
if(!testEdges4(data0, data1,
V4GetX(edge0_12), V4GetY(edge0_12), V4GetZ(edge0_12),
edge1_xs, edge1_ys, edge1_zs))
return false;
const Vec4V edge0_20 = V4Sub(data0_V2, data0_V0);
if(!testEdges4(data0, data1,
V4GetX(edge0_20), V4GetY(edge0_20), V4GetZ(edge0_20),
edge1_xs, edge1_ys, edge1_zs))
return false;
}
return true;
}
// PT: beware, needs padding at the end of src
static PX_FORCE_INLINE void transformV(PxVec3p* PX_RESTRICT dst, const PxVec3* PX_RESTRICT src, const Vec4V& c0, const Vec4V& c1, const Vec4V& c2, const Vec4V& c3)
{
const Vec4V vertexV = V4LoadU(&src->x);
Vec4V ResV = V4Scale(c0, V4GetX(vertexV));
// PT: TODO: V4ScaleAdd
ResV = V4Add(ResV, V4Scale(c1, V4GetY(vertexV)));
ResV = V4Add(ResV, V4Scale(c2, V4GetZ(vertexV)));
ResV = V4Add(ResV, c3);
V4StoreU(ResV, &dst->x);
}
static bool accumulateResults(PxReportCallback<PxGeomIndexPair>& callback, PxGeomIndexPair*& dst, PxU32& capacity, PxU32& currentSize, PxU32 primIndex0, PxU32 primIndex1, bool mustFlip, bool& abort)
{
dst[currentSize].id0 = mustFlip ? primIndex1 : primIndex0;
dst[currentSize].id1 = mustFlip ? primIndex0 : primIndex1;
currentSize++;
if(currentSize==capacity)
{
callback.mSize = 0;
if(!callback.flushResults(currentSize, dst))
{
abort = true;
return false;
}
dst = callback.mBuffer;
capacity = callback.mCapacity;
currentSize = callback.mSize;
}
return true;
}
namespace
{
struct TriVsTriParams;
typedef bool (*trisVsTrisFunction)( const TriVsTriParams& params,
PxU32 nb0, PxU32 startPrim0, const TriangleData* data0,
PxU32 nb1, PxU32 startPrim1, const TriangleData* data1,
bool& abort);
enum TriVsTriImpl
{
TRI_TRI_MOLLER_REGULAR, // https://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/code/
TRI_TRI_MOLLER_NEW, // Alternative implementation in Gu
TRI_TRI_NEW_SAT, // "New" SAT-based implementation
TRI_TRI_NEW_SAT_SIMD, // "New" SAT-based implementation using SIMD
};
struct TriVsTriParams
{
PX_FORCE_INLINE TriVsTriParams(trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, float tolerance, bool mustFlip, bool ignoreCoplanar) :
mLeafFunction (leafFunc),
mCallback (callback),
mTolerance (tolerance),
mMustFlip (mustFlip),
mIgnoreCoplanar (ignoreCoplanar)
{
}
const trisVsTrisFunction mLeafFunction;
PxReportCallback<PxGeomIndexPair>& mCallback;
const float mTolerance;
const bool mMustFlip;
const bool mIgnoreCoplanar;
PX_NOCOPY(TriVsTriParams)
};
}
template<const TriVsTriImpl impl>
static bool doTriVsTri_Overlap( const TriVsTriParams& params,
PxU32 nb0, PxU32 startPrim0, const TriangleData* data0,
PxU32 nb1, PxU32 startPrim1, const TriangleData* data1,
bool& abort)
{
PX_ASSERT(nb0<=16);
PX_ASSERT(nb1<=16);
PxReportCallback<PxGeomIndexPair>& callback = params.mCallback;
PxGeomIndexPair* dst = callback.mBuffer;
PxU32 capacity = callback.mCapacity;
PxU32 currentSize = callback.mSize;
PX_ASSERT(currentSize<capacity);
const bool ignoreCoplanar = params.mIgnoreCoplanar;
const bool mustFlip = params.mMustFlip;
bool foundHit = false;
abort = false;
for(PxU32 i=0;i<nb0;i++)
{
for(PxU32 j=0;j<nb1;j++)
{
bool ret;
if(impl==TRI_TRI_MOLLER_REGULAR)
ret = TriTriOverlap(data0[i], data1[j], ignoreCoplanar);
else if(impl==TRI_TRI_MOLLER_NEW)
ret = trianglesIntersect(data0[i].mV0, data0[i].mV1, data0[i].mV2, data1[j].mV0, data1[j].mV1, data1[j].mV2, ignoreCoplanar);
else if(impl==TRI_TRI_NEW_SAT)
ret = TriTriSAT(data0[i], data1[j], ignoreCoplanar);
else if(impl==TRI_TRI_NEW_SAT_SIMD)
ret = TriTriSAT_SIMD(data0[i], data1[j], ignoreCoplanar);
else
ret = false;
if(ret)
{
foundHit = true;
if(!accumulateResults(callback, dst, capacity, currentSize, startPrim0 + i, startPrim1 + j, mustFlip, abort))
return true;
}
}
}
callback.mSize = currentSize;
return foundHit;
}
static bool doTriVsTri_Distance(const TriVsTriParams& params,
PxU32 nb0, PxU32 startPrim0, const TriangleData* data0,
PxU32 nb1, PxU32 startPrim1, const TriangleData* data1,
bool& abort)
{
PX_ASSERT(nb0<=16);
PX_ASSERT(nb1<=16);
PxReportCallback<PxGeomIndexPair>& callback = params.mCallback;
PxGeomIndexPair* dst = callback.mBuffer;
PxU32 capacity = callback.mCapacity;
PxU32 currentSize = callback.mSize;
PX_ASSERT(currentSize<capacity);
const bool mustFlip = params.mMustFlip;
bool foundHit = false;
abort = false;
const float toleranceSquared = params.mTolerance * params.mTolerance;
for(PxU32 i=0;i<nb0;i++)
{
// PT: TODO: improve this
const PxVec3p pp[3] = { data0[i].mV0, data0[i].mV1, data0[i].mV2 };
for(PxU32 j=0;j<nb1;j++)
{
PxVec3 cp, cq;
// PT: TODO: improve this
const PxVec3p qq[3] = { data1[j].mV0, data1[j].mV1, data1[j].mV2 };
const float d = distanceTriangleTriangleSquared(cp, cq, pp, qq);
if(d<=toleranceSquared)
{
foundHit = true;
// PT: TODO: this is not enough here
if(!accumulateResults(callback, dst, capacity, currentSize, startPrim0 + i, startPrim1 + j, mustFlip, abort))
return true;
}
}
}
callback.mSize = currentSize;
return foundHit;
}
static bool doLeafVsLeaf(const TriVsTriParams& params, const PxU32 prim0, const PxU32 prim1, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1, bool& abort)
{
// PT: TODO: revisit this approach, it was fine with the original overlap code but now with the 2 additional queries, not so much
TriangleData data0[16];
TriangleData data1[16];
PxU32 nb0 = 0;
PxU32 startPrim0;
{
PxU32 primIndex0 = prim0;
PxU32 nbTris0 = getNbPrimitives(primIndex0);
startPrim0 = primIndex0;
const PxVec3* verts0 = mesh0->getVerts();
do
{
PX_ASSERT(primIndex0<mesh0->getNbTriangles());
PxU32 VRef00, VRef01, VRef02;
getVertexReferences(VRef00, VRef01, VRef02, primIndex0++, mesh0->getTris32(), mesh0->getTris16());
PX_ASSERT(VRef00<mesh0->getNbVertices());
PX_ASSERT(VRef01<mesh0->getNbVertices());
PX_ASSERT(VRef02<mesh0->getNbVertices());
if(mat0to1)
{
//const PxVec3 p0 = mat0to1->transform(verts0[VRef00]);
//const PxVec3 p1 = mat0to1->transform(verts0[VRef01]);
//const PxVec3 p2 = mat0to1->transform(verts0[VRef02]);
//data0[nb0++].init(p0, p1, p2);
const Vec4V c0 = V4LoadU(&mat0to1->column0.x);
const Vec4V c1 = V4LoadU(&mat0to1->column1.x);
const Vec4V c2 = V4LoadU(&mat0to1->column2.x);
const Vec4V c3 = V4LoadU(&mat0to1->column3.x);
PxVec3p p0, p1, p2;
transformV(&p0, &verts0[VRef00], c0, c1, c2, c3);
transformV(&p1, &verts0[VRef01], c0, c1, c2, c3);
transformV(&p2, &verts0[VRef02], c0, c1, c2, c3);
data0[nb0++].init(p0, p1, p2);
}
else
{
data0[nb0++].init(verts0[VRef00], verts0[VRef01], verts0[VRef02]);
}
}while(nbTris0--);
}
PxU32 nb1 = 0;
PxU32 startPrim1;
{
PxU32 primIndex1 = prim1;
PxU32 nbTris1 = getNbPrimitives(primIndex1);
startPrim1 = primIndex1;
const PxVec3* verts1 = mesh1->getVerts();
do
{
PX_ASSERT(primIndex1<mesh1->getNbTriangles());
PxU32 VRef10, VRef11, VRef12;
getVertexReferences(VRef10, VRef11, VRef12, primIndex1++, mesh1->getTris32(), mesh1->getTris16());
PX_ASSERT(VRef10<mesh1->getNbVertices());
PX_ASSERT(VRef11<mesh1->getNbVertices());
PX_ASSERT(VRef12<mesh1->getNbVertices());
data1[nb1++].init(verts1[VRef10], verts1[VRef11], verts1[VRef12]);
}while(nbTris1--);
}
return (params.mLeafFunction)(params, nb0, startPrim0, data0, nb1, startPrim1, data1, abort);
}
namespace
{
struct MeshMeshParams : OBBTestParams
{
PX_FORCE_INLINE MeshMeshParams( trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1, const BV4Tree& tree,
bool mustFlip, bool ignoreCoplanar, float tolerance) :
mTriVsTriParams (leafFunc, callback, tolerance, mustFlip, ignoreCoplanar),
mMesh0 (mesh0),
mMesh1 (mesh1),
mMat0to1 (mat0to1),
mStatus (false)
{
V4StoreA_Safe(V4LoadU_Safe(&tree.mCenterOrMinCoeff.x), &mCenterOrMinCoeff_PaddedAligned.x);
V4StoreA_Safe(V4LoadU_Safe(&tree.mExtentsOrMaxCoeff.x), &mExtentsOrMaxCoeff_PaddedAligned.x);
PxMat33 mLocalBox_rot;
if(mat0to1)
mLocalBox_rot = PxMat33(PxVec3(mat0to1->column0.x, mat0to1->column0.y, mat0to1->column0.z),
PxVec3(mat0to1->column1.x, mat0to1->column1.y, mat0to1->column1.z),
PxVec3(mat0to1->column2.x, mat0to1->column2.y, mat0to1->column2.z));
else
mLocalBox_rot = PxMat33(PxIdentity);
precomputeData(this, &mAbsRot, &mLocalBox_rot);
}
void setupForTraversal(const PxVec3p& center, const PxVec3p& extents, float tolerance)
{
if(mMat0to1)
{
const Vec4V c0 = V4LoadU(&mMat0to1->column0.x);
const Vec4V c1 = V4LoadU(&mMat0to1->column1.x);
const Vec4V c2 = V4LoadU(&mMat0to1->column2.x);
const Vec4V c3 = V4LoadU(&mMat0to1->column3.x);
transformV(&mTBoxToModel_PaddedAligned, ¢er, c0, c1, c2, c3);
}
else
mTBoxToModel_PaddedAligned = center;
setupBoxData(this, extents + PxVec3(tolerance), &mAbsRot);
}
PxMat33 mAbsRot; //!< Absolute rotation matrix
const TriVsTriParams mTriVsTriParams;
const SourceMesh* const mMesh0;
const SourceMesh* const mMesh1;
const PxMat44* const mMat0to1;
PxU32 mPrimIndex0;
bool mStatus;
PX_NOCOPY(MeshMeshParams)
};
class LeafFunction_MeshMesh
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(MeshMeshParams* PX_RESTRICT params, PxU32 primIndex1)
{
bool abort;
if(doLeafVsLeaf(params->mTriVsTriParams, params->mPrimIndex0, primIndex1, params->mMesh0, params->mMesh1, params->mMat0to1, abort))
params->mStatus = true;
return PxIntBool(abort);
}
};
}
static PX_FORCE_INLINE void getNodeBounds(Vec4V& centerV, Vec4V& extentsV, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, const PxVec3p* PX_RESTRICT centerOrMinCoeff_PaddedAligned, const PxVec3p* PX_RESTRICT extentsOrMaxCoeff_PaddedAligned)
{
// Dequantize box0
//OPC_SLABS_GET_MIN_MAX(tn0, i)
const VecI32V minVi = I4LoadXYZW(node->mX[i].mMin, node->mY[i].mMin, node->mZ[i].mMin, 0);
const Vec4V minCoeffV = V4LoadA_Safe(¢erOrMinCoeff_PaddedAligned->x);
Vec4V minV = V4Mul(Vec4V_From_VecI32V(minVi), minCoeffV);
const VecI32V maxVi = I4LoadXYZW(node->mX[i].mMax, node->mY[i].mMax, node->mZ[i].mMax, 0);
const Vec4V maxCoeffV = V4LoadA_Safe(&extentsOrMaxCoeff_PaddedAligned->x);
Vec4V maxV = V4Mul(Vec4V_From_VecI32V(maxVi), maxCoeffV);
// OPC_SLABS_GET_CEQ(i)
const FloatV HalfV = FLoad(0.5f);
centerV = V4Scale(V4Add(maxV, minV), HalfV);
extentsV = V4Scale(V4Sub(maxV, minV), HalfV);
}
static PX_FORCE_INLINE void getNodeBounds(Vec4V& centerV, Vec4V& extentsV, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, const PxVec3p* PX_RESTRICT /*centerOrMinCoeff_PaddedAligned*/, const PxVec3p* PX_RESTRICT /*extentsOrMaxCoeff_PaddedAligned*/)
{
const FloatV HalfV = FLoad(0.5f);
const Vec4V minV = V4LoadXYZW(node->mMinX[i], node->mMinY[i], node->mMinZ[i], 0.0f);
const Vec4V maxV = V4LoadXYZW(node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i], 0.0f);
centerV = V4Scale(V4Add(maxV, minV), HalfV);
extentsV = V4Scale(V4Sub(maxV, minV), HalfV);
}
static PX_FORCE_INLINE PxIntBool doLeafVsNode(const BVDataPackedQ* const PX_RESTRICT root, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, MeshMeshParams* PX_RESTRICT params)
{
return BV4_ProcessStreamSwizzledNoOrderQ<LeafFunction_MeshMesh, MeshMeshParams>(root, node->getChildData(i), params);
}
static PX_FORCE_INLINE PxIntBool doLeafVsNode(const BVDataPackedNQ* const PX_RESTRICT root, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, MeshMeshParams* PX_RESTRICT params)
{
return BV4_ProcessStreamSwizzledNoOrderNQ<LeafFunction_MeshMesh, MeshMeshParams>(root, node->getChildData(i), params);
}
static void computeBoundsAroundVertices(Vec4V& centerV, Vec4V& extentsV, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts)
{
Vec4V minV = V4LoadU(&verts[0].x);
Vec4V maxV = minV;
for(PxU32 i=1; i<nbVerts; i++)
{
const Vec4V vV = V4LoadU(&verts[i].x);
minV = V4Min(minV, vV);
maxV = V4Max(maxV, vV);
}
const FloatV HalfV = FLoad(0.5f);
centerV = V4Scale(V4Add(maxV, minV), HalfV);
extentsV = V4Scale(V4Sub(maxV, minV), HalfV);
}
static PX_NOINLINE bool abortQuery(PxReportCallback<PxGeomIndexPair>& callback, bool& abort)
{
abort = true;
callback.mSize = 0;
return true;
}
static PX_FORCE_INLINE trisVsTrisFunction getLeafFunc(PxMeshMeshQueryFlags meshMeshFlags, float tolerance)
{
if(tolerance!=0.0f)
return doTriVsTri_Distance;
if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED1)
return doTriVsTri_Overlap<TRI_TRI_MOLLER_NEW>;
if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED2)
return doTriVsTri_Overlap<TRI_TRI_NEW_SAT>;
if(meshMeshFlags & PxMeshMeshQueryFlag::eRESERVED3)
return doTriVsTri_Overlap<TRI_TRI_NEW_SAT_SIMD>;
return doTriVsTri_Overlap<TRI_TRI_MOLLER_REGULAR>;
}
static PX_NOINLINE bool doSmallMeshVsSmallMesh( PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1, const PxMat44* mat0to1,
bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance)
{
const PxU32 nbTris0 = mesh0->getNbTriangles();
PX_ASSERT(nbTris0<16);
const PxU32 nbTris1 = mesh1->getNbTriangles();
PX_ASSERT(nbTris1<16);
const TriVsTriParams params(leafFunc, callback, tolerance, false, ignoreCoplanar);
bool abort;
bool status = false;
if(doLeafVsLeaf(params, nbTris0, nbTris1, mesh0, mesh1, mat0to1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
return status;
}
template<class PackedNodeT, class SwizzledNodeT>
static PX_NOINLINE bool doSmallMeshVsTree( PxReportCallback<PxGeomIndexPair>& callback, MeshMeshParams& params,
const PackedNodeT* PX_RESTRICT node, const SourceMesh* mesh0, const SourceMesh* mesh1, bool& _abort)
{
const PxU32 nbTris = mesh0->getNbTriangles();
PX_ASSERT(nbTris<16);
{
BV4_ALIGN16(PxVec3p boxCenter);
BV4_ALIGN16(PxVec3p boxExtents);
Vec4V centerV, extentsV;
computeBoundsAroundVertices(centerV, extentsV, mesh0->getNbVertices(), mesh0->getVerts());
V4StoreA(centerV, &boxCenter.x);
V4StoreA(extentsV, &boxExtents.x);
params.setupForTraversal(boxCenter, boxExtents, params.mTriVsTriParams.mTolerance);
params.mPrimIndex0 = nbTris;
}
const PackedNodeT* const root = node;
const SwizzledNodeT* tn = reinterpret_cast<const SwizzledNodeT*>(node);
bool status = false;
for(PxU32 i=0;i<4;i++)
{
if(tn->mData[i]==0xffffffff)
continue;
Vec4V centerV1, extentsV1;
getNodeBounds(centerV1, extentsV1, tn, i, ¶ms.mCenterOrMinCoeff_PaddedAligned, ¶ms.mExtentsOrMaxCoeff_PaddedAligned);
if(BV4_BoxBoxOverlap(centerV1, extentsV1, ¶ms))
{
if(tn->isLeaf(i))
{
bool abort;
if(doLeafVsLeaf(params.mTriVsTriParams, nbTris, tn->getPrimitive(i), mesh0, mesh1, params.mMat0to1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
}
else
{
if(doLeafVsNode(root, tn, i, ¶ms))
return abortQuery(callback, _abort);
}
}
}
return status || params.mStatus;
}
template<class PackedNodeT0, class PackedNodeT1, class SwizzledNodeT0, class SwizzledNodeT1>
static bool BV4_OverlapMeshVsMeshT( PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0,
bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance)
{
const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface);
const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface);
const PackedNodeT0* PX_RESTRICT node0 = reinterpret_cast<const PackedNodeT0*>(tree0.mNodes);
const PackedNodeT1* PX_RESTRICT node1 = reinterpret_cast<const PackedNodeT1*>(tree1.mNodes);
PX_ASSERT(node0 || node1);
if(!node0 && node1)
{
MeshMeshParams ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, mat0to1, tree1, false, ignoreCoplanar, tolerance);
return doSmallMeshVsTree<PackedNodeT1, SwizzledNodeT1>(callback, ParamsForTree1Traversal, node1, mesh0, mesh1, _abort);
}
else if(node0 && !node1)
{
MeshMeshParams ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, mat1to0, tree0, true, ignoreCoplanar, tolerance);
return doSmallMeshVsTree<PackedNodeT0, SwizzledNodeT0>(callback, ParamsForTree0Traversal, node0, mesh1, mesh0, _abort);
}
else
{
PX_ASSERT(node0);
PX_ASSERT(node1);
MeshMeshParams ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, mat0to1, tree1, false, ignoreCoplanar, tolerance);
MeshMeshParams ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, mat1to0, tree0, true, ignoreCoplanar, tolerance);
BV4_ALIGN16(PxVec3p boxCenter0);
BV4_ALIGN16(PxVec3p boxExtents0);
BV4_ALIGN16(PxVec3p boxCenter1);
BV4_ALIGN16(PxVec3p boxExtents1);
struct indexPair
{
PxU32 index0;
PxU32 index1;
};
PxU32 nb=1;
indexPair stack[GU_BV4_STACK_SIZE];
stack[0].index0 = tree0.mInitData;
stack[0].index1 = tree1.mInitData;
bool status = false;
const PackedNodeT0* const root0 = node0;
const PackedNodeT1* const root1 = node1;
do
{
const indexPair& childData = stack[--nb];
node0 = root0 + getChildOffset(childData.index0);
node1 = root1 + getChildOffset(childData.index1);
const SwizzledNodeT0* tn0 = reinterpret_cast<const SwizzledNodeT0*>(node0);
const SwizzledNodeT1* tn1 = reinterpret_cast<const SwizzledNodeT1*>(node1);
for(PxU32 i=0;i<4;i++)
{
if(tn0->mData[i]==0xffffffff)
continue;
Vec4V centerV0, extentsV0;
getNodeBounds(centerV0, extentsV0, tn0, i, &ParamsForTree0Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree0Traversal.mExtentsOrMaxCoeff_PaddedAligned);
V4StoreA(centerV0, &boxCenter0.x);
V4StoreA(extentsV0, &boxExtents0.x);
ParamsForTree1Traversal.setupForTraversal(boxCenter0, boxExtents0, tolerance);
for(PxU32 j=0;j<4;j++)
{
if(tn1->mData[j]==0xffffffff)
continue;
Vec4V centerV1, extentsV1;
getNodeBounds(centerV1, extentsV1, tn1, j, &ParamsForTree1Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree1Traversal.mExtentsOrMaxCoeff_PaddedAligned);
if(BV4_BoxBoxOverlap(centerV1, extentsV1, &ParamsForTree1Traversal))
{
const PxU32 isLeaf0 = tn0->isLeaf(i);
const PxU32 isLeaf1 = tn1->isLeaf(j);
if(isLeaf0)
{
if(isLeaf1)
{
bool abort;
if(doLeafVsLeaf(ParamsForTree1Traversal.mTriVsTriParams, tn0->getPrimitive(i), tn1->getPrimitive(j), mesh0, mesh1, mat0to1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
}
else
{
ParamsForTree1Traversal.mPrimIndex0 = tn0->getPrimitive(i);
if(doLeafVsNode(root1, tn1, j, &ParamsForTree1Traversal))
return abortQuery(callback, _abort);
}
}
else
{
if(isLeaf1)
{
V4StoreA(centerV1, &boxCenter1.x);
V4StoreA(extentsV1, &boxExtents1.x);
ParamsForTree0Traversal.setupForTraversal(boxCenter1, boxExtents1, tolerance);
ParamsForTree0Traversal.mPrimIndex0 = tn1->getPrimitive(j);
if(doLeafVsNode(root0, tn0, i, &ParamsForTree0Traversal))
return abortQuery(callback, _abort);
}
else
{
stack[nb].index0 = tn0->getChildData(i);
stack[nb].index1 = tn1->getChildData(j);
nb++;
}
}
}
}
}
}while(nb);
return status || ParamsForTree0Traversal.mStatus || ParamsForTree1Traversal.mStatus;
}
}
// PT: each mesh can be:
// 1) a small mesh without tree
// 2) a regular mesh with a quantized tree
// 3) a regular mesh with a non-quantized tree
//
// So for mesh-vs-mesh that's 3*3 = 9 possibilities. Some of them are redundant (e.g. 1 vs 2 and 2 vs 1) so it comes down to:
// 1) small mesh vs small mesh
// 2) small mesh vs quantized tree
// 3) small mesh vs non-quantized tree
// 4) non-quantized tree vs non-quantized tree
// 5) quantized tree vs non-quantized tree
// 6) quantized tree vs quantized tree
// => 6 codepaths
//
// But for each of this codepath the query can be:
// - all hits or any hits
// - using PxRegularReportCallback / PxLocalStorageReportCallback / PxExternalStorageReportCallback / PxDynamicArrayReportCallback
// So for each codepath that's 2*4 = 8 possible queries.
//
// Thus we'd need 6*8 = 48 different test cases.
//
// This gets worse if we take scaling into account.
//
// UPDATE: and now we also want distance/tolerance queries so multiply this by 2. This is getting too complicated.
// We were at 48 test cases, *2 for scaling, *2 for distance queries = 192 cases to test?
bool BV4_OverlapMeshVsMesh(
PxReportCallback<PxGeomIndexPair>& callback,
const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0, PxMeshMeshQueryFlags meshMeshFlags, float tolerance)
{
PxGeomIndexPair stackBuffer[256];
bool mustResetBuffer;
if(callback.mBuffer)
{
PX_ASSERT(callback.mCapacity);
mustResetBuffer = false;
}
else
{
callback.mBuffer = stackBuffer;
PX_ASSERT(callback.mCapacity<=256);
if(callback.mCapacity==0 || callback.mCapacity>256)
{
callback.mCapacity = 256;
}
callback.mSize = 0;
mustResetBuffer = true;
}
const bool ignoreCoplanar = meshMeshFlags & PxMeshMeshQueryFlag::eDISCARD_COPLANAR;
const trisVsTrisFunction leafFunc = getLeafFunc(meshMeshFlags, tolerance);
bool status;
bool abort = false;
if(!tree0.mNodes && !tree1.mNodes)
{
const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface);
const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface);
status = doSmallMeshVsSmallMesh(callback, mesh0, mesh1, mat0to1, abort, ignoreCoplanar, leafFunc, tolerance);
}
else
{
if(tree0.mQuantized)
{
if(tree1.mQuantized)
status = BV4_OverlapMeshVsMeshT<BVDataPackedQ, BVDataPackedQ, BVDataSwizzledQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance);
else
status = BV4_OverlapMeshVsMeshT<BVDataPackedQ, BVDataPackedNQ, BVDataSwizzledQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance);
}
else
{
if(tree1.mQuantized)
status = BV4_OverlapMeshVsMeshT<BVDataPackedNQ, BVDataPackedQ, BVDataSwizzledNQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance);
else
status = BV4_OverlapMeshVsMeshT<BVDataPackedNQ, BVDataPackedNQ, BVDataSwizzledNQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, abort, ignoreCoplanar, leafFunc, tolerance);
}
}
if(!abort)
{
const PxU32 currentSize = callback.mSize;
if(currentSize)
{
callback.mSize = 0;
callback.flushResults(currentSize, callback.mBuffer);
}
}
if(mustResetBuffer)
callback.mBuffer = NULL;
return status;
}
// PT: experimental version supporting scaling. Passed matrices etc are all temporary.
#include "geometry/PxMeshScale.h"
#include "CmMatrix34.h"
#include "CmScaling.h"
#include "GuConvexUtilsInternal.h"
#include "GuBoxConversion.h"
using namespace Cm;
// PT/ dups from NpDebugViz.cpp
static PX_FORCE_INLINE Vec4V multiply3x3V_(const Vec4V p, const PxMat34& mat)
{
Vec4V ResV = V4Scale(V4LoadU(&mat.m.column0.x), V4GetX(p));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column1.x), V4GetY(p)));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column2.x), V4GetZ(p)));
return ResV;
}
// PT: beware, needs padding at the end of dst/src
static PX_FORCE_INLINE void transformV_(PxVec3* dst, const PxVec3* src, const Vec4V p, const PxMat34& mat)
{
const Vec4V vertexV = V4LoadU(&src->x);
const Vec4V transformedV = V4Add(multiply3x3V_(vertexV, mat), p);
V4StoreU(transformedV, &dst->x);
}
// PT: Following ones fetched from GuBounds.cpp and adapted to Vec4V inputs.
// TODO: refactor! this is just a test
// PT: this one may have duplicates in GuBV4_BoxSweep_Internal.h & GuBV4_Raycast.cpp
static PX_FORCE_INLINE Vec4V multiply3x3V_(const Vec4V p, const PxMat33Padded& mat_Padded)
{
Vec4V ResV = V4Scale(V4LoadU(&mat_Padded.column0.x), V4GetX(p));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat_Padded.column1.x), V4GetY(p)));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat_Padded.column2.x), V4GetZ(p)));
return ResV;
}
static PX_FORCE_INLINE void transformNoEmptyTestV(Vec4V& c, Vec4V& ext, const PxMat33Padded& rot, const PxVec3& pos, Vec4V boundsCenterV, Vec4V boundsExtentsV)
{
// PT: unfortunately we can't V4LoadU 'pos' directly (it can come directly from users!). So we have to live with this for now:
const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&pos.x));
// PT: but eventually we'd like to use the "unsafe" version (e.g. by switching p&q in PxTransform), which would save 6 instructions on Win32
const Vec4V cV = V4Add(multiply3x3V_(boundsCenterV, rot), posV);
c = cV;
// extended basis vectors
const Vec4V c0V = V4Scale(V4LoadU(&rot.column0.x), V4GetX(boundsExtentsV));
const Vec4V c1V = V4Scale(V4LoadU(&rot.column1.x), V4GetY(boundsExtentsV));
const Vec4V c2V = V4Scale(V4LoadU(&rot.column2.x), V4GetZ(boundsExtentsV));
// find combination of base vectors that produces max. distance for each component = sum of abs()
Vec4V extentsV = V4Add(V4Abs(c0V), V4Abs(c1V));
extentsV = V4Add(extentsV, V4Abs(c2V));
ext = extentsV;
}
static PX_FORCE_INLINE void transformNoEmptyTest(const PxMat34& absPose, Vec4V& c, Vec4V& ext, Vec4V boundsCenterV, Vec4V boundsExtentsV)
{
transformNoEmptyTestV(c, ext, static_cast<const PxMat33Padded&>(absPose.m), absPose.p, boundsCenterV, boundsExtentsV);
}
static void computeMeshBounds(const PxMat34& absPose, Vec4V boundsCenterV, Vec4V boundsExtentsV, Vec4V& origin, Vec4V& extent)
{
transformNoEmptyTest(absPose, origin, extent, boundsCenterV, boundsExtentsV);
}
// PT: TODO: refactor with non-scaled version
static bool doLeafVsLeaf_Scaled(const TriVsTriParams& params, const PxU32 prim0, const PxU32 prim1, const SourceMesh* mesh0, const SourceMesh* mesh1,
const PxMat34& absPose0, const PxMat34& absPose1, bool& abort)
{
TriangleData data0[16];
TriangleData data1[16];
PxU32 nb0 = 0;
PxU32 startPrim0;
{
PxU32 primIndex0 = prim0;
PxU32 nbTris0 = getNbPrimitives(primIndex0);
startPrim0 = primIndex0;
const PxVec3* verts0 = mesh0->getVerts();
do
{
PX_ASSERT(primIndex0<mesh0->getNbTriangles());
PxU32 VRef00, VRef01, VRef02;
getVertexReferences(VRef00, VRef01, VRef02, primIndex0++, mesh0->getTris32(), mesh0->getTris16());
PX_ASSERT(VRef00<mesh0->getNbVertices());
PX_ASSERT(VRef01<mesh0->getNbVertices());
PX_ASSERT(VRef02<mesh0->getNbVertices());
PxVec3p p0, p1, p2;
const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose0.p.x));
transformV_(&p0, &verts0[VRef00], posV, absPose0);
transformV_(&p1, &verts0[VRef01], posV, absPose0);
transformV_(&p2, &verts0[VRef02], posV, absPose0);
data0[nb0++].init(p0, p1, p2);
}while(nbTris0--);
}
PxU32 nb1 = 0;
PxU32 startPrim1;
{
PxU32 primIndex1 = prim1;
PxU32 nbTris1 = getNbPrimitives(primIndex1);
startPrim1 = primIndex1;
const PxVec3* verts1 = mesh1->getVerts();
do
{
PX_ASSERT(primIndex1<mesh1->getNbTriangles());
PxU32 VRef10, VRef11, VRef12;
getVertexReferences(VRef10, VRef11, VRef12, primIndex1++, mesh1->getTris32(), mesh1->getTris16());
PX_ASSERT(VRef10<mesh1->getNbVertices());
PX_ASSERT(VRef11<mesh1->getNbVertices());
PX_ASSERT(VRef12<mesh1->getNbVertices());
PxVec3p p0, p1, p2;
const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose1.p.x));
transformV_(&p0, &verts1[VRef10], posV, absPose1);
transformV_(&p1, &verts1[VRef11], posV, absPose1);
transformV_(&p2, &verts1[VRef12], posV, absPose1);
data1[nb1++].init(p0, p1, p2);
}while(nbTris1--);
}
return (params.mLeafFunction)(params, nb0, startPrim0, data0, nb1, startPrim1, data1, abort);
}
static PX_NOINLINE bool doSmallMeshVsSmallMesh_Scaled( PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1,
const PxMat34& absPose0, const PxMat34& absPose1,
bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance)
{
const PxU32 nbTris0 = mesh0->getNbTriangles();
PX_ASSERT(nbTris0<16);
const PxU32 nbTris1 = mesh1->getNbTriangles();
PX_ASSERT(nbTris1<16);
const TriVsTriParams params(leafFunc, callback, tolerance, false, ignoreCoplanar);
bool abort;
bool status = false;
if(doLeafVsLeaf_Scaled(params, nbTris0, nbTris1, mesh0, mesh1, absPose0, absPose1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
return status;
}
namespace
{
// PT: this bit from NpDebugViz.cpp, visualizeTriangleMesh()
static PxMat34 getAbsPose(const PxTransform& meshPose, const PxMeshScale& meshScale)
{
const PxMat33Padded m33(meshPose.q);
return PxMat34(m33 * toMat33(meshScale), meshPose.p);
}
struct MeshMeshParams_Scaled : MeshMeshParams
{
PX_FORCE_INLINE MeshMeshParams_Scaled(trisVsTrisFunction leafFunc, PxReportCallback<PxGeomIndexPair>& callback, const SourceMesh* mesh0, const SourceMesh* mesh1,
const PxTransform& meshPose0, const PxTransform& meshPose1,
const PxMeshScale& meshScale0, const PxMeshScale& meshScale1,
const PxMat34& absPose0, const PxMat34& absPose1,
const PxMat44* mat0to1, const BV4Tree& tree, bool mustFlip, bool ignoreCoplanar, float tolerance) :
MeshMeshParams (leafFunc, callback, mesh0, mesh1, mat0to1, tree, mustFlip, ignoreCoplanar, tolerance),
mMeshPose0 (meshPose0),
mMeshPose1 (meshPose1),
mMeshScale0 (meshScale0),
mMeshScale1 (meshScale1),
mAbsPose0 (absPose0),
mAbsPose1 (absPose1)
{
}
PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space
PxVec3p mTModelToBox_Padded; //!< Translation from model space to obb space
const PxTransform& mMeshPose0;
const PxTransform& mMeshPose1;
const PxMeshScale& mMeshScale0;
const PxMeshScale& mMeshScale1;
const PxMat34& mAbsPose0;
const PxMat34& mAbsPose1;
PX_NOCOPY(MeshMeshParams_Scaled)
};
template<class ParamsT>
static PX_FORCE_INLINE void setupBoxParams2(ParamsT* PX_RESTRICT params, const Box& localBox)
{
invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, localBox);
params->mTBoxToModel_PaddedAligned = localBox.center;
params->precomputeBoxData(localBox.extents, &localBox.rot);
}
class LeafFunction_MeshMesh_Scaled
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(MeshMeshParams_Scaled* PX_RESTRICT params, PxU32 primIndex1)
{
bool abort;
if(doLeafVsLeaf_Scaled(params->mTriVsTriParams, params->mPrimIndex0, primIndex1, params->mMesh0, params->mMesh1, params->mAbsPose0, params->mAbsPose1, abort))
params->mStatus = true;
return PxIntBool(abort);
}
};
PX_FORCE_INLINE PxIntBool BV4_AABBAABBOverlap(const Vec4VArg boxCenter0V, const Vec4VArg extents0V, const Vec4VArg boxCenter1V, const Vec4VArg extents1V)
{
const Vec4V absTV = V4Abs(V4Sub(boxCenter0V, boxCenter1V));
const BoolV res = V4IsGrtr(absTV, V4Add(extents0V, extents1V));
const PxU32 test = BGetBitMask(res);
if(test&7)
return 0;
return 1;
}
}
static PX_FORCE_INLINE PxIntBool doLeafVsNode_Scaled(const BVDataPackedQ* const PX_RESTRICT root, const BVDataSwizzledQ* PX_RESTRICT node, PxU32 i, MeshMeshParams_Scaled* PX_RESTRICT params)
{
return BV4_ProcessStreamSwizzledNoOrderQ<LeafFunction_MeshMesh_Scaled, MeshMeshParams_Scaled>(root, node->getChildData(i), params);
}
static PX_FORCE_INLINE PxIntBool doLeafVsNode_Scaled(const BVDataPackedNQ* const PX_RESTRICT root, const BVDataSwizzledNQ* PX_RESTRICT node, PxU32 i, MeshMeshParams_Scaled* PX_RESTRICT params)
{
return BV4_ProcessStreamSwizzledNoOrderNQ<LeafFunction_MeshMesh_Scaled, MeshMeshParams_Scaled>(root, node->getChildData(i), params);
}
static void computeVertexSpaceOBB(Box& dst, const Box& src, const PxMat34& inverse)
{
dst = transform(inverse, src);
}
template<class PackedNodeT, class SwizzledNodeT>
static PX_NOINLINE bool doSmallMeshVsTree_Scaled( PxReportCallback<PxGeomIndexPair>& callback, MeshMeshParams_Scaled& params,
const PackedNodeT* PX_RESTRICT node, const SourceMesh* mesh0, const SourceMesh* mesh1, bool& _abort)
{
const PxU32 nbTris = mesh0->getNbTriangles();
PX_ASSERT(nbTris<16);
Vec4V scaledCenterV, scaledExtentV;
Box vertexOBB; // query box in vertex space
// {
BV4_ALIGN16(PxVec3p boxCenter);
BV4_ALIGN16(PxVec3p boxExtents);
Vec4V centerV, extentsV;
computeBoundsAroundVertices(centerV, extentsV, mesh0->getNbVertices(), mesh0->getVerts());
computeMeshBounds(params.mAbsPose0, centerV, extentsV, scaledCenterV, scaledExtentV);
centerV = scaledCenterV;
extentsV = scaledExtentV;
V4StoreA(centerV, &boxCenter.x);
V4StoreA(extentsV, &boxExtents.x);
Box box;
buildFrom(box, boxCenter, boxExtents, PxQuat(PxIdentity));
computeVertexSpaceOBB(vertexOBB, box, params.mMeshPose1, params.mMeshScale1);
params.setupForTraversal(boxCenter, boxExtents, 0.0f/*params.mTolerance*/);
setupBoxParams2(¶ms, vertexOBB);
params.mPrimIndex0 = nbTris;
// }
const PackedNodeT* const root = node;
const SwizzledNodeT* tn = reinterpret_cast<const SwizzledNodeT*>(node);
bool status = false;
for(PxU32 i=0;i<4;i++)
{
if(tn->mData[i]==0xffffffff)
continue;
Vec4V centerV1, extentsV1;
getNodeBounds(centerV1, extentsV1, tn, i, ¶ms.mCenterOrMinCoeff_PaddedAligned, ¶ms.mExtentsOrMaxCoeff_PaddedAligned);
Vec4V scaledCenterV1, scaledExtentV1;
computeMeshBounds(params.mAbsPose1, centerV1, extentsV1, scaledCenterV1, scaledExtentV1);
centerV1 = scaledCenterV1;
extentsV1 = scaledExtentV1;
if(BV4_AABBAABBOverlap(scaledCenterV, scaledExtentV, scaledCenterV1, scaledExtentV1))
{
if(tn->isLeaf(i))
{
bool abort;
if(doLeafVsLeaf_Scaled(params.mTriVsTriParams, nbTris, tn->getPrimitive(i), mesh0, mesh1, params.mAbsPose0, params.mAbsPose1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
}
else
{
if(doLeafVsNode_Scaled(root, tn, i, ¶ms))
return abortQuery(callback, _abort);
}
}
}
return status || params.mStatus;
}
template<class PackedNodeT0, class PackedNodeT1, class SwizzledNodeT0, class SwizzledNodeT1>
static bool BV4_OverlapMeshVsMeshT_Scaled(PxReportCallback<PxGeomIndexPair>& callback, const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0,
const PxTransform& meshPose0, const PxTransform& meshPose1,
const PxMeshScale& meshScale0, const PxMeshScale& meshScale1,
const PxMat34& absPose0, const PxMat34& absPose1,
bool& _abort, bool ignoreCoplanar, trisVsTrisFunction leafFunc, float tolerance)
{
const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface);
const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface);
const PackedNodeT0* PX_RESTRICT node0 = reinterpret_cast<const PackedNodeT0*>(tree0.mNodes);
const PackedNodeT1* PX_RESTRICT node1 = reinterpret_cast<const PackedNodeT1*>(tree1.mNodes);
PX_ASSERT(node0 || node1);
if(!node0 && node1)
{
MeshMeshParams_Scaled ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, mat0to1, tree1, false, ignoreCoplanar, tolerance);
return doSmallMeshVsTree_Scaled<PackedNodeT1, SwizzledNodeT1>(callback, ParamsForTree1Traversal, node1, mesh0, mesh1, _abort);
}
else if(node0 && !node1)
{
MeshMeshParams_Scaled ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, meshPose1, meshPose0, meshScale1, meshScale0, absPose1, absPose0, mat1to0, tree0, true, ignoreCoplanar, tolerance);
return doSmallMeshVsTree_Scaled<PackedNodeT0, SwizzledNodeT0>(callback, ParamsForTree0Traversal, node0, mesh1, mesh0, _abort);
}
else
{
PX_ASSERT(node0);
PX_ASSERT(node1);
// ### some useless computations in there now
MeshMeshParams_Scaled ParamsForTree1Traversal(leafFunc, callback, mesh0, mesh1, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, mat0to1, tree1, false, ignoreCoplanar, tolerance);
MeshMeshParams_Scaled ParamsForTree0Traversal(leafFunc, callback, mesh1, mesh0, meshPose1, meshPose0, meshScale1, meshScale0, absPose1, absPose0, mat1to0, tree0, true, ignoreCoplanar, tolerance);
const PxMat34 inverse0 = meshScale0.getInverse() * Matrix34FromTransform(meshPose0.getInverse());
const PxMat34 inverse1 = meshScale1.getInverse() * Matrix34FromTransform(meshPose1.getInverse());
BV4_ALIGN16(PxVec3p boxCenter0);
BV4_ALIGN16(PxVec3p boxExtents0);
BV4_ALIGN16(PxVec3p boxCenter1);
BV4_ALIGN16(PxVec3p boxExtents1);
struct indexPair
{
PxU32 index0;
PxU32 index1;
};
PxU32 nb=1;
indexPair stack[GU_BV4_STACK_SIZE];
stack[0].index0 = tree0.mInitData;
stack[0].index1 = tree1.mInitData;
bool status = false;
const PackedNodeT0* const root0 = node0;
const PackedNodeT1* const root1 = node1;
do
{
const indexPair& childData = stack[--nb];
node0 = root0 + getChildOffset(childData.index0);
node1 = root1 + getChildOffset(childData.index1);
const SwizzledNodeT0* tn0 = reinterpret_cast<const SwizzledNodeT0*>(node0);
const SwizzledNodeT1* tn1 = reinterpret_cast<const SwizzledNodeT1*>(node1);
for(PxU32 i=0;i<4;i++)
{
if(tn0->mData[i]==0xffffffff)
continue;
Vec4V centerV0, extentsV0;
getNodeBounds(centerV0, extentsV0, tn0, i, &ParamsForTree0Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree0Traversal.mExtentsOrMaxCoeff_PaddedAligned);
Vec4V scaledCenterV0, scaledExtentV0;
computeMeshBounds(absPose0, centerV0, extentsV0, scaledCenterV0, scaledExtentV0);
centerV0 = scaledCenterV0;
extentsV0 = scaledExtentV0;
V4StoreA(centerV0, &boxCenter0.x);
V4StoreA(extentsV0, &boxExtents0.x);
for(PxU32 j=0;j<4;j++)
{
if(tn1->mData[j]==0xffffffff)
continue;
Vec4V centerV1, extentsV1;
getNodeBounds(centerV1, extentsV1, tn1, j, &ParamsForTree1Traversal.mCenterOrMinCoeff_PaddedAligned, &ParamsForTree1Traversal.mExtentsOrMaxCoeff_PaddedAligned);
Vec4V scaledCenterV1, scaledExtentV1;
computeMeshBounds(absPose1, centerV1, extentsV1, scaledCenterV1, scaledExtentV1);
centerV1 = scaledCenterV1;
extentsV1 = scaledExtentV1;
if(BV4_AABBAABBOverlap(scaledCenterV0, scaledExtentV0, scaledCenterV1, scaledExtentV1))
{
const PxU32 isLeaf0 = tn0->isLeaf(i);
const PxU32 isLeaf1 = tn1->isLeaf(j);
if(isLeaf0)
{
if(isLeaf1)
{
bool abort;
if(doLeafVsLeaf_Scaled(ParamsForTree1Traversal.mTriVsTriParams, tn0->getPrimitive(i), tn1->getPrimitive(j), mesh0, mesh1, absPose0, absPose1, abort))
status = true;
if(abort)
return abortQuery(callback, _abort);
}
else
{
Box box;
buildFrom(box, boxCenter0, boxExtents0, PxQuat(PxIdentity));
Box vertexOBB; // query box in vertex space
computeVertexSpaceOBB(vertexOBB, box, inverse1);
setupBoxParams2(&ParamsForTree1Traversal, vertexOBB);
ParamsForTree1Traversal.mPrimIndex0 = tn0->getPrimitive(i);
if(doLeafVsNode_Scaled(root1, tn1, j, &ParamsForTree1Traversal))
return abortQuery(callback, _abort);
}
}
else
{
if(isLeaf1)
{
V4StoreA(centerV1, &boxCenter1.x);
V4StoreA(extentsV1, &boxExtents1.x);
Box box;
buildFrom(box, boxCenter1, boxExtents1, PxQuat(PxIdentity));
Box vertexOBB; // query box in vertex space
computeVertexSpaceOBB(vertexOBB, box, inverse0);
setupBoxParams2(&ParamsForTree0Traversal, vertexOBB);
ParamsForTree0Traversal.mPrimIndex0 = tn1->getPrimitive(j);
if(doLeafVsNode_Scaled(root0, tn0, i, &ParamsForTree0Traversal))
return abortQuery(callback, _abort);
}
else
{
stack[nb].index0 = tn0->getChildData(i);
stack[nb].index1 = tn1->getChildData(j);
nb++;
}
}
}
}
}
}while(nb);
return status || ParamsForTree0Traversal.mStatus || ParamsForTree1Traversal.mStatus;
}
}
bool BV4_OverlapMeshVsMesh(
PxReportCallback<PxGeomIndexPair>& callback,
const BV4Tree& tree0, const BV4Tree& tree1, const PxMat44* mat0to1, const PxMat44* mat1to0,
const PxTransform& meshPose0, const PxTransform& meshPose1,
const PxMeshScale& meshScale0, const PxMeshScale& meshScale1,
PxMeshMeshQueryFlags meshMeshFlags, float tolerance)
{
PxGeomIndexPair stackBuffer[256];
bool mustResetBuffer;
if(callback.mBuffer)
{
PX_ASSERT(callback.mCapacity);
mustResetBuffer = false;
}
else
{
callback.mBuffer = stackBuffer;
PX_ASSERT(callback.mCapacity<=256);
if(callback.mCapacity==0 || callback.mCapacity>256)
{
callback.mCapacity = 256;
}
callback.mSize = 0;
mustResetBuffer = true;
}
// PT: TODO: we now compute this pose eagerly rather than lazily. Maybe revisit this later.
const PxMat34 absPose0 = getAbsPose(meshPose0, meshScale0);
const PxMat34 absPose1 = getAbsPose(meshPose1, meshScale1);
const bool ignoreCoplanar = meshMeshFlags & PxMeshMeshQueryFlag::eDISCARD_COPLANAR;
const trisVsTrisFunction leafFunc = getLeafFunc(meshMeshFlags, tolerance);
bool status;
bool abort = false;
if(!tree0.mNodes && !tree1.mNodes)
{
const SourceMesh* mesh0 = static_cast<const SourceMesh*>(tree0.mMeshInterface);
const SourceMesh* mesh1 = static_cast<const SourceMesh*>(tree1.mMeshInterface);
status = doSmallMeshVsSmallMesh_Scaled(callback, mesh0, mesh1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance);
}
else
{
if(tree0.mQuantized)
{
if(tree1.mQuantized)
status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedQ, BVDataPackedQ, BVDataSwizzledQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance);
else
status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedQ, BVDataPackedNQ, BVDataSwizzledQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance);
}
else
{
if(tree1.mQuantized)
status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedNQ, BVDataPackedQ, BVDataSwizzledNQ, BVDataSwizzledQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance);
else
status = BV4_OverlapMeshVsMeshT_Scaled<BVDataPackedNQ, BVDataPackedNQ, BVDataSwizzledNQ, BVDataSwizzledNQ>(callback, tree0, tree1, mat0to1, mat1to0, meshPose0, meshPose1, meshScale0, meshScale1, absPose0, absPose1, abort, ignoreCoplanar, leafFunc, tolerance);
}
}
if(!abort)
{
const PxU32 currentSize = callback.mSize;
if(currentSize)
{
callback.mSize = 0;
callback.flushResults(currentSize, callback.mBuffer);
}
}
if(mustResetBuffer)
callback.mBuffer = NULL;
return status;
}
| 63,268 | C++ | 32.004173 | 263 | 0.695628 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_SwizzledNoOrder.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SLABS_SWIZZLED_NO_ORDER_H
#define GU_BV4_SLABS_SWIZZLED_NO_ORDER_H
// Generic, no sort
/* template<class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamSwizzledNoOrder(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node);
const PxU32 nodeType = getChildType(childData);
if(nodeType>1 && BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 3>(stack, nb, tn, params))
return 1;
if(nodeType>0 && BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 2>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 1>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_Swizzled<LeafTestT, 0>(stack, nb, tn, params))
return 1;
}while(nb);
return 0;
}*/
template<class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamSwizzledNoOrderQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node);
const PxU32 nodeType = getChildType(childData);
if(nodeType>1 && BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 3>(stack, nb, tn, params))
return 1;
if(nodeType>0 && BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 2>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 1>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_SwizzledQ<LeafTestT, 0>(stack, nb, tn, params))
return 1;
}while(nb);
return 0;
}
template<class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamSwizzledNoOrderNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedNQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node);
const PxU32 nodeType = getChildType(childData);
if(nodeType>1 && BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 3>(stack, nb, tn, params))
return 1;
if(nodeType>0 && BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 2>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 1>(stack, nb, tn, params))
return 1;
if(BV4_ProcessNodeNoOrder_SwizzledNQ<LeafTestT, 0>(stack, nb, tn, params))
return 1;
}while(nb);
return 0;
}
#endif // GU_BV4_SLABS_SWIZZLED_NO_ORDER_H
| 4,669 | C | 34.923077 | 137 | 0.730992 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_CapsuleSweep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
#include "GuSweepSphereTriangle.h"
using namespace physx;
using namespace Gu;
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#include "GuInternal.h"
#include "GuBV4_BoxOverlap_Internal.h"
#include "GuBV4_BoxSweep_Params.h"
namespace
{
struct CapsuleSweepParams : BoxSweepParams
{
Capsule mLocalCapsule;
PxVec3 mCapsuleCenter;
PxVec3 mExtrusionDir;
float mBestAlignmentValue;
float mBestDistance;
float mMaxDist;
// PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; }
PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; }
};
}
#include "GuBV4_CapsuleSweep_Internal.h"
#include "GuBV4_BoxBoxOverlapTest.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
#endif
#include "GuBV4_ProcessStreamOrdered_OBBOBB.h"
#include "GuBV4_ProcessStreamNoOrder_OBBOBB.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_SwizzledNoOrder.h"
#include "GuBV4_Slabs_SwizzledOrdered.h"
#endif
#define GU_BV4_PROCESS_STREAM_NO_ORDER
#define GU_BV4_PROCESS_STREAM_ORDERED
#include "GuBV4_Internal.h"
PxIntBool BV4_CapsuleSweepSingle(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
CapsuleSweepParams Params;
setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags);
if(tree.mNodes)
{
if(Params.mEarlyExit)
processStreamNoOrder<LeafFunction_CapsuleSweepAny>(tree, &Params);
else
processStreamOrdered<LeafFunction_CapsuleSweepClosest>(tree, &Params);
}
else
doBruteForceTests<LeafFunction_CapsuleSweepAny, LeafFunction_CapsuleSweepClosest>(mesh->getNbTriangles(), &Params);
return computeImpactDataT<ImpactFunctionCapsule>(capsule, dir, hit, &Params, NULL, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0);
}
// PT: capsule sweep callback version - currently not used
namespace
{
struct CapsuleSweepParamsCB : CapsuleSweepParams
{
// PT: these new members are only here to call computeImpactDataT during traversal :(
// PT: TODO: most of them may not be needed
// PT: TODO: for example mCapsuleCB probably dup of mLocalCapsule
Capsule mCapsuleCB; // Capsule in original space (maybe not local/mesh space)
PxVec3 mDirCB; // Dir in original space (maybe not local/mesh space)
const PxMat44* mWorldm_Aligned;
PxU32 mFlags;
SweepUnlimitedCallback mCallback;
void* mUserData;
bool mNodeSorting;
};
class LeafFunction_CapsuleSweepCB
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(CapsuleSweepParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(triCapsuleSweep(params, primIndex, params->mNodeSorting))
{
// PT: TODO: in this version we must compute the impact data immediately,
// which is a terrible idea in general, but I'm not sure what else I can do.
SweepHit hit;
const bool b = computeImpactDataT<ImpactFunctionCapsule>(params->mCapsuleCB, params->mDirCB, &hit, params, params->mWorldm_Aligned, (params->mFlags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (params->mFlags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0);
PX_ASSERT(b);
PX_UNUSED(b);
reportUnlimitedCallbackHit(params, hit);
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
// PT: for design decisions in this function, refer to the comments of BV4_GenericSweepCB().
void BV4_CapsuleSweepCB(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, SweepUnlimitedCallback callback, void* userData, PxU32 flags, bool nodeSorting)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
CapsuleSweepParamsCB Params;
Params.mCapsuleCB = capsule;
Params.mDirCB = dir;
Params.mWorldm_Aligned = worldm_Aligned;
Params.mFlags = flags;
Params.mCallback = callback;
Params.mUserData = userData;
Params.mMaxDist = maxDist;
Params.mNodeSorting = nodeSorting;
setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags);
PX_ASSERT(!Params.mEarlyExit);
if(tree.mNodes)
{
if(nodeSorting)
processStreamOrdered<LeafFunction_CapsuleSweepCB>(tree, &Params);
else
processStreamNoOrder<LeafFunction_CapsuleSweepCB>(tree, &Params);
}
else
doBruteForceTests<LeafFunction_CapsuleSweepCB, LeafFunction_CapsuleSweepCB>(mesh->getNbTriangles(), &Params);
}
| 6,216 | C++ | 35.145349 | 241 | 0.757239 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_CapsuleSweepAA.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
#include "GuSweepSphereTriangle.h"
using namespace physx;
using namespace Gu;
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#include "GuBV4_Common.h"
#include "GuInternal.h"
#define SWEEP_AABB_IMPL
// PT: TODO: refactor structure (TA34704)
namespace
{
struct RayParams
{
BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned);
#ifndef GU_BV4_USE_SLABS
BV4_ALIGN16(PxVec3p mData2_PaddedAligned);
BV4_ALIGN16(PxVec3p mFDir_PaddedAligned);
BV4_ALIGN16(PxVec3p mData_PaddedAligned);
BV4_ALIGN16(PxVec3p mLocalDir_PaddedAligned);
#endif
BV4_ALIGN16(PxVec3p mOrigin_Padded); // PT: TODO: this one could be switched to PaddedAligned & V4LoadA (TA34704)
};
}
#include "GuBV4_BoxSweep_Params.h"
namespace
{
struct CapsuleSweepParams : BoxSweepParams
{
Capsule mLocalCapsule;
PxVec3 mCapsuleCenter;
PxVec3 mExtrusionDir;
float mBestAlignmentValue;
float mBestDistance;
float mMaxDist;
// PX_FORCE_INLINE float getReportDistance() const { return mStabbedFace.mDistance; }
PX_FORCE_INLINE float getReportDistance() const { return mBestDistance; }
};
}
#include "GuBV4_CapsuleSweep_Internal.h"
#include "GuBV4_AABBAABBSweepTest.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
#endif
#include "GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h"
#include "GuBV4_ProcessStreamNoOrder_SegmentAABB_Inflated.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_KajiyaNoOrder.h"
#include "GuBV4_Slabs_KajiyaOrdered.h"
#endif
#define GU_BV4_PROCESS_STREAM_RAY_NO_ORDER
#define GU_BV4_PROCESS_STREAM_RAY_ORDERED
#include "GuBV4_Internal.h"
PxIntBool BV4_CapsuleSweepSingleAA(const Capsule& capsule, const PxVec3& dir, float maxDist, const BV4Tree& tree, SweepHit* PX_RESTRICT hit, PxU32 flags)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
CapsuleSweepParams Params;
setupCapsuleParams(&Params, capsule, dir, maxDist, &tree, mesh, flags);
if(tree.mNodes)
{
if(Params.mEarlyExit)
processStreamRayNoOrder<1, LeafFunction_CapsuleSweepAny>(tree, &Params);
else
processStreamRayOrdered<1, LeafFunction_CapsuleSweepClosest>(tree, &Params);
}
else
doBruteForceTests<LeafFunction_CapsuleSweepAny, LeafFunction_CapsuleSweepClosest>(mesh->getNbPrimitives(), &Params);
return computeImpactDataT<ImpactFunctionCapsule>(capsule, dir, hit, &Params, NULL, (flags & QUERY_MODIFIER_DOUBLE_SIDED)!=0, (flags & QUERY_MODIFIER_MESH_BOTH_SIDES)!=0);
}
| 4,216 | C++ | 36.651785 | 171 | 0.771347 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMesh.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuMidphaseInterface.h"
#include "GuMeshFactory.h"
#include "GuConvexEdgeFlags.h"
#include "GuEdgeList.h"
#include "geometry/PxGeometryInternal.h"
using namespace physx;
using namespace Gu;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PxConcreteType::Enum gTable[] = { PxConcreteType::eTRIANGLE_MESH_BVH33,
PxConcreteType::eTRIANGLE_MESH_BVH34
};
TriangleMesh::TriangleMesh(MeshFactory* factory, TriangleMeshData& d) :
PxTriangleMesh (PxType(gTable[d.mType]), PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mNbVertices (d.mNbVertices),
mNbTriangles (d.mNbTriangles),
mVertices (d.mVertices),
mTriangles (d.mTriangles),
mAABB (d.mAABB),
mExtraTrigData (d.mExtraTrigData),
mGeomEpsilon (d.mGeomEpsilon),
mFlags (d.mFlags),
mMaterialIndices (d.mMaterialIndices),
mFaceRemap (d.mFaceRemap),
mAdjacencies (d.mAdjacencies),
mMeshFactory (factory),
mEdgeList (NULL),
mMass (d.mMass),
mInertia (d.mInertia),
mLocalCenterOfMass (d.mLocalCenterOfMass),
mGRB_triIndices (d.mGRB_primIndices),
mGRB_triAdjacencies (d.mGRB_primAdjacencies),
mGRB_faceRemap (d.mGRB_faceRemap),
mGRB_faceRemapInverse (d.mGRB_faceRemapInverse),
mGRB_BV32Tree (d.mGRB_BV32Tree),
mSdfData (d.mSdfData),
mAccumulatedTrianglesRef (d.mAccumulatedTrianglesRef),
mTrianglesReferences (d.mTrianglesReferences),
mNbTrianglesReferences (d.mNbTrianglesReferences)
{
// this constructor takes ownership of memory from the data object
d.mVertices = NULL;
d.mTriangles = NULL;
d.mExtraTrigData = NULL;
d.mFaceRemap = NULL;
d.mAdjacencies = NULL;
d.mMaterialIndices = NULL;
d.mGRB_primIndices = NULL;
d.mGRB_primAdjacencies = NULL;
d.mGRB_faceRemap = NULL;
d.mGRB_faceRemapInverse = NULL;
d.mGRB_BV32Tree = NULL;
d.mSdfData.mSdf = NULL;
d.mSdfData.mSubgridStartSlots = NULL;
d.mSdfData.mSubgridSdf = NULL;
d.mAccumulatedTrianglesRef = NULL;
d.mTrianglesReferences = NULL;
// PT: 'getPaddedBounds()' is only safe if we make sure the bounds member is followed by at least 32bits of data
PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(TriangleMesh, mExtraTrigData)>=PX_OFFSET_OF(TriangleMesh, mAABB)+4);
}
// PT: temporary for Kit
TriangleMesh::TriangleMesh(const PxTriangleMeshInternalData& data) :
PxTriangleMesh (PxConcreteType::eTRIANGLE_MESH_BVH34, PxBaseFlags(0)),
mNbVertices (data.mNbVertices),
mNbTriangles (data.mNbTriangles),
mVertices (data.mVertices),
mTriangles (data.mTriangles),
mExtraTrigData (NULL),
mGeomEpsilon (data.mGeomEpsilon),
mFlags (data.mFlags),
mMaterialIndices (NULL),
mFaceRemap (data.mFaceRemap),
mAdjacencies (NULL),
mMeshFactory (NULL),
mEdgeList (NULL),
mGRB_triIndices (NULL),
mGRB_triAdjacencies (NULL),
mGRB_faceRemap (NULL),
mGRB_faceRemapInverse (NULL),
mGRB_BV32Tree (NULL),
mAccumulatedTrianglesRef(NULL),
mTrianglesReferences (NULL),
mNbTrianglesReferences (0)
{
mAABB.mCenter = data.mAABB_Center;
mAABB.mExtents = data.mAABB_Extents;
}
//~ PT: temporary for Kit
TriangleMesh::~TriangleMesh()
{
if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
{
PX_FREE(mExtraTrigData);
PX_FREE(mFaceRemap);
PX_FREE(mAdjacencies);
PX_FREE(mMaterialIndices);
PX_FREE(mTriangles);
PX_FREE(mVertices);
PX_FREE(mGRB_triIndices);
PX_FREE(mGRB_triAdjacencies);
PX_FREE(mGRB_faceRemap);
PX_FREE(mGRB_faceRemapInverse);
PX_DELETE(mGRB_BV32Tree);
PX_FREE(mAccumulatedTrianglesRef);
PX_FREE(mTrianglesReferences);
}
PX_DELETE(mEdgeList);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PT: used to be automatic but making it manual saves bytes in the internal mesh
void TriangleMesh::exportExtraData(PxSerializationContext& stream)
{
//PX_DEFINE_DYNAMIC_ARRAY(TriangleMesh, mVertices, PxField::eVEC3, mNbVertices, Ps::PxFieldFlag::eSERIALIZE),
if(mVertices)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mVertices, mNbVertices * sizeof(PxVec3));
}
if(mTriangles)
{
const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32);
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mTriangles, mNbTriangles * 3 * triangleSize);
}
//PX_DEFINE_DYNAMIC_ARRAY(TriangleMesh, mExtraTrigData, PxField::eBYTE, mNbTriangles, Ps::PxFieldFlag::eSERIALIZE),
if(mExtraTrigData)
{
// PT: it might not be needed to 16-byte align this array of PxU8....
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mExtraTrigData, mNbTriangles * sizeof(PxU8));
}
if(mMaterialIndices)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mMaterialIndices, mNbTriangles * sizeof(PxU16));
}
if(mFaceRemap)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mFaceRemap, mNbTriangles * sizeof(PxU32));
}
if(mAdjacencies)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mAdjacencies, mNbTriangles * sizeof(PxU32) * 3);
}
if(mGRB_triIndices)
{
const PxU32 triangleSize = mFlags & PxTriangleMeshFlag::e16_BIT_INDICES ? sizeof(PxU16) : sizeof(PxU32);
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mGRB_triIndices, mNbTriangles * 3 * triangleSize);
}
if(mGRB_triAdjacencies)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mGRB_triAdjacencies, mNbTriangles * sizeof(PxU32) * 4);
}
if(mGRB_faceRemap)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mGRB_faceRemap, mNbTriangles * sizeof(PxU32));
}
if(mGRB_faceRemapInverse)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mGRB_faceRemapInverse, mNbTriangles * sizeof(PxU32));
}
if(mGRB_BV32Tree)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mGRB_BV32Tree, sizeof(BV32Tree));
mGRB_BV32Tree->exportExtraData(stream);
}
mSdfData.exportExtraData(stream);
}
void TriangleMesh::importExtraData(PxDeserializationContext& context)
{
// PT: vertices are followed by indices, so it will be safe to V4Load vertices from a deserialized binary file
if(mVertices)
mVertices = context.readExtraData<PxVec3, PX_SERIAL_ALIGN>(mNbVertices);
if(mTriangles)
{
if(mFlags & PxTriangleMeshFlag::e16_BIT_INDICES)
mTriangles = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(3*mNbTriangles);
else
mTriangles = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3*mNbTriangles);
}
if(mExtraTrigData)
mExtraTrigData = context.readExtraData<PxU8, PX_SERIAL_ALIGN>(mNbTriangles);
if(mMaterialIndices)
mMaterialIndices = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(mNbTriangles);
if(mFaceRemap)
mFaceRemap = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles);
if(mAdjacencies)
mAdjacencies = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3*mNbTriangles);
if(mGRB_triIndices)
{
if(mFlags & PxTriangleMeshFlag::e16_BIT_INDICES)
mGRB_triIndices = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(3 * mNbTriangles);
else
mGRB_triIndices = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(3 * mNbTriangles);
}
if(mGRB_triAdjacencies)
{
mGRB_triAdjacencies = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(4 * mNbTriangles);
}
if(mGRB_faceRemap)
{
mGRB_faceRemap = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles);
}
if(mGRB_faceRemapInverse)
{
mGRB_faceRemapInverse = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mNbTriangles);
}
if(mGRB_BV32Tree)
{
mGRB_BV32Tree = context.readExtraData<BV32Tree, PX_SERIAL_ALIGN>();
PX_PLACEMENT_NEW(mGRB_BV32Tree, BV32Tree(PxEmpty));
mGRB_BV32Tree->importExtraData(context);
}
mSdfData.importExtraData(context);
}
void TriangleMesh::onRefCountZero()
{
::onRefCountZero(this, mMeshFactory, false, "PxTriangleMesh::release: double deletion detected!");
}
void TriangleMesh::release()
{
Cm::RefCountable_decRefCount(*this);
}
PxVec3* TriangleMesh::getVerticesForModification()
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxTriangleMesh::getVerticesForModification() is not supported for this type of meshes.");
return NULL;
}
PxBounds3 TriangleMesh::refitBVH()
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxTriangleMesh::refitBVH() is not supported for this type of meshes.");
return PxBounds3(mAABB.getMin(), mAABB.getMax());
}
void TriangleMesh::setAllEdgesActive()
{
if(mExtraTrigData)
{
const PxU32 nbTris = mNbTriangles;
for(PxU32 i=0; i<nbTris; i++)
mExtraTrigData[i] |= ETD_CONVEX_EDGE_ALL;
}
}
const EdgeList* TriangleMesh::requestEdgeList() const
{
if(!mEdgeList)
{
EDGELISTCREATE create;
create.NbFaces = mNbTriangles;
create.Verts = mVertices;
if(has16BitIndices())
create.WFaces = reinterpret_cast<const PxU16*>(mTriangles);
else
create.DFaces = reinterpret_cast<const PxU32*>(mTriangles);
mEdgeList = PX_NEW(EdgeList);
mEdgeList->init(create);
}
return mEdgeList;
}
| 10,815 | C++ | 30.625731 | 199 | 0.716412 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuMidphaseInterface.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_MIDPHASE_INTERFACE_H
#define GU_MIDPHASE_INTERFACE_H
#include "GuOverlapTests.h"
#include "GuRaycastTests.h"
#include "GuTriangleMesh.h"
#include "GuTetrahedronMesh.h"
#include "foundation/PxVecMath.h"
#include "PxQueryReport.h"
#include "geometry/PxMeshQuery.h" // PT: TODO: revisit this include
// PT: this file contains the common interface for all midphase implementations. Specifically the Midphase namespace contains the
// midphase-related entry points, dispatching calls to the proper implementations depending on the triangle mesh's type. The rest of it
// is simply classes & structs shared by all implementations.
namespace physx
{
class PxMeshScale;
class PxTriangleMeshGeometry;
namespace Cm
{
class FastVertex2ShapeScaling;
}
namespace Gu
{
struct ConvexHullData;
struct CallbackMode { enum Enum { eANY, eCLOSEST, eMULTIPLE }; };
template<typename HitType>
struct MeshHitCallback
{
CallbackMode::Enum mode;
MeshHitCallback(CallbackMode::Enum aMode) : mode(aMode) {}
PX_FORCE_INLINE bool inAnyMode() const { return mode == CallbackMode::eANY; }
PX_FORCE_INLINE bool inClosestMode() const { return mode == CallbackMode::eCLOSEST; }
PX_FORCE_INLINE bool inMultipleMode() const { return mode == CallbackMode::eMULTIPLE; }
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const HitType& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal& shrunkMaxT, const PxU32* vIndices) = 0;
virtual ~MeshHitCallback() {}
};
template<typename HitType>
struct TetMeshHitCallback
{
CallbackMode::Enum mode;
TetMeshHitCallback(CallbackMode::Enum aMode) : mode(aMode) {}
PX_FORCE_INLINE bool inAnyMode() const { return mode == CallbackMode::eANY; }
PX_FORCE_INLINE bool inClosestMode() const { return mode == CallbackMode::eCLOSEST; }
PX_FORCE_INLINE bool inMultipleMode() const { return mode == CallbackMode::eMULTIPLE; }
virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position
const HitType& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& v3, PxReal& shrunkMaxT, const PxU32* vIndices) = 0;
virtual ~TetMeshHitCallback() {}
};
struct SweepConvexMeshHitCallback;
struct LimitedResults
{
PxU32* mResults;
PxU32 mNbResults;
PxU32 mMaxResults;
PxU32 mStartIndex;
PxU32 mNbSkipped;
bool mOverflow;
PX_FORCE_INLINE LimitedResults(PxU32* results, PxU32 maxResults, PxU32 startIndex)
: mResults(results), mMaxResults(maxResults), mStartIndex(startIndex)
{
reset();
}
PX_FORCE_INLINE void reset()
{
mNbResults = 0;
mNbSkipped = 0;
mOverflow = false;
}
PX_FORCE_INLINE bool add(PxU32 index)
{
if(mNbResults>=mMaxResults)
{
mOverflow = true;
return false;
}
if(mNbSkipped>=mStartIndex)
mResults[mNbResults++] = index;
else
mNbSkipped++;
return true;
}
};
// RTree forward declarations
PX_PHYSX_COMMON_API PxU32 raycast_triangleMesh_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose,
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist,
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride);
PX_PHYSX_COMMON_API bool intersectSphereVsMesh_RTREE(const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API bool intersectBoxVsMesh_RTREE (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API bool intersectCapsuleVsMesh_RTREE(const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API void intersectOBB_RTREE(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned);
PX_PHYSX_COMMON_API bool sweepCapsule_MeshGeom_RTREE( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
PX_PHYSX_COMMON_API bool sweepBox_MeshGeom_RTREE( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Box& box, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
PX_PHYSX_COMMON_API void sweepConvex_MeshGeom_RTREE(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit);
PX_PHYSX_COMMON_API void pointMeshDistance_RTREE(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt);
// BV4 forward declarations
PX_PHYSX_COMMON_API PxU32 raycast_triangleMesh_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose,
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist,
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride);
PX_PHYSX_COMMON_API bool intersectSphereVsMesh_BV4 (const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API bool intersectBoxVsMesh_BV4 (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API bool intersectCapsuleVsMesh_BV4 (const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
PX_PHYSX_COMMON_API void intersectOBB_BV4(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned);
PX_PHYSX_COMMON_API void intersectOBB_BV4(const TetrahedronMesh* mesh, const Box& obb, TetMeshHitCallback<PxGeomRaycastHit>& callback);
PX_PHYSX_COMMON_API bool sweepCapsule_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
PX_PHYSX_COMMON_API bool sweepBox_MeshGeom_BV4( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Box& box, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
PX_PHYSX_COMMON_API void sweepConvex_MeshGeom_BV4(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit);
PX_PHYSX_COMMON_API void pointMeshDistance_BV4(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt);
PX_PHYSX_COMMON_API bool intersectMeshVsMesh_BV4( PxReportCallback<PxGeomIndexPair>& callback,
const TriangleMesh& triMesh0, const PxTransform& meshPose0, const PxMeshScale& meshScale0,
const TriangleMesh& triMesh1, const PxTransform& meshPose1, const PxMeshScale& meshScale1,
PxMeshMeshQueryFlags meshMeshFlags, float tolerance);
typedef PxU32 (*MidphaseRaycastFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose,
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist,
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride);
typedef bool (*MidphaseSphereOverlapFunction) (const Sphere& sphere, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
typedef bool (*MidphaseBoxOverlapFunction) (const Box& box, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
typedef bool (*MidphaseCapsuleOverlapFunction) (const Capsule& capsule, const TriangleMesh& triMesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results);
typedef void (*MidphaseBoxCBOverlapFunction) (const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned);
typedef bool (*MidphaseCapsuleSweepFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Capsule& lss, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
typedef bool (*MidphaseBoxSweepFunction)( const TriangleMesh* mesh, const PxTriangleMeshGeometry& triMeshGeom, const PxTransform& pose,
const Gu::Box& box, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation);
typedef void (*MidphaseConvexSweepFunction)( const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit);
typedef void (*MidphasePointMeshFunction)(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist, PxU32& index, float& dist, PxVec3& closestPt);
static const MidphaseRaycastFunction gMidphaseRaycastTable[PxMeshMidPhase::eLAST] =
{
raycast_triangleMesh_RTREE,
raycast_triangleMesh_BV4,
};
static const MidphaseSphereOverlapFunction gMidphaseSphereOverlapTable[PxMeshMidPhase::eLAST] =
{
intersectSphereVsMesh_RTREE,
intersectSphereVsMesh_BV4,
};
static const MidphaseBoxOverlapFunction gMidphaseBoxOverlapTable[PxMeshMidPhase::eLAST] =
{
intersectBoxVsMesh_RTREE,
intersectBoxVsMesh_BV4,
};
static const MidphaseCapsuleOverlapFunction gMidphaseCapsuleOverlapTable[PxMeshMidPhase::eLAST] =
{
intersectCapsuleVsMesh_RTREE,
intersectCapsuleVsMesh_BV4,
};
static const MidphaseBoxCBOverlapFunction gMidphaseBoxCBOverlapTable[PxMeshMidPhase::eLAST] =
{
intersectOBB_RTREE,
intersectOBB_BV4,
};
static const MidphaseBoxSweepFunction gMidphaseBoxSweepTable[PxMeshMidPhase::eLAST] =
{
sweepBox_MeshGeom_RTREE,
sweepBox_MeshGeom_BV4,
};
static const MidphaseCapsuleSweepFunction gMidphaseCapsuleSweepTable[PxMeshMidPhase::eLAST] =
{
sweepCapsule_MeshGeom_RTREE,
sweepCapsule_MeshGeom_BV4,
};
static const MidphaseConvexSweepFunction gMidphaseConvexSweepTable[PxMeshMidPhase::eLAST] =
{
sweepConvex_MeshGeom_RTREE,
sweepConvex_MeshGeom_BV4,
};
static const MidphasePointMeshFunction gMidphasePointMeshTable[PxMeshMidPhase::eLAST] =
{
pointMeshDistance_RTREE,
pointMeshDistance_BV4,
};
namespace Midphase
{
// \param[in] mesh triangle mesh to raycast against
// \param[in] meshGeom geometry object associated with the mesh
// \param[in] meshTransform pose/transform of geometry object
// \param[in] rayOrigin ray's origin
// \param[in] rayDir ray's unit dir
// \param[in] maxDist ray's length/max distance
// \param[in] hitFlags query behavior flags
// \param[in] maxHits max number of hits = size of 'hits' buffer
// \param[out] hits result buffer where to write raycast hits
// \return number of hits written to 'hits' result buffer
// \note there's no mechanism to report overflow. Returned number of hits is just clamped to maxHits.
PX_FORCE_INLINE PxU32 raycastTriangleMesh( const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform,
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist,
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseRaycastTable[index](mesh, meshGeom, meshTransform, rayOrigin, rayDir, maxDist, hitFlags, maxHits, hits, stride);
}
// \param[in] sphere sphere
// \param[in] mesh triangle mesh
// \param[in] meshTransform pose/transform of triangle mesh
// \param[in] meshScale mesh scale
// \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough
// \return true if at least one overlap has been found
PX_FORCE_INLINE bool intersectSphereVsMesh(const Sphere& sphere, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseSphereOverlapTable[index](sphere, mesh, meshTransform, meshScale, results);
}
// \param[in] box box
// \param[in] mesh triangle mesh
// \param[in] meshTransform pose/transform of triangle mesh
// \param[in] meshScale mesh scale
// \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough
// \return true if at least one overlap has been found
PX_FORCE_INLINE bool intersectBoxVsMesh(const Box& box, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseBoxOverlapTable[index](box, mesh, meshTransform, meshScale, results);
}
// \param[in] capsule capsule
// \param[in] mesh triangle mesh
// \param[in] meshTransform pose/transform of triangle mesh
// \param[in] meshScale mesh scale
// \param[out] results results object if multiple hits are needed, NULL if a simple boolean answer is enough
// \return true if at least one overlap has been found
PX_FORCE_INLINE bool intersectCapsuleVsMesh(const Capsule& capsule, const TriangleMesh& mesh, const PxTransform& meshTransform, const PxMeshScale& meshScale, LimitedResults* results)
{
const PxU32 index = PxU32(mesh.getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseCapsuleOverlapTable[index](capsule, mesh, meshTransform, meshScale, results);
}
// \param[in] mesh triangle mesh
// \param[in] box box
// \param[in] callback callback object, called each time a hit is found
// \param[in] bothTriangleSidesCollide true for double-sided meshes
// \param[in] checkObbIsAligned true to use a dedicated codepath for axis-aligned boxes
PX_FORCE_INLINE void intersectOBB(const TriangleMesh* mesh, const Box& obb, MeshHitCallback<PxGeomRaycastHit>& callback, bool bothTriangleSidesCollide, bool checkObbIsAligned = true)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
gMidphaseBoxCBOverlapTable[index](mesh, obb, callback, bothTriangleSidesCollide, checkObbIsAligned);
}
// \param[in] mesh tetrahedron mesh
// \param[in] box box
// \param[in] callback callback object, called each time a hit is found
PX_FORCE_INLINE void intersectOBB(const TetrahedronMesh* mesh, const Box& obb, TetMeshHitCallback<PxGeomRaycastHit>& callback)
{
intersectOBB_BV4(mesh, obb, callback);
}
// \param[in] mesh triangle mesh
// \param[in] meshGeom geometry object associated with the mesh
// \param[in] meshTransform pose/transform of geometry object
// \param[in] capsule swept capsule
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] sweepHit hit result
// \param[in] hitFlags query behavior flags
// \param[in] inflation optional inflation value for swept shape
// \return true if a hit was found, false otherwise
PX_FORCE_INLINE bool sweepCapsuleVsMesh(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform,
const Gu::Capsule& capsule, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseCapsuleSweepTable[index](mesh, meshGeom, meshTransform, capsule, unitDir, distance, sweepHit, hitFlags, inflation);
}
// \param[in] mesh triangle mesh
// \param[in] meshGeom geometry object associated with the mesh
// \param[in] meshTransform pose/transform of geometry object
// \param[in] box swept box
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] sweepHit hit result
// \param[in] hitFlags query behavior flags
// \param[in] inflation optional inflation value for swept shape
// \return true if a hit was found, false otherwise
PX_FORCE_INLINE bool sweepBoxVsMesh(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshTransform,
const Gu::Box& box, const PxVec3& unitDir, PxReal distance,
PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
return gMidphaseBoxSweepTable[index](mesh, meshGeom, meshTransform, box, unitDir, distance, sweepHit, hitFlags, inflation);
}
// \param[in] mesh triangle mesh
// \param[in] hullBox hull's bounding box
// \param[in] localDir sweep's unit dir, in local/mesh space
// \param[in] distance sweep's length/max distance
// \param[in] callback callback object, called each time a hit is found
// \param[in] anyHit true for PxHitFlag::eMESH_ANY queries
PX_FORCE_INLINE void sweepConvexVsMesh(const TriangleMesh* mesh, const Gu::Box& hullBox, const PxVec3& localDir, PxReal distance, SweepConvexMeshHitCallback& callback, bool anyHit)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
gMidphaseConvexSweepTable[index](mesh, hullBox, localDir, distance, callback, anyHit);
}
PX_FORCE_INLINE void pointMeshDistance(const TriangleMesh* mesh, const PxTriangleMeshGeometry& meshGeom, const PxTransform& pose, const PxVec3& point, float maxDist
, PxU32& closestIndex, float& dist, PxVec3& closestPt)
{
const PxU32 index = PxU32(mesh->getConcreteType() - PxConcreteType::eTRIANGLE_MESH_BVH33);
gMidphasePointMeshTable[index](mesh, meshGeom, pose, point, maxDist, closestIndex, dist, closestPt);
}
}
}
}
#endif // GU_MIDPHASE_INTERFACE_H
| 20,406 | C | 52.56168 | 223 | 0.764971 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxBoxOverlapTest.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_BOX_BOX_OVERLAP_TEST_H
#define GU_BV4_BOX_BOX_OVERLAP_TEST_H
#ifndef GU_BV4_USE_SLABS
PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const PxVec3& extents, const PxVec3& center, const OBBTestParams* PX_RESTRICT params)
{
const Vec4V extentsV = V4LoadU(&extents.x);
const Vec4V TV = V4Sub(V4LoadA_Safe(¶ms->mTBoxToModel_PaddedAligned.x), V4LoadU(¢er.x));
{
const Vec4V absTV = V4Abs(TV);
const BoolV resTV = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(¶ms->mBB_PaddedAligned.x)));
const PxU32 test = BGetBitMask(resTV);
if(test&7)
return 0;
}
Vec4V tV;
{
const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV);
const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV);
tV = V4Mul(TV, V4LoadA_Safe(¶ms->mPreca0_PaddedAligned.x));
tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(¶ms->mPreca1_PaddedAligned.x)));
tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(¶ms->mPreca2_PaddedAligned.x)));
}
Vec4V t2V;
{
const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV);
const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV);
t2V = V4Mul(extentsV, V4LoadA_Safe(¶ms->mPreca0b_PaddedAligned.x));
t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(¶ms->mPreca1b_PaddedAligned.x)));
t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(¶ms->mPreca2b_PaddedAligned.x)));
t2V = V4Add(t2V, V4LoadA_Safe(¶ms->mBoxExtents_PaddedAligned.x));
}
{
const Vec4V abstV = V4Abs(tV);
const BoolV resB = V4IsGrtr(abstV, t2V);
const PxU32 test = BGetBitMask(resB);
if(test&7)
return 0;
}
return 1;
}
#ifdef GU_BV4_QUANTIZED_TREE
template<class T>
PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const T* PX_RESTRICT node, const OBBTestParams* PX_RESTRICT params)
{
// A.B. enable new version only for intel non simd path
#if PX_INTEL_FAMILY && !defined(PX_SIMD_DISABLED)
// #define NEW_VERSION
#endif
#ifdef NEW_VERSION
SSE_CONST4(maskV, 0x7fffffff);
SSE_CONST4(maskQV, 0x0000ffff);
#endif
#ifdef NEW_VERSION
Vec4V centerV = V4LoadA((float*)node->mAABB.mData);
__m128 extentsV = _mm_castsi128_ps(_mm_and_si128(_mm_castps_si128(centerV), SSE_CONST(maskQV)));
extentsV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(extentsV)), V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x));
centerV = _mm_castsi128_ps(_mm_srai_epi32(_mm_castps_si128(centerV), 16));
centerV = V4Mul(_mm_cvtepi32_ps(_mm_castps_si128(centerV)), V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x));
#else
const VecI32V centerVI = I4LoadA((PxI32*)node->mAABB.mData);
const VecI32V extentsVI = VecI32V_And(centerVI, I4Load(0x0000ffff));
const Vec4V extentsV = V4Mul(Vec4V_From_VecI32V(extentsVI), V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x));
const VecI32V centerVShift = VecI32V_RightShift(centerVI, 16);
const Vec4V centerV = V4Mul(Vec4V_From_VecI32V(centerVShift), V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x));
#endif
const Vec4V TV = V4Sub(V4LoadA_Safe(¶ms->mTBoxToModel_PaddedAligned.x), centerV);
{
#ifdef NEW_VERSION
const __m128 absTV = _mm_and_ps(TV, SSE_CONSTF(maskV));
#else
const Vec4V absTV = V4Abs(TV);
#endif
const BoolV resTV = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(¶ms->mBB_PaddedAligned.x)));
const PxU32 test = BGetBitMask(resTV);
if(test&7)
return 0;
}
Vec4V tV;
{
const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV);
const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV);
tV = V4Mul(TV, V4LoadA_Safe(¶ms->mPreca0_PaddedAligned.x));
tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(¶ms->mPreca1_PaddedAligned.x)));
tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(¶ms->mPreca2_PaddedAligned.x)));
}
Vec4V t2V;
{
const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV);
const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV);
t2V = V4Mul(extentsV, V4LoadA_Safe(¶ms->mPreca0b_PaddedAligned.x));
t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(¶ms->mPreca1b_PaddedAligned.x)));
t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(¶ms->mPreca2b_PaddedAligned.x)));
t2V = V4Add(t2V, V4LoadA_Safe(¶ms->mBoxExtents_PaddedAligned.x));
}
{
#ifdef NEW_VERSION
const __m128 abstV = _mm_and_ps(tV, SSE_CONSTF(maskV));
#else
const Vec4V abstV = V4Abs(tV);
#endif
const BoolV resB = V4IsGrtr(abstV, t2V);
const PxU32 test = BGetBitMask(resB);
if(test&7)
return 0;
}
return 1;
}
#endif // GU_BV4_QUANTIZED_TREE
#endif // GU_BV4_USE_SLABS
#ifdef GU_BV4_USE_SLABS
PX_FORCE_INLINE PxIntBool BV4_BoxBoxOverlap(const Vec4V boxCenter, const Vec4V extentsV, const OBBTestParams* PX_RESTRICT params)
{
const Vec4V TV = V4Sub(V4LoadA_Safe(¶ms->mTBoxToModel_PaddedAligned.x), boxCenter);
{
const Vec4V absTV = V4Abs(TV);
const BoolV res = V4IsGrtr(absTV, V4Add(extentsV, V4LoadA_Safe(¶ms->mBB_PaddedAligned.x)));
const PxU32 test = BGetBitMask(res);
if(test&7)
return 0;
}
Vec4V tV;
{
const Vec4V T_YZX_V = V4Perm<1, 2, 0, 3>(TV);
const Vec4V T_ZXY_V = V4Perm<2, 0, 1, 3>(TV);
tV = V4Mul(TV, V4LoadA_Safe(¶ms->mPreca0_PaddedAligned.x));
tV = V4Add(tV, V4Mul(T_YZX_V, V4LoadA_Safe(¶ms->mPreca1_PaddedAligned.x)));
tV = V4Add(tV, V4Mul(T_ZXY_V, V4LoadA_Safe(¶ms->mPreca2_PaddedAligned.x)));
}
Vec4V t2V;
{
const Vec4V extents_YZX_V = V4Perm<1, 2, 0, 3>(extentsV);
const Vec4V extents_ZXY_V = V4Perm<2, 0, 1, 3>(extentsV);
t2V = V4Mul(extentsV, V4LoadA_Safe(¶ms->mPreca0b_PaddedAligned.x));
t2V = V4Add(t2V, V4Mul(extents_YZX_V, V4LoadA_Safe(¶ms->mPreca1b_PaddedAligned.x)));
t2V = V4Add(t2V, V4Mul(extents_ZXY_V, V4LoadA_Safe(¶ms->mPreca2b_PaddedAligned.x)));
t2V = V4Add(t2V, V4LoadA_Safe(¶ms->mBoxExtents_PaddedAligned.x));
}
{
const Vec4V abstV = V4Abs(tV);
const BoolV resB = V4IsGrtr(abstV, t2V);
const PxU32 test = BGetBitMask(resB);
if(test&7)
return 0;
}
return 1;
}
#endif // GU_BV4_USE_SLABS
#endif // GU_BV4_BOX_BOX_OVERLAP_TEST_H
| 7,726 | C | 37.829146 | 130 | 0.705022 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_Slabs_KajiyaNoOrder.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_SLABS_KAJIYA_NO_ORDER_H
#define GU_BV4_SLABS_KAJIYA_NO_ORDER_H
#include "GuBVConstants.h"
#ifdef REMOVED
// Kajiya, no sort
template<int inflateT, class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamKajiyaNoOrder(const BVDataPacked* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPacked* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
#ifdef GU_BV4_QUANTIZED_TREE
const Vec4V minCoeffV = V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x);
const Vec4V maxCoeffV = V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV);
const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV);
const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV);
const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV);
const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV);
const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV);
#endif
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzled* tn = reinterpret_cast<const BVDataSwizzled*>(node);
#ifdef GU_BV4_QUANTIZED_TREE
Vec4V minx4a;
Vec4V maxx4a;
OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV)
Vec4V miny4a;
Vec4V maxy4a;
OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV)
Vec4V minz4a;
Vec4V maxz4a;
OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV)
#else
Vec4V minx4a = V4LoadA(tn->mMinX);
Vec4V miny4a = V4LoadA(tn->mMinY);
Vec4V minz4a = V4LoadA(tn->mMinZ);
Vec4V maxx4a = V4LoadA(tn->mMaxX);
Vec4V maxy4a = V4LoadA(tn->mMaxY);
Vec4V maxz4a = V4LoadA(tn->mMaxZ);
#endif
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
SLABS_TEST2
#define DO_LEAF_TEST(x) \
{if(tn->isLeaf(x)) \
{ \
if(LeafTestT::doLeafTest(params, tn->getPrimitive(x))) \
return 1; \
} \
else \
stack[nb++] = tn->getChildData(x);}
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
}while(nb);
return 0;
}
#undef DO_LEAF_TEST
#endif
#define DO_LEAF_TEST(x) \
{if(tn->isLeaf(x)) \
{ \
if(LeafTestT::doLeafTest(params, tn->getPrimitive(x))) \
return 1; \
} \
else \
stack[nb++] = tn->getChildData(x);}
// Kajiya, no sort
template<int inflateT, class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamKajiyaNoOrderQ(const BVDataPackedQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
const Vec4V minCoeffV = V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x);
const Vec4V maxCoeffV = V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x);
const Vec4V minCoeffxV = V4SplatElement<0>(minCoeffV);
const Vec4V minCoeffyV = V4SplatElement<1>(minCoeffV);
const Vec4V minCoeffzV = V4SplatElement<2>(minCoeffV);
const Vec4V maxCoeffxV = V4SplatElement<0>(maxCoeffV);
const Vec4V maxCoeffyV = V4SplatElement<1>(maxCoeffV);
const Vec4V maxCoeffzV = V4SplatElement<2>(maxCoeffV);
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(node);
Vec4V minx4a;
Vec4V maxx4a;
OPC_DEQ4(maxx4a, minx4a, mX, minCoeffxV, maxCoeffxV)
Vec4V miny4a;
Vec4V maxy4a;
OPC_DEQ4(maxy4a, miny4a, mY, minCoeffyV, maxCoeffyV)
Vec4V minz4a;
Vec4V maxz4a;
OPC_DEQ4(maxz4a, minz4a, mZ, minCoeffzV, maxCoeffzV)
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
SLABS_TEST2
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
}while(nb);
return 0;
}
// Kajiya, no sort
template<int inflateT, class LeafTestT, class ParamsT>
static PxIntBool BV4_ProcessStreamKajiyaNoOrderNQ(const BVDataPackedNQ* PX_RESTRICT node, PxU32 initData, ParamsT* PX_RESTRICT params)
{
const BVDataPackedNQ* root = node;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
///
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
if(inflateT)
{
Vec4V fattenAABBs4 = V4LoadU_Safe(¶ms->mOriginalExtents_Padded.x);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
///
SLABS_INIT
do
{
const PxU32 childData = stack[--nb];
node = root + getChildOffset(childData);
const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(node);
Vec4V minx4a = V4LoadA(tn->mMinX);
Vec4V miny4a = V4LoadA(tn->mMinY);
Vec4V minz4a = V4LoadA(tn->mMinZ);
Vec4V maxx4a = V4LoadA(tn->mMaxX);
Vec4V maxy4a = V4LoadA(tn->mMaxY);
Vec4V maxz4a = V4LoadA(tn->mMaxZ);
if(inflateT)
{
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
SLABS_TEST
SLABS_TEST2
const PxU32 nodeType = getChildType(childData);
if(!(code&8) && nodeType>1)
DO_LEAF_TEST(3)
if(!(code&4) && nodeType>0)
DO_LEAF_TEST(2)
if(!(code&2))
DO_LEAF_TEST(1)
if(!(code&1))
DO_LEAF_TEST(0)
}while(nb);
return 0;
}
#undef DO_LEAF_TEST
#endif // GU_BV4_SLABS_KAJIYA_NO_ORDER_H
| 9,139 | C | 28.869281 | 142 | 0.696466 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamOrdered_SegmentAABB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_H
#define GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_H
#ifndef GU_BV4_USE_SLABS
template<class LeafTestT, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params, PxU32 i, PxU32 limit)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(i<limit && BV4_SegmentAABBOverlap(node+i, params))
#else
if(i<limit && BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
Stack[Nb++] = node[i].getChildData();
}
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2(PxU32& code, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_SegmentAABBOverlap(node+i, params))
#else
if(BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
code |= 1<<i;
}
}
#endif
#endif // GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_H
| 2,922 | C | 42.626865 | 170 | 0.746749 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamNoOrder_SegmentAABB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_H
#define GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_H
#ifndef GU_BV4_USE_SLABS
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_SegmentAABBOverlap(node+i, params))
#else
if(BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params))
#endif
{
if(node[i].isLeaf())
{
if(LeafTestT::doLeafTest(params, node[i].getPrimitive()))
return 1;
}
else
Stack[Nb++] = node[i].getChildData();
}
return 0;
}
#endif
#endif // GU_BV4_PROCESS_STREAM_NOORDER_SEGMENT_AABB_H
| 2,457 | C | 43.690908 | 153 | 0.750509 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_SphereOverlap.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
using namespace physx;
using namespace Gu;
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#include "GuBV4_Common.h"
#include "GuSphere.h"
#include "GuDistancePointTriangle.h"
#if PX_VC
#pragma warning ( disable : 4324 )
#endif
// Sphere overlap any
struct SphereParams
{
const IndTri32* PX_RESTRICT mTris32;
const IndTri16* PX_RESTRICT mTris16;
const PxVec3* PX_RESTRICT mVerts;
BV4_ALIGN16(PxVec3p mCenterOrMinCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3p mExtentsOrMaxCoeff_PaddedAligned);
BV4_ALIGN16(PxVec3 mCenter_PaddedAligned); float mRadius2;
#ifdef GU_BV4_USE_SLABS
BV4_ALIGN16(PxVec3 mCenter_PaddedAligned2); float mRadius22;
#endif
};
#ifndef GU_BV4_USE_SLABS
// PT: TODO: refactor with bucket pruner code (TA34704)
static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const PxVec3& center, const PxVec3& extents, const SphereParams* PX_RESTRICT params)
{
const Vec4V mCenter = V4LoadA_Safe(¶ms->mCenter_PaddedAligned.x);
const FloatV mRadius2 = FLoad(params->mRadius2);
const Vec4V boxCenter = V4LoadU(¢er.x);
const Vec4V boxExtents = V4LoadU(&extents.x);
const Vec4V offset = V4Sub(mCenter, boxCenter);
const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents);
const Vec4V d = V4Sub(offset, closest);
const PxU32 test = (PxU32)_mm_movemask_ps(FIsGrtrOrEq(mRadius2, V4Dot3(d, d)));
return (test & 0x7) == 0x7;
}
#endif
static PX_FORCE_INLINE PxIntBool SphereTriangle(const SphereParams* PX_RESTRICT params, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
{
{
const float sqrDist = (p0 - params->mCenter_PaddedAligned).magnitudeSquared();
if(sqrDist <= params->mRadius2)
return 1;
}
const PxVec3 edge10 = p1 - p0;
const PxVec3 edge20 = p2 - p0;
const PxVec3 cp = closestPtPointTriangle2(params->mCenter_PaddedAligned, p0, p1, p2, edge10, edge20);
const float sqrDist = (cp - params->mCenter_PaddedAligned).magnitudeSquared();
return sqrDist <= params->mRadius2;
}
// PT: TODO: evaluate if SIMD distance function would be faster here (TA34704)
// PT: TODO: __fastcall removed to make it compile everywhere. Revisit.
static /*PX_FORCE_INLINE*/ PxIntBool /*__fastcall*/ SphereTriangle(const SphereParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
return SphereTriangle(params, params->mVerts[VRef0], params->mVerts[VRef1], params->mVerts[VRef2]);
}
namespace
{
class LeafFunction_SphereOverlapAny
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const SphereParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(SphereTriangle(params, primIndex))
return 1;
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
template<class ParamsT>
static PX_FORCE_INLINE void setupSphereParams(ParamsT* PX_RESTRICT params, const Sphere& sphere, const BV4Tree* PX_RESTRICT tree, const PxMat44* PX_RESTRICT worldm_Aligned, const SourceMesh* PX_RESTRICT mesh)
{
computeLocalSphere(params->mRadius2, params->mCenter_PaddedAligned, sphere, worldm_Aligned);
#ifdef GU_BV4_USE_SLABS
params->mCenter_PaddedAligned2 = params->mCenter_PaddedAligned*2.0f;
params->mRadius22 = params->mRadius2*4.0f;
#endif
setupMeshPointersAndQuantizedCoeffs(params, mesh, tree);
}
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs.h"
static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const Vec4V boxCenter, const Vec4V boxExtents, const SphereParams* PX_RESTRICT params)
{
const Vec4V mCenter = V4LoadA_Safe(¶ms->mCenter_PaddedAligned2.x);
const FloatV mRadius2 = FLoad(params->mRadius22);
const Vec4V offset = V4Sub(mCenter, boxCenter);
const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents);
const Vec4V d = V4Sub(offset, closest);
const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, V4Dot3(d, d)));
return (test & 0x7) == 0x7;
}
#else
#ifdef GU_BV4_QUANTIZED_TREE
static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap(const BVDataPacked* PX_RESTRICT node, const SphereParams* PX_RESTRICT params)
{
const VecI32V testV = I4LoadA((const PxI32*)&node->mAABB.mData[0]);
const VecI32V qextentsV = VecI32V_And(testV, I4LoadXYZW(0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff));
const VecI32V qcenterV = VecI32V_RightShift(testV, 16);
const Vec4V boxCenter = V4Mul(Vec4V_From_VecI32V(qcenterV), V4LoadA_Safe(¶ms->mCenterOrMinCoeff_PaddedAligned.x));
const Vec4V boxExtents = V4Mul(Vec4V_From_VecI32V(qextentsV), V4LoadA_Safe(¶ms->mExtentsOrMaxCoeff_PaddedAligned.x));
const Vec4V mCenter = V4LoadA_Safe(¶ms->mCenter_PaddedAligned.x);
const FloatV mRadius2 = FLoad(params->mRadius2);
const Vec4V offset = V4Sub(mCenter, boxCenter);
const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents);
const Vec4V d = V4Sub(offset, closest);
const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, V4Dot3(d, d)));
return (test & 0x7) == 0x7;
}
#endif
#endif
#include "GuBV4_ProcessStreamNoOrder_SphereAABB.h"
#ifdef GU_BV4_USE_SLABS
#include "GuBV4_Slabs_SwizzledNoOrder.h"
#endif
#define GU_BV4_PROCESS_STREAM_NO_ORDER
#include "GuBV4_Internal.h"
PxIntBool BV4_OverlapSphereAny(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned)
{
const SourceMesh* PX_RESTRICT mesh =static_cast<const SourceMesh*>(tree.mMeshInterface);
SphereParams Params;
setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
return processStreamNoOrder<LeafFunction_SphereOverlapAny>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbPrimitives();
PX_ASSERT(nbTris<16);
return LeafFunction_SphereOverlapAny::doLeafTest(&Params, nbTris);
}
}
// Sphere overlap all
struct SphereParamsAll : SphereParams
{
PxU32 mNbHits;
PxU32 mMaxNbHits;
PxU32* mHits;
};
namespace
{
class LeafFunction_SphereOverlapAll
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(SphereParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
if(SphereTriangle(params, primIndex))
{
SphereParamsAll* ParamsAll = static_cast<SphereParamsAll*>(params);
if(ParamsAll->mNbHits==ParamsAll->mMaxNbHits)
return 1;
ParamsAll->mHits[ParamsAll->mNbHits] = primIndex;
ParamsAll->mNbHits++;
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
PxU32 BV4_OverlapSphereAll(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, PxU32* results, PxU32 size, bool& overflow)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<const SourceMesh*>(tree.mMeshInterface);
SphereParamsAll Params;
Params.mNbHits = 0;
Params.mMaxNbHits = size;
Params.mHits = results;
setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
overflow = processStreamNoOrder<LeafFunction_SphereOverlapAll>(tree, &Params)!=0;
else
{
const PxU32 nbTris = mesh->getNbPrimitives();
PX_ASSERT(nbTris<16);
overflow = LeafFunction_SphereOverlapAll::doLeafTest(&Params, nbTris)!=0;
}
return Params.mNbHits;
}
// Sphere overlap - callback version
struct SphereParamsCB : SphereParams
{
MeshOverlapCallback mCallback;
void* mUserData;
};
namespace
{
class LeafFunction_SphereOverlapCB
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(const SphereParamsCB* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
const PxVec3& p0 = params->mVerts[VRef0];
const PxVec3& p1 = params->mVerts[VRef1];
const PxVec3& p2 = params->mVerts[VRef2];
if(SphereTriangle(params, p0, p1, p2))
{
const PxU32 vrefs[3] = { VRef0, VRef1, VRef2 };
if((params->mCallback)(params->mUserData, p0, p1, p2, primIndex, vrefs))
return 1;
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
// PT: this one is currently not used
void BV4_OverlapSphereCB(const Sphere& sphere, const BV4Tree& tree, const PxMat44* PX_RESTRICT worldm_Aligned, MeshOverlapCallback callback, void* userData)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface);
SphereParamsCB Params;
Params.mCallback = callback;
Params.mUserData = userData;
setupSphereParams(&Params, sphere, &tree, worldm_Aligned, mesh);
if(tree.mNodes)
processStreamNoOrder<LeafFunction_SphereOverlapCB>(tree, &Params);
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
LeafFunction_SphereOverlapCB::doLeafTest(&Params, nbTris);
}
}
// Point distance query
// Implemented here as a variation on the sphere-overlap codepath
// TODO:
// * visit closest nodes first
// - revisit inlining
// - lazy-compute final results
// - SIMD
// - return uvs
// - maxDist input param
struct PointDistanceParams : SphereParams
{
PxVec3 mClosestPt;
PxU32 mIndex;
};
namespace
{
class LeafFunction_PointDistance
{
public:
static PX_FORCE_INLINE PxIntBool doLeafTest(SphereParams* PX_RESTRICT params, PxU32 primIndex)
{
PxU32 nbToGo = getNbPrimitives(primIndex);
do
{
PxU32 VRef0, VRef1, VRef2;
getVertexReferences(VRef0, VRef1, VRef2, primIndex, params->mTris32, params->mTris16);
const PxVec3& p0 = params->mVerts[VRef0];
const PxVec3& p1 = params->mVerts[VRef1];
const PxVec3& p2 = params->mVerts[VRef2];
const PxVec3 edge10 = p1 - p0;
const PxVec3 edge20 = p2 - p0;
const PxVec3 cp = closestPtPointTriangle2(params->mCenter_PaddedAligned, p0, p1, p2, edge10, edge20);
const float sqrDist = (cp - params->mCenter_PaddedAligned).magnitudeSquared();
if(sqrDist <= params->mRadius2)
{
PointDistanceParams* Params = static_cast<PointDistanceParams*>(params);
Params->mClosestPt = cp;
Params->mIndex = primIndex;
Params->mRadius2 = sqrDist;
#ifdef GU_BV4_USE_SLABS
Params->mRadius22 = sqrDist*4.0f;
#endif
}
primIndex++;
}while(nbToGo--);
return 0;
}
};
}
namespace
{
static PX_FORCE_INLINE PxIntBool BV4_SphereAABBOverlap2(const Vec4V boxCenter, const Vec4V boxExtents, const SphereParams* PX_RESTRICT params, float* PX_RESTRICT _d)
{
const Vec4V mCenter = V4LoadA_Safe(¶ms->mCenter_PaddedAligned2.x);
const FloatV mRadius2 = FLoad(params->mRadius22);
const Vec4V offset = V4Sub(mCenter, boxCenter);
const Vec4V closest = V4Clamp(offset, V4Neg(boxExtents), boxExtents);
const Vec4V d = V4Sub(offset, closest);
const FloatV dot = V4Dot3(d, d);
FStore(dot, _d);
const PxU32 test = BGetBitMask(FIsGrtrOrEq(mRadius2, dot));
return (test & 0x7) == 0x7;
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeNoOrder_SwizzledQ2(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params, float* PX_RESTRICT _d)
{
OPC_SLABS_GET_CE2Q(i)
if(BV4_SphereAABBOverlap2(centerV, extentsV, params, _d))
{
if(node->isLeaf(i))
LeafTestT::doLeafTest(params, node->getPrimitive(i));
else
Stack[Nb++] = node->getChildData(i);
}
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeNoOrder_SwizzledNQ2(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledNQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params, float* PX_RESTRICT _d)
{
OPC_SLABS_GET_CE2NQ(i)
if(BV4_SphereAABBOverlap2(centerV, extentsV, params, _d))
{
if(node->isLeaf(i))
{
LeafTestT::doLeafTest(params, node->getPrimitive(i));
}
else
Stack[Nb++] = node->getChildData(i);
}
}
static PX_FORCE_INLINE void sort(PxU32* next, float* di, PxU32 i, PxU32 j)
{
if(di[i]<di[j]) // PT: "wrong" side on purpose, it's a LIFO stack
{
PxSwap(next[i], next[j]);
PxSwap(di[i], di[j]);
}
}
static PX_FORCE_INLINE void sortCandidates(PxU32 nbMore, PxU32* next, float* di, PxU32* stack, PxU32& nb)
{
// PT: this is not elegant and it looks slow, but for distance queries the time spent here is well worth it.
if(0)
{
while(nbMore)
{
float minDist = di[0];
PxU32 minIndex = 0;
for(PxU32 i=1;i<nbMore;i++)
{
if(di[i]>minDist) // PT: "wrong" side on purpose, it's a LIFO stack
{
minDist = di[i];
minIndex = i;
}
}
stack[nb++] = next[minIndex];
nbMore--;
PxSwap(next[minIndex], next[nbMore]);
PxSwap(di[minIndex], di[nbMore]);
}
}
else
{
switch(nbMore)
{
case 1:
{
stack[nb++] = next[0];
break;
}
case 2:
{
sort(next, di, 0, 1);
PX_ASSERT(di[0]>=di[1]);
stack[nb++] = next[0];
stack[nb++] = next[1];
break;
}
case 3:
{
sort(next, di, 0, 1);
sort(next, di, 1, 2);
sort(next, di, 0, 1);
PX_ASSERT(di[0]>=di[1]);
PX_ASSERT(di[1]>=di[2]);
stack[nb++] = next[0];
stack[nb++] = next[1];
stack[nb++] = next[2];
break;
}
case 4:
{
sort(next, di, 0, 1);
sort(next, di, 2, 3);
sort(next, di, 0, 2);
sort(next, di, 1, 3);
sort(next, di, 1, 2);
PX_ASSERT(di[0]>=di[1]);
PX_ASSERT(di[1]>=di[2]);
PX_ASSERT(di[2]>=di[3]);
stack[nb++] = next[0];
stack[nb++] = next[1];
stack[nb++] = next[2];
stack[nb++] = next[3];
break;
}
}
}
}
}
void BV4_PointDistance(const PxVec3& point, const BV4Tree& tree, float maxDist, PxU32& index, float& dist, PxVec3& cp/*, const PxMat44* PX_RESTRICT worldm_Aligned*/)
{
const SourceMesh* PX_RESTRICT mesh = static_cast<SourceMesh*>(tree.mMeshInterface);
const float limit = sqrtf(sqrtf(PX_MAX_F32));
if(maxDist>limit)
maxDist = limit;
PointDistanceParams Params;
setupSphereParams(&Params, Sphere(point, maxDist), &tree, NULL/*worldm_Aligned*/, mesh);
if(tree.mNodes)
{
if(0)
{
// PT: unfortunately distance queries don't map nicely to the current BV4 framework
// This works but it doesn't visit closest nodes first so it's suboptimal. We also
// cannot use the ordered traversal since it's based on PNS, i.e. a fixed ray direction.
processStreamNoOrder<LeafFunction_PointDistance>(tree, &Params);
}
PxU32 initData = tree.mInitData;
PointDistanceParams* PX_RESTRICT params = &Params;
if(tree.mQuantized)
{
const BVDataPackedQ* PX_RESTRICT nodes = reinterpret_cast<const BVDataPackedQ*>(tree.mNodes);
const BVDataPackedQ* root = nodes;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
nodes = root + getChildOffset(childData);
const BVDataSwizzledQ* tn = reinterpret_cast<const BVDataSwizzledQ*>(nodes);
const PxU32 nodeType = getChildType(childData);
PxU32 nbMore=0;
PxU32 next[4];
float di[4];
if(nodeType>1)
BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 3>(next, nbMore, tn, params, &di[nbMore]);
if(nodeType>0)
BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 2>(next, nbMore, tn, params, &di[nbMore]);
BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 1>(next, nbMore, tn, params, &di[nbMore]);
BV4_ProcessNodeNoOrder_SwizzledQ2<LeafFunction_PointDistance, 0>(next, nbMore, tn, params, &di[nbMore]);
sortCandidates(nbMore, next, di, stack, nb);
}while(nb);
}
else
{
const BVDataPackedNQ* PX_RESTRICT nodes = reinterpret_cast<const BVDataPackedNQ*>(tree.mNodes);
const BVDataPackedNQ* root = nodes;
PxU32 nb=1;
PxU32 stack[GU_BV4_STACK_SIZE];
stack[0] = initData;
do
{
const PxU32 childData = stack[--nb];
nodes = root + getChildOffset(childData);
const BVDataSwizzledNQ* tn = reinterpret_cast<const BVDataSwizzledNQ*>(nodes);
const PxU32 nodeType = getChildType(childData);
PxU32 nbMore=0;
PxU32 next[4];
float di[4];
if(nodeType>1)
BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 3>(next, nbMore, tn, params, &di[nbMore]);
if(nodeType>0)
BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 2>(next, nbMore, tn, params, &di[nbMore]);
BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 1>(next, nbMore, tn, params, &di[nbMore]);
BV4_ProcessNodeNoOrder_SwizzledNQ2<LeafFunction_PointDistance, 0>(next, nbMore, tn, params, &di[nbMore]);
sortCandidates(nbMore, next, di, stack, nb);
}while(nb);
}
}
else
{
const PxU32 nbTris = mesh->getNbTriangles();
PX_ASSERT(nbTris<16);
LeafFunction_PointDistance::doLeafTest(&Params, nbTris);
}
index = Params.mIndex;
dist = sqrtf(Params.mRadius2);
cp = Params.mClosestPt;
}
| 18,353 | C++ | 28.699029 | 208 | 0.711764 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuRTreeQueries.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
/*
General notes:
rtree depth-first traversal looks like this:
push top level page onto stack
pop page from stack
for each node in page
if node overlaps with testrect
push node's subpage
we want to efficiently keep track of current stack level to know if the current page is a leaf or not
(since we don't store a flag with the page due to no space, we can't determine it just by looking at current page)
since we traverse depth first, the levels for nodes on the stack look like this:
l0 l0 l1 l2 l2 l3 l3 l3 l4
we can encode this as an array of 4 bits per level count into a 32-bit integer
to simplify the code->level computation we also keep track of current level by incrementing the level whenever any subpages
from current test page are pushed onto the stack
when we pop a page off the stack we use this encoding to determine if we should decrement the stack level
*/
#include "foundation/PxBounds3.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxBitUtils.h"
#include "GuRTree.h"
#include "GuBox.h"
#include "foundation/PxVecMath.h"
#include "PxQueryReport.h" // for PxAgain
#include "GuBVConstants.h"
//#define VERIFY_RTREE
#ifdef VERIFY_RTREE
#include "GuIntersectionRayBox.h"
#include "GuIntersectionBoxBox.h"
#include "stdio.h"
#endif
using namespace physx;
using namespace aos;
namespace physx
{
namespace Gu {
using namespace aos;
#define v_absm(a) V4Andc(a, signMask)
#define V4FromF32A(x) V4LoadA(x)
#define PxF32FV(x) FStore(x)
#define CAST_U8(a) reinterpret_cast<PxU8*>(a)
/////////////////////////////////////////////////////////////////////////
void RTree::traverseAABB(const PxVec3& boxMin, const PxVec3& boxMax, const PxU32 maxResults, PxU32* resultsPtr, Callback* callback) const
{
PX_UNUSED(resultsPtr);
PX_ASSERT(callback);
PX_ASSERT(maxResults >= mPageSize);
PX_UNUSED(maxResults);
const PxU32 maxStack = 128;
PxU32 stack1[maxStack];
PxU32* stack = stack1+1;
PX_ASSERT(mPages);
PX_ASSERT((uintptr_t(mPages) & 127) == 0);
PX_ASSERT((uintptr_t(this) & 15) == 0);
// conservatively quantize the input box
Vec4V nqMin = Vec4V_From_PxVec3_WUndefined(boxMin);
Vec4V nqMax = Vec4V_From_PxVec3_WUndefined(boxMax);
Vec4V nqMinx4 = V4SplatElement<0>(nqMin);
Vec4V nqMiny4 = V4SplatElement<1>(nqMin);
Vec4V nqMinz4 = V4SplatElement<2>(nqMin);
Vec4V nqMaxx4 = V4SplatElement<0>(nqMax);
Vec4V nqMaxy4 = V4SplatElement<1>(nqMax);
Vec4V nqMaxz4 = V4SplatElement<2>(nqMax);
// on 64-bit platforms the dynamic rtree pointer is also relative to mPages
PxU8* treeNodes8 = CAST_U8(mPages);
PxU32* stackPtr = stack;
// AP potential perf optimization - fetch the top level right away
PX_ASSERT(RTREE_N == 4 || RTREE_N == 8);
PX_ASSERT(PxIsPowerOfTwo(mPageSize));
for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --)
*stackPtr++ = j*sizeof(RTreePage);
PxU32 cacheTopValid = true;
PxU32 cacheTop = 0;
do {
stackPtr--;
PxU32 top;
if (cacheTopValid) // branch is faster than lhs
top = cacheTop;
else
top = stackPtr[0];
PX_ASSERT(!cacheTopValid || stackPtr[0] == cacheTop);
RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top);
const PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs;
Vec4V minx4 = V4LoadA(tn->minx);
Vec4V miny4 = V4LoadA(tn->miny);
Vec4V minz4 = V4LoadA(tn->minz);
Vec4V maxx4 = V4LoadA(tn->maxx);
Vec4V maxy4 = V4LoadA(tn->maxy);
Vec4V maxz4 = V4LoadA(tn->maxz);
// AABB/AABB overlap test
BoolV res0 = V4IsGrtr(nqMinx4, maxx4); BoolV res1 = V4IsGrtr(nqMiny4, maxy4); BoolV res2 = V4IsGrtr(nqMinz4, maxz4);
BoolV res3 = V4IsGrtr(minx4, nqMaxx4); BoolV res4 = V4IsGrtr(miny4, nqMaxy4); BoolV res5 = V4IsGrtr(minz4, nqMaxz4);
BoolV resx = BOr(BOr(BOr(res0, res1), BOr(res2, res3)), BOr(res4, res5));
PX_ALIGN_PREFIX(16) PxU32 resa[RTREE_N] PX_ALIGN_SUFFIX(16);
VecU32V res4x = VecU32V_From_BoolV(resx);
U4StoreA(res4x, resa);
cacheTopValid = false;
for (PxU32 i = 0; i < RTREE_N; i++)
{
PxU32 ptr = ptrs[i] & ~1; // clear the isLeaf bit
if (resa[i])
continue;
if (tn->isLeaf(i))
{
if (!callback->processResults(1, &ptr))
return;
}
else
{
*(stackPtr++) = ptr;
cacheTop = ptr;
cacheTopValid = true;
}
}
} while (stackPtr > stack);
}
/////////////////////////////////////////////////////////////////////////
template <int inflate>
void RTree::traverseRay(
const PxVec3& rayOrigin, const PxVec3& rayDir,
const PxU32 maxResults, PxU32* resultsPtr, Gu::RTree::CallbackRaycast* callback,
const PxVec3* fattenAABBs, PxF32 maxT) const
{
// implements Kay-Kajiya 4-way SIMD test
PX_UNUSED(resultsPtr);
PX_UNUSED(maxResults);
const PxU32 maxStack = 128;
PxU32 stack1[maxStack];
PxU32* stack = stack1+1;
PX_ASSERT(mPages);
PX_ASSERT((uintptr_t(mPages) & 127) == 0);
PX_ASSERT((uintptr_t(this) & 15) == 0);
PxU8* treeNodes8 = CAST_U8(mPages);
Vec4V fattenAABBsX, fattenAABBsY, fattenAABBsZ;
PX_UNUSED(fattenAABBsX); PX_UNUSED(fattenAABBsY); PX_UNUSED(fattenAABBsZ);
if (inflate)
{
Vec4V fattenAABBs4 = Vec4V_From_PxVec3_WUndefined(*fattenAABBs);
fattenAABBs4 = V4Add(fattenAABBs4, epsInflateFloat4); // US2385 - shapes are "closed" meaning exactly touching shapes should report overlap
fattenAABBsX = V4SplatElement<0>(fattenAABBs4);
fattenAABBsY = V4SplatElement<1>(fattenAABBs4);
fattenAABBsZ = V4SplatElement<2>(fattenAABBs4);
}
Vec4V maxT4;
maxT4 = V4Load(maxT);
Vec4V rayP = Vec4V_From_PxVec3_WUndefined(rayOrigin);
Vec4V rayD = Vec4V_From_PxVec3_WUndefined(rayDir);
VecU32V raySign = V4U32and(VecU32V_ReinterpretFrom_Vec4V(rayD), signMask);
Vec4V rayDAbs = V4Abs(rayD); // abs value of rayD
Vec4V rayInvD = Vec4V_ReinterpretFrom_VecU32V(V4U32or(raySign, VecU32V_ReinterpretFrom_Vec4V(V4Max(rayDAbs, epsFloat4)))); // clamp near-zero components up to epsilon
rayD = rayInvD;
//rayInvD = V4Recip(rayInvD);
// Newton-Raphson iteration for reciprocal (see wikipedia):
// X[n+1] = X[n]*(2-original*X[n]), X[0] = V4RecipFast estimate
//rayInvD = rayInvD*(twos-rayD*rayInvD);
rayInvD = V4RecipFast(rayInvD); // initial estimate, not accurate enough
rayInvD = V4Mul(rayInvD, V4NegMulSub(rayD, rayInvD, twos));
// P+tD=a; t=(a-P)/D
// t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x)
Vec4V rayPinvD = V4NegMulSub(rayInvD, rayP, zeroes);
Vec4V rayInvDsplatX = V4SplatElement<0>(rayInvD);
Vec4V rayInvDsplatY = V4SplatElement<1>(rayInvD);
Vec4V rayInvDsplatZ = V4SplatElement<2>(rayInvD);
Vec4V rayPinvDsplatX = V4SplatElement<0>(rayPinvD);
Vec4V rayPinvDsplatY = V4SplatElement<1>(rayPinvD);
Vec4V rayPinvDsplatZ = V4SplatElement<2>(rayPinvD);
PX_ASSERT(RTREE_N == 4 || RTREE_N == 8);
PX_ASSERT(mNumRootPages > 0);
PxU32 stackPtr = 0;
for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --)
stack[stackPtr++] = j*sizeof(RTreePage);
PX_ALIGN_PREFIX(16) PxU32 resa[4] PX_ALIGN_SUFFIX(16);
while (stackPtr)
{
PxU32 top = stack[--stackPtr];
if (top&1) // isLeaf test
{
top--;
PxF32 newMaxT = maxT;
if (!callback->processResults(1, &top, newMaxT))
return;
/* shrink the ray if newMaxT is reduced compared to the original maxT */
if (maxT != newMaxT)
{
PX_ASSERT(newMaxT < maxT);
maxT = newMaxT;
maxT4 = V4Load(newMaxT);
}
continue;
}
RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top);
// 6i load
Vec4V minx4a = V4LoadA(tn->minx), miny4a = V4LoadA(tn->miny), minz4a = V4LoadA(tn->minz);
Vec4V maxx4a = V4LoadA(tn->maxx), maxy4a = V4LoadA(tn->maxy), maxz4a = V4LoadA(tn->maxz);
// 1i disabled test
// AP scaffold - optimization opportunity - can save 2 instructions here
VecU32V ignore4a = V4IsGrtrV32u(minx4a, maxx4a); // 1 if degenerate box (empty slot in the page)
if (inflate)
{
// 6i
maxx4a = V4Add(maxx4a, fattenAABBsX); maxy4a = V4Add(maxy4a, fattenAABBsY); maxz4a = V4Add(maxz4a, fattenAABBsZ);
minx4a = V4Sub(minx4a, fattenAABBsX); miny4a = V4Sub(miny4a, fattenAABBsY); minz4a = V4Sub(minz4a, fattenAABBsZ);
}
// P+tD=a; t=(a-P)/D
// t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x)
// 6i
Vec4V tminxa0 = V4MulAdd(minx4a, rayInvDsplatX, rayPinvDsplatX);
Vec4V tminya0 = V4MulAdd(miny4a, rayInvDsplatY, rayPinvDsplatY);
Vec4V tminza0 = V4MulAdd(minz4a, rayInvDsplatZ, rayPinvDsplatZ);
Vec4V tmaxxa0 = V4MulAdd(maxx4a, rayInvDsplatX, rayPinvDsplatX);
Vec4V tmaxya0 = V4MulAdd(maxy4a, rayInvDsplatY, rayPinvDsplatY);
Vec4V tmaxza0 = V4MulAdd(maxz4a, rayInvDsplatZ, rayPinvDsplatZ);
// test half-spaces
// P+tD=dN
// t = (d(N,D)-(P,D))/(D,D) , (D,D)=1
// compute 4x dot products (N,D) and (P,N) for each AABB in the page
// 6i
// now compute tnear and tfar for each pair of planes for each box
Vec4V tminxa = V4Min(tminxa0, tmaxxa0); Vec4V tmaxxa = V4Max(tminxa0, tmaxxa0);
Vec4V tminya = V4Min(tminya0, tmaxya0); Vec4V tmaxya = V4Max(tminya0, tmaxya0);
Vec4V tminza = V4Min(tminza0, tmaxza0); Vec4V tmaxza = V4Max(tminza0, tmaxza0);
// 8i
Vec4V maxOfNeasa = V4Max(V4Max(tminxa, tminya), tminza);
Vec4V minOfFarsa = V4Min(V4Min(tmaxxa, tmaxya), tmaxza);
ignore4a = V4U32or(ignore4a, V4IsGrtrV32u(epsFloat4, minOfFarsa)); // if tfar is negative, ignore since its a ray, not a line
// AP scaffold: update the build to eliminate 3 more instructions for ignore4a above
//VecU32V ignore4a = V4IsGrtrV32u(epsFloat4, minOfFarsa); // if tfar is negative, ignore since its a ray, not a line
ignore4a = V4U32or(ignore4a, V4IsGrtrV32u(maxOfNeasa, maxT4)); // if tnear is over maxT, ignore this result
// 2i
VecU32V resa4 = V4IsGrtrV32u(maxOfNeasa, minOfFarsa); // if 1 => fail
resa4 = V4U32or(resa4, ignore4a);
// 1i
V4U32StoreAligned(resa4, reinterpret_cast<VecU32V*>(resa));
PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs;
stack[stackPtr] = ptrs[0]; stackPtr += (1+resa[0]); // AP scaffold TODO: use VecU32add
stack[stackPtr] = ptrs[1]; stackPtr += (1+resa[1]);
stack[stackPtr] = ptrs[2]; stackPtr += (1+resa[2]);
stack[stackPtr] = ptrs[3]; stackPtr += (1+resa[3]);
}
}
//explicit template instantiation
template void RTree::traverseRay<0>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const;
template void RTree::traverseRay<1>(const PxVec3&, const PxVec3&, const PxU32, PxU32*, Gu::RTree::CallbackRaycast*, const PxVec3*, PxF32) const;
/////////////////////////////////////////////////////////////////////////
void RTree::traverseOBB(
const Gu::Box& obb, const PxU32 maxResults, PxU32* resultsPtr, Gu::RTree::Callback* callback) const
{
PX_UNUSED(resultsPtr);
PX_UNUSED(maxResults);
const PxU32 maxStack = 128;
PxU32 stack[maxStack];
PX_ASSERT(mPages);
PX_ASSERT((uintptr_t(mPages) & 127) == 0);
PX_ASSERT((uintptr_t(this) & 15) == 0);
PxU8* treeNodes8 = CAST_U8(mPages);
PxU32* stackPtr = stack;
Vec4V ones, halves, eps;
ones = V4Load(1.0f);
halves = V4Load(0.5f);
eps = V4Load(1e-6f);
PX_UNUSED(ones);
Vec4V obbO = Vec4V_From_PxVec3_WUndefined(obb.center);
Vec4V obbE = Vec4V_From_PxVec3_WUndefined(obb.extents);
// Gu::Box::rot matrix columns are the OBB axes
Vec4V obbX = Vec4V_From_PxVec3_WUndefined(obb.rot.column0);
Vec4V obbY = Vec4V_From_PxVec3_WUndefined(obb.rot.column1);
Vec4V obbZ = Vec4V_From_PxVec3_WUndefined(obb.rot.column2);
#if PX_WINDOWS
// Visual Studio compiler hangs with #defines
// On VMX platforms we use #defines in the other branch of this #ifdef to avoid register spills (LHS)
Vec4V obbESplatX = V4SplatElement<0>(obbE);
Vec4V obbESplatY = V4SplatElement<1>(obbE);
Vec4V obbESplatZ = V4SplatElement<2>(obbE);
Vec4V obbESplatNegX = V4Sub(zeroes, obbESplatX);
Vec4V obbESplatNegY = V4Sub(zeroes, obbESplatY);
Vec4V obbESplatNegZ = V4Sub(zeroes, obbESplatZ);
Vec4V obbXE = V4MulAdd(obbX, obbESplatX, zeroes); // scale axii by E
Vec4V obbYE = V4MulAdd(obbY, obbESplatY, zeroes); // scale axii by E
Vec4V obbZE = V4MulAdd(obbZ, obbESplatZ, zeroes); // scale axii by E
Vec4V obbOSplatX = V4SplatElement<0>(obbO);
Vec4V obbOSplatY = V4SplatElement<1>(obbO);
Vec4V obbOSplatZ = V4SplatElement<2>(obbO);
Vec4V obbXSplatX = V4SplatElement<0>(obbX);
Vec4V obbXSplatY = V4SplatElement<1>(obbX);
Vec4V obbXSplatZ = V4SplatElement<2>(obbX);
Vec4V obbYSplatX = V4SplatElement<0>(obbY);
Vec4V obbYSplatY = V4SplatElement<1>(obbY);
Vec4V obbYSplatZ = V4SplatElement<2>(obbY);
Vec4V obbZSplatX = V4SplatElement<0>(obbZ);
Vec4V obbZSplatY = V4SplatElement<1>(obbZ);
Vec4V obbZSplatZ = V4SplatElement<2>(obbZ);
Vec4V obbXESplatX = V4SplatElement<0>(obbXE);
Vec4V obbXESplatY = V4SplatElement<1>(obbXE);
Vec4V obbXESplatZ = V4SplatElement<2>(obbXE);
Vec4V obbYESplatX = V4SplatElement<0>(obbYE);
Vec4V obbYESplatY = V4SplatElement<1>(obbYE);
Vec4V obbYESplatZ = V4SplatElement<2>(obbYE);
Vec4V obbZESplatX = V4SplatElement<0>(obbZE);
Vec4V obbZESplatY = V4SplatElement<1>(obbZE);
Vec4V obbZESplatZ = V4SplatElement<2>(obbZE);
#else
#define obbESplatX V4SplatElement<0>(obbE)
#define obbESplatY V4SplatElement<1>(obbE)
#define obbESplatZ V4SplatElement<2>(obbE)
#define obbESplatNegX V4Sub(zeroes, obbESplatX)
#define obbESplatNegY V4Sub(zeroes, obbESplatY)
#define obbESplatNegZ V4Sub(zeroes, obbESplatZ)
#define obbXE V4MulAdd(obbX, obbESplatX, zeroes)
#define obbYE V4MulAdd(obbY, obbESplatY, zeroes)
#define obbZE V4MulAdd(obbZ, obbESplatZ, zeroes)
#define obbOSplatX V4SplatElement<0>(obbO)
#define obbOSplatY V4SplatElement<1>(obbO)
#define obbOSplatZ V4SplatElement<2>(obbO)
#define obbXSplatX V4SplatElement<0>(obbX)
#define obbXSplatY V4SplatElement<1>(obbX)
#define obbXSplatZ V4SplatElement<2>(obbX)
#define obbYSplatX V4SplatElement<0>(obbY)
#define obbYSplatY V4SplatElement<1>(obbY)
#define obbYSplatZ V4SplatElement<2>(obbY)
#define obbZSplatX V4SplatElement<0>(obbZ)
#define obbZSplatY V4SplatElement<1>(obbZ)
#define obbZSplatZ V4SplatElement<2>(obbZ)
#define obbXESplatX V4SplatElement<0>(obbXE)
#define obbXESplatY V4SplatElement<1>(obbXE)
#define obbXESplatZ V4SplatElement<2>(obbXE)
#define obbYESplatX V4SplatElement<0>(obbYE)
#define obbYESplatY V4SplatElement<1>(obbYE)
#define obbYESplatZ V4SplatElement<2>(obbYE)
#define obbZESplatX V4SplatElement<0>(obbZE)
#define obbZESplatY V4SplatElement<1>(obbZE)
#define obbZESplatZ V4SplatElement<2>(obbZE)
#endif
PX_ASSERT(mPageSize == 4 || mPageSize == 8);
PX_ASSERT(mNumRootPages > 0);
for (PxI32 j = PxI32(mNumRootPages-1); j >= 0; j --)
*stackPtr++ = j*sizeof(RTreePage);
PxU32 cacheTopValid = true;
PxU32 cacheTop = 0;
PX_ALIGN_PREFIX(16) PxU32 resa_[4] PX_ALIGN_SUFFIX(16);
do {
stackPtr--;
PxU32 top;
if (cacheTopValid) // branch is faster than lhs
top = cacheTop;
else
top = stackPtr[0];
PX_ASSERT(!cacheTopValid || top == cacheTop);
RTreePage* PX_RESTRICT tn = reinterpret_cast<RTreePage*>(treeNodes8 + top);
const PxU32 offs = 0;
PxU32* ptrs = (reinterpret_cast<RTreePage*>(tn))->ptrs;
// 6i
Vec4V minx4a = V4LoadA(tn->minx+offs);
Vec4V miny4a = V4LoadA(tn->miny+offs);
Vec4V minz4a = V4LoadA(tn->minz+offs);
Vec4V maxx4a = V4LoadA(tn->maxx+offs);
Vec4V maxy4a = V4LoadA(tn->maxy+offs);
Vec4V maxz4a = V4LoadA(tn->maxz+offs);
VecU32V noOverlapa;
VecU32V resa4u;
{
// PRECOMPUTE FOR A BLOCK
// 109 instr per 4 OBB/AABB
// ABB iteration 1, start with OBB origin as other point -- 6
Vec4V p1ABBxa = V4Max(minx4a, V4Min(maxx4a, obbOSplatX));
Vec4V p1ABBya = V4Max(miny4a, V4Min(maxy4a, obbOSplatY));
Vec4V p1ABBza = V4Max(minz4a, V4Min(maxz4a, obbOSplatZ));
// OBB iteration 1, move to OBB space first -- 12
Vec4V p1ABBOxa = V4Sub(p1ABBxa, obbOSplatX);
Vec4V p1ABBOya = V4Sub(p1ABBya, obbOSplatY);
Vec4V p1ABBOza = V4Sub(p1ABBza, obbOSplatZ);
Vec4V obbPrjXa = V4MulAdd(p1ABBOxa, obbXSplatX, V4MulAdd(p1ABBOya, obbXSplatY, V4MulAdd(p1ABBOza, obbXSplatZ, zeroes)));
Vec4V obbPrjYa = V4MulAdd(p1ABBOxa, obbYSplatX, V4MulAdd(p1ABBOya, obbYSplatY, V4MulAdd(p1ABBOza, obbYSplatZ, zeroes)));
Vec4V obbPrjZa = V4MulAdd(p1ABBOxa, obbZSplatX, V4MulAdd(p1ABBOya, obbZSplatY, V4MulAdd(p1ABBOza, obbZSplatZ, zeroes)));
// clamp AABB point in OBB space to OBB extents. Since we scaled the axii, the extents are [-1,1] -- 6
Vec4V pOBBxa = V4Max(obbESplatNegX, V4Min(obbPrjXa, obbESplatX));
Vec4V pOBBya = V4Max(obbESplatNegY, V4Min(obbPrjYa, obbESplatY));
Vec4V pOBBza = V4Max(obbESplatNegZ, V4Min(obbPrjZa, obbESplatZ));
// go back to AABB space. we have x,y,z in obb space, need to multiply by axii -- 9
Vec4V p1OBBxa = V4MulAdd(pOBBxa, obbXSplatX, V4MulAdd(pOBBya, obbYSplatX, V4MulAdd(pOBBza, obbZSplatX, obbOSplatX)));
Vec4V p1OBBya = V4MulAdd(pOBBxa, obbXSplatY, V4MulAdd(pOBBya, obbYSplatY, V4MulAdd(pOBBza, obbZSplatY, obbOSplatY)));
Vec4V p1OBBza = V4MulAdd(pOBBxa, obbXSplatZ, V4MulAdd(pOBBya, obbYSplatZ, V4MulAdd(pOBBza, obbZSplatZ, obbOSplatZ)));
// ABB iteration 2 -- 6 instructions
Vec4V p2ABBxa = V4Max(minx4a, V4Min(maxx4a, p1OBBxa));
Vec4V p2ABBya = V4Max(miny4a, V4Min(maxy4a, p1OBBya));
Vec4V p2ABBza = V4Max(minz4a, V4Min(maxz4a, p1OBBza));
// above blocks add up to 12+12+15=39 instr
// END PRECOMPUTE FOR A BLOCK
// for AABBs precompute extents and center -- 9i
Vec4V abbCxa = V4MulAdd(V4Add(maxx4a, minx4a), halves, zeroes);
Vec4V abbCya = V4MulAdd(V4Add(maxy4a, miny4a), halves, zeroes);
Vec4V abbCza = V4MulAdd(V4Add(maxz4a, minz4a), halves, zeroes);
Vec4V abbExa = V4Sub(maxx4a, abbCxa);
Vec4V abbEya = V4Sub(maxy4a, abbCya);
Vec4V abbEza = V4Sub(maxz4a, abbCza);
// now test separating axes D1 = p1OBB-p1ABB and D2 = p1OBB-p2ABB -- 37 instructions per axis
// D1 first -- 3 instructions
Vec4V d1xa = V4Sub(p1OBBxa, p1ABBxa), d1ya = V4Sub(p1OBBya, p1ABBya), d1za = V4Sub(p1OBBza, p1ABBza);
// for AABB compute projections of extents and center -- 6
Vec4V abbExd1Prja = V4MulAdd(d1xa, abbExa, zeroes);
Vec4V abbEyd1Prja = V4MulAdd(d1ya, abbEya, zeroes);
Vec4V abbEzd1Prja = V4MulAdd(d1za, abbEza, zeroes);
Vec4V abbCd1Prja = V4MulAdd(d1xa, abbCxa, V4MulAdd(d1ya, abbCya, V4MulAdd(d1za, abbCza, zeroes)));
// for obb project each halfaxis and origin and add abs values of half-axis projections -- 12 instructions
Vec4V obbXEd1Prja = V4MulAdd(d1xa, obbXESplatX, V4MulAdd(d1ya, obbXESplatY, V4MulAdd(d1za, obbXESplatZ, zeroes)));
Vec4V obbYEd1Prja = V4MulAdd(d1xa, obbYESplatX, V4MulAdd(d1ya, obbYESplatY, V4MulAdd(d1za, obbYESplatZ, zeroes)));
Vec4V obbZEd1Prja = V4MulAdd(d1xa, obbZESplatX, V4MulAdd(d1ya, obbZESplatY, V4MulAdd(d1za, obbZESplatZ, zeroes)));
Vec4V obbOd1Prja = V4MulAdd(d1xa, obbOSplatX, V4MulAdd(d1ya, obbOSplatY, V4MulAdd(d1za, obbOSplatZ, zeroes)));
// compare lengths between projected centers with sum of projected radii -- 16i
Vec4V originDiffd1a = v_absm(V4Sub(abbCd1Prja, obbOd1Prja));
Vec4V absABBRd1a = V4Add(V4Add(v_absm(abbExd1Prja), v_absm(abbEyd1Prja)), v_absm(abbEzd1Prja));
Vec4V absOBBRd1a = V4Add(V4Add(v_absm(obbXEd1Prja), v_absm(obbYEd1Prja)), v_absm(obbZEd1Prja));
VecU32V noOverlapd1a = V4IsGrtrV32u(V4Sub(originDiffd1a, eps), V4Add(absABBRd1a, absOBBRd1a));
VecU32V epsNoOverlapd1a = V4IsGrtrV32u(originDiffd1a, eps);
// D2 next (35 instr)
// 3i
Vec4V d2xa = V4Sub(p1OBBxa, p2ABBxa), d2ya = V4Sub(p1OBBya, p2ABBya), d2za = V4Sub(p1OBBza, p2ABBza);
// for AABB compute projections of extents and center -- 6
Vec4V abbExd2Prja = V4MulAdd(d2xa, abbExa, zeroes);
Vec4V abbEyd2Prja = V4MulAdd(d2ya, abbEya, zeroes);
Vec4V abbEzd2Prja = V4MulAdd(d2za, abbEza, zeroes);
Vec4V abbCd2Prja = V4MulAdd(d2xa, abbCxa, V4MulAdd(d2ya, abbCya, V4MulAdd(d2za, abbCza, zeroes)));
// for obb project each halfaxis and origin and add abs values of half-axis projections -- 12i
Vec4V obbXEd2Prja = V4MulAdd(d2xa, obbXESplatX, V4MulAdd(d2ya, obbXESplatY, V4MulAdd(d2za, obbXESplatZ, zeroes)));
Vec4V obbYEd2Prja = V4MulAdd(d2xa, obbYESplatX, V4MulAdd(d2ya, obbYESplatY, V4MulAdd(d2za, obbYESplatZ, zeroes)));
Vec4V obbZEd2Prja = V4MulAdd(d2xa, obbZESplatX, V4MulAdd(d2ya, obbZESplatY, V4MulAdd(d2za, obbZESplatZ, zeroes)));
Vec4V obbOd2Prja = V4MulAdd(d2xa, obbOSplatX, V4MulAdd(d2ya, obbOSplatY, V4MulAdd(d2za, obbOSplatZ, zeroes)));
// compare lengths between projected centers with sum of projected radii -- 16i
Vec4V originDiffd2a = v_absm(V4Sub(abbCd2Prja, obbOd2Prja));
Vec4V absABBRd2a = V4Add(V4Add(v_absm(abbExd2Prja), v_absm(abbEyd2Prja)), v_absm(abbEzd2Prja));
Vec4V absOBBRd2a = V4Add(V4Add(v_absm(obbXEd2Prja), v_absm(obbYEd2Prja)), v_absm(obbZEd2Prja));
VecU32V noOverlapd2a = V4IsGrtrV32u(V4Sub(originDiffd2a, eps), V4Add(absABBRd2a, absOBBRd2a));
VecU32V epsNoOverlapd2a = V4IsGrtrV32u(originDiffd2a, eps);
// 8i
noOverlapa = V4U32or(V4U32and(noOverlapd1a, epsNoOverlapd1a), V4U32and(noOverlapd2a, epsNoOverlapd2a));
VecU32V ignore4a = V4IsGrtrV32u(minx4a, maxx4a); // 1 if degenerate box (empty slot)
noOverlapa = V4U32or(noOverlapa, ignore4a);
resa4u = V4U32Andc(U4Load(1), noOverlapa); // 1 & ~noOverlap
V4U32StoreAligned(resa4u, reinterpret_cast<VecU32V*>(resa_));
///// 8+16+12+6+3+16+12+6+3+9+6+9+6+12+6+6=136i from load to result
}
cacheTopValid = false;
for (PxU32 i = 0; i < 4; i++)
{
PxU32 ptr = ptrs[i+offs] & ~1; // clear the isLeaf bit
if (resa_[i])
{
if (tn->isLeaf(i))
{
if (!callback->processResults(1, &ptr))
return;
}
else
{
*(stackPtr++) = ptr;
cacheTop = ptr;
cacheTopValid = true;
}
}
}
} while (stackPtr > stack);
}
} // namespace Gu
}
| 23,271 | C++ | 39.685315 | 167 | 0.713678 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBVConstants.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_BV_CONSTANTS_H
#define GU_BV_CONSTANTS_H
#include "foundation/PxVecMath.h"
namespace
{
const physx::aos::VecU32V signMask = physx::aos::U4LoadXYZW((physx::PxU32(1)<<31), (physx::PxU32(1)<<31), (physx::PxU32(1)<<31), (physx::PxU32(1)<<31));
const physx::aos::Vec4V epsFloat4 = physx::aos::V4Load(1e-9f);
const physx::aos::Vec4V zeroes = physx::aos::V4Zero();
const physx::aos::Vec4V twos = physx::aos::V4Load(2.0f);
const physx::aos::Vec4V epsInflateFloat4 = physx::aos::V4Load(1e-7f);
}
#endif // GU_BV_CONSTANTS_H
| 2,232 | C | 49.749999 | 153 | 0.747312 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamOrdered_OBBOBB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_ORDERED_OBB_OBB_H
#define GU_BV4_PROCESS_STREAM_ORDERED_OBB_OBB_H
#ifdef GU_BV4_USE_SLABS
/* template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2_Swizzled(PxU32& code, const BVDataSwizzled* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CE(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
LeafTestT::doLeafTest(params, node->getPrimitive(i));
else
code |= 1<<i;
}
}*/
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2_SwizzledQ(PxU32& code, const BVDataSwizzledQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CEQ(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
LeafTestT::doLeafTest(params, node->getPrimitive(i));
else
code |= 1<<i;
}
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2_SwizzledNQ(PxU32& code, const BVDataSwizzledNQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CENQ(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
LeafTestT::doLeafTest(params, node->getPrimitive(i));
else
code |= 1<<i;
}
}
#else
template<class LeafTestT, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params, PxU32 i, PxU32 limit)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(i<limit && BV4_BoxBoxOverlap(node+i, params))
#else
if(i<limit && BV4_BoxBoxOverlap(node[i].mAABB.mExtents, node[i].mAABB.mCenter, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
Stack[Nb++] = node[i].getChildData();
}
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2(PxU32& code, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_BoxBoxOverlap(node+i, params))
#else
if(BV4_BoxBoxOverlap(node[i].mAABB.mExtents, node[i].mAABB.mCenter, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
code |= 1<<i;
}
}
#endif
#endif // GU_BV4_PROCESS_STREAM_ORDERED_OBB_OBB_H
| 4,052 | C | 35.845454 | 170 | 0.731244 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshBV4.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuTriangleMesh.h"
#include "GuTriangleMeshBV4.h"
#include "geometry/PxGeometryInternal.h"
using namespace physx;
using namespace Gu;
namespace physx
{
// PT: temporary for Kit
BV4TriangleMesh::BV4TriangleMesh(const PxTriangleMeshInternalData& data) : TriangleMesh(data)
{
mMeshInterface.setNbTriangles(getNbTrianglesFast());
if(has16BitIndices())
mMeshInterface.setPointers(NULL, const_cast<IndTri16*>(reinterpret_cast<const IndTri16*>(getTrianglesFast())), getVerticesFast());
else
mMeshInterface.setPointers(const_cast<IndTri32*>(reinterpret_cast<const IndTri32*>(getTrianglesFast())), NULL, getVerticesFast());
mBV4Tree.mMeshInterface = &mMeshInterface;
mBV4Tree.mLocalBounds.mCenter = data.mAABB_Center;
mBV4Tree.mLocalBounds.mExtentsMagnitude = data.mAABB_Extents.magnitude();
mBV4Tree.mNbNodes = data.mNbNodes;
mBV4Tree.mNodes = data.mNodes;
mBV4Tree.mInitData = data.mInitData;
mBV4Tree.mCenterOrMinCoeff = data.mCenterOrMinCoeff;
mBV4Tree.mExtentsOrMaxCoeff = data.mExtentsOrMaxCoeff;
mBV4Tree.mQuantized = data.mQuantized;
mBV4Tree.mUserAllocated = true;
}
bool BV4TriangleMesh::getInternalData(PxTriangleMeshInternalData& data, bool takeOwnership) const
{
data.mNbVertices = mNbVertices;
data.mNbTriangles = mNbTriangles;
data.mVertices = mVertices;
data.mTriangles = mTriangles;
data.mFaceRemap = mFaceRemap;
data.mAABB_Center = mAABB.mCenter;
data.mAABB_Extents = mAABB.mExtents;
data.mGeomEpsilon = mGeomEpsilon;
data.mFlags = mFlags;
data.mNbNodes = mBV4Tree.mNbNodes;
data.mNodeSize = mBV4Tree.mQuantized ? sizeof(BVDataPackedQ) : sizeof(BVDataPackedNQ);
data.mNodes = mBV4Tree.mNodes;
data.mInitData = mBV4Tree.mInitData;
data.mCenterOrMinCoeff = mBV4Tree.mCenterOrMinCoeff;
data.mExtentsOrMaxCoeff = mBV4Tree.mExtentsOrMaxCoeff;
data.mQuantized = mBV4Tree.mQuantized;
if(takeOwnership)
{
const_cast<BV4TriangleMesh*>(this)->setBaseFlag(PxBaseFlag::eOWNS_MEMORY, false);
const_cast<BV4TriangleMesh*>(this)->mBV4Tree.mUserAllocated = true;
}
return true;
}
bool PxGetTriangleMeshInternalData(PxTriangleMeshInternalData& data, const PxTriangleMesh& mesh, bool takeOwnership)
{
return static_cast<const TriangleMesh&>(mesh).getInternalData(data, takeOwnership);
}
//~ PT: temporary for Kit
BV4TriangleMesh::BV4TriangleMesh(MeshFactory* factory, TriangleMeshData& d) : TriangleMesh(factory, d)
{
PX_ASSERT(d.mType==PxMeshMidPhase::eBVH34);
BV4TriangleData& bv4Data = static_cast<BV4TriangleData&>(d);
mMeshInterface = bv4Data.mMeshInterface;
mBV4Tree = bv4Data.mBV4Tree;
mBV4Tree.mMeshInterface = &mMeshInterface;
}
TriangleMesh* BV4TriangleMesh::createObject(PxU8*& address, PxDeserializationContext& context)
{
BV4TriangleMesh* obj = PX_PLACEMENT_NEW(address, BV4TriangleMesh(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(BV4TriangleMesh);
obj->importExtraData(context);
return obj;
}
void BV4TriangleMesh::exportExtraData(PxSerializationContext& stream)
{
mBV4Tree.exportExtraData(stream);
TriangleMesh::exportExtraData(stream);
}
void BV4TriangleMesh::importExtraData(PxDeserializationContext& context)
{
mBV4Tree.importExtraData(context);
TriangleMesh::importExtraData(context);
if(has16BitIndices())
mMeshInterface.setPointers(NULL, const_cast<IndTri16*>(reinterpret_cast<const IndTri16*>(getTrianglesFast())), getVerticesFast());
else
mMeshInterface.setPointers(const_cast<IndTri32*>(reinterpret_cast<const IndTri32*>(getTrianglesFast())), NULL, getVerticesFast());
mBV4Tree.mMeshInterface = &mMeshInterface;
}
PxVec3 * BV4TriangleMesh::getVerticesForModification()
{
return const_cast<PxVec3*>(getVertices());
}
PxBounds3 BV4TriangleMesh::refitBVH()
{
PxBounds3 newBounds;
const float gBoxEpsilon = 2e-4f;
if(mBV4Tree.refit(newBounds, gBoxEpsilon))
{
mAABB.setMinMax(newBounds.minimum, newBounds.maximum);
}
else
{
newBounds = PxBounds3::centerExtents(mAABB.mCenter, mAABB.mExtents);
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "BVH34 trees: refit operation only available on non-quantized trees.\n");
}
// PT: copied from RTreeTriangleMesh::refitBVH()
// reset edge flags and remember we did that using a mesh flag (optimization)
if(!mBV4Tree.mIsEdgeSet)
{
mBV4Tree.mIsEdgeSet = true;
setAllEdgesActive();
}
return newBounds;
}
} // namespace physx
| 6,038 | C++ | 35.161676 | 139 | 0.776913 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMeshUtils.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_TETRAHEDRONMESHUTILS_H
#define GU_TETRAHEDRONMESHUTILS_H
#include <GuTetrahedronMesh.h>
namespace physx
{
namespace Gu
{
PX_PHYSX_COMMON_API
void convertSoftbodyCollisionToSimMeshTets(const PxTetrahedronMesh& simMesh, const SoftBodyAuxData& simState,
const BVTetrahedronMesh& collisionMesh, PxU32 inTetId,
const PxVec4& inTetBarycentric, PxU32& outTetId,
PxVec4& outTetBarycentric);
PX_PHYSX_COMMON_API
PxVec4 addAxisToSimMeshBarycentric(const PxTetrahedronMesh& simMesh, const PxU32 simTetId,
const PxVec4& simBarycentric, const PxVec3& axis);
}
}
#endif
| 2,300 | C | 44.117646 | 109 | 0.728261 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_BoxSweep_Params.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// This is used by the box-sweep & capsule-sweep code
#if PX_VC
#pragma warning(disable: 4505) // unreferenced local function has been removed
#endif
#include "foundation/PxBasicTemplates.h"
namespace
{
#ifdef SWEEP_AABB_IMPL
struct BoxSweepParams : RayParams
#else
struct BoxSweepParams : OBBTestParams
#endif
{
const IndTri32* PX_RESTRICT mTris32;
const IndTri16* PX_RESTRICT mTris16;
const PxVec3* PX_RESTRICT mVerts;
#ifndef SWEEP_AABB_IMPL
Box mLocalBox;
#endif
PxVec3 mLocalDir_Padded;
RaycastHitInternal mStabbedFace;
PxU32 mBackfaceCulling;
PxU32 mEarlyExit;
PxVec3 mP0, mP1, mP2;
PxVec3 mBestTriNormal;
float mOffset;
PxVec3 mProj;
PxVec3 mDP;
#ifndef SWEEP_AABB_IMPL
PxMat33 mAR; //!< Absolute rotation matrix
#endif
PxMat33 mRModelToBox_Padded; //!< Rotation from model space to obb space
PxVec3 mTModelToBox_Padded; //!< Translation from model space to obb space
PxVec3 mOriginalExtents_Padded;
PxVec3 mOriginalDir_Padded;
PxVec3 mOneOverDir_Padded;
PxVec3 mOneOverOriginalDir;
#ifndef SWEEP_AABB_IMPL
PX_FORCE_INLINE void ShrinkOBB(float d)
{
const PxVec3 BoxExtents = mDP + d * mProj;
mTBoxToModel_PaddedAligned = mLocalBox.center + mLocalDir_Padded*d*0.5f;
setupBoxData(this, BoxExtents, &mAR);
}
#endif
};
}
// PT: TODO: check asm again in PhysX version, compare to original (TA34704)
static void prepareSweepData(const Box& box, const PxVec3& dir, float maxDist, BoxSweepParams* PX_RESTRICT params)
{
invertBoxMatrix(params->mRModelToBox_Padded, params->mTModelToBox_Padded, box);
params->mOriginalExtents_Padded = box.extents;
const PxVec3 OriginalDir = params->mRModelToBox_Padded.transform(dir);
params->mOriginalDir_Padded = OriginalDir;
const PxVec3 OneOverOriginalDir(OriginalDir.x!=0.0f ? 1.0f/OriginalDir.x : 0.0f,
OriginalDir.y!=0.0f ? 1.0f/OriginalDir.y : 0.0f,
OriginalDir.z!=0.0f ? 1.0f/OriginalDir.z : 0.0f);
params->mOneOverOriginalDir = OneOverOriginalDir;
params->mOneOverDir_Padded = OneOverOriginalDir / maxDist;
{
const Box& LocalBox = box;
const PxVec3& LocalDir = dir;
params->mLocalDir_Padded = LocalDir;
params->mStabbedFace.mDistance = maxDist;
#ifndef SWEEP_AABB_IMPL
params->mLocalBox = LocalBox; // PT: TODO: check asm for operator=
#endif
PxMat33 boxToModelR;
// Original code:
// OBB::CreateOBB(LocalBox, LocalDir, 0.5f)
{
PxVec3 R1, R2;
{
float dd[3];
dd[0] = fabsf(LocalBox.rot.column0.dot(LocalDir));
dd[1] = fabsf(LocalBox.rot.column1.dot(LocalDir));
dd[2] = fabsf(LocalBox.rot.column2.dot(LocalDir));
float dmax = dd[0];
PxU32 ax0=1;
PxU32 ax1=2;
if(dd[1]>dmax)
{
dmax=dd[1];
ax0=0;
ax1=2;
}
if(dd[2]>dmax)
{
dmax=dd[2];
ax0=0;
ax1=1;
}
if(dd[ax1]<dd[ax0])
PxSwap(ax0, ax1);
R1 = LocalBox.rot[ax0];
R1 -= R1.dot(LocalDir)*LocalDir; // Project to plane whose normal is dir
R1.normalize();
R2 = LocalDir.cross(R1);
}
// Original code:
// mRot = params->mRBoxToModel
boxToModelR.column0 = LocalDir;
boxToModelR.column1 = R1;
boxToModelR.column2 = R2;
// Original code:
// float Offset[3];
// 0.5f comes from the Offset[r]*0.5f, doesn't mean 'd' is 0.5f
params->mProj.x = 0.5f;
params->mProj.y = LocalDir.dot(R1)*0.5f;
params->mProj.z = LocalDir.dot(R2)*0.5f;
// Original code:
//mExtents[r] = Offset[r]*0.5f + fabsf(box.mRot[0]|R)*box.mExtents.x + fabsf(box.mRot[1]|R)*box.mExtents.y + fabsf(box.mRot[2]|R)*box.mExtents.z;
// => we store the first part of the computation, minus 'Offset[r]*0.5f'
for(PxU32 r=0;r<3;r++)
{
const PxVec3& R = boxToModelR[r];
params->mDP[r] = fabsf(LocalBox.rot.column0.dot(R)*LocalBox.extents.x)
+ fabsf(LocalBox.rot.column1.dot(R)*LocalBox.extents.y)
+ fabsf(LocalBox.rot.column2.dot(R)*LocalBox.extents.z);
}
// In the original code, both mCenter & mExtents depend on 'd', and thus we will need to recompute these two members.
//
// For mExtents we have:
//
// float Offset[3];
// Offset[0] = d;
// Offset[1] = d*(dir|R1);
// Offset[2] = d*(dir|R2);
//
// mExtents[r] = Offset[r]*0.5f + fabsf(box.mRot[0]|R)*box.mExtents.x + fabsf(box.mRot[1]|R)*box.mExtents.y + fabsf(box.mRot[2]|R)*box.mExtents.z;
// <=> mExtents[r] = Offset[r]*0.5f + Params.mDP[r]; We precompute the second part that doesn't depend on d, stored in mDP
// <=> mExtents[r] = Params.mProj[r]*d + Params.mDP[r]; We extract d from the first part, store what is left in mProj
//
// Thus in ShrinkOBB the code needed to update the extents is just:
// mBoxExtents = mDP + d * mProj;
//
// For mCenter we have:
//
// mCenter = box.mCenter + dir*d*0.5f;
//
// So we simply use this formula directly, with the new d. Result is stored in 'mTBoxToModel'
/*
PX_FORCE_INLINE void ShrinkOBB(float d)
{
mBoxExtents = mDP + d * mProj;
mTBoxToModel = mLocalBox.mCenter + mLocalDir*d*0.5f;
*/
}
// This one is for culling tris, unrelated to CreateOBB
params->mOffset = params->mDP.x + LocalBox.center.dot(LocalDir);
#ifndef SWEEP_AABB_IMPL
precomputeData(params, ¶ms->mAR, &boxToModelR);
params->ShrinkOBB(maxDist);
#endif
}
}
| 6,999 | C | 32.175355 | 150 | 0.690956 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTetrahedronMeshUtils.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#include "GuTetrahedronMeshUtils.h"
#include "GuDistancePointTetrahedron.h"
namespace physx
{
namespace Gu
{
void convertSoftbodyCollisionToSimMeshTets(const PxTetrahedronMesh& simMesh, const SoftBodyAuxData& simState,
const BVTetrahedronMesh& collisionMesh, PxU32 inTetId,
const PxVec4& inTetBarycentric, PxU32& outTetId, PxVec4& outTetBarycentric)
{
if (inTetId == 0xFFFFFFFF)
{
outTetId = 0xFFFFFFFF;
outTetBarycentric = PxVec4(0.0f);
return;
}
// Map from CPU tet ID (corresponds to the ID in the BV4 mesh) to the GPU tet ID (corresponds to the ID in
// the BV32 mesh)
inTetId = collisionMesh.mGRB_faceRemapInverse[inTetId];
const PxU32 endIdx = simState.mTetsAccumulatedRemapColToSim[inTetId];
const PxU32 startIdx = inTetId != 0 ? simState.mTetsAccumulatedRemapColToSim[inTetId - 1] : 0;
const PxU32* const tetRemapColToSim = simState.mTetsRemapColToSim;
typedef PxVec4T<unsigned int> uint4;
const uint4* const collInds =
reinterpret_cast<const uint4*>(collisionMesh.mGRB_tetraIndices /*collisionMesh->mTetrahedrons*/);
const uint4* const simInds = reinterpret_cast<const uint4*>(simMesh.getTetrahedrons());
const PxVec3* const collVerts = collisionMesh.mVertices;
const PxVec3* const simVerts = simMesh.getVertices();
const uint4 ind = collInds[inTetId];
const PxVec3 point = collVerts[ind.x] * inTetBarycentric.x + collVerts[ind.y] * inTetBarycentric.y +
collVerts[ind.z] * inTetBarycentric.z + collVerts[ind.w] * inTetBarycentric.w;
PxReal currDist = PX_MAX_F32;
for(PxU32 i = startIdx; i < endIdx; ++i)
{
const PxU32 simTet = tetRemapColToSim[i];
const uint4 simInd = simInds[simTet];
const PxVec3 a = simVerts[simInd.x];
const PxVec3 b = simVerts[simInd.y];
const PxVec3 c = simVerts[simInd.z];
const PxVec3 d = simVerts[simInd.w];
const PxVec3 tmpClosest = closestPtPointTetrahedronWithInsideCheck(point, a, b, c, d);
const PxVec3 v = point - tmpClosest;
const PxReal tmpDist = v.dot(v);
if(tmpDist < currDist)
{
PxVec4 tmpBarycentric;
computeBarycentric(a, b, c, d, tmpClosest, tmpBarycentric);
currDist = tmpDist;
outTetId = simTet;
outTetBarycentric = tmpBarycentric;
if(tmpDist < 1e-6f)
break;
}
}
PX_ASSERT(outTetId != 0xFFFFFFFF);
}
PxVec4 addAxisToSimMeshBarycentric(const PxTetrahedronMesh& simMesh, const PxU32 simTetId, const PxVec4& simBary, const PxVec3& axis)
{
const PxVec3* simMeshVerts = simMesh.getVertices();
PxVec3 tetVerts[4];
if(simMesh.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES)
{
const PxU16* indices = reinterpret_cast<const PxU16*>(simMesh.getTetrahedrons());
tetVerts[0] = simMeshVerts[indices[simTetId*4 + 0]];
tetVerts[1] = simMeshVerts[indices[simTetId*4 + 1]];
tetVerts[2] = simMeshVerts[indices[simTetId*4 + 2]];
tetVerts[3] = simMeshVerts[indices[simTetId*4 + 3]];
}
else
{
const PxU32* indices = reinterpret_cast<const PxU32*>(simMesh.getTetrahedrons());
tetVerts[0] = simMeshVerts[indices[simTetId*4 + 0]];
tetVerts[1] = simMeshVerts[indices[simTetId*4 + 1]];
tetVerts[2] = simMeshVerts[indices[simTetId*4 + 2]];
tetVerts[3] = simMeshVerts[indices[simTetId*4 + 3]];
}
const PxVec3 simPoint = tetVerts[0]*simBary.x + tetVerts[1]*simBary.y + tetVerts[2]*simBary.z + tetVerts[3]*simBary.w;
const PxVec3 offsetPoint = simPoint + axis;
PxVec4 offsetBary;
computeBarycentric(tetVerts[0], tetVerts[1], tetVerts[2], tetVerts[3], offsetPoint, offsetBary);
return offsetBary;
}
}
} | 5,145 | C++ | 38.282442 | 133 | 0.732945 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV32Build.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxVec4.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxMemory.h"
#include "geometry/PxTriangle.h"
#include "GuBV32Build.h"
#include "GuBV32.h"
#include "GuCenterExtents.h"
#include "GuBV4Build.h"
using namespace physx;
using namespace Gu;
#include "foundation/PxVecMath.h"
using namespace physx::aos;
struct BV32Node : public physx::PxUserAllocated
{
BV32Node() : mNbChildBVNodes(0)
{}
BV32Data mBVData[32];
PxU32 mNbChildBVNodes;
PX_FORCE_INLINE size_t isLeaf(PxU32 i) const { return mBVData[i].mData & 1; }
PX_FORCE_INLINE PxU32 getPrimitive(PxU32 i) const { return PxU32(mBVData[i].mData >> 1); }
PX_FORCE_INLINE const BV32Node* getChild(PxU32 i) const { return reinterpret_cast<BV32Node*>(mBVData[i].mData); }
PxU32 getSize() const
{
return sizeof(BV32Data)*mNbChildBVNodes;
}
};
static void fillInNodes(const AABBTreeNode* current_node, const PxU32 startIndex, const PxU32 endIndex, const AABBTreeNode** NODES, PxU32& stat)
{
if (startIndex + 1 == endIndex)
{
//fill in nodes
const AABBTreeNode* P = current_node->getPos();
const AABBTreeNode* N = current_node->getNeg();
NODES[startIndex] = P;
NODES[endIndex] = N;
stat += 2;
}
else
{
const AABBTreeNode* P = current_node->getPos();
const AABBTreeNode* N = current_node->getNeg();
const PxU32 midIndex = startIndex + ((endIndex - startIndex) / 2);
if (!P->isLeaf())
fillInNodes(P, startIndex, midIndex, NODES, stat);
else
{
NODES[startIndex] = P;
stat++;
}
if (!N->isLeaf())
fillInNodes(N, midIndex + 1, endIndex, NODES, stat);
else
{
NODES[midIndex + 1] = N;
stat++;
}
}
}
static void setPrimitive(const BV4_AABBTree& source, BV32Node* node32, PxU32 i, const AABBTreeNode* node, float epsilon)
{
const PxU32 nbPrims = node->getNbPrimitives();
PX_ASSERT(nbPrims<=32);
const PxU32* indexBase = source.getIndices();
const PxU32* prims = node->getPrimitives();
const PxU32 offset = PxU32(prims - indexBase);
#if BV32_VALIDATE
for (PxU32 j = 0; j<nbPrims; j++)
{
PX_ASSERT(prims[j] == offset + j);
}
#endif
const PxU32 primitiveIndex = (offset << 6) | (nbPrims & 63);
node32->mBVData[i].mMin = node->getAABB().minimum;
node32->mBVData[i].mMax = node->getAABB().maximum;
if (epsilon != 0.0f)
{
node32->mBVData[i].mMin -= PxVec3(epsilon);
node32->mBVData[i].mMax += PxVec3(epsilon);
}
node32->mBVData[i].mData = (primitiveIndex << 1) | 1;
}
static BV32Node* setNode(const BV4_AABBTree& source, BV32Node* node32, PxU32 i, const AABBTreeNode* node, float epsilon)
{
BV32Node* child = NULL;
if (node)
{
if (node->isLeaf())
{
setPrimitive(source, node32, i, node, epsilon);
}
else
{
node32->mBVData[i].mMin = node->getAABB().minimum;
node32->mBVData[i].mMax = node->getAABB().maximum;
if (epsilon != 0.0f)
{
node32->mBVData[i].mMin -= PxVec3(epsilon);
node32->mBVData[i].mMax += PxVec3(epsilon);
}
child = PX_NEW(BV32Node);
node32->mBVData[i].mData = size_t(child);
}
}
return child;
}
static void buildBV32(const BV4_AABBTree& source, BV32Node* tmp, const AABBTreeNode* current_node, float epsilon, PxU32& nbNodes)
{
PX_ASSERT(!current_node->isLeaf());
const AABBTreeNode* NODES[32];
PxMemSet(NODES, 0, sizeof(AABBTreeNode*) * 32);
fillInNodes(current_node, 0, 31, NODES, tmp->mNbChildBVNodes);
PxU32 left = 0;
PxU32 right = 31;
while (left < right)
{
//sweep from the front
while (left<right)
{
//found a hole
if (NODES[left] == NULL)
break;
left++;
}
//sweep from the back
while (left < right)
{
//found a node
if (NODES[right])
break;
right--;
}
if (left != right)
{
//swap left and right
const AABBTreeNode* node = NODES[right];
NODES[right] = NODES[left];
NODES[left] = node;
}
}
nbNodes += tmp->mNbChildBVNodes;
for (PxU32 i = 0; i < tmp->mNbChildBVNodes; ++i)
{
const AABBTreeNode* tempNode = NODES[i];
BV32Node* Child = setNode(source, tmp, i, tempNode, epsilon);
if (Child)
{
buildBV32(source, Child, tempNode, epsilon, nbNodes);
}
}
}
//
//static void validateTree(const AABBTree& Source, const AABBTreeNode* currentNode)
//{
// if (currentNode->isLeaf())
// {
// const PxU32* indexBase = Source.getIndices();
// const PxU32* prims = currentNode->getPrimitives();
// const PxU32 offset = PxU32(prims - indexBase);
// const PxU32 nbPrims = currentNode->getNbPrimitives();
// for (PxU32 j = 0; j<nbPrims; j++)
// {
// PX_ASSERT(prims[j] == offset + j);
// }
// }
// else
// {
// const AABBTreeNode* pos = currentNode->getPos();
// validateTree(Source, pos);
// const AABBTreeNode* neg = currentNode->getNeg();
// validateTree(Source, neg);
// }
//}
#if BV32_VALIDATE
static void validateNodeBound(const BV32Node* currentNode, SourceMeshBase* mesh, float epsilon)
{
const PxU32 nbPrimitivesFromMesh = mesh->getNbPrimitives();
const PxReal eps = 1e-5f;
const PxU32 nbNodes = currentNode->mNbChildBVNodes;
for (PxU32 i = 0; i < nbNodes; ++i)
{
const BV32Node* node = currentNode->getChild(i);
if (currentNode->isLeaf(i))
{
BV32Data data = currentNode->mBVData[i];
PxU32 nbPrimitives = data.getNbReferencedPrimitives();
PxU32 startIndex = data.getPrimitiveStartIndex();
PX_ASSERT(startIndex< nbPrimitivesFromMesh);
PxVec3 min(PX_MAX_F32, PX_MAX_F32, PX_MAX_F32);
PxVec3 max(-PX_MAX_F32, -PX_MAX_F32, -PX_MAX_F32);
const PxVec3* verts = mesh->getVerts();
if (mesh->getMeshType() == SourceMeshBase::MeshType::TRI_MESH)
{
const IndTri32* triIndices = static_cast<SourceMesh*>(mesh)->getTris32();
for (PxU32 j = 0; j < nbPrimitives; ++j)
{
IndTri32 index = triIndices[startIndex + j];
for (PxU32 k = 0; k < 3; ++k)
{
const PxVec3& v = verts[index.mRef[k]];
min.x = (min.x > v.x) ? v.x : min.x;
min.y = (min.y > v.y) ? v.y : min.y;
min.z = (min.z > v.z) ? v.z : min.z;
max.x = (max.x < v.x) ? v.x : max.x;
max.y = (max.y < v.y) ? v.y : max.y;
max.z = (max.z < v.z) ? v.z : max.z;
}
}
}
else
{
const IndTetrahedron32* tetIndices = static_cast<TetrahedronSourceMesh*>(mesh)->getTetrahedrons32();
for (PxU32 j = 0; j < nbPrimitives; ++j)
{
IndTetrahedron32 index = tetIndices[startIndex + j];
for (PxU32 k = 0; k < 4; ++k)
{
const PxVec3& v = verts[index.mRef[k]];
min.x = (min.x > v.x) ? v.x : min.x;
min.y = (min.y > v.y) ? v.y : min.y;
min.z = (min.z > v.z) ? v.z : min.z;
max.x = (max.x < v.x) ? v.x : max.x;
max.y = (max.y < v.y) ? v.y : max.y;
max.z = (max.z < v.z) ? v.z : max.z;
}
}
}
PxVec3 dMin, dMax;
data.getMinMax(dMin, dMax);
const PxVec3 difMin = min - dMin;
const PxVec3 difMax = dMax - max;
PX_ASSERT(PxAbs(difMin.x - epsilon) < eps && PxAbs(difMin.y - epsilon) < eps && PxAbs(difMin.z - epsilon) < eps);
PX_ASSERT(PxAbs(difMax.x - epsilon) < eps && PxAbs(difMax.y - epsilon) < eps && PxAbs(difMax.z - epsilon) < eps);
}
else
{
validateNodeBound(node, mesh, epsilon);
}
}
}
#endif
static bool BuildBV32Internal(BV32Tree& bv32Tree, const BV4_AABBTree& Source, SourceMeshBase* mesh, float epsilon)
{
GU_PROFILE_ZONE("..BuildBV32Internal")
const PxU32 nbPrimitives = mesh->getNbPrimitives();
if (nbPrimitives <= 32)
{
bv32Tree.mNbPackedNodes = 1;
bv32Tree.mPackedNodes = reinterpret_cast<BV32DataPacked*>(PX_ALLOC(sizeof(BV32DataPacked), "BV32DataPacked"));
BV32DataPacked& packedData = bv32Tree.mPackedNodes[0];
packedData.mNbNodes = 1;
packedData.mMin[0] = PxVec4(Source.getBV().minimum, 0.f);
packedData.mMax[0] = PxVec4(Source.getBV().maximum, 0.f);
packedData.mData[0] = (nbPrimitives << 1) | 1;
bv32Tree.mMaxTreeDepth = 1;
bv32Tree.mTreeDepthInfo = reinterpret_cast<BV32DataDepthInfo*>(PX_ALLOC(sizeof(BV32DataDepthInfo), "BV32DataDepthInfo"));
bv32Tree.mRemapPackedNodeIndexWithDepth = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32), "PxU32"));
bv32Tree.mTreeDepthInfo[0].offset = 0;
bv32Tree.mTreeDepthInfo[0].count = 1;
bv32Tree.mRemapPackedNodeIndexWithDepth[0] = 0;
return bv32Tree.init(mesh, Source.getBV());
}
{
GU_PROFILE_ZONE("...._checkMD")
struct Local
{
static void _checkMD(const AABBTreeNode* current_node, PxU32& md, PxU32& cd)
{
cd++;
md = PxMax(md, cd);
if (current_node->getPos()) { _checkMD(current_node->getPos(), md, cd); cd--; }
if (current_node->getNeg()) { _checkMD(current_node->getNeg(), md, cd); cd--; }
}
static void _check(AABBTreeNode* current_node)
{
if (current_node->isLeaf())
return;
AABBTreeNode* P = const_cast<AABBTreeNode*>(current_node->getPos());
AABBTreeNode* N = const_cast<AABBTreeNode*>(current_node->getNeg());
{
PxU32 MDP = 0; PxU32 CDP = 0; _checkMD(P, MDP, CDP);
PxU32 MDN = 0; PxU32 CDN = 0; _checkMD(N, MDN, CDN);
if (MDP>MDN)
// if(MDP<MDN)
{
PxSwap(*P, *N);
PxSwap(P, N);
}
}
_check(P);
_check(N);
}
};
Local::_check(const_cast<AABBTreeNode*>(Source.getNodes()));
}
PxU32 nbNodes = 1;
BV32Node* Root32 = PX_NEW(BV32Node);
{
GU_PROFILE_ZONE("....buildBV32")
buildBV32(Source, Root32, Source.getNodes(), epsilon, nbNodes);
}
#if BV32_VALIDATE
validateNodeBound(Root32, mesh, epsilon);
#endif
if (!bv32Tree.init(mesh, Source.getBV()))
return false;
BV32Tree* T = &bv32Tree;
PxU32 MaxDepth = 0;
// Version with variable-sized nodes in single stream
{
GU_PROFILE_ZONE("...._flatten")
struct Local
{
static void _flatten(BV32Data* const dest, const PxU32 box_id, PxU32& current_id, const BV32Node* current, PxU32& max_depth, PxU32& current_depth, const PxU32 nb_nodes)
{
// Entering a new node => increase depth
current_depth++;
// Keep track of max depth
if (current_depth>max_depth)
max_depth = current_depth;
for (PxU32 i = 0; i<current->mNbChildBVNodes; i++)
{
dest[box_id + i].mMin = current->mBVData[i].mMin;
dest[box_id + i].mMax = current->mBVData[i].mMax;
dest[box_id + i].mData = PxU32(current->mBVData[i].mData);
dest[box_id + i].mDepth = current_depth;
PX_ASSERT(box_id + i < nb_nodes);
}
PxU32 NbToGo = 0;
PxU32 NextIDs[32];
PxMemSet(NextIDs, PX_INVALID_U32, sizeof(PxU32)*32);
const BV32Node* ChildNodes[32];
PxMemSet(ChildNodes, 0, sizeof(BV32Node*)*32);
BV32Data* data = dest + box_id;
for (PxU32 i = 0; i<current->mNbChildBVNodes; i++)
{
PX_ASSERT(current->mBVData[i].mData != PX_INVALID_U32);
if (!current->isLeaf(i))
{
const BV32Node* ChildNode = current->getChild(i);
const PxU32 NextID = current_id;
const PxU32 ChildSize = ChildNode->mNbChildBVNodes;
current_id += ChildSize;
const PxU32 ChildType = ChildNode->mNbChildBVNodes << 1;
data[i].mData = size_t(ChildType + (NextID << GU_BV4_CHILD_OFFSET_SHIFT_COUNT));
//PX_ASSERT(data[i].mData == size_t(ChildType+(NextID<<3)));
PX_ASSERT(box_id + i < nb_nodes);
NextIDs[NbToGo] = NextID;
ChildNodes[NbToGo] = ChildNode;
NbToGo++;
}
}
for (PxU32 i = 0; i<NbToGo; i++)
{
_flatten(dest, NextIDs[i], current_id, ChildNodes[i], max_depth, current_depth, nb_nodes);
current_depth--;
}
PX_DELETE(current);
}
};
PxU32 CurID = Root32->mNbChildBVNodes+1;
BV32Data* Nodes = PX_NEW(BV32Data)[nbNodes];
Nodes[0].mMin = Source.getBV().minimum;
Nodes[0].mMax = Source.getBV().maximum;
const PxU32 ChildType = Root32->mNbChildBVNodes << 1;
Nodes[0].mData = size_t(ChildType + (1 << GU_BV4_CHILD_OFFSET_SHIFT_COUNT));
const PxU32 nbChilden = Nodes[0].getNbChildren();
PX_UNUSED(nbChilden);
T->mInitData = CurID;
PxU32 CurrentDepth = 0;
Local::_flatten(Nodes, 1, CurID, Root32, MaxDepth, CurrentDepth, nbNodes);
PX_ASSERT(CurID == nbNodes);
T->mNbNodes = nbNodes;
T->mNodes = Nodes;
}
{
GU_PROFILE_ZONE("....calculateLeafNode")
BV32Data* nodes = bv32Tree.mNodes;
for(PxU32 i=0; i<nbNodes; i++)
{
BV32Data& node = nodes[i];
if(!node.isLeaf())
{
PxU32 nbChildren = node.getNbChildren();
PxU32 offset = node.getChildOffset();
//calculate how many children nodes are leaf nodes
PxU32 nbLeafNodes = 0;
while(nbChildren--)
{
BV32Data& child = nodes[offset++];
if(child.isLeaf())
nbLeafNodes++;
}
node.mNbLeafNodes = nbLeafNodes;
}
}
}
bv32Tree.mPackedNodes = PX_ALLOCATE(BV32DataPacked, nbNodes, "BV32DataPacked");
bv32Tree.mNbPackedNodes = nbNodes;
bv32Tree.mMaxTreeDepth = MaxDepth;
PxU32 nbPackedNodes = 1;
PxU32 currentIndex = bv32Tree.mNodes[0].getNbChildren() - bv32Tree.mNodes[0].mNbLeafNodes + 1;
BV32DataPacked& packedData = bv32Tree.mPackedNodes[0];
//BV32DataDepth& depthData = bv32Tree.mMaxDepthForPackedNodes[0];
{
GU_PROFILE_ZONE("....createSOAformatNode")
bv32Tree.createSOAformatNode(packedData, bv32Tree.mNodes[0], 1, currentIndex, nbPackedNodes);
}
PX_ASSERT(nbPackedNodes == currentIndex);
PX_ASSERT(nbPackedNodes > 0);
bv32Tree.mNbPackedNodes = nbPackedNodes;
#if BV32_VALIDATE
/*for (PxU32 i = 0; i < nbNodes; ++i)
{
BV32Data& iNode = bv32Tree.mNodes[i];
for (PxU32 j = i+1; j < nbNodes; ++j)
{
BV32Data& jNode = bv32Tree.mNodes[j];
PX_ASSERT(iNode.mDepth <= jNode.mDepth);
}
}*/
#endif
{
GU_PROFILE_ZONE("....depth stuff")
//bv32Tree.mMaxDepthForPackedNodes = reinterpret_cast<BV32DataDepth*>(PX_ALLOC(sizeof(BV32DataDepth)*MaxDepth, "BV32DataDepth"));
bv32Tree.mTreeDepthInfo = PX_ALLOCATE(BV32DataDepthInfo, MaxDepth, "BV32DataDepthInfo");
PxU32 totalCount = 0;
for (PxU32 i = 0; i < MaxDepth; ++i)
{
PxU32 count = 0;
for (PxU32 j = 0; j < nbPackedNodes; ++j)
{
BV32DataPacked& jPackedData = bv32Tree.mPackedNodes[j];
if (jPackedData.mDepth == i)
{
count++;
}
}
bv32Tree.mTreeDepthInfo[i].offset = totalCount;
bv32Tree.mTreeDepthInfo[i].count = count;
totalCount += count;
}
PX_ASSERT(totalCount == nbPackedNodes);
bv32Tree.mRemapPackedNodeIndexWithDepth = PX_ALLOCATE(PxU32, nbPackedNodes, "PxU32");
for (PxU32 i = 0; i < MaxDepth; ++i)
{
PxU32 count = 0;
const PxU32 offset = bv32Tree.mTreeDepthInfo[i].offset;
PxU32* treeDepth = &bv32Tree.mRemapPackedNodeIndexWithDepth[offset];
for (PxU32 j = 0; j < nbPackedNodes; ++j)
{
BV32DataPacked& jPackedData = bv32Tree.mPackedNodes[j];
if (jPackedData.mDepth == i)
{
treeDepth[count++] = j;
}
}
}
#if BV32_VALIDATE
for (PxU32 i = MaxDepth; i > 0; i--)
{
const PxU32 iOffset = bv32Tree.mTreeDepthInfo[i - 1].offset;
const PxU32 iCount = bv32Tree.mTreeDepthInfo[i - 1].count;
PxU32* iRempapNodeIndex = &bv32Tree.mRemapPackedNodeIndexWithDepth[iOffset];
for (PxU32 j = 0; j < iCount; ++j)
{
const PxU32 nodeIndex = iRempapNodeIndex[j];
BV32DataPacked& currentNode = bv32Tree.mPackedNodes[nodeIndex];
PX_ASSERT(currentNode.mDepth == i - 1);
}
}
#endif
}
return true;
}
/////
struct ReorderData32
{
//const SourceMesh* mMesh;
SourceMeshBase* mMesh;
PxU32* mOrder;
PxU32 mNbPrimitivesPerLeaf;
PxU32 mIndex;
PxU32 mNbPrimitives;
PxU32 mStats[32];
};
static bool gReorderCallback(const AABBTreeNode* current, PxU32 /*depth*/, void* userData)
{
ReorderData32* Data = reinterpret_cast<ReorderData32*>(userData);
if (current->isLeaf())
{
const PxU32 n = current->getNbPrimitives();
PX_ASSERT(n > 0);
PX_ASSERT(n <= Data->mNbPrimitivesPerLeaf);
Data->mStats[n-1]++;
PxU32* Prims = const_cast<PxU32*>(current->getPrimitives());
for (PxU32 i = 0; i<n; i++)
{
PX_ASSERT(Prims[i]<Data->mNbPrimitives);
Data->mOrder[Data->mIndex] = Prims[i];
PX_ASSERT(Data->mIndex<Data->mNbPrimitives);
Prims[i] = Data->mIndex;
Data->mIndex++;
}
}
return true;
}
bool physx::Gu::BuildBV32Ex(BV32Tree& tree, SourceMeshBase& mesh, float epsilon, PxU32 nbPrimitivesPerLeaf)
{
const PxU32 nbPrimitives = mesh.getNbPrimitives();
BV4_AABBTree Source;
{
GU_PROFILE_ZONE("..BuildBV32Ex_buildFromMesh")
// if (!Source.buildFromMesh(mesh, nbPrimitivesPerLeaf, BV4_SPLATTER_POINTS_SPLIT_GEOM_CENTER))
if (!Source.buildFromMesh(mesh, nbPrimitivesPerLeaf, BV4_SAH))
return false;
}
{
GU_PROFILE_ZONE("..BuildBV32Ex_remap")
PxU32* order = PX_ALLOCATE(PxU32, nbPrimitives, "BV32");
ReorderData32 RD;
RD.mMesh = &mesh;
RD.mOrder = order;
RD.mNbPrimitivesPerLeaf = nbPrimitivesPerLeaf;
RD.mIndex = 0;
RD.mNbPrimitives = nbPrimitives;
for (PxU32 i = 0; i<32; i++)
RD.mStats[i] = 0;
Source.walk(gReorderCallback, &RD);
PX_ASSERT(RD.mIndex == nbPrimitives);
mesh.remapTopology(order);
PX_FREE(order);
// for(PxU32 i=0;i<16;i++)
// printf("%d: %d\n", i, RD.mStats[i]);
}
/*if (mesh.getNbPrimitives() <= nbPrimitivesPerLeaf)
return tree.init(&mesh, Source.getBV());*/
return BuildBV32Internal(tree, Source, &mesh, epsilon);
}
| 18,784 | C++ | 26.028777 | 171 | 0.659497 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_AABBSweep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuBV4.h"
using namespace physx;
using namespace Gu;
#define SWEEP_AABB_IMPL
#include "foundation/PxVecMath.h"
using namespace physx::aos;
#include "GuBV4_BoxSweep_Internal.h"
| 1,884 | C++ | 49.945945 | 74 | 0.767516 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamOrdered_SegmentAABB_Inflated.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_INFLATED_H
#define GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_INFLATED_H
#ifndef GU_BV4_USE_SLABS
template<class LeafTestT, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params, PxU32 i, PxU32 limit)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(i<limit && BV4_SegmentAABBOverlap(node+i, params->mOriginalExtents, params))
#else
if(i<limit && BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params->mOriginalExtents, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
Stack[Nb++] = node[i].getChildData();
}
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE void BV4_ProcessNodeOrdered2(PxU32& code, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_SegmentAABBOverlap(node+i, params->mOriginalExtents_Padded, params))
#else
if(BV4_SegmentAABBOverlap(node[i].mAABB.mCenter, node[i].mAABB.mExtents, params->mOriginalExtents_Padded, params))
#endif
{
if(node[i].isLeaf())
LeafTestT::doLeafTest(params, node[i].getPrimitive());
else
code |= 1<<i;
}
}
#endif
#endif // GU_BV4_PROCESS_STREAM_ORDERED_SEGMENT_AABB_INFLATED_H
| 3,067 | C | 44.791044 | 170 | 0.751875 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuBV4_ProcessStreamNoOrder_OBBOBB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BV4_PROCESS_STREAM_NOORDER_OBB_OBB_H
#define GU_BV4_PROCESS_STREAM_NOORDER_OBB_OBB_H
#ifdef GU_BV4_USE_SLABS
/* template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_Swizzled(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzled* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CE(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}*/
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_SwizzledQ(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CEQ(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder_SwizzledNQ(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataSwizzledNQ* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
OPC_SLABS_GET_CENQ(i)
if(BV4_BoxBoxOverlap(centerV, extentsV, params))
{
if(node->isLeaf(i))
{
if(LeafTestT::doLeafTest(params, node->getPrimitive(i)))
return 1;
}
else
Stack[Nb++] = node->getChildData(i);
}
return 0;
}
#else
template<class LeafTestT, int i, class ParamsT>
PX_FORCE_INLINE PxIntBool BV4_ProcessNodeNoOrder(PxU32* PX_RESTRICT Stack, PxU32& Nb, const BVDataPacked* PX_RESTRICT node, ParamsT* PX_RESTRICT params)
{
#ifdef GU_BV4_QUANTIZED_TREE
if(BV4_BoxBoxOverlap(node+i, params))
#else
if(BV4_BoxBoxOverlap(node[i].mAABB.mExtents, node[i].mAABB.mCenter, params))
#endif
{
if(node[i].isLeaf())
{
if(LeafTestT::doLeafTest(params, node[i].getPrimitive()))
return 1;
}
else
Stack[Nb++] = node[i].getChildData();
}
return 0;
}
#endif
#endif // GU_BV4_PROCESS_STREAM_NOORDER_OBB_OBB_H
| 3,869 | C | 34.181818 | 168 | 0.724477 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/mesh/GuTriangleMeshRTree.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "GuTriangleMesh.h"
#include "GuTriangleMeshRTree.h"
using namespace physx;
namespace physx
{
Gu::RTreeTriangleMesh::RTreeTriangleMesh(MeshFactory* factory, TriangleMeshData& d) : TriangleMesh(factory, d)
{
PX_ASSERT(d.mType==PxMeshMidPhase::eBVH33);
RTreeTriangleData& rtreeData = static_cast<RTreeTriangleData&>(d);
mRTree = rtreeData.mRTree;
rtreeData.mRTree.mPages = NULL;
}
Gu::TriangleMesh* Gu::RTreeTriangleMesh::createObject(PxU8*& address, PxDeserializationContext& context)
{
RTreeTriangleMesh* obj = PX_PLACEMENT_NEW(address, RTreeTriangleMesh(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(RTreeTriangleMesh);
obj->importExtraData(context);
return obj;
}
void Gu::RTreeTriangleMesh::exportExtraData(PxSerializationContext& stream)
{
mRTree.exportExtraData(stream);
TriangleMesh::exportExtraData(stream);
}
void Gu::RTreeTriangleMesh::importExtraData(PxDeserializationContext& context)
{
mRTree.importExtraData(context);
TriangleMesh::importExtraData(context);
}
PxVec3 * Gu::RTreeTriangleMesh::getVerticesForModification()
{
return const_cast<PxVec3*>(getVertices());
}
template<typename IndexType>
struct RefitCallback : Gu::RTree::CallbackRefit
{
const PxVec3* newPositions;
const IndexType* indices;
RefitCallback(const PxVec3* aNewPositions, const IndexType* aIndices) : newPositions(aNewPositions), indices(aIndices) {}
PX_FORCE_INLINE ~RefitCallback() {}
virtual void recomputeBounds(PxU32 index, aos::Vec3V& aMn, aos::Vec3V& aMx)
{
using namespace aos;
// Each leaf box has a set of triangles
Gu::LeafTriangles currentLeaf; currentLeaf.Data = index;
PxU32 nbTris = currentLeaf.GetNbTriangles();
PxU32 baseTri = currentLeaf.GetTriangleIndex();
PX_ASSERT(nbTris > 0);
const IndexType* vInds = indices + 3 * baseTri;
Vec3V vPos = V3LoadU(newPositions[vInds[0]]);
Vec3V mn = vPos, mx = vPos;
//PxBounds3 result(newPositions[vInds[0]], newPositions[vInds[0]]);
vPos = V3LoadU(newPositions[vInds[1]]);
mn = V3Min(mn, vPos); mx = V3Max(mx, vPos);
vPos = V3LoadU(newPositions[vInds[2]]);
mn = V3Min(mn, vPos); mx = V3Max(mx, vPos);
for (PxU32 i = 1; i < nbTris; i++)
{
const IndexType* vInds1 = indices + 3 * (baseTri + i);
vPos = V3LoadU(newPositions[vInds1[0]]);
mn = V3Min(mn, vPos); mx = V3Max(mx, vPos);
vPos = V3LoadU(newPositions[vInds1[1]]);
mn = V3Min(mn, vPos); mx = V3Max(mx, vPos);
vPos = V3LoadU(newPositions[vInds1[2]]);
mn = V3Min(mn, vPos); mx = V3Max(mx, vPos);
}
aMn = mn;
aMx = mx;
}
};
PxBounds3 Gu::RTreeTriangleMesh::refitBVH()
{
PxBounds3 meshBounds;
if (has16BitIndices())
{
RefitCallback<PxU16> cb(mVertices, static_cast<const PxU16*>(mTriangles));
mRTree.refitAllStaticTree(cb, &meshBounds);
}
else
{
RefitCallback<PxU32> cb(mVertices, static_cast<const PxU32*>(mTriangles));
mRTree.refitAllStaticTree(cb, &meshBounds);
}
// reset edge flags and remember we did that using a mesh flag (optimization)
if ((mRTree.mFlags & RTree::IS_EDGE_SET) == 0)
{
mRTree.mFlags |= RTree::IS_EDGE_SET;
setAllEdgesActive();
}
mAABB = meshBounds;
return meshBounds;
}
} // namespace physx
| 4,837 | C++ | 33.805755 | 122 | 0.738888 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRaySphere.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_SPHERE_H
#define GU_INTERSECTION_RAY_SPHERE_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
// PT: basic version, limited accuracy, might fail for long rays vs small spheres
PX_PHYSX_COMMON_API bool intersectRaySphereBasic(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos = NULL);
// PT: version with improved accuracy
PX_PHYSX_COMMON_API bool intersectRaySphere(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos = NULL);
} // namespace Gu
}
#endif
| 2,359 | C | 47.163264 | 181 | 0.764731 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_TRIANGLE_H
#define GU_INTERSECTION_RAY_TRIANGLE_H
#include "foundation/PxVec3.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
// PT: this is used for backface culling. It existed in Moller's original code already. Basically this is only to avoid dividing by zero.
// This should not depend on what units are used, and neither should it depend on the size of triangles. A large triangle with the same
// orientation as a small triangle should be backface culled the same way. A triangle whose orientation does not change should not suddenly
// become culled or visible when we scale it.
//
// An absolute epsilon is fine here. The computation will work fine for small triangles, and large triangles will simply make 'det' larger,
// more and more inaccurate, but it won't suddenly make it negative.
//
// Using FLT_EPSILON^2 ensures that triangles whose edges are smaller than FLT_EPSILON long are rejected. This epsilon makes the code work
// for very small triangles, while still preventing divisions by too small values.
#define GU_CULLING_EPSILON_RAY_TRIANGLE FLT_EPSILON*FLT_EPSILON
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Computes a ray-triangle intersection test.
* From Tomas Moeller's "Fast Minimum Storage Ray-Triangle Intersection"
* Could be optimized and cut into 2 methods (culled or not). Should make a batch one too to avoid the call overhead, or make it inline.
*
* \param orig [in] ray origin
* \param dir [in] ray direction
* \param vert0 [in] triangle vertex
* \param vert1 [in] triangle vertex
* \param vert2 [in] triangle vertex
* \param at [out] distance
* \param au [out] impact barycentric coordinate
* \param av [out] impact barycentric coordinate
* \param cull [in] true to use backface culling
* \param enlarge [in] enlarge triangle by specified epsilon in UV space to avoid false near-edge rejections
* \return true on overlap
* \note u, v and t will remain unchanged if false is returned.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE bool intersectRayTriangle( const PxVec3& orig, const PxVec3& dir,
const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2,
PxReal& at, PxReal& au, PxReal& av,
bool cull, float enlarge=0.0f)
{
// Find vectors for two edges sharing vert0
const PxVec3 edge1 = vert1 - vert0;
const PxVec3 edge2 = vert2 - vert0;
// Begin calculating determinant - also used to calculate U parameter
const PxVec3 pvec = dir.cross(edge2); // error ~ |v2-v0|
// If determinant is near zero, ray lies in plane of triangle
const PxReal det = edge1.dot(pvec); // error ~ |v2-v0|*|v1-v0|
if(cull)
{
if(det<GU_CULLING_EPSILON_RAY_TRIANGLE)
return false;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0;
// Calculate U parameter and test bounds
const PxReal u = tvec.dot(pvec);
const PxReal enlargeCoeff = enlarge*det;
const PxReal uvlimit = -enlargeCoeff;
const PxReal uvlimit2 = det + enlargeCoeff;
if(u<uvlimit || u>uvlimit2)
return false;
// Prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
const PxReal v = dir.dot(qvec);
if(v<uvlimit || (u+v)>uvlimit2)
return false;
// Calculate t, scale parameters, ray intersects triangle
const PxReal t = edge2.dot(qvec);
const PxReal inv_det = 1.0f / det;
at = t*inv_det;
au = u*inv_det;
av = v*inv_det;
}
else
{
// the non-culling branch
if(PxAbs(det)<GU_CULLING_EPSILON_RAY_TRIANGLE)
return false;
const PxReal inv_det = 1.0f / det;
// Calculate distance from vert0 to ray origin
const PxVec3 tvec = orig - vert0; // error ~ |orig-v0|
// Calculate U parameter and test bounds
const PxReal u = tvec.dot(pvec) * inv_det;
if(u<-enlarge || u>1.0f+enlarge)
return false;
// prepare to test V parameter
const PxVec3 qvec = tvec.cross(edge1);
// Calculate V parameter and test bounds
const PxReal v = dir.dot(qvec) * inv_det;
if(v<-enlarge || (u+v)>1.0f+enlarge)
return false;
// Calculate t, ray intersects triangle
const PxReal t = edge2.dot(qvec) * inv_det;
at = t;
au = u;
av = v;
}
return true;
}
/* \note u, v and t will remain unchanged if false is returned. */
PX_FORCE_INLINE bool intersectRayTriangleCulling( const PxVec3& orig, const PxVec3& dir,
const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2,
PxReal& t, PxReal& u, PxReal& v,
float enlarge=0.0f)
{
return intersectRayTriangle(orig, dir, vert0, vert1, vert2, t, u, v, true, enlarge);
}
/* \note u, v and t will remain unchanged if false is returned. */
PX_FORCE_INLINE bool intersectRayTriangleNoCulling( const PxVec3& orig, const PxVec3& dir,
const PxVec3& vert0, const PxVec3& vert1, const PxVec3& vert2,
PxReal& t, PxReal& u, PxReal& v,
float enlarge=0.0f)
{
return intersectRayTriangle(orig, dir, vert0, vert1, vert2, t, u, v, false, enlarge);
}
} // namespace Gu
}
#endif
| 7,202 | C | 39.466292 | 200 | 0.667037 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionSphereBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_SPHERE_BOX_H
#define GU_INTERSECTION_SPHERE_BOX_H
namespace physx
{
namespace Gu
{
class Sphere;
class Box;
/**
Checks if a sphere intersects a box. Based on: Jim Arvo, A Simple Method for Box-Sphere Intersection Testing, Graphics Gems, pp. 247-250.
\param sphere [in] sphere
\param box [in] box
\return true if sphere overlaps box (or exactly touches it)
*/
bool intersectSphereBox(const Gu::Sphere& sphere, const Gu::Box& box);
} // namespace Gu
}
#endif
| 2,196 | C | 39.685184 | 138 | 0.756375 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRaySphere.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 "GuIntersectionRaySphere.h"
#include "GuIntersectionRay.h"
using namespace physx;
// Based on GD Mag code, but now works correctly when origin is inside the sphere.
// This version has limited accuracy.
bool Gu::intersectRaySphereBasic(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
// get the offset vector
const PxVec3 offset = center - origin;
// get the distance along the ray to the center point of the sphere
const PxReal ray_dist = dir.dot(offset);
// get the squared distances
const PxReal off2 = offset.dot(offset);
const PxReal rad_2 = radius * radius;
if(off2 <= rad_2)
{
// we're in the sphere
if(hit_pos)
*hit_pos = origin;
dist = 0.0f;
return true;
}
if(ray_dist <= 0 || (ray_dist - length) > radius)
{
// moving away from object or too far away
return false;
}
// find hit distance squared
const PxReal d = rad_2 - (off2 - ray_dist * ray_dist);
if(d<0.0f)
{
// ray passes by sphere without hitting
return false;
}
// get the distance along the ray
dist = ray_dist - PxSqrt(d);
if(dist > length)
{
// hit point beyond length
return false;
}
// sort out the details
if(hit_pos)
*hit_pos = origin + dir * dist;
return true;
}
// PT: modified version calls the previous function, but moves the ray origin closer to the sphere. The test accuracy is
// greatly improved as a result. This is an idea proposed on the GD-Algorithms list by Eddie Edwards.
// See: http://www.codercorner.com/blog/?p=321
bool Gu::intersectRaySphere(const PxVec3& origin, const PxVec3& dir, PxReal length, const PxVec3& center, PxReal radius, PxReal& dist, PxVec3* hit_pos)
{
const PxVec3 x = origin - center;
PxReal l = PxSqrt(x.dot(x)) - radius - GU_RAY_SURFACE_OFFSET;
// if(l<0.0f)
// l=0.0f;
l = physx::intrinsics::selectMax(l, 0.0f);
bool status = intersectRaySphereBasic(origin + l*dir, dir, length - l, center, radius, dist, hit_pos);
if(status)
{
// dist += l/length;
dist += l;
}
return status;
}
| 3,784 | C++ | 35.047619 | 156 | 0.724366 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTetrahedronBox.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 "GuIntersectionTetrahedronBox.h"
#include "foundation/PxBasicTemplates.h"
#include "GuIntersectionTriangleBox.h"
#include "GuBox.h"
using namespace physx;
namespace physx
{
namespace Gu
{
bool intersectTetrahedronBox(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxBounds3& box)
{
if (box.contains(a) || box.contains(b) || box.contains(c) || box.contains(d))
return true;
PxBounds3 tetBox = PxBounds3::empty();
tetBox.include(a);
tetBox.include(b);
tetBox.include(c);
tetBox.include(d);
tetBox.fattenFast(1e-6f);
if (!box.intersects(tetBox))
return false;
Gu::BoxPadded boxP;
boxP.center = box.getCenter();
boxP.extents = box.getExtents();
boxP.rot = PxMat33(PxIdentity);
return intersectTriangleBox(boxP, a, b, c) || intersectTriangleBox(boxP, a, b, d) || intersectTriangleBox(boxP, a, c, d) || intersectTriangleBox(boxP, b, c, d);
}
}
}
| 2,614 | C++ | 40.507936 | 162 | 0.745601 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayCapsule.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_CAPSULE_H
#define GU_INTERSECTION_RAY_CAPSULE_H
#include "GuCapsule.h"
#include "GuDistancePointSegment.h"
#include "GuIntersectionRay.h"
namespace physx
{
namespace Gu
{
PxU32 intersectRayCapsuleInternal(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal s[2]);
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const PxVec3& p0, const PxVec3& p1, float radius, PxReal& t)
{
// PT: move ray origin close to capsule, to solve accuracy issues.
// We compute the distance D between the ray origin and the capsule's segment.
// Then E = D - radius = distance between the ray origin and the capsule.
// We can move the origin freely along 'dir' up to E units before touching the capsule.
PxReal l = distancePointSegmentSquaredInternal(p0, p1 - p0, origin);
l = PxSqrt(l) - radius;
// PT: if this becomes negative or null, the ray starts inside the capsule and we can early exit
if(l<=0.0f)
{
t = 0.0f;
return true;
}
// PT: we remove an arbitrary GU_RAY_SURFACE_OFFSET units to E, to make sure we don't go close to the surface.
// If we're moving in the direction of the capsule, the origin is now about GU_RAY_SURFACE_OFFSET units from it.
// If we're moving away from the capsule, the ray won't hit the capsule anyway.
// If l is smaller than GU_RAY_SURFACE_OFFSET we're close enough, accuracy is good, there is nothing to do.
if(l>GU_RAY_SURFACE_OFFSET)
l -= GU_RAY_SURFACE_OFFSET;
else
l = 0.0f;
// PT: move origin closer to capsule and do the raycast
PxReal s[2];
const PxU32 nbHits = Gu::intersectRayCapsuleInternal(origin + l*dir, dir, p0, p1, radius, s);
if(!nbHits)
return false;
// PT: keep closest hit only
if(nbHits == 1)
t = s[0];
else
t = (s[0] < s[1]) ? s[0] : s[1];
// PT: fix distance (smaller than expected after moving ray close to capsule)
t += l;
return true;
}
PX_FORCE_INLINE bool intersectRayCapsule(const PxVec3& origin, const PxVec3& dir, const Gu::Capsule& capsule, PxReal& t)
{
return Gu::intersectRayCapsule(origin, dir, capsule.p0, capsule.p1, capsule.radius, t);
}
}
}
#endif
| 3,900 | C | 41.402173 | 143 | 0.730513 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionEdgeEdge.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 "GuIntersectionEdgeEdge.h"
#include "GuInternal.h"
using namespace physx;
bool Gu::intersectEdgeEdge(const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip)
{
const PxVec3 v1 = p2 - p1;
// Build plane P based on edge (p1, p2) and direction (dir)
PxPlane plane;
plane.n = v1.cross(dir);
plane.d = -(plane.n.dot(p1));
// if colliding edge (p3,p4) does not cross plane return no collision
// same as if p3 and p4 on same side of plane return 0
//
// Derivation:
// d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated.
// d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated.
// if d3 and d4 have the same sign, they're on the same side of the plane => no collision
// We test both sides at the same time by only testing Sign(d3 * d4).
// ### put that in the Plane class
// ### also check that code in the triangle class that might be similar
const PxReal d3 = plane.distance(p3);
PxReal temp = d3 * plane.distance(p4);
if(temp>0.0f) return false;
// if colliding edge (p3,p4) and plane are parallel return no collision
PxVec3 v2 = p4 - p3;
temp = plane.n.dot(v2);
if(temp==0.0f) return false; // ### epsilon would be better
// compute intersection point of plane and colliding edge (p3,p4)
ip = p3-v2*(d3/temp);
// find largest 2D plane projection
PxU32 i,j;
closestAxis(plane.n, i, j);
// compute distance of intersection from line (ip, -dir) to line (p1,p2)
dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))/(v1[i]*dir[j]-v1[j]*dir[i]);
if(dist<0.0f) return false;
// compute intersection point on edge (p1,p2) line
ip -= dist*dir;
// check if intersection point (ip) is between edge (p1,p2) vertices
temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z);
if(temp<1e-3f) return true; // collision found
return false; // no collision
}
| 3,697 | C++ | 43.554216 | 143 | 0.713552 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionEdgeEdge.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_EDGE_EDGE_H
#define GU_INTERSECTION_EDGE_EDGE_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
// collide edge (p1,p2) moving in direction (dir) colliding
// width edge (p3,p4). Return true on a collision with
// collision distance (dist) and intersection point (ip)
// note: dist and ip are invalid if function returns false.
// note: ip is on (p1,p2), not (p1+dist*dir,p2+dist*dir)
PX_PHYSX_COMMON_API bool intersectEdgeEdge(const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip);
} // namespace Gu
}
#endif
| 2,332 | C | 44.745097 | 161 | 0.754717 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionCapsuleTriangle.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 "GuIntersectionCapsuleTriangle.h"
#include "GuDistancePointSegment.h"
using namespace physx;
using namespace Gu;
bool Gu::intersectCapsuleTriangle(const PxVec3& N, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params)
{
PX_ASSERT(capsule.p0!=capsule.p1);
{
const PxReal d2 = distancePointSegmentSquaredInternal(capsule.p0, params.mCapsuleDir, p0);
if(d2<=capsule.radius*capsule.radius)
return true;
}
// const PxVec3 N = (p0 - p1).cross(p0 - p2);
if(!testAxis(p0, p1, p2, capsule, N))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p0, p1 - p0, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p1, p2 - p1, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
if(!testAxis(p0, p1, p2, capsule, computeEdgeAxis(p2, p0 - p2, capsule.p0, params.mCapsuleDir, params.mBDotB, params.mOneOverBDotB)))
return false;
return true;
}
| 2,767 | C++ | 44.377048 | 174 | 0.755331 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayPlane.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_PLANE_H
#define GU_INTERSECTION_RAY_PLANE_H
#include "foundation/PxPlane.h"
namespace physx
{
namespace Gu
{
// Returns true if line and plane are not parallel
PX_INLINE bool intersectRayPlane(const PxVec3& orig, const PxVec3& dir, const PxPlane& plane, float& distanceAlongLine, PxVec3* pointOnPlane = NULL)
{
const float dn = dir.dot(plane.n);
if(-1E-7f < dn && dn < 1E-7f)
return false; // parallel
distanceAlongLine = -plane.distance(orig)/dn;
if(pointOnPlane)
*pointOnPlane = orig + distanceAlongLine * dir;
return true;
}
} // namespace Gu
}
#endif
| 2,309 | C | 38.827586 | 149 | 0.751841 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionBoxBox.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 "GuIntersectionBoxBox.h"
using namespace physx;
bool Gu::intersectOBBOBB(const PxVec3& e0, const PxVec3& c0, const PxMat33& r0, const PxVec3& e1, const PxVec3& c1, const PxMat33& r1, bool full_test)
{
// Translation, in parent frame
const PxVec3 v = c1 - c0;
// Translation, in A's frame
const PxVec3 T(v.dot(r0[0]), v.dot(r0[1]), v.dot(r0[2]));
// B's basis with respect to A's local frame
PxReal R[3][3];
PxReal FR[3][3];
PxReal ra, rb, t;
// Calculate rotation matrix
for(PxU32 i=0;i<3;i++)
{
for(PxU32 k=0;k<3;k++)
{
R[i][k] = r0[i].dot(r1[k]);
FR[i][k] = 1e-6f + PxAbs(R[i][k]); // Precompute fabs matrix
}
}
// A's basis vectors
for(PxU32 i=0;i<3;i++)
{
ra = e0[i];
rb = e1[0]*FR[i][0] + e1[1]*FR[i][1] + e1[2]*FR[i][2];
t = PxAbs(T[i]);
if(t > ra + rb) return false;
}
// B's basis vectors
for(PxU32 k=0;k<3;k++)
{
ra = e0[0]*FR[0][k] + e0[1]*FR[1][k] + e0[2]*FR[2][k];
rb = e1[k];
t = PxAbs(T[0]*R[0][k] + T[1]*R[1][k] + T[2]*R[2][k]);
if( t > ra + rb ) return false;
}
if(full_test)
{
//9 cross products
//L = A0 x B0
ra = e0[1]*FR[2][0] + e0[2]*FR[1][0];
rb = e1[1]*FR[0][2] + e1[2]*FR[0][1];
t = PxAbs(T[2]*R[1][0] - T[1]*R[2][0]);
if(t > ra + rb) return false;
//L = A0 x B1
ra = e0[1]*FR[2][1] + e0[2]*FR[1][1];
rb = e1[0]*FR[0][2] + e1[2]*FR[0][0];
t = PxAbs(T[2]*R[1][1] - T[1]*R[2][1]);
if(t > ra + rb) return false;
//L = A0 x B2
ra = e0[1]*FR[2][2] + e0[2]*FR[1][2];
rb = e1[0]*FR[0][1] + e1[1]*FR[0][0];
t = PxAbs(T[2]*R[1][2] - T[1]*R[2][2]);
if(t > ra + rb) return false;
//L = A1 x B0
ra = e0[0]*FR[2][0] + e0[2]*FR[0][0];
rb = e1[1]*FR[1][2] + e1[2]*FR[1][1];
t = PxAbs(T[0]*R[2][0] - T[2]*R[0][0]);
if(t > ra + rb) return false;
//L = A1 x B1
ra = e0[0]*FR[2][1] + e0[2]*FR[0][1];
rb = e1[0]*FR[1][2] + e1[2]*FR[1][0];
t = PxAbs(T[0]*R[2][1] - T[2]*R[0][1]);
if(t > ra + rb) return false;
//L = A1 x B2
ra = e0[0]*FR[2][2] + e0[2]*FR[0][2];
rb = e1[0]*FR[1][1] + e1[1]*FR[1][0];
t = PxAbs(T[0]*R[2][2] - T[2]*R[0][2]);
if(t > ra + rb) return false;
//L = A2 x B0
ra = e0[0]*FR[1][0] + e0[1]*FR[0][0];
rb = e1[1]*FR[2][2] + e1[2]*FR[2][1];
t = PxAbs(T[1]*R[0][0] - T[0]*R[1][0]);
if(t > ra + rb) return false;
//L = A2 x B1
ra = e0[0]*FR[1][1] + e0[1]*FR[0][1];
rb = e1[0] *FR[2][2] + e1[2]*FR[2][0];
t = PxAbs(T[1]*R[0][1] - T[0]*R[1][1]);
if(t > ra + rb) return false;
//L = A2 x B2
ra = e0[0]*FR[1][2] + e0[1]*FR[0][2];
rb = e1[0]*FR[2][1] + e1[1]*FR[2][0];
t = PxAbs(T[1]*R[0][2] - T[0]*R[1][2]);
if(t > ra + rb) return false;
}
return true;
}
| 4,345 | C++ | 30.266187 | 150 | 0.591484 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTriangleTriangle.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 "GuIntersectionTriangleTriangle.h"
#include "foundation/PxPlane.h"
using namespace physx;
using namespace Gu;
namespace
{
//Based on the paper A Fast Triangle-Triangle Intersection Test by T. Moeller
//http://web.stanford.edu/class/cs277/resources/papers/Moller1997b.pdf
struct Interval
{
PxReal min;
PxReal max;
PxVec3 minPoint;
PxVec3 maxPoint;
PX_FORCE_INLINE Interval() : min(FLT_MAX), max(-FLT_MAX), minPoint(PxVec3(NAN)), maxPoint(PxVec3(NAN)) { }
PX_FORCE_INLINE static bool overlapOrTouch(const Interval& a, const Interval& b)
{
return !(a.min > b.max || b.min > a.max);
}
PX_FORCE_INLINE static Interval intersection(const Interval& a, const Interval& b)
{
Interval result;
if (!overlapOrTouch(a, b))
return result;
if (a.min > b.min)
{
result.min = a.min;
result.minPoint = a.minPoint;
}
else
{
result.min = b.min;
result.minPoint = b.minPoint;
}
if (a.max < b.max)
{
result.max = a.max;
result.maxPoint = a.maxPoint;
}
else
{
result.max = b.max;
result.maxPoint = b.maxPoint;
}
return result;
}
PX_FORCE_INLINE void include(PxReal d, const PxVec3& p)
{
if (d < min) { min = d; minPoint = p; }
if (d > max) { max = d; maxPoint = p; }
}
};
PX_FORCE_INLINE static Interval computeInterval(PxReal distanceA, PxReal distanceB, PxReal distanceC, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& dir)
{
Interval i;
const bool bA = distanceA > 0;
const bool bB = distanceB > 0;
const bool bC = distanceC > 0;
distanceA = PxAbs(distanceA);
distanceB = PxAbs(distanceB);
distanceC = PxAbs(distanceC);
if (bA != bB)
{
const PxVec3 p = (distanceA / (distanceA + distanceB)) * b + (distanceB / (distanceA + distanceB)) * a;
i.include(dir.dot(p), p);
}
if (bA != bC)
{
const PxVec3 p = (distanceA / (distanceA + distanceC)) * c + (distanceC / (distanceA + distanceC)) * a;
i.include(dir.dot(p), p);
}
if (bB != bC)
{
const PxVec3 p = (distanceB / (distanceB + distanceC)) * c + (distanceC / (distanceB + distanceC)) * b;
i.include(dir.dot(p), p);
}
return i;
}
PX_FORCE_INLINE PxReal orient2d(const PxVec3& a, const PxVec3& b, const PxVec3& c, PxU32 x, PxU32 y)
{
return (a[y] - c[y]) * (b[x] - c[x]) - (a[x] - c[x]) * (b[y] - c[y]);
}
PX_FORCE_INLINE PxReal pointInTriangle(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& point, PxU32 x, PxU32 y)
{
const PxReal ab = orient2d(a, b, point, x, y);
const PxReal bc = orient2d(b, c, point, x, y);
const PxReal ca = orient2d(c, a, point, x, y);
if ((ab >= 0) == (bc >= 0) && (ab >= 0) == (ca >= 0))
return true;
return false;
}
PX_FORCE_INLINE PxReal linesIntersect(const PxVec3& startA, const PxVec3& endA, const PxVec3& startB, const PxVec3& endB, PxU32 x, PxU32 y)
{
const PxReal aaS = orient2d(startA, endA, startB, x, y);
const PxReal aaE = orient2d(startA, endA, endB, x, y);
if ((aaS >= 0) == (aaE >= 0))
return false;
const PxReal bbS = orient2d(startB, endB, startA, x, y);
const PxReal bbE = orient2d(startB, endB, endA, x, y);
if ((bbS >= 0) == (bbE >= 0))
return false;
return true;
}
PX_FORCE_INLINE void getProjectionIndices(PxVec3 normal, PxU32& x, PxU32& y)
{
normal.x = PxAbs(normal.x);
normal.y = PxAbs(normal.y);
normal.z = PxAbs(normal.z);
if (normal.x >= normal.y && normal.x >= normal.z)
{
//x is the dominant normal direction
x = 1;
y = 2;
}
else if (normal.y >= normal.x && normal.y >= normal.z)
{
//y is the dominant normal direction
x = 2;
y = 0;
}
else
{
//z is the dominant normal direction
x = 0;
y = 1;
}
}
PX_FORCE_INLINE bool trianglesIntersectCoplanar(const PxPlane& p1, const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2)
{
PxU32 x = 0;
PxU32 y = 0;
getProjectionIndices(p1.n, x, y);
const PxReal third = (1.0f / 3.0f);
//A bit of the computations done inside the following functions could be shared but it's kept simple since the
//difference is not very big and the coplanar case is not expected to be the most common case
if (linesIntersect(a1, b1, a2, b2, x, y) || linesIntersect(a1, b1, b2, c2, x, y) || linesIntersect(a1, b1, c2, a2, x, y) ||
linesIntersect(b1, c1, a2, b2, x, y) || linesIntersect(b1, c1, b2, c2, x, y) || linesIntersect(b1, c1, c2, a2, x, y) ||
linesIntersect(c1, a1, a2, b2, x, y) || linesIntersect(c1, a1, b2, c2, x, y) || linesIntersect(c1, a1, c2, a2, x, y) ||
pointInTriangle(a1, b1, c1, third * (a2 + b2 + c2), x, y) || pointInTriangle(a2, b2, c2, third * (a1 + b1 + c1), x, y))
return true;
return false;
}
}
bool Gu::trianglesIntersect(const PxVec3& a1, const PxVec3& b1, const PxVec3& c1, const PxVec3& a2, const PxVec3& b2, const PxVec3& c2/*, Segment* intersection*/, bool ignoreCoplanar)
{
const PxReal tolerance = 1e-8f;
const PxPlane p1(a1, b1, c1);
const PxReal p1ToA = p1.distance(a2);
const PxReal p1ToB = p1.distance(b2);
const PxReal p1ToC = p1.distance(c2);
if(PxAbs(p1ToA) < tolerance && PxAbs(p1ToB) < tolerance &&PxAbs(p1ToC) < tolerance)
return ignoreCoplanar ? false : trianglesIntersectCoplanar(p1, a1, b1, c1, a2, b2, c2); //Coplanar triangles
if ((p1ToA > 0) == (p1ToB > 0) && (p1ToA > 0) == (p1ToC > 0))
return false; //All points of triangle 2 on same side of triangle 1 -> no intersection
const PxPlane p2(a2, b2, c2);
const PxReal p2ToA = p2.distance(a1);
const PxReal p2ToB = p2.distance(b1);
const PxReal p2ToC = p2.distance(c1);
if ((p2ToA > 0) == (p2ToB > 0) && (p2ToA > 0) == (p2ToC > 0))
return false; //All points of triangle 1 on same side of triangle 2 -> no intersection
PxVec3 intersectionDirection = p1.n.cross(p2.n);
const PxReal l2 = intersectionDirection.magnitudeSquared();
intersectionDirection *= 1.0f / PxSqrt(l2);
const Interval i1 = computeInterval(p2ToA, p2ToB, p2ToC, a1, b1, c1, intersectionDirection);
const Interval i2 = computeInterval(p1ToA, p1ToB, p1ToC, a2, b2, c2, intersectionDirection);
if (Interval::overlapOrTouch(i1, i2))
{
/*if (intersection)
{
const Interval i = Interval::intersection(i1, i2);
intersection->p0 = i.minPoint;
intersection->p1 = i.maxPoint;
}*/
return true;
}
return false;
}
| 8,051 | C++ | 32.272727 | 183 | 0.667371 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionSphereBox.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 "GuIntersectionSphereBox.h"
#include "GuSphere.h"
#include "GuBox.h"
using namespace physx;
bool Gu::intersectSphereBox(const Sphere& sphere, const Box& box)
{
const PxVec3 delta = sphere.center - box.center;
PxVec3 dRot = box.rot.transformTranspose(delta); //transform delta into OBB body coords. (use method call!)
//check if delta is outside AABB - and clip the vector to the AABB.
bool outside = false;
if(dRot.x < -box.extents.x)
{
outside = true;
dRot.x = -box.extents.x;
}
else if(dRot.x > box.extents.x)
{
outside = true;
dRot.x = box.extents.x;
}
if(dRot.y < -box.extents.y)
{
outside = true;
dRot.y = -box.extents.y;
}
else if(dRot.y > box.extents.y)
{
outside = true;
dRot.y = box.extents.y;
}
if(dRot.z < -box.extents.z)
{
outside = true;
dRot.z = -box.extents.z;
}
else if(dRot.z > box.extents.z)
{
outside = true;
dRot.z = box.extents.z;
}
if(outside) //if clipping was done, sphere center is outside of box.
{
const PxVec3 clippedDelta = box.rot.transform(dRot); //get clipped delta back in world coords.
const PxVec3 clippedVec = delta - clippedDelta; //what we clipped away.
const PxReal lenSquared = clippedVec.magnitudeSquared();
const PxReal radius = sphere.radius;
if(lenSquared > radius * radius) // PT: objects are defined as closed, so we return 'true' in case of equality
return false; //disjoint
}
return true;
}
| 3,137 | C++ | 34.659091 | 112 | 0.722665 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayBox.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxVec3.h"
#include "foundation/PxMathIntrinsics.h"
#include "foundation/PxFPU.h"
#include "GuIntersectionRayBox.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: [email protected]
*
* \param aabb [in] the axis-aligned bounding box
* \param origin [in] ray origin
* \param dir [in] ray direction
* \param coord [out] impact coordinates
* \return true if ray intersects AABB
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define RAYAABB_EPSILON 0.00001f
bool Gu::rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
return true;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return false;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON)
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i])
#endif
return false;
}
}
return true; // ray hits box
}
/**
* Computes a ray-AABB intersection.
* Original code by Andrew Woo, from "Graphics Gems", Academic Press, 1990
* Optimized code by Pierre Terdiman, 2000 (~20-30% faster on my Celeron 500)
* Epsilon value added by Klaus Hartmann. (discarding it saves a few cycles only)
* Return of intersected face code and parameter by Adam! Also modified behavior for ray starts inside AABB. 2004 :-p
*
* Hence this version is faster as well as more robust than the original one.
*
* Should work provided:
* 1) the integer representation of 0.0f is 0x00000000
* 2) the sign bit of the float is the most significant one
*
* Report bugs: [email protected]
*
* \param minimum [in] the smaller corner of the bounding box
* \param maximum [in] the larger corner of the bounding box
* \param origin [in] ray origin
* \param _dir [in] ray direction
* \param coord [out] impact coordinates
* \param t [out] t such that coord = origin + dir * t
* \return false if ray does not intersect AABB, or ray origin is inside AABB. Else:
1 + coordinate index of box axis that was hit
Note: sign bit that determines if the minimum (0) or maximum (1) of the axis was hit is equal to sign(coord[returnVal-1]).
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxU32 Gu::rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t)
{
PxIntBool Inside = PxIntTrue;
PxVec3 MaxT(-1.0f, -1.0f, -1.0f);
const PxReal* dir = &_dir.x;
const PxU32* idir = reinterpret_cast<const PxU32*>(dir);
// Find candidate planes.
for(PxU32 i=0;i<3;i++)
{
if(origin[i] < minimum[i])
{
coord[i] = minimum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (minimum[i] - origin[i]) / dir[i];
}
else if(origin[i] > maximum[i])
{
coord[i] = maximum[i];
Inside = PxIntFalse;
// Calculate T distances to candidate planes
if(idir[i])
// if(PX_IR(dir[i]))
MaxT[i] = (maximum[i] - origin[i]) / dir[i];
}
}
// Ray origin inside bounding box
if(Inside)
{
coord = origin;
t = 0;
return 1;
}
// Get largest of the maxT's for final choice of intersection
PxU32 WhichPlane = 0;
if(MaxT[1] > MaxT[WhichPlane]) WhichPlane = 1;
if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
// Check final candidate actually inside box
const PxU32* tmp = reinterpret_cast<const PxU32*>(&MaxT[WhichPlane]);
if((*tmp)&PX_SIGN_BITMASK)
// if(PX_IR(MaxT[WhichPlane])&PX_SIGN_BITMASK)
return 0;
for(PxU32 i=0;i<3;i++)
{
if(i!=WhichPlane)
{
coord[i] = origin[i] + MaxT[WhichPlane] * dir[i];
#ifdef RAYAABB_EPSILON
if(coord[i] < minimum[i] - RAYAABB_EPSILON || coord[i] > maximum[i] + RAYAABB_EPSILON) return 0;
#else
if(coord[i] < minimum[i] || coord[i] > maximum[i]) return 0;
#endif
}
}
t = MaxT[WhichPlane];
return 1 + WhichPlane; // ray hits box
}
// Collide ray defined by ray origin (ro) and ray direction (rd)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
// ptchernev:
// Should we use an enum, or should we keep the anonymous ints?
// Should we increment the return code by one (return 0 for non intersection)?
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float& tnear, float& tfar)
{
// Refactor
int ret=-1;
tnear = -PX_MAX_F32;
tfar = PX_MAX_F32;
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
for(unsigned int a=0;a<3;a++)
{
if(rd[a]>-LOCAL_EPSILON && rd[a]<LOCAL_EPSILON)
{
if(ro[a]<minimum[a] || ro[a]>maximum[a])
return -1;
}
else
{
const PxReal OneOverDir = 1.0f / rd[a];
PxReal t1 = (minimum[a]-ro[a]) * OneOverDir;
PxReal t2 = (maximum[a]-ro[a]) * OneOverDir;
unsigned int b = a;
if(t1>t2)
{
PxReal t=t1;
t1=t2;
t2=t;
b += 3;
}
if(t1>tnear)
{
tnear = t1;
ret = int(b);
}
if(t2<tfar)
tfar=t2;
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
}
}
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
// PT: specialized version where oneOverDir is available
int Gu::intersectRayAABB(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, const PxVec3& oneOverDir, float& tnear, float& tfar)
{
// PT: why did we change the initial epsilon value?
#define LOCAL_EPSILON PX_EPS_F32
//#define LOCAL_EPSILON 0.0001f
if(physx::intrinsics::abs(rd.x)<LOCAL_EPSILON)
// if(rd.x>-LOCAL_EPSILON && rd.x<LOCAL_EPSILON)
if(ro.x<minimum.x || ro.x>maximum.x)
return -1;
if(physx::intrinsics::abs(rd.y)<LOCAL_EPSILON)
// if(rd.y>-LOCAL_EPSILON && rd.y<LOCAL_EPSILON)
if(ro.y<minimum.y || ro.y>maximum.y)
return -1;
if(physx::intrinsics::abs(rd.z)<LOCAL_EPSILON)
// if(rd.z>-LOCAL_EPSILON && rd.z<LOCAL_EPSILON)
if(ro.z<minimum.z || ro.z>maximum.z)
return -1;
PxReal t1x = (minimum.x - ro.x) * oneOverDir.x;
PxReal t2x = (maximum.x - ro.x) * oneOverDir.x;
PxReal t1y = (minimum.y - ro.y) * oneOverDir.y;
PxReal t2y = (maximum.y - ro.y) * oneOverDir.y;
PxReal t1z = (minimum.z - ro.z) * oneOverDir.z;
PxReal t2z = (maximum.z - ro.z) * oneOverDir.z;
int bx;
int by;
int bz;
if(t1x>t2x)
{
PxReal t=t1x; t1x=t2x; t2x=t;
bx = 3;
}
else
{
bx = 0;
}
if(t1y>t2y)
{
PxReal t=t1y; t1y=t2y; t2y=t;
by = 4;
}
else
{
by = 1;
}
if(t1z>t2z)
{
PxReal t=t1z; t1z=t2z; t2z=t;
bz = 5;
}
else
{
bz = 2;
}
int ret;
// if(t1x>tnear) // PT: no need to test for the first value
{
tnear = t1x;
ret = bx;
}
// tfar = PxMin(tfar, t2x);
tfar = t2x; // PT: no need to test for the first value
if(t1y>tnear)
{
tnear = t1y;
ret = by;
}
tfar = PxMin(tfar, t2y);
if(t1z>tnear)
{
tnear = t1z;
ret = bz;
}
tfar = PxMin(tfar, t2z);
if(tnear>tfar || tfar<LOCAL_EPSILON)
return -1;
return ret;
}
bool Gu::intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar)
{
PX_ASSERT(maximum.x-minimum.x >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.y-minimum.y >= GU_MIN_AABB_EXTENT*0.5f);
PX_ASSERT(maximum.z-minimum.z >= GU_MIN_AABB_EXTENT*0.5f);
// not using vector math due to vector to integer pipeline penalties. TODO: verify that it's indeed faster
namespace i = physx::intrinsics;
// P+tD=a; t=(a-P)/D
// t=(a - p.x)*1/d.x = a/d.x +(- p.x/d.x)
const PxF32 dEpsilon = 1e-9f;
// using recipFast fails height field unit tests case where a ray cast from y=10000 to 0 gets clipped to 0.27 in y
PxF32 invDx = i::recip(i::selectMax(i::abs(rd.x), dEpsilon) * i::sign(rd.x));
#ifdef RAYAABB_EPSILON
PxF32 tx0 = (minimum.x - RAYAABB_EPSILON - ro.x) * invDx;
PxF32 tx1 = (maximum.x + RAYAABB_EPSILON - ro.x) * invDx;
#else
PxF32 tx0 = (minimum.x - ro.x) * invDx;
PxF32 tx1 = (maximum.x - ro.x) * invDx;
#endif
PxF32 txMin = i::selectMin(tx0, tx1);
PxF32 txMax = i::selectMax(tx0, tx1);
PxF32 invDy = i::recip(i::selectMax(i::abs(rd.y), dEpsilon) * i::sign(rd.y));
#ifdef RAYAABB_EPSILON
PxF32 ty0 = (minimum.y - RAYAABB_EPSILON - ro.y) * invDy;
PxF32 ty1 = (maximum.y + RAYAABB_EPSILON - ro.y) * invDy;
#else
PxF32 ty0 = (minimum.y - ro.y) * invDy;
PxF32 ty1 = (maximum.y - ro.y) * invDy;
#endif
PxF32 tyMin = i::selectMin(ty0, ty1);
PxF32 tyMax = i::selectMax(ty0, ty1);
PxF32 invDz = i::recip(i::selectMax(i::abs(rd.z), dEpsilon) * i::sign(rd.z));
#ifdef RAYAABB_EPSILON
PxF32 tz0 = (minimum.z - RAYAABB_EPSILON - ro.z) * invDz;
PxF32 tz1 = (maximum.z + RAYAABB_EPSILON - ro.z) * invDz;
#else
PxF32 tz0 = (minimum.z - ro.z) * invDz;
PxF32 tz1 = (maximum.z - ro.z) * invDz;
#endif
PxF32 tzMin = i::selectMin(tz0, tz1);
PxF32 tzMax = i::selectMax(tz0, tz1);
PxF32 maxOfNears = i::selectMax(i::selectMax(txMin, tyMin), tzMin);
PxF32 minOfFars = i::selectMin(i::selectMin(txMax, tyMax), tzMax);
tnear = i::selectMax(maxOfNears, 0.0f);
tfar = i::selectMin(minOfFars, maxDist);
return (tnear<tfar);
}
bool Gu::intersectRayAABB2(const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar)
{
using namespace aos;
const FloatV zero = FZero();
const Vec3V eps = V3Load(1e-9f);
const Vec3V absRD = V3Max(V3Abs(rd), eps);
const Vec3V signRD = V3Sign(rd);
const Vec3V rdV = V3Mul(absRD, signRD);
const Vec3V rdVRecip = V3Recip(rdV);
const Vec3V _min = V3Mul(V3Sub(minimum, ro), rdVRecip);
const Vec3V _max = V3Mul(V3Sub(maximum, ro), rdVRecip);
const Vec3V min = V3Min(_max, _min);
const Vec3V max = V3Max(_max, _min);
const FloatV maxOfNears = FMax(V3GetX(min), FMax(V3GetY(min), V3GetZ(min)));
const FloatV minOfFars = FMin(V3GetX(max), FMin(V3GetY(max), V3GetZ(max)));
tnear = FMax(maxOfNears, zero);
tfar = FMin(minOfFars, maxDist);
//tfar = FAdd(FMin(minOfFars, maxDist), V3GetX(eps)); // AP: + epsilon because a test vs empty box should return true
return FAllGrtr(tfar, tnear) != 0;
}
| 14,037 | C++ | 30.334821 | 199 | 0.644725 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayCapsule.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 "GuIntersectionRayCapsule.h"
#include "foundation/PxBasicTemplates.h"
using namespace physx;
static bool intersectRaySphere(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& sphereCenter, float radius2, float& tmin, float& tmax)
{
const PxVec3 CO = rayOrigin - sphereCenter;
const float a = rayDir.dot(rayDir);
const float b = 2.0f * CO.dot(rayDir);
const float c = CO.dot(CO) - radius2;
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return false;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
tmin = (-b - sqrtDet) * OneOver2A;
tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
return true;
}
PxU32 Gu::intersectRayCapsuleInternal(const PxVec3& rayOrigin, const PxVec3& rayDir, const PxVec3& capsuleP0, const PxVec3& capsuleP1, float radius, PxReal s[2])
{
const float radius2 = radius * radius;
const PxVec3 AB = capsuleP1 - capsuleP0;
const PxVec3 AO = rayOrigin - capsuleP0;
const float AB_dot_d = AB.dot(rayDir);
const float AB_dot_AO = AB.dot(AO);
const float AB_dot_AB = AB.dot(AB);
const float OneOverABDotAB = AB_dot_AB!=0.0f ? 1.0f / AB_dot_AB : 0.0f;
const float m = AB_dot_d * OneOverABDotAB;
const float n = AB_dot_AO * OneOverABDotAB;
const PxVec3 Q = rayDir - (AB * m);
const PxVec3 R = AO - (AB * n);
const float a = Q.dot(Q);
const float b = 2.0f * Q.dot(R);
const float c = R.dot(R) - radius2;
if(a == 0.0f)
{
float atmin, atmax, btmin, btmax;
if( !intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, atmin, atmax)
|| !intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, btmin, btmax))
return 0;
s[0] = atmin < btmin ? atmin : btmin;
return 1;
}
const float discriminant = b * b - 4.0f * a * c;
if(discriminant < 0.0f)
return 0;
const float OneOver2A = 1.0f / (2.0f * a);
const float sqrtDet = sqrtf(discriminant);
float tmin = (-b - sqrtDet) * OneOver2A;
float tmax = (-b + sqrtDet) * OneOver2A;
if(tmin > tmax)
PxSwap(tmin, tmax);
const float t_k1 = tmin * m + n;
if(t_k1 < 0.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP0, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else if(t_k1 > 1.0f)
{
float stmin, stmax;
if(intersectRaySphere(rayOrigin, rayDir, capsuleP1, radius2, stmin, stmax))
s[0] = stmin;
else
return 0;
}
else
s[0] = tmin;
return 1;
}
| 4,142 | C++ | 32.959016 | 161 | 0.707146 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRay.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_H
#define GU_INTERSECTION_RAY_H
// PT: small distance between a ray origin and a potentially hit surface. Should be small enough to
// limit accuracy issues coming from large distance values, but not too close to the surface to make
// sure we don't start inside the shape.
#define GU_RAY_SURFACE_OFFSET 10.0f
#endif
| 2,045 | C | 52.842104 | 100 | 0.767237 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionRayBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_RAY_BOX_H
#define GU_INTERSECTION_RAY_BOX_H
#include "foundation/PxMathIntrinsics.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
bool rayAABBIntersect(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord);
PxU32 rayAABBIntersect2(const PxVec3& minimum, const PxVec3& maximum, const PxVec3& origin, const PxVec3& _dir, PxVec3& coord, PxReal & t);
// Collide ray defined by ray origin (rayOrigin) and ray direction (rayDirection)
// with the bounding box. Returns -1 on no collision and the face index
// for first intersection if a collision is found together with
// the distance to the collision points (tnear and tfar)
//
// ptchernev:
// Even though the above is the original comment by Pierre I am quite confident
// that the tnear and tfar parameters are parameters along rayDirection of the
// intersection points:
//
// ip0 = rayOrigin + (rayDirection * tnear)
// ip1 = rayOrigin + (rayDirection * tfar)
//
// The return code is:
// -1 no intersection
// 0 the ray first hits the plane at aabbMin.x
// 1 the ray first hits the plane at aabbMin.y
// 2 the ray first hits the plane at aabbMin.z
// 3 the ray first hits the plane at aabbMax.x
// 4 the ray first hits the plane at aabbMax.y
// 5 the ray first hits the plane at aabbMax.z
//
// The return code will be -1 if the RAY does not intersect the AABB.
// The tnear and tfar values will give the parameters of the intersection
// points between the INFINITE LINE and the AABB.
int PX_PHYSX_COMMON_API intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection,
float& tnear, float& tfar);
// Faster version when one-over-dir is available
int intersectRayAABB( const PxVec3& minimum, const PxVec3& maximum,
const PxVec3& rayOrigin, const PxVec3& rayDirection, const PxVec3& invDirection,
float& tnear, float& tfar);
// minimum extent length required for intersectRayAABB2 to return true for a zero-extent box
// this can happen when inflating the raycast by a 2-d square
#define GU_MIN_AABB_EXTENT 1e-3f
// a much faster version that doesn't return face codes
bool PX_PHYSX_COMMON_API intersectRayAABB2(
const PxVec3& minimum, const PxVec3& maximum, const PxVec3& ro, const PxVec3& rd, float maxDist, float& tnear, float& tfar);
bool PX_PHYSX_COMMON_API intersectRayAABB2( const aos::Vec3VArg minimum, const aos::Vec3VArg maximum,
const aos::Vec3VArg ro, const aos::Vec3VArg rd, const aos::FloatVArg maxDist,
aos::FloatV& tnear, aos::FloatV& tfar);
} // namespace Gu
}
#endif
| 4,446 | C | 46.817204 | 140 | 0.74269 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionTriangleBox.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 "GuIntersectionTriangleBox.h"
#include "GuIntersectionTriangleBoxRef.h"
#include "GuBox.h"
#include "foundation/PxVecMath.h"
using namespace physx;
PxIntBool Gu::intersectTriangleBox_ReferenceCode(const PxVec3& boxcenter, const PxVec3& extents, const PxVec3& tp0, const PxVec3& tp1, const PxVec3& tp2)
{
return intersectTriangleBox_RefImpl(boxcenter, extents, tp0, tp1, tp2);
}
using namespace aos;
static PX_FORCE_INLINE int testClassIIIAxes(const Vec4V& e0V, const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
const Vec4V e0XZY_V = V4PermYZXW(e0V);
const Vec4V v0XZY_V = V4PermYZXW(v0V);
const Vec4V p0V = V4NegMulSub(v0XZY_V, e0V, V4Mul(v0V, e0XZY_V));
const Vec4V v1XZY_V = V4PermYZXW(v1V);
const Vec4V p1V = V4NegMulSub(v1XZY_V, e0V, V4Mul(v1V, e0XZY_V));
const Vec4V v2XZY_V = V4PermYZXW(v2V);
const Vec4V p2V = V4NegMulSub(v2XZY_V, e0V, V4Mul(v2V, e0XZY_V));
Vec4V minV = V4Min(p0V, p1V);
minV = V4Min(minV, p2V);
const Vec4V extentsV = V4LoadU(&extents.x);
const Vec4V fe0ZYX_V = V4Abs(e0V);
const Vec4V fe0XZY_V = V4PermYZXW(fe0ZYX_V);
const Vec4V extentsXZY_V = V4PermYZXW(extentsV);
Vec4V radV = V4MulAdd(extentsV, fe0XZY_V, V4Mul(extentsXZY_V, fe0ZYX_V));
if(V4AnyGrtr3(minV, radV))
return 0;
Vec4V maxV = V4Max(p0V, p1V);
maxV = V4Max(maxV, p2V);
radV = V4Sub(V4Zero(), radV);
if(V4AnyGrtr3(radV, maxV))
return 0;
return 1;
}
static const VecU32V signV = U4LoadXYZW(0x80000000, 0x80000000, 0x80000000, 0x80000000);
static PX_FORCE_INLINE PxIntBool intersectTriangleBoxInternal(const Vec4V v0V, const Vec4V v1V, const Vec4V v2V, const PxVec3& extents)
{
// Test box axes
{
Vec4V extentsV = V4LoadU(&extents.x);
{
const Vec4V cV = V4Abs(v0V);
if(V4AllGrtrOrEq3(extentsV, cV))
return 1;
}
Vec4V minV = V4Min(v0V, v1V);
minV = V4Min(minV, v2V);
if(V4AnyGrtr3(minV, extentsV))
return 0;
Vec4V maxV = V4Max(v0V, v1V);
maxV = V4Max(maxV, v2V);
extentsV = V4Sub(V4Zero(), extentsV);
if(V4AnyGrtr3(extentsV, maxV))
return 0;
}
// Test if the box intersects the plane of the triangle
const Vec4V e0V = V4Sub(v1V, v0V);
const Vec4V e1V = V4Sub(v2V, v1V);
{
const Vec4V normalV = V4Cross(e0V, e1V);
const Vec4V dV = Vec4V_From_FloatV(V4Dot3(normalV, v0V));
const Vec4V extentsV = V4LoadU(&extents.x);
VecU32V normalSignsV = V4U32and(VecU32V_ReinterpretFrom_Vec4V(normalV), signV);
const Vec4V maxV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
Vec4V tmpV = Vec4V_From_FloatV(V4Dot3(normalV, maxV));
if(V4AnyGrtr3(dV, tmpV))
return 0;
normalSignsV = V4U32xor(normalSignsV, signV);
const Vec4V minV = Vec4V_ReinterpretFrom_VecU32V(V4U32or(VecU32V_ReinterpretFrom_Vec4V(extentsV), normalSignsV));
tmpV = Vec4V_From_FloatV(V4Dot3(normalV, minV));
if(V4AnyGrtr3(tmpV, dV))
return 0;
}
// Edge-edge tests
{
if(!testClassIIIAxes(e0V, v0V, v1V, v2V, extents))
return 0;
if(!testClassIIIAxes(e1V, v0V, v1V, v2V, extents))
return 0;
const Vec4V e2V = V4Sub(v0V, v2V);
if(!testClassIIIAxes(e2V, v0V, v1V, v2V, extents))
return 0;
}
return 1;
}
// PT: a SIMD version of Tomas Moller's triangle-box SAT code
PxIntBool Gu::intersectTriangleBox_Unsafe(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
{
// Move everything so that the boxcenter is in (0,0,0)
const Vec4V BoxCenterV = V4LoadU(¢er.x);
const Vec4V v0V = V4Sub(V4LoadU(&p0.x), BoxCenterV);
const Vec4V v1V = V4Sub(V4LoadU(&p1.x), BoxCenterV);
const Vec4V v2V = V4Sub(V4LoadU(&p2.x), BoxCenterV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}
PxIntBool Gu::intersectTriangleBox(const BoxPadded& box, const PxVec3& p0_, const PxVec3& p1_, const PxVec3& p2_)
{
// PT: TODO: SIMDify this part
// PxVec3p ensures we can safely V4LoadU the data
const PxVec3p p0 = box.rotateInv(p0_ - box.center);
const PxVec3p p1 = box.rotateInv(p1_ - box.center);
const PxVec3p p2 = box.rotateInv(p2_ - box.center);
const Vec4V v0V = V4LoadU(&p0.x);
const Vec4V v1V = V4LoadU(&p1.x);
const Vec4V v2V = V4LoadU(&p2.x);
return intersectTriangleBoxInternal(v0V, v1V, v2V, box.extents);
}
static PX_FORCE_INLINE Vec4V multiply3x3V(const Vec4V p, const PxMat33& mat)
{
const FloatV xxxV = V4GetX(p);
const FloatV yyyV = V4GetY(p);
const FloatV zzzV = V4GetZ(p);
Vec4V ResV = V4Scale(V4LoadU(&mat.column0.x), xxxV);
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column1.x), yyyV));
ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.column2.x), zzzV));
return ResV;
}
// PT: warning: all params must be safe to V4LoadU
PxIntBool intersectTriangleBoxBV4( const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents)
{
const Vec4V transModelToBoxV = V4LoadU(&transModelToBox.x);
const Vec4V v0V = V4Add(multiply3x3V(V4LoadU(&p0.x), rotModelToBox), transModelToBoxV);
const Vec4V v1V = V4Add(multiply3x3V(V4LoadU(&p1.x), rotModelToBox), transModelToBoxV);
const Vec4V v2V = V4Add(multiply3x3V(V4LoadU(&p2.x), rotModelToBox), transModelToBoxV);
return intersectTriangleBoxInternal(v0V, v1V, v2V, extents);
}
| 6,931 | C++ | 34.731959 | 153 | 0.732939 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/intersection/GuIntersectionCapsuleTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_CAPSULE_TRIANGLE_H
#define GU_INTERSECTION_CAPSULE_TRIANGLE_H
#include "GuCapsule.h"
#include "foundation/PxUtilities.h"
namespace physx
{
namespace Gu
{
// PT: precomputed data for capsule-triangle test. Useful when testing the same capsule vs several triangles.
struct CapsuleTriangleOverlapData
{
PxVec3 mCapsuleDir;
float mBDotB;
float mOneOverBDotB;
void init(const Capsule& capsule)
{
const PxVec3 dir = capsule.p1 - capsule.p0;
const float BDotB = dir.dot(dir);
mCapsuleDir = dir;
mBDotB = BDotB;
mOneOverBDotB = BDotB!=0.0f ? 1.0f/BDotB : 0.0f;
}
};
// PT: tests if projections of capsule & triangle overlap on given axis
PX_FORCE_INLINE PxU32 testAxis(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Capsule& capsule, const PxVec3& axis)
{
// Project capsule
float min0 = capsule.p0.dot(axis);
float max0 = capsule.p1.dot(axis);
if(min0>max0)
PxSwap(min0, max0);
const float MR = axis.magnitude()*capsule.radius;
min0 -= MR;
max0 += MR;
// Project triangle
float min1, max1;
{
min1 = max1 = p0.dot(axis);
float dp = p1.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
dp = p2.dot(axis);
if(dp<min1) min1 = dp;
if(dp>max1) max1 = dp;
}
// Test projections
if(max0<min1 || max1<min0)
return 0;
return 1;
}
// PT: computes shortest vector going from capsule axis to triangle edge
PX_FORCE_INLINE PxVec3 computeEdgeAxis( const PxVec3& p, const PxVec3& a,
const PxVec3& q, const PxVec3& b,
float BDotB, float oneOverBDotB)
{
const PxVec3 T = q - p;
const float ADotA = a.dot(a);
const float ADotB = a.dot(b);
const float ADotT = a.dot(T);
const float BDotT = b.dot(T);
const float denom = ADotA*BDotB - ADotB*ADotB;
float t = denom!=0.0f ? (ADotT*BDotB - BDotT*ADotB) / denom : 0.0f;
t = PxClamp(t, 0.0f, 1.0f);
float u = (t*ADotB - BDotT) * oneOverBDotB;
if(u<0.0f)
{
u = 0.0f;
t = ADotT / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
else if(u>1.0f)
{
u = 1.0f;
t = (ADotB + ADotT) / ADotA;
t = PxClamp(t, 0.0f, 1.0f);
}
return T + b*u - a*t;
}
/**
* Checks if a capsule intersects a triangle.
*
* \param normal [in] triangle normal (orientation does not matter)
* \param p0 [in] triangle's first point
* \param p1 [in] triangle's second point
* \param p2 [in] triangle's third point
* \param capsule [in] capsule
* \param params [in] precomputed capsule params
* \return true if capsule overlaps triangle
*/
bool intersectCapsuleTriangle(const PxVec3& normal, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const Gu::Capsule& capsule, const CapsuleTriangleOverlapData& params);
}
}
#endif
| 4,447 | C | 31.705882 | 177 | 0.697549 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSphere.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_SPHERE_H
#define GU_SPHERE_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxVec3.h"
namespace physx
{
/**
\brief Represents a sphere defined by its center point and radius.
*/
namespace Gu
{
class Sphere
{
public:
/**
\brief Constructor
*/
PX_INLINE Sphere()
{
}
/**
\brief Constructor
*/
PX_INLINE Sphere(const PxVec3& _center, PxF32 _radius) : center(_center), radius(_radius)
{
}
/**
\brief Copy constructor
*/
PX_INLINE Sphere(const Sphere& sphere) : center(sphere.center), radius(sphere.radius)
{
}
/**
\brief Destructor
*/
PX_INLINE ~Sphere()
{
}
PX_INLINE void set(const PxVec3& _center, float _radius) { center = _center; radius = _radius; }
/**
\brief Checks the sphere is valid.
\return true if the sphere is valid
*/
PX_INLINE bool isValid() const
{
// Consistency condition for spheres: Radius >= 0.0f
return radius >= 0.0f;
}
/**
\brief Tests if a point is contained within the sphere.
\param[in] p the point to test
\return true if inside the sphere
*/
PX_INLINE bool contains(const PxVec3& p) const
{
return (center-p).magnitudeSquared() <= radius*radius;
}
PxVec3 center; //!< Sphere's center
PxF32 radius; //!< Sphere's radius
};
}
}
/** @} */
#endif
| 2,998 | C | 27.028037 | 99 | 0.708139 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCooking.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_H
#define GU_COOKING_H
/** \addtogroup geomutils
@{
*/
// PT: TODO: the SDK always had this questionable design decision that all APIs can include all high-level public headers,
// regardless of where they fit in the header hierarchy. For example PhysXCommon can include headers from the higher-level
// PhysX DLL. We take advantage of that here by including PxCooking from PhysXCommon. That way we can reuse the same code
// as before without decoupling it from high-level classes like PxConvexMeshDesc/etc. A cleaner solution would be to decouple
// the two and only use PxConvexMeshDesc/etc in the higher level cooking DLL. The lower-level Gu functions below would then
// operate either on Gu-level types (see e.g. PxBVH / GuBVH which was done this way), or on basic types like float and ints
// to pass vertex & triangle data around. We could also split the kitchen-sink PxCookingParams structure into separate classes
// for convex / triangle mesh / etc. Overall there might be some more refactoring to do here, and that's why these functions
// have been put in the "semi public" Gu API for now, instead of the Px API (which is more strict in terms of backward
// compatibility and how we deal with deprecated functions).
#include "cooking/PxCooking.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxMemory.h"
namespace physx
{
class PxInsertionCallback;
class PxOutputStream;
class PxBVHDesc;
class PxBVH;
class PxHeightField;
struct PxCookingParams;
namespace immediateCooking
{
PX_FORCE_INLINE static void gatherStrided(const void* src, void* dst, PxU32 nbElem, PxU32 elemSize, PxU32 stride)
{
const PxU8* s = reinterpret_cast<const PxU8*>(src);
PxU8* d = reinterpret_cast<PxU8*>(dst);
while(nbElem--)
{
PxMemCopy(d, s, elemSize);
d += elemSize;
s += stride;
}
}
PX_INLINE static bool platformMismatch()
{
// Get current endianness (the one for the platform where cooking is performed)
const PxI8 currentEndian = PxLittleEndian();
const bool mismatch = currentEndian!=1; // The files must be little endian - we don't have big endian platforms anymore.
return mismatch;
}
PX_C_EXPORT PX_PHYSX_COMMON_API PxInsertionCallback* getInsertionCallback(); // PT: should be a reference but using a pointer for C
// BVH
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookBVH(const PxBVHDesc& desc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxBVH* createBVH(const PxBVHDesc& desc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxBVH* createBVH(const PxBVHDesc& desc)
{
return createBVH(desc, *getInsertionCallback());
}
// Heightfield
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookHeightField(const PxHeightFieldDesc& desc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxHeightField* createHeightField(const PxHeightFieldDesc& desc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxHeightField* createHeightField(const PxHeightFieldDesc& desc)
{
return createHeightField(desc, *getInsertionCallback());
}
// Convex meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc, PxOutputStream& stream, PxConvexMeshCookingResult::Enum* condition=NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API PxConvexMesh* createConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc, PxInsertionCallback& insertionCallback, PxConvexMeshCookingResult::Enum* condition=NULL);
PX_FORCE_INLINE PxConvexMesh* createConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc)
{
return createConvexMesh(params, desc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API bool validateConvexMesh(const PxCookingParams& params, const PxConvexMeshDesc& desc);
PX_C_EXPORT PX_PHYSX_COMMON_API bool computeHullPolygons(const PxCookingParams& params, const PxSimpleTriangleMesh& mesh, PxAllocatorCallback& inCallback, PxU32& nbVerts, PxVec3*& vertices,
PxU32& nbIndices, PxU32*& indices, PxU32& nbPolygons, PxHullPolygon*& hullPolygons);
// Triangle meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool validateTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxTriangleMesh* createTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxInsertionCallback& insertionCallback, PxTriangleMeshCookingResult::Enum* condition=NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc, PxOutputStream& stream, PxTriangleMeshCookingResult::Enum* condition=NULL);
PX_FORCE_INLINE PxTriangleMesh* createTriangleMesh(const PxCookingParams& params, const PxTriangleMeshDesc& desc)
{
return createTriangleMesh(params, desc, *getInsertionCallback());
}
// Tetrahedron & soft body meshes
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxTetrahedronMesh* createTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxTetrahedronMesh* createTetrahedronMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& meshDesc)
{
return createTetrahedronMesh(params, meshDesc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API bool cookSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxOutputStream& stream);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* createSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc, PxInsertionCallback& insertionCallback);
PX_FORCE_INLINE PxSoftBodyMesh* createSoftBodyMesh(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc, const PxTetrahedronMeshDesc& collisionMeshDesc,
const PxSoftBodySimulationDataDesc& softbodyDataDesc)
{
return createSoftBodyMesh(params, simulationMeshDesc, collisionMeshDesc, softbodyDataDesc, *getInsertionCallback());
}
PX_C_EXPORT PX_PHYSX_COMMON_API PxCollisionMeshMappingData* computeModelsMapping(const PxCookingParams& params, PxTetrahedronMeshData& simulationMesh, const PxTetrahedronMeshData& collisionMesh,
const PxSoftBodyCollisionData& collisionData, const PxBoundedData* vertexToTet = NULL);
PX_C_EXPORT PX_PHYSX_COMMON_API PxCollisionTetrahedronMeshData* computeCollisionData(const PxCookingParams& params, const PxTetrahedronMeshDesc& collisionMeshDesc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSimulationTetrahedronMeshData* computeSimulationData(const PxCookingParams& params, const PxTetrahedronMeshDesc& simulationMeshDesc);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* assembleSoftBodyMesh(PxTetrahedronMeshData& simulationMesh, PxSoftBodySimulationData& simulationData, PxTetrahedronMeshData& collisionMesh,
PxSoftBodyCollisionData& collisionData, PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback);
PX_C_EXPORT PX_PHYSX_COMMON_API PxSoftBodyMesh* assembleSoftBodyMesh_Sim(PxSimulationTetrahedronMeshData& simulationMesh, PxCollisionTetrahedronMeshData& collisionMesh,
PxCollisionMeshMappingData& mappingData, PxInsertionCallback& insertionCallback);
}
}
/** @} */
#endif
| 9,422 | C | 56.457317 | 223 | 0.786351 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuOverlapTests.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_OVERLAP_TESTS_H
#define GU_OVERLAP_TESTS_H
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxAssert.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFoundation.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
namespace Gu
{
class Capsule;
class Sphere;
// PT: this is just a shadow of what it used to be. We currently don't use TRIGGER_INSIDE anymore, but I leave it for now,
// since I really want to put this back the way it was before.
enum TriggerStatus
{
TRIGGER_DISJOINT,
TRIGGER_INSIDE,
TRIGGER_OVERLAP
};
// PT: currently only used for convex triggers
struct TriggerCache
{
PxVec3 dir;
PxU16 state;
PxU16 gjkState; //gjk succeed or fail
};
#define UNUSED_OVERLAP_THREAD_CONTEXT NULL
// PT: we use a define to be able to quickly change the signature of all overlap functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom0 first geometry object
// \param[in] pose0 pose of first geometry object
// \param[in] geom1 second geometry object
// \param[in] pose1 pose of second geometry object
// \param[in] cache optional cached data for triggers
// \param[in] threadContext optional per-thread context
#define GU_OVERLAP_FUNC_PARAMS const PxGeometry& geom0, const PxTransform& pose0, \
const PxGeometry& geom1, const PxTransform& pose1, \
Gu::TriggerCache* cache, PxOverlapThreadContext* threadContext
// PT: function pointer for Geom-indexed overlap functions
// See GU_OVERLAP_FUNC_PARAMS for function parameters details.
// \return true if an overlap was found, false otherwise
typedef bool (*GeomOverlapFunc) (GU_OVERLAP_FUNC_PARAMS);
// PT: typedef for a bundle of all overlap functions, i.e. the function table itself (indexed by geom-type).
typedef GeomOverlapFunc GeomOverlapTable[PxGeometryType::eGEOMETRY_COUNT];
// PT: retrieves the overlap function table (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomOverlapTable* getOverlapFuncTable();
PX_FORCE_INLINE bool overlap( const PxGeometry& geom0, const PxTransform& pose0,
const PxGeometry& geom1, const PxTransform& pose1,
const GeomOverlapTable* PX_RESTRICT overlapFuncs, PxOverlapThreadContext* threadContext)
{
PX_CHECK_AND_RETURN_VAL(pose0.isValid(), "Gu::overlap(): pose0 is not valid.", false);
PX_CHECK_AND_RETURN_VAL(pose1.isValid(), "Gu::overlap(): pose1 is not valid.", false);
if(geom0.getType() > geom1.getType())
{
GeomOverlapFunc overlapFunc = overlapFuncs[geom1.getType()][geom0.getType()];
PX_ASSERT(overlapFunc);
return overlapFunc(geom1, pose1, geom0, pose0, NULL, threadContext);
}
else
{
GeomOverlapFunc overlapFunc = overlapFuncs[geom0.getType()][geom1.getType()];
PX_ASSERT(overlapFunc);
return overlapFunc(geom0, pose0, geom1, pose1, NULL, threadContext);
}
}
} // namespace Gu
}
#endif
| 4,733 | C | 39.810344 | 123 | 0.747517 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSweepTests.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_TESTS_H
#define GU_SWEEP_TESTS_H
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
class PxConvexMeshGeometry;
class PxCapsuleGeometry;
class PxTriangle;
class PxBoxGeometry;
#define UNUSED_SWEEP_THREAD_CONTEXT NULL
// PT: TODO: unify this with raycast calls (names and order of params)
// PT: we use defines to be able to quickly change the signature of all sweep functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom geometry object to sweep against
// \param[in] pose pose of geometry object
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] sweepHit hit result
// \param[in] hitFlags query behavior flags
// \param[in] inflation optional inflation value for swept shape
// \param[in] threadContext optional per-thread context
// PT: sweep parameters for capsule
#define GU_CAPSULE_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxCapsuleGeometry& capsuleGeom_, const PxTransform& capsulePose_, const Gu::Capsule& lss, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
// PT: sweep parameters for box
#define GU_BOX_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxBoxGeometry& boxGeom_, const PxTransform& boxPose_, const Gu::Box& box, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
// PT: sweep parameters for convex
#define GU_CONVEX_SWEEP_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose, \
const PxVec3& unitDir, PxReal distance, \
PxGeomSweepHit& sweepHit, const PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* threadContext
namespace Gu
{
class Capsule;
class Box;
// PT: function pointer for Geom-indexed capsule sweep functions
// See GU_CAPSULE_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepCapsuleFunc) (GU_CAPSULE_SWEEP_FUNC_PARAMS);
// PT: function pointer for Geom-indexed box sweep functions
// See GU_BOX_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepBoxFunc) (GU_BOX_SWEEP_FUNC_PARAMS);
// PT: function pointer for Geom-indexed box sweep functions
// See GU_CONVEX_SWEEP_FUNC_PARAMS for function parameters details.
// \return true if a hit was found, false otherwise
typedef bool (*SweepConvexFunc) (GU_CONVEX_SWEEP_FUNC_PARAMS);
// PT: typedef for bundles of all sweep functions, i.e. the function tables themselves (indexed by geom-type).
typedef SweepCapsuleFunc GeomSweepCapsuleTable [PxGeometryType::eGEOMETRY_COUNT];
typedef SweepBoxFunc GeomSweepBoxTable [PxGeometryType::eGEOMETRY_COUNT];
typedef SweepConvexFunc GeomSweepConvexTable [PxGeometryType::eGEOMETRY_COUNT];
struct GeomSweepFuncs
{
GeomSweepCapsuleTable capsuleMap;
GeomSweepCapsuleTable preciseCapsuleMap;
GeomSweepBoxTable boxMap;
GeomSweepBoxTable preciseBoxMap;
GeomSweepConvexTable convexMap;
};
// PT: grabs all sweep function tables at once (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomSweepFuncs& getSweepFuncTable();
// PT: signature for sweep-vs-triangles functions.
// We use defines to be able to quickly change the signature of all sweep functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] nbTris number of triangles in input array
// \param[in] triangles array of triangles to sweep the shape against
// \param[in] doubleSided true if input triangles are double-sided
// \param[in] x geom to sweep against input triangles
// \param[in] pose pose of geom x
// \param[in] unitDir sweep's unit dir
// \param[in] distance sweep's length/max distance
// \param[out] hit hit result
// \param[in] cachedIndex optional initial triangle index (must be <nbTris)
// \param[in] inflation optional inflation value for swept shape
// \param[in] hitFlags query behavior flags
#define GU_SWEEP_TRIANGLES_FUNC_PARAMS(x) PxU32 nbTris, const PxTriangle* triangles, bool doubleSided, \
const x& geom, const PxTransform& pose, \
const PxVec3& unitDir, const PxReal distance, \
PxGeomSweepHit& hit, const PxU32* cachedIndex, \
const PxReal inflation, PxHitFlags hitFlags
bool sweepCapsuleTriangles (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxCapsuleGeometry));
bool sweepBoxTriangles (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxBoxGeometry));
bool sweepBoxTriangles_Precise (GU_SWEEP_TRIANGLES_FUNC_PARAMS(PxBoxGeometry));
} // namespace Gu
}
#endif
| 6,901 | C | 48.654676 | 117 | 0.737864 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPrunerPayload.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_PRUNER_PAYLOAD_H
#define GU_PRUNER_PAYLOAD_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/Px.h"
namespace physx
{
class PxBounds3;
namespace Gu
{
// PT: anonymous payload structure used by the pruners. This is similar in spirit to a userData pointer.
struct PrunerPayload
{
size_t data[2]; // Enough space for two arbitrary pointers
PX_FORCE_INLINE bool operator == (const PrunerPayload& other) const
{
return (data[0] == other.data[0]) && (data[1] == other.data[1]);
}
};
// PT: pointers to internal data associated with a pruner payload. The lifetime of these pointers
// is usually limited and they should be used immediately after retrieval.
struct PrunerPayloadData
{
PxBounds3* mBounds; // Pointer to internal bounds.
PxTransform* mTransform; // Pointer to internal transform, or NULL.
};
// PT: called for each removed payload. Gives users a chance to cleanup their data
// structures without duplicating the pruner-data to payload mapping on their side.
struct PrunerPayloadRemovalCallback
{
PrunerPayloadRemovalCallback() {}
virtual ~PrunerPayloadRemovalCallback() {}
virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed) = 0;
};
}
}
#endif
| 2,939 | C | 39.273972 | 105 | 0.752977 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_BOX_H
#define GU_BOX_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxTransform.h"
#include "foundation/PxMat33.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class Capsule;
PX_PHYSX_COMMON_API void computeOBBPoints(PxVec3* PX_RESTRICT pts, const PxVec3& center, const PxVec3& extents, const PxVec3& base0, const PxVec3& base1, const PxVec3& base2);
/**
\brief Represents an oriented bounding box.
As a center point, extents(radii) and a rotation. i.e. the center of the box is at the center point,
the box is rotated around this point with the rotation and it is 2*extents in width, height and depth.
*/
/**
Box geometry
The rot member describes the world space orientation of the box.
The center member gives the world space position of the box.
The extents give the local space coordinates of the box corner in the positive octant.
Dimensions of the box are: 2*extent.
Transformation to world space is: worldPoint = rot * localPoint + center
Transformation to local space is: localPoint = T(rot) * (worldPoint - center)
Where T(M) denotes the transpose of M.
*/
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class
#endif
class PX_PHYSX_COMMON_API Box
{
public:
/**
\brief Constructor
*/
PX_FORCE_INLINE Box()
{
}
/**
\brief Constructor
\param origin Center of the OBB
\param extent Extents/radii of the obb.
\param base rotation to apply to the obb.
*/
//! Construct from center, extent and rotation
PX_FORCE_INLINE Box(const PxVec3& origin, const PxVec3& extent, const PxMat33& base) : rot(base), center(origin), extents(extent)
{}
//! Copy constructor
PX_FORCE_INLINE Box(const Box& other) : rot(other.rot), center(other.center), extents(other.extents)
{}
/**
\brief Destructor
*/
PX_FORCE_INLINE ~Box()
{
}
//! Assignment operator
PX_FORCE_INLINE const Box& operator=(const Box& other)
{
rot = other.rot;
center = other.center;
extents = other.extents;
return *this;
}
/**
\brief Setups an empty box.
*/
PX_INLINE void setEmpty()
{
center = PxVec3(0);
extents = PxVec3(-PX_MAX_REAL, -PX_MAX_REAL, -PX_MAX_REAL);
rot = PxMat33(PxIdentity);
}
/**
\brief Checks the box is valid.
\return true if the box is valid
*/
PX_INLINE bool isValid() const
{
// Consistency condition for (Center, Extents) boxes: Extents >= 0.0f
if(extents.x < 0.0f) return false;
if(extents.y < 0.0f) return false;
if(extents.z < 0.0f) return false;
return true;
}
/////////////
PX_FORCE_INLINE void setAxes(const PxVec3& axis0, const PxVec3& axis1, const PxVec3& axis2)
{
rot.column0 = axis0;
rot.column1 = axis1;
rot.column2 = axis2;
}
PX_FORCE_INLINE PxVec3 rotate(const PxVec3& src) const
{
return rot * src;
}
PX_FORCE_INLINE PxVec3 rotateInv(const PxVec3& src) const
{
return rot.transformTranspose(src);
}
PX_FORCE_INLINE PxVec3 transform(const PxVec3& src) const
{
return rot * src + center;
}
PX_FORCE_INLINE PxTransform getTransform() const
{
return PxTransform(center, PxQuat(rot));
}
PX_INLINE PxVec3 computeAABBExtent() const
{
const PxReal a00 = PxAbs(rot[0][0]);
const PxReal a01 = PxAbs(rot[0][1]);
const PxReal a02 = PxAbs(rot[0][2]);
const PxReal a10 = PxAbs(rot[1][0]);
const PxReal a11 = PxAbs(rot[1][1]);
const PxReal a12 = PxAbs(rot[1][2]);
const PxReal a20 = PxAbs(rot[2][0]);
const PxReal a21 = PxAbs(rot[2][1]);
const PxReal a22 = PxAbs(rot[2][2]);
const PxReal ex = extents.x;
const PxReal ey = extents.y;
const PxReal ez = extents.z;
return PxVec3( a00 * ex + a10 * ey + a20 * ez,
a01 * ex + a11 * ey + a21 * ez,
a02 * ex + a12 * ey + a22 * ez);
}
/**
Computes the obb points.
\param pts [out] 8 box points
*/
PX_FORCE_INLINE void computeBoxPoints(PxVec3* PX_RESTRICT pts) const
{
Gu::computeOBBPoints(pts, center, extents, rot.column0, rot.column1, rot.column2);
}
void create(const Gu::Capsule& capsule);
PxMat33 rot;
PxVec3 center;
PxVec3 extents;
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::Box) == 60);
//! A padded version of Gu::Box, to safely load its data using SIMD
class BoxPadded : public Box
{
public:
PX_FORCE_INLINE BoxPadded() {}
PX_FORCE_INLINE ~BoxPadded() {}
PxU32 padding;
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::BoxPadded) == 64);
#if PX_VC
#pragma warning(pop)
#endif
}
}
/** @} */
#endif
| 6,273 | C | 27.008928 | 176 | 0.692013 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTriangleTriangle.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TRIANGLE_TRIANGLE_H
#define GU_INTERSECTION_TRIANGLE_TRIANGLE_H
#include "GuSegment.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
/**
Tests if a two triangles intersect
\param a1 [in] Fist point of the first triangle
\param b1 [in] Second point of the first triangle
\param c1 [in] Third point of the first triangle
\param a2 [in] Fist point of the second triangle
\param b2 [in] Second point of the second triangle
\param c2 [in] Third point of the second triangle
\param ignoreCoplanar [in] True to filter out coplanar triangles
\return true if triangles intersect
*/
PX_PHYSX_COMMON_API bool trianglesIntersect(const PxVec3& a1, const PxVec3& b1, const PxVec3& c1,
const PxVec3& a2, const PxVec3& b2, const PxVec3& c2,
bool ignoreCoplanar = false);
} // namespace Gu
}
#endif
| 2,589 | C | 43.655172 | 98 | 0.750097 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCapsule.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_CAPSULE_H
#define GU_CAPSULE_H
/** \addtogroup geomutils
@{
*/
#include "GuSegment.h"
namespace physx
{
namespace Gu
{
/**
\brief Represents a capsule.
*/
class Capsule : public Segment
{
public:
/**
\brief Constructor
*/
PX_INLINE Capsule()
{
}
/**
\brief Constructor
\param seg Line segment to create capsule from.
\param _radius Radius of the capsule.
*/
PX_INLINE Capsule(const Segment& seg, PxF32 _radius) : Segment(seg), radius(_radius)
{
}
/**
\brief Constructor
\param _p0 First segment point
\param _p1 Second segment point
\param _radius Radius of the capsule.
*/
PX_INLINE Capsule(const PxVec3& _p0, const PxVec3& _p1, PxF32 _radius) : Segment(_p0, _p1), radius(_radius)
{
}
/**
\brief Destructor
*/
PX_INLINE ~Capsule()
{
}
PxF32 radius;
};
}
}
/** @} */
#endif
| 2,570 | C | 26.945652 | 109 | 0.715953 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTriangleBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TRIANGLE_BOX_H
#define GU_INTERSECTION_TRIANGLE_BOX_H
#include "foundation/PxMat33.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class Box;
class BoxPadded;
/**
Tests if a triangle overlaps a box (AABB). This is the reference non-SIMD code.
\param center [in] the box center
\param extents [in] the box extents
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox_ReferenceCode(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
/**
Tests if a triangle overlaps a box (AABB). This is the optimized SIMD code.
WARNING: the function has various SIMD requirements, left to the calling code:
- function will load 4 bytes after 'center'. Make sure it's safe to load from there.
- function will load 4 bytes after 'extents'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p0'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p1'. Make sure it's safe to load from there.
- function will load 4 bytes after 'p2'. Make sure it's safe to load from there.
If you can't guarantee these requirements, please use the non-SIMD reference code instead.
\param center [in] the box center.
\param extents [in] the box extents
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox_Unsafe(const PxVec3& center, const PxVec3& extents, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
/**
Tests if a triangle overlaps a box (OBB).
There are currently no SIMD-related requirements for p0, p1, p2.
\param box [in] the box
\param p0 [in] triangle's first point
\param p1 [in] triangle's second point
\param p2 [in] triangle's third point
\return true if triangle overlaps box
*/
PX_PHYSX_COMMON_API PxIntBool intersectTriangleBox(const BoxPadded& box, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2);
} // namespace Gu
}
#endif
| 3,940 | C | 42.788888 | 165 | 0.75 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuActorShapeMap.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_ACTOR_SHAPE_MAP_H
#define GU_ACTOR_SHAPE_MAP_H
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxHashMap.h"
namespace physx
{
namespace Gu
{
typedef PxU64 ActorShapeData;
#define PX_INVALID_INDEX 0xffffffff
class ActorShapeMap
{
public:
PX_PHYSX_COMMON_API ActorShapeMap();
PX_PHYSX_COMMON_API ~ActorShapeMap();
PX_PHYSX_COMMON_API bool add(PxU32 actorIndex, const void* actor, const void* shape, ActorShapeData actorShapeData);
PX_PHYSX_COMMON_API bool remove(PxU32 actorIndex, const void* actor, const void* shape, ActorShapeData* removed);
PX_PHYSX_COMMON_API ActorShapeData find(PxU32 actorIndex, const void* actor, const void* shape) const;
struct ActorShape
{
PX_FORCE_INLINE ActorShape() {}
PX_FORCE_INLINE ActorShape(const void* actor, const void* shape) : mActor(actor), mShape(shape) {}
const void* mActor;
const void* mShape;
PX_FORCE_INLINE bool operator==(const ActorShape& p) const
{
return mActor == p.mActor && mShape == p.mShape;
}
};
private:
PxHashMap<ActorShape, ActorShapeData> mDatabase;
struct Cache
{
// const void* mActor;
const void* mShape;
ActorShapeData mData;
};
PxU32 mCacheSize;
Cache* mCache;
void resizeCache(PxU32 index);
};
}
}
#endif
| 3,073 | C | 35.164705 | 120 | 0.732184 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSqInternal.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_SQ_INTERNAL_H
#define GU_SQ_INTERNAL_H
#include "foundation/PxSimpleTypes.h"
#include "common/PxPhysXCommonConfig.h"
#define SQ_DEBUG_VIZ_STATIC_COLOR PxU32(PxDebugColor::eARGB_BLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR PxU32(PxDebugColor::eARGB_RED)
#define SQ_DEBUG_VIZ_STATIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKBLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKRED)
#define SQ_DEBUG_VIZ_COMPOUND_COLOR PxU32(PxDebugColor::eARGB_MAGENTA)
namespace physx
{
class PxRenderOutput;
class PxBounds3;
namespace Gu
{
class BVH;
class AABBTree;
class IncrementalAABBTree;
class IncrementalAABBTreeNode;
}
class DebugVizCallback
{
public:
DebugVizCallback() {}
virtual ~DebugVizCallback() {}
virtual bool visualizeNode(const physx::Gu::IncrementalAABBTreeNode& node, const physx::PxBounds3& bounds) = 0;
};
}
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::BVH* tree);
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::AABBTree* tree);
PX_PHYSX_COMMON_API void visualizeTree(physx::PxRenderOutput& out, physx::PxU32 color, const physx::Gu::IncrementalAABBTree* tree, physx::DebugVizCallback* cb=NULL);
// PT: macros to try limiting the code duplication in headers. Mostly it just redefines the
// SqPruner API in implementation classes, and you shouldn't have to worry about it.
// Note that this assumes pool-based pruners with an mPool class member (for now).
#define DECLARE_BASE_PRUNER_API \
virtual void shiftOrigin(const PxVec3& shift); \
virtual void visualize(PxRenderOutput& out, PxU32 primaryColor, PxU32 secondaryColor) const;
#define DECLARE_PRUNER_API_COMMON \
virtual bool addObjects(PrunerHandle* results, const PxBounds3* bounds, const PrunerPayload* data, const PxTransform* transforms, PxU32 count, bool hasPruningStructure); \
virtual void removeObjects(const PrunerHandle* handles, PxU32 count, PrunerPayloadRemovalCallback* removalCallback); \
virtual void updateObjects(const PrunerHandle* handles, PxU32 count, float inflation, const PxU32* boundsIndices, const PxBounds3* newBounds, const PxTransform32* newTransforms); \
virtual void purge(); \
virtual void commit(); \
virtual void merge(const void* mergeParams); \
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, Gu::PrunerRaycastCallback&) const; \
virtual bool overlap(const Gu::ShapeData& queryVolume, Gu::PrunerOverlapCallback&) const; \
virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, Gu::PrunerRaycastCallback&) const; \
virtual const PrunerPayload& getPayloadData(PrunerHandle handle, PrunerPayloadData* data) const { return mPool.getPayloadData(handle, data); } \
virtual void preallocate(PxU32 entries) { mPool.preallocate(entries); } \
virtual bool setTransform(PrunerHandle handle, const PxTransform& transform) { return mPool.setTransform(handle, transform); } \
virtual void getGlobalBounds(PxBounds3&) const;
#endif
| 5,221 | C | 56.384615 | 187 | 0.712507 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/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 "common/PxPhysXCommonConfig.h"
#include "GuDistancePointTriangle.h"
#include "foundation/PxMathUtils.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);
PxVec3 diff = bestClosestPt - p;
PxReal bestSqDist = diff.dot(diff);
// 0, 2, 3
PxVec3 closestPt = closestPtPointTriangle2(p, a, c, d, ac, ad);
diff = closestPt - p;
PxReal sqDist = diff.dot(diff);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
// 0, 3, 1
closestPt = closestPtPointTriangle2(p, a, d, b, ad, ab);
diff = closestPt - p;
sqDist = diff.dot(diff);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
// 1, 3, 2
closestPt = closestPtPointTriangle2(p, b, d, c, bd, bc);
diff = closestPt - p;
sqDist = diff.dot(diff);
if (sqDist < bestSqDist)
{
bestClosestPt = closestPt;
bestSqDist = sqDist;
}
return bestClosestPt;
}
PX_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTetrahedronWithInsideCheck(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxReal eps = 0)
{
PxVec4 tmpBarycentric;
computeBarycentric(a, b, c, d, p, tmpBarycentric);
if ((tmpBarycentric.x >= -eps && tmpBarycentric.x <= 1.f + eps) && (tmpBarycentric.y >= -eps && tmpBarycentric.y <= 1.f + eps) &&
(tmpBarycentric.z >= -eps && tmpBarycentric.z <= 1.f + eps) && (tmpBarycentric.w >= -eps && tmpBarycentric.w <= 1.f + eps))
return p;
return closestPtPointTetrahedron(p, a, b, c, d);
}
}
}
#endif
| 4,087 | C | 37.205607 | 183 | 0.705897 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuRaycastTests.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_RAYCAST_TESTS_H
#define GU_RAYCAST_TESTS_H
#include "foundation/PxSimpleTypes.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
namespace physx
{
#define UNUSED_RAYCAST_THREAD_CONTEXT NULL
// PT: we use a define to be able to quickly change the signature of all raycast functions.
// (this also ensures they all use consistent names for passed parameters).
// \param[in] geom geometry object to raycast against
// \param[in] pose pose of geometry object
// \param[in] rayOrigin ray's origin
// \param[in] rayDir ray's unit dir
// \param[in] maxDist ray's length/max distance
// \param[in] hitFlags query behavior flags
// \param[in] maxHits max number of hits = size of 'hits' buffer
// \param[out] hits result buffer where to write raycast hits
// \param[in] stride size of hit structure
// \param[in] threadContext optional per-thread context
#define GU_RAY_FUNC_PARAMS const PxGeometry& geom, const PxTransform& pose, \
const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, \
PxHitFlags hitFlags, PxU32 maxHits, PxGeomRaycastHit* PX_RESTRICT hits, PxU32 stride, PxRaycastThreadContext* threadContext
namespace Gu
{
// PT: function pointer for Geom-indexed raycast functions
// See GU_RAY_FUNC_PARAMS for function parameters details.
// \return number of hits written to 'hits' result buffer
// \note there's no mechanism to report overflow. Returned number of hits is just clamped to maxHits.
typedef PxU32 (*RaycastFunc) (GU_RAY_FUNC_PARAMS);
// PT: typedef for a bundle of all raycast functions, i.e. the function table itself (indexed by geom-type).
typedef RaycastFunc GeomRaycastTable[PxGeometryType::eGEOMETRY_COUNT];
// PT: retrieves the raycast function table (for access by external non-Gu modules)
PX_PHYSX_COMMON_API const GeomRaycastTable& getRaycastFuncTable();
} // namespace Gu
}
#endif
| 3,674 | C | 47.999999 | 131 | 0.752041 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuQuerySystem.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_QUERY_SYSTEM_H
#define GU_QUERY_SYSTEM_H
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
#include "foundation/PxBounds3.h"
#include "GuPruner.h"
#include "GuActorShapeMap.h"
namespace physx
{
class PxGeometry;
namespace Gu
{
class BVH;
class Adapter
{
public:
Adapter() {}
virtual ~Adapter() {}
virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const = 0;
};
class PrunerFilter
{
public:
PrunerFilter() {}
virtual ~PrunerFilter() {}
virtual bool processPruner(PxU32 prunerIndex/*, const PxQueryThreadContext* context*/) const = 0;
};
typedef PxU32 PrunerInfo;
PX_FORCE_INLINE PrunerInfo createPrunerInfo(PxU32 prunerIndex, bool isDynamic) { return (prunerIndex << 1) | PxU32(isDynamic); }
PX_FORCE_INLINE PxU32 getPrunerIndex(PrunerInfo info) { return PxU32(info)>>1; }
PX_FORCE_INLINE PxU32 getDynamic(PrunerInfo info) { return PxU32(info) & 1; }
PX_FORCE_INLINE ActorShapeData createActorShapeData(PrunerInfo info, PrunerHandle h) { return (ActorShapeData(h) << 32) | ActorShapeData(info); }
PX_FORCE_INLINE PrunerInfo getPrunerInfo(ActorShapeData data) { return PrunerInfo(data); }
PX_FORCE_INLINE PrunerHandle getPrunerHandle(ActorShapeData data) { return PrunerHandle(data >> 32); }
#define INVALID_ACTOR_SHAPE_DATA PxU64(-1)
class QuerySystem : public PxUserAllocated
{
public: // PT: TODO: public only to implement checkPrunerIndex easily, revisit this
struct PrunerExt : public PxUserAllocated
{
PrunerExt(Pruner* pruner, PxU32 preallocated);
~PrunerExt();
void flushMemory();
void addToDirtyList(PrunerHandle handle, PxU32 dynamic, const PxTransform& transform, const PxBounds3* userBounds=NULL);
void removeFromDirtyList(PrunerHandle handle);
bool processDirtyList(const Adapter& adapter, float inflation);
Pruner* mPruner;
PxBitMap mDirtyMap;
PxArray<PrunerHandle> mDirtyList;
PxU32 mNbStatic; // nb static objects in pruner
PxU32 mNbDynamic; // nb dynamic objects in pruner
bool mDirtyStatic; // true if dirty list contains a static
struct Data
{
PxTransform mPose;
PxBounds3 mBounds;
};
PxArray<Data> mDirtyData;
PX_NOCOPY(PrunerExt)
};
public:
PX_PHYSX_COMMON_API QuerySystem(PxU64 contextID, float inflation, const Adapter& adapter, bool usesTreeOfPruners=false);
PX_PHYSX_COMMON_API ~QuerySystem();
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
PX_FORCE_INLINE const Adapter& getAdapter() const { return mAdapter; }
PX_FORCE_INLINE PxU32 getStaticTimestamp() const { return mStaticTimestamp; }
PX_PHYSX_COMMON_API PxU32 addPruner(Pruner* pruner, PxU32 preallocated);
PX_PHYSX_COMMON_API void removePruner(PxU32 prunerIndex);
PX_FORCE_INLINE PxU32 getNbPruners() const { return mPrunerExt.size(); }
PX_FORCE_INLINE const Pruner* getPruner(PxU32 index) const { return mPrunerExt[index]->mPruner; }
PX_FORCE_INLINE Pruner* getPruner(PxU32 index) { return mPrunerExt[index]->mPruner; }
PX_PHYSX_COMMON_API ActorShapeData addPrunerShape(const PrunerPayload& payload, PxU32 prunerIndex, bool dynamic, const PxTransform& transform, const PxBounds3* userBounds=NULL);
PX_PHYSX_COMMON_API void removePrunerShape(ActorShapeData data, PrunerPayloadRemovalCallback* removalCallback);
PX_PHYSX_COMMON_API void updatePrunerShape(ActorShapeData data, bool immediately, const PxTransform& transform, const PxBounds3* userBounds=NULL);
PX_PHYSX_COMMON_API const PrunerPayload& getPayloadData(ActorShapeData data, PrunerPayloadData* ppd=NULL) const;
PX_PHYSX_COMMON_API void commitUpdates();
PX_PHYSX_COMMON_API void update(bool buildStep, bool commit);
PX_PHYSX_COMMON_API void sync(PxU32 prunerIndex, const PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count);
PX_PHYSX_COMMON_API void flushMemory();
PX_PHYSX_COMMON_API void raycast(const PxVec3& origin, const PxVec3& unitDir, float& inOutDistance, PrunerRaycastCallback& cb, const PrunerFilter* prunerFilter) const;
PX_PHYSX_COMMON_API void overlap(const ShapeData& queryVolume, PrunerOverlapCallback& cb, const PrunerFilter* prunerFilter) const;
PX_PHYSX_COMMON_API void sweep(const ShapeData& queryVolume, const PxVec3& unitDir, float& inOutDistance, PrunerRaycastCallback& cb, const PrunerFilter* prunerFilter) const;
PxU32 startCustomBuildstep();
void customBuildstep(PxU32 index);
void finishCustomBuildstep();
void createTreeOfPruners();
private:
const Adapter& mAdapter;
PxArray<PrunerExt*> mPrunerExt;
PxArray<PxU32> mDirtyPruners;
PxArray<PxU32> mFreePruners;
Gu::BVH* mTreeOfPruners;
const PxU64 mContextID;
PxU32 mStaticTimestamp;
const float mInflation; // SQ_PRUNER_EPSILON
PxMutex mSQLock; // to make sure only one query updates the dirty pruner structure if multiple queries run in parallel
volatile bool mPrunerNeedsUpdating;
volatile bool mTimestampNeedsUpdating;
const bool mUsesTreeOfPruners;
void processDirtyLists();
PX_FORCE_INLINE void invalidateStaticTimestamp() { mStaticTimestamp++; }
PX_NOCOPY(QuerySystem)
};
}
}
#include "geometry/PxGeometryHit.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "GuCachedFuncs.h"
#include "GuCapsule.h"
#include "GuBounds.h"
#if PX_VC
#pragma warning(disable: 4355 ) // "this" used in base member initializer list
#endif
namespace physx
{
namespace Gu
{
// PT: TODO: use templates instead of v-calls?
// PT: we decouple the filter callback from the rest, so that the same filter callback can easily be reused for all pruner queries.
// This combines the pre-filter callback and fetching the payload's geometry in a single call. Return null to ignore that object.
struct PrunerFilterCallback
{
virtual ~PrunerFilterCallback() {}
// Query's hit flags can be tweaked per object. (Note that 'hitFlags' is unused for overlaps though)
virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& hitFlags) = 0;
};
struct DefaultPrunerRaycastCallback : public PrunerRaycastCallback, public PxRaycastThreadContext
{
PxRaycastThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomRaycastTable& mCachedRaycastFuncs;
const PxVec3& mOrigin;
const PxVec3& mDir;
PxGeomRaycastHit* mLocalHits;
const PxU32 mMaxLocalHits;
const PxHitFlags mHitFlags;
PxGeomRaycastHit mClosestHit;
PrunerPayload mClosestPayload;
bool mFoundHit;
const bool mAnyHit;
DefaultPrunerRaycastCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance, PxU32 maxLocalHits, PxGeomRaycastHit* localHits, PxHitFlags hitFlags, bool anyHit, PxRaycastThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedRaycastFuncs (funcs),
mOrigin (origin),
mDir (dir),
mLocalHits (localHits),
mMaxLocalHits (maxLocalHits),
mHitFlags (hitFlags),
mFoundHit (false),
mAnyHit (anyHit)
{
mClosestHit.distance = distance;
}
virtual bool reportHits(const PrunerPayload& /*payload*/, PxU32 /*nbHits*/, PxGeomRaycastHit* /*hits*/)
{
return true;
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
PxHitFlags filteredHitFlags = mHitFlags;
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, filteredHitFlags);
if(!shapeGeom)
return true;
const RaycastFunc func = mCachedRaycastFuncs[shapeGeom->getType()];
const PxU32 nbHits = func(*shapeGeom, transforms[primIndex], mOrigin, mDir, aDist, filteredHitFlags, mMaxLocalHits, mLocalHits, sizeof(PxGeomRaycastHit), mContext);
if(!nbHits || !reportHits(payload, nbHits, mLocalHits))
return true;
const PxGeomRaycastHit& localHit = mLocalHits[0];
if(localHit.distance < mClosestHit.distance)
{
mFoundHit = true;
if(mAnyHit)
return false;
aDist = localHit.distance;
mClosestHit = localHit;
mClosestPayload = payload;
}
return true;
}
PX_NOCOPY(DefaultPrunerRaycastCallback)
};
struct DefaultPrunerRaycastAnyCallback : public DefaultPrunerRaycastCallback
{
PxGeomRaycastHit mLocalHit;
DefaultPrunerRaycastAnyCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) :
DefaultPrunerRaycastCallback (filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eANY_HIT, true) {}
};
struct DefaultPrunerRaycastClosestCallback : public DefaultPrunerRaycastCallback
{
PxGeomRaycastHit mLocalHit;
DefaultPrunerRaycastClosestCallback(PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance, PxHitFlags hitFlags) :
DefaultPrunerRaycastCallback (filterCB, funcs, origin, dir, distance, 1, &mLocalHit, hitFlags, false) {}
};
struct DefaultPrunerOverlapCallback : public PrunerOverlapCallback, public PxOverlapThreadContext
{
PxOverlapThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomOverlapTable* mCachedFuncs;
const PxGeometry& mGeometry;
const PxTransform& mPose;
PxHitFlags mUnused;
DefaultPrunerOverlapCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose, PxOverlapThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedFuncs (funcs),
mGeometry (geometry),
mPose (pose)
{
}
virtual bool reportHit(const PrunerPayload& /*payload*/)
{
return true;
}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, mUnused);
if(!shapeGeom || !Gu::overlap(mGeometry, mPose, *shapeGeom, transforms[primIndex], mCachedFuncs, mContext))
return true;
return reportHit(payload);
}
PX_NOCOPY(DefaultPrunerOverlapCallback)
};
struct BoxShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& queryVolume,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eBOX);
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepBoxFunc func = precise ? sf.preciseBoxMap[geom.getType()] : sf.boxMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxBoxGeometry&>(queryGeom), queryPose, queryVolume.getGuBox(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct SphereShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& /*queryVolume*/,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eSPHERE);
// PT: we don't use sd.getGuSphere() here because PhysX doesn't expose a set of 'SweepSphereFunc' functions,
// we have to go through a capsule (which is then seen as a sphere internally when the half-length is zero).
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(queryGeom);
const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f);
const Capsule worldCapsule(queryPose.p, queryPose.p, sphereGeom.radius); // AP: precompute?
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom.getType()] : sf.capsuleMap[geom.getType()];
return PxU32(func(geom, pose, capsuleGeom, queryPose, worldCapsule, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct CapsuleShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& queryVolume,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eCAPSULE);
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom.getType()] : sf.capsuleMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxCapsuleGeometry&>(queryGeom), queryPose, queryVolume.getGuCapsule(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct ConvexShapeCast
{
static PX_FORCE_INLINE PxU32 sweep( const GeomSweepFuncs& sf, const PxGeometry& geom, const PxTransform& pose,
const PxGeometry& queryGeom, const PxTransform& queryPose, const ShapeData& /*queryVolume*/,
const PxVec3& unitDir, PxReal distance, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, PxReal inflation, PxSweepThreadContext* context)
{
PX_ASSERT(queryGeom.getType()==PxGeometryType::eCONVEXMESH);
const SweepConvexFunc func = sf.convexMap[geom.getType()];
return PxU32(func(geom, pose, static_cast<const PxConvexMeshGeometry&>(queryGeom), queryPose, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
};
struct DefaultPrunerSweepCallback : public PrunerRaycastCallback, public PxSweepThreadContext
{
virtual bool reportHit(const PrunerPayload& /*payload*/, PxGeomSweepHit& /*hit*/)
{
return true;
}
};
template<class ShapeCast>
struct DefaultPrunerSweepCallbackT : public DefaultPrunerSweepCallback
{
PxSweepThreadContext* mContext;
PrunerFilterCallback& mFilterCB;
const GeomSweepFuncs& mCachedFuncs;
const PxGeometry& mGeometry;
const PxTransform& mPose;
const ShapeData& mQueryVolume;
const PxVec3& mDir;
PxGeomSweepHit mLocalHit;
const PxHitFlags mHitFlags;
PxGeomSweepHit mClosestHit;
PrunerPayload mClosestPayload;
bool mFoundHit;
const bool mAnyHit;
DefaultPrunerSweepCallbackT(PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs,
const PxGeometry& geometry, const PxTransform& pose, const ShapeData& queryVolume,
const PxVec3& dir, float distance, PxHitFlags hitFlags, bool anyHit, PxSweepThreadContext* context=NULL) :
mContext (context ? context : this),
mFilterCB (filterCB),
mCachedFuncs (funcs),
mGeometry (geometry),
mPose (pose),
mQueryVolume (queryVolume),
mDir (dir),
mHitFlags (hitFlags),
mFoundHit (false),
mAnyHit (anyHit)
{
mClosestHit.distance = distance;
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
PX_ASSERT(payloads && transforms);
const PrunerPayload& payload = payloads[primIndex];
PxHitFlags filteredHitFlags = mHitFlags;
const PxGeometry* shapeGeom = mFilterCB.validatePayload(payload, filteredHitFlags);
if(!shapeGeom)
return true;
// PT: ### TODO: missing bit from PhysX version here
const float inflation = 0.0f; // ####
const PxU32 retVal = ShapeCast::sweep(mCachedFuncs, *shapeGeom, transforms[primIndex], mGeometry, mPose, mQueryVolume, mDir, aDist, mLocalHit, filteredHitFlags, inflation, mContext);
if(!retVal || !reportHit(payload, mLocalHit))
return true;
if(mLocalHit.distance < mClosestHit.distance)
{
mFoundHit = true;
if(mAnyHit)
return false;
aDist = mLocalHit.distance;
mClosestHit = mLocalHit;
mClosestPayload = payload;
}
return true;
}
PX_NOCOPY(DefaultPrunerSweepCallbackT)
};
typedef DefaultPrunerSweepCallbackT<SphereShapeCast> DefaultPrunerSphereSweepCallback;
typedef DefaultPrunerSweepCallbackT<BoxShapeCast> DefaultPrunerBoxSweepCallback;
typedef DefaultPrunerSweepCallbackT<CapsuleShapeCast> DefaultPrunerCapsuleSweepCallback;
typedef DefaultPrunerSweepCallbackT<ConvexShapeCast> DefaultPrunerConvexSweepCallback;
}
}
#endif
| 18,786 | C | 39.489224 | 273 | 0.741243 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuSegment.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_SEGMENT_H
#define GU_SEGMENT_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxVec3.h"
namespace physx
{
namespace Gu
{
/**
\brief Represents a line segment.
Line segment geometry
In some cases this structure will be used to represent the infinite line that passes point0 and point1.
*/
class Segment
{
public:
/**
\brief Constructor
*/
PX_INLINE Segment()
{
}
/**
\brief Constructor
*/
PX_INLINE Segment(const PxVec3& _p0, const PxVec3& _p1) : p0(_p0), p1(_p1)
{
}
/**
\brief Copy constructor
*/
PX_INLINE Segment(const Segment& seg) : p0(seg.p0), p1(seg.p1)
{
}
/**
\brief Destructor
*/
PX_INLINE ~Segment()
{
}
//! Assignment operator
PX_INLINE Segment& operator=(const Segment& other)
{
p0 = other.p0;
p1 = other.p1;
return *this;
}
//! Equality operator
PX_INLINE bool operator==(const Segment& other) const
{
return (p0==other.p0 && p1==other.p1);
}
//! Inequality operator
PX_INLINE bool operator!=(const Segment& other) const
{
return (p0!=other.p0 || p1!=other.p1);
}
PX_INLINE const PxVec3& getOrigin() const
{
return p0;
}
//! Return the vector from point0 to point1
PX_INLINE PxVec3 computeDirection() const
{
return p1 - p0;
}
//! Return the vector from point0 to point1
PX_INLINE void computeDirection(PxVec3& dir) const
{
dir = p1 - p0;
}
//! Return the center of the segment segment
PX_INLINE PxVec3 computeCenter() const
{
return (p0 + p1)*0.5f;
}
PX_INLINE PxF32 computeLength() const
{
return (p1-p0).magnitude();
}
PX_INLINE PxF32 computeSquareLength() const
{
return (p1-p0).magnitudeSquared();
}
// PT: TODO: remove this one
//! Return the square of the length of vector from point0 to point1
PX_INLINE PxReal lengthSquared() const
{
return ((p1 - p0).magnitudeSquared());
}
// PT: TODO: remove this one
//! Return the length of vector from point0 to point1
PX_INLINE PxReal length() const
{
return ((p1 - p0).magnitude());
}
/* PX_INLINE void setOriginDirection(const PxVec3& origin, const PxVec3& direction)
{
p0 = p1 = origin;
p1 += direction;
}*/
/**
\brief Computes a point on the segment
\param[out] pt point on segment
\param[in] t point's parameter [t=0 => pt = mP0, t=1 => pt = mP1]
*/
PX_INLINE void computePoint(PxVec3& pt, PxF32 t) const
{
pt = p0 + t * (p1 - p0);
}
// PT: TODO: remove this one
//! Return the point at parameter t along the line: point0 + t*(point1-point0)
PX_INLINE PxVec3 getPointAt(PxReal t) const
{
return (p1 - p0)*t + p0;
}
PxVec3 p0; //!< Start of segment
PxVec3 p1; //!< End of segment
};
PX_COMPILE_TIME_ASSERT(sizeof(Gu::Segment) == 24);
}
}
/** @} */
#endif
| 4,496 | C | 23.983333 | 104 | 0.68016 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCachedFuncs.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_CACHED_FUNCS_H
#define GU_CACHED_FUNCS_H
#include "GuRaycastTests.h"
#include "GuSweepTests.h"
#include "GuOverlapTests.h"
namespace physx
{
namespace Gu
{
struct CachedFuncs
{
CachedFuncs() :
mCachedRaycastFuncs (Gu::getRaycastFuncTable()),
mCachedSweepFuncs (Gu::getSweepFuncTable()),
mCachedOverlapFuncs (Gu::getOverlapFuncTable())
{
}
const Gu::GeomRaycastTable& mCachedRaycastFuncs;
const Gu::GeomSweepFuncs& mCachedSweepFuncs;
const Gu::GeomOverlapTable* mCachedOverlapFuncs;
PX_NOCOPY(CachedFuncs)
};
}
}
#endif
| 2,259 | C | 37.305084 | 74 | 0.761399 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuDistanceSegmentBox.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_BOX_H
#define GU_DISTANCE_SEGMENT_BOX_H
#include "foundation/PxMat33.h"
#include "GuSegment.h"
#include "GuBox.h"
namespace physx
{
namespace Gu
{
//! Compute the smallest distance from the (finite) line segment to the box.
PX_PHYSX_COMMON_API PxReal distanceSegmentBoxSquared( const PxVec3& segmentPoint0, const PxVec3& segmentPoint1,
const PxVec3& boxOrigin, const PxVec3& boxExtent, const PxMat33& boxBase,
PxReal* segmentParam = NULL,
PxVec3* boxParam = NULL);
PX_FORCE_INLINE PxReal distanceSegmentBoxSquared(const Gu::Segment& segment, const Gu::Box& box, PxReal* t = NULL, PxVec3* p = NULL)
{
return distanceSegmentBoxSquared(segment.p0, segment.p1, box.center, box.extents, box.rot, t, p);
}
} // namespace Gu
}
#endif
| 2,512 | C | 43.087719 | 133 | 0.74801 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPruner.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_PRUNER_H
#define GU_PRUNER_H
#include "foundation/PxUserAllocated.h"
#include "foundation/PxTransform.h"
#include "GuPrunerPayload.h"
#include "GuPrunerTypedef.h"
namespace physx
{
class PxRenderOutput;
class PxBounds3;
namespace Gu
{
class ShapeData;
struct PrunerRaycastCallback
{
PrunerRaycastCallback() {}
virtual ~PrunerRaycastCallback() {}
virtual bool invoke(PxReal& distance, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) = 0;
};
struct PrunerOverlapCallback
{
PrunerOverlapCallback() {}
virtual ~PrunerOverlapCallback() {}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) = 0;
};
class BasePruner : public PxUserAllocated
{
public:
BasePruner() {}
virtual ~BasePruner() {}
// shift the origin of the pruner objects
virtual void shiftOrigin(const PxVec3& shift) = 0;
// additional 'internal' interface
virtual void visualize(PxRenderOutput&, PxU32, PxU32) const {}
};
class Pruner : public BasePruner
{
public:
Pruner() {}
virtual ~Pruner() {}
/**
\brief Adds objects to the pruner.
\param[out] results Returned handles for added objects
\param[in] bounds Bounds of added objects. These bounds are used as-is so they should be pre-inflated if inflation is needed.
\param[in] data Payloads for added objects.
\param[in] transforms Transforms of added objects.
\param[in] count Number of objects in the arrays
\param[in] hasPruningStructure True if added objects have pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner.
\return true if success, false if internal allocation failed. The first failing add results in a INVALID_PRUNERHANDLE.
@see PxPruningStructure
*/
virtual bool addObjects(PrunerHandle* results, const PxBounds3* bounds, const PrunerPayload* data, const PxTransform* transforms, PxU32 count, bool hasPruningStructure) = 0;
/**
\brief Removes objects from the pruner.
\param[in] handles The objects to remove
\param[in] count The number of objects to remove
\param[in] removalCallback Optional callback, called for each removed object (giving access to its payload for keeping external structures in sync)
*/
virtual void removeObjects(const PrunerHandle* handles, PxU32 count, PrunerPayloadRemovalCallback* removalCallback) = 0;
/**
\brief Updates objects with new bounds & transforms.
There are two ways to use this function:
1) manual bounds update: you can manually update the bounds via "getPayloadData" calls prior to calling "updateObjects".
In this case "updateObjects" only notifies the system that the data for these objects has changed. In this mode the
"inflation", "boundsIndices", "newBounds" and "newTransforms" parameters should remain null.
2) synchronization mode: in this case the new bounds (and optionally the new transforms) have been computed by an
external source and "updateObjects" tells the system to update its data from passed buffers. The new bounds are
always inflated by the "inflation" parameter while being copied. "boundsIndices" is an optional remap table, allowing
this call to only update a subset of the existing bounds (i.e. the updated bounds don't have to be first copied to a
separate contiguous buffer).
\param[in] handles The objects to update
\param[in] count The number of objects to update
\param[in] inflation Bounds inflation value
\param[in] boundsIndices The indices of the bounds in the bounds array (or NULL)
\param[in] newBounds Updated bounds array (or NULL)
\param[in] newTransforms Updated transforms array (or NULL)
*/
virtual void updateObjects(const PrunerHandle* handles, PxU32 count, float inflation=0.0f, const PxU32* boundsIndices=NULL, const PxBounds3* newBounds=NULL, const PxTransform32* newTransforms=NULL) = 0;
/**
\brief Gets rid of internal accel struct.
*/
virtual void purge() = 0;
/**
\brief Makes the queries consistent with previous changes.
This function must be called before starting queries on an updated Pruner and assert otherwise.
*/
virtual void commit() = 0;
/**
\brief Merges pruning structure to current pruner, parameters may differ for each pruner implementation.
\param[in] mergeParams Implementation-dependent merge data
*/
virtual void merge(const void* mergeParams) = 0;
/**
* Query functions
*
* Note: return value may disappear if PrunerCallback contains the necessary information
* currently it is still used for the dynamic pruner internally (to decide if added objects must be queried)
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, PrunerRaycastCallback&) const = 0;
virtual bool overlap(const Gu::ShapeData& queryVolume, PrunerOverlapCallback&) const = 0;
virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, PrunerRaycastCallback&) const = 0;
/**
\brief Retrieves the object's payload and data associated with the handle.
This function returns the payload associated with a given handle. Additionally it can return the
destination addresses for the object's bounds & transform. The user can then write the new bounds
and transform there, before eventually calling updateObjects().
\param[in] handle Object handle (initially returned by addObjects())
\param[out] data Optional location where to store the internal data associated with the payload.
\return The payload associated with the given handle.
*/
virtual const PrunerPayload& getPayloadData(PrunerHandle handle, PrunerPayloadData* data=NULL) const = 0;
/**
\brief Preallocate space
\param[in] nbEntries The number of entries to preallocate space for
*/
virtual void preallocate(PxU32 nbEntries) = 0;
/**
\brief Sets object's transform
\note This is equivalent to retrieving the transform's address with "getPayloadData" and writing
the transform there.
\param[in] handle Object handle (initially returned by addObjects())
\param[in] transform New transform
\return True if success
*/
virtual bool setTransform(PrunerHandle handle, const PxTransform& transform) = 0;
// PT: from the SQ branch, maybe temporary, unclear if a getType() function would be better etc
virtual bool isDynamic() const { return false; }
virtual void getGlobalBounds(PxBounds3&) const = 0;
};
/**
* Pruner building accel structure over time base class
*/
class DynamicPruner : public Pruner
{
public:
/**
* sets the rebuild hint rate used for step building the accel structure.
*/
virtual void setRebuildRateHint(PxU32 nbStepsForRebuild) = 0;
/**
* Steps the accel structure build.
* synchronousCall specifies if initialization can happen. It should not initialize build when called from a different thread
* returns true if finished
*/
virtual bool buildStep(bool synchronousCall = true) = 0;
/**
* Prepares new tree build
* returns true if new tree is needed
*/
virtual bool prepareBuild() = 0;
};
}
}
#endif
| 8,983 | C | 38.403509 | 208 | 0.740176 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuCenterExtents.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_CENTER_EXTENTS_H
#define GU_CENTER_EXTENTS_H
/** \addtogroup geomutils
@{
*/
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBounds3.h"
namespace physx
{
namespace Gu
{
class CenterExtents : public physx::PxUserAllocated
{
public:
PX_FORCE_INLINE CenterExtents() {}
PX_FORCE_INLINE CenterExtents(const PxBounds3& b) { mCenter = b.getCenter(); mExtents = b.getExtents(); }
PX_FORCE_INLINE ~CenterExtents() {}
PX_FORCE_INLINE void getMin(PxVec3& min) const { min = mCenter - mExtents; }
PX_FORCE_INLINE void getMax(PxVec3& max) const { max = mCenter + mExtents; }
PX_FORCE_INLINE float getMin(PxU32 axis) const { return mCenter[axis] - mExtents[axis]; }
PX_FORCE_INLINE float getMax(PxU32 axis) const { return mCenter[axis] + mExtents[axis]; }
PX_FORCE_INLINE PxVec3 getMin() const { return mCenter - mExtents; }
PX_FORCE_INLINE PxVec3 getMax() const { return mCenter + mExtents; }
PX_FORCE_INLINE void setMinMax(const PxVec3& min, const PxVec3& max)
{
mCenter = (max + min)*0.5f;
mExtents = (max - min)*0.5f;
}
PX_FORCE_INLINE PxU32 isInside(const CenterExtents& box) const
{
if(box.getMin(0)>getMin(0)) return 0;
if(box.getMin(1)>getMin(1)) return 0;
if(box.getMin(2)>getMin(2)) return 0;
if(box.getMax(0)<getMax(0)) return 0;
if(box.getMax(1)<getMax(1)) return 0;
if(box.getMax(2)<getMax(2)) return 0;
return 1;
}
PX_FORCE_INLINE void setEmpty()
{
mExtents = PxVec3(-PX_MAX_BOUNDS_EXTENTS);
}
PX_FORCE_INLINE bool isEmpty() const
{
PX_ASSERT(isValid());
return mExtents.x<0.0f;
}
PX_FORCE_INLINE bool isFinite() const
{
return mCenter.isFinite() && mExtents.isFinite();
}
PX_FORCE_INLINE bool isValid() const
{
const PxVec3& c = mCenter;
const PxVec3& e = mExtents;
return (c.isFinite() && e.isFinite() && (((e.x >= 0.0f) && (e.y >= 0.0f) && (e.z >= 0.0f)) ||
((e.x == -PX_MAX_BOUNDS_EXTENTS) &&
(e.y == -PX_MAX_BOUNDS_EXTENTS) &&
(e.z == -PX_MAX_BOUNDS_EXTENTS))));
}
PX_FORCE_INLINE PxBounds3 transformFast(const PxMat33& matrix) const
{
PX_ASSERT(isValid());
return PxBounds3::basisExtent(matrix * mCenter, matrix, mExtents);
}
PxVec3 mCenter;
PxVec3 mExtents;
};
//! A padded version of CenterExtents, to safely load its data using SIMD
class CenterExtentsPadded : public CenterExtents
{
public:
PX_FORCE_INLINE CenterExtentsPadded() {}
PX_FORCE_INLINE ~CenterExtentsPadded() {}
PxU32 padding;
};
PX_COMPILE_TIME_ASSERT(sizeof(CenterExtentsPadded) == 7*4);
}
}
/** @} */
#endif
| 4,614 | C | 35.054687 | 110 | 0.653446 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionBoxBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_BOX_BOX_H
#define GU_INTERSECTION_BOX_BOX_H
#include "foundation/PxMat33.h"
#include "foundation/PxBounds3.h"
#include "GuBox.h"
namespace physx
{
namespace Gu
{
PX_PHYSX_COMMON_API bool intersectOBBOBB(const PxVec3& e0, const PxVec3& c0, const PxMat33& r0, const PxVec3& e1, const PxVec3& c1, const PxMat33& r1, bool full_test);
PX_FORCE_INLINE bool intersectOBBAABB(const Gu::Box& obb, const PxBounds3& aabb)
{
PxVec3 center = aabb.getCenter();
PxVec3 extents = aabb.getExtents();
return intersectOBBOBB(obb.extents, obb.center, obb.rot, extents, center, PxMat33(PxIdentity), true);
}
} // namespace Gu
}
#endif
| 2,352 | C | 42.574073 | 168 | 0.758503 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuDistanceSegmentSegment.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_SEGMENT_H
#define GU_DISTANCE_SEGMENT_SEGMENT_H
#include "common/PxPhysXCommonConfig.h"
#include "GuSegment.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
// This version fixes accuracy issues (e.g. TTP 4617), but needs to do 2 square roots in order
// to find the normalized direction and length of the segments, and then
// a division in order to renormalize the output
PX_PHYSX_COMMON_API PxReal distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& dir0, PxReal extent0,
const PxVec3& origin1, const PxVec3& dir1, PxReal extent1,
PxReal* s=NULL, PxReal* t=NULL);
PX_PHYSX_COMMON_API PxReal distanceSegmentSegmentSquared( const PxVec3& origin0, const PxVec3& extent0,
const PxVec3& origin1, const PxVec3& extent1,
PxReal* s=NULL, PxReal* t=NULL);
PX_FORCE_INLINE PxReal distanceSegmentSegmentSquared( const Gu::Segment& segment0,
const Gu::Segment& segment1,
PxReal* s=NULL, PxReal* t=NULL)
{
return distanceSegmentSegmentSquared( segment0.p0, segment0.computeDirection(),
segment1.p0, segment1.computeDirection(),
s, t);
}
PX_PHYSX_COMMON_API aos::FloatV distanceSegmentSegmentSquared( const aos::Vec3VArg p1, const aos::Vec3VArg d1, const aos::Vec3VArg p2, const aos::Vec3VArg d2,
aos::FloatV& param0,
aos::FloatV& param1);
// This function do four segment segment closest point test in one go
aos::Vec4V distanceSegmentSegmentSquared4( const aos::Vec3VArg p, const aos::Vec3VArg d,
const aos::Vec3VArg p02, const aos::Vec3VArg d02,
const aos::Vec3VArg p12, const aos::Vec3VArg d12,
const aos::Vec3VArg p22, const aos::Vec3VArg d22,
const aos::Vec3VArg p32, const aos::Vec3VArg d32,
aos::Vec4V& s, aos::Vec4V& t);
} // namespace Gu
}
#endif
| 3,643 | C | 46.324675 | 159 | 0.721383 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTetrahedronBox.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TETRAHEDRON_BOX_H
#define GU_INTERSECTION_TETRAHEDRON_BOX_H
#include "foundation/PxVec3.h"
#include "foundation/PxBounds3.h"
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Gu
{
class Box;
class BoxPadded;
/**
Tests if a tetrahedron overlaps a box (AABB).
\param a [in] tetrahedron's first point
\param b [in] tetrahedron's second point
\param c [in] tetrahedron's third point
\param d [in] tetrahedron's fourth point
\param box [in] The axis aligned box box to check for overlap
\return true if tetrahedron overlaps box
*/
PX_PHYSX_COMMON_API bool intersectTetrahedronBox(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d, const PxBounds3& box);
} // namespace Gu
}
#endif
| 2,452 | C | 39.883333 | 140 | 0.760196 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuIntersectionTriangleBoxRef.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef GU_INTERSECTION_TRIANGLE_BOX_REF_H
#define GU_INTERSECTION_TRIANGLE_BOX_REF_H
#include "foundation/PxVec3.h"
/********************************************************/
/* AABB-triangle overlap test code */
/* by Tomas Akenine-M?r */
/* Function: int triBoxOverlap(float boxcenter[3], */
/* float boxhalfsize[3],float triverts[3][3]); */
/* History: */
/* 2001-03-05: released the code in its first version */
/* 2001-06-18: changed the order of the tests, faster */
/* */
/* Acknowledgement: Many thanks to Pierre Terdiman for */
/* suggestions and discussions on how to optimize code. */
/* Thanks to David Hunt for finding a ">="-bug! */
/********************************************************/
namespace physx
{
#define CROSS(dest,v1,v2) \
dest.x=v1.y*v2.z-v1.z*v2.y; \
dest.y=v1.z*v2.x-v1.x*v2.z; \
dest.z=v1.x*v2.y-v1.y*v2.x;
#define DOT(v1,v2) (v1.x*v2.x+v1.y*v2.y+v1.z*v2.z)
#define FINDMINMAX(x0, x1, x2, minimum, maximum) \
minimum = physx::intrinsics::selectMin(x0, x1); \
maximum = physx::intrinsics::selectMax(x0, x1); \
minimum = physx::intrinsics::selectMin(minimum, x2); \
maximum = physx::intrinsics::selectMax(maximum, x2);
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxIntBool planeBoxOverlap(const PxVec3& normal, PxReal d, const PxVec3& maxbox)
{
PxVec3 vmin, vmax;
if (normal.x>0.0f)
{
vmin.x = -maxbox.x;
vmax.x = maxbox.x;
}
else
{
vmin.x = maxbox.x;
vmax.x = -maxbox.x;
}
if (normal.y>0.0f)
{
vmin.y = -maxbox.y;
vmax.y = maxbox.y;
}
else
{
vmin.y = maxbox.y;
vmax.y = -maxbox.y;
}
if (normal.z>0.0f)
{
vmin.z = -maxbox.z;
vmax.z = maxbox.z;
}
else
{
vmin.z = maxbox.z;
vmax.z = -maxbox.z;
}
if(normal.dot(vmin) + d > 0.0f)
return PxIntFalse;
if(normal.dot(vmax) + d >= 0.0f)
return PxIntTrue;
return PxIntFalse;
}
/*======================== X-tests ========================*/
#define AXISTEST_X01(a, b, fa, fb) \
p0 = a*v0.y - b*v0.z; \
p2 = a*v2.y - b*v2.z; \
minimum = physx::intrinsics::selectMin(p0, p2); \
maximum = physx::intrinsics::selectMax(p0, p2); \
rad = fa * extents.y + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_X2(a, b, fa, fb) \
p0 = a*v0.y - b*v0.z; \
p1 = a*v1.y - b*v1.z; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.y + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
/*======================== Y-tests ========================*/
#define AXISTEST_Y02(a, b, fa, fb) \
p0 = -a*v0.x + b*v0.z; \
p2 = -a*v2.x + b*v2.z; \
minimum = physx::intrinsics::selectMin(p0, p2); \
maximum = physx::intrinsics::selectMax(p0, p2); \
rad = fa * extents.x + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_Y1(a, b, fa, fb) \
p0 = -a*v0.x + b*v0.z; \
p1 = -a*v1.x + b*v1.z; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.x + fb * extents.z; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
/*======================== Z-tests ========================*/
#define AXISTEST_Z12(a, b, fa, fb) \
p1 = a*v1.x - b*v1.y; \
p2 = a*v2.x - b*v2.y; \
minimum = physx::intrinsics::selectMin(p1, p2); \
maximum = physx::intrinsics::selectMax(p1, p2); \
rad = fa * extents.x + fb * extents.y; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
#define AXISTEST_Z0(a, b, fa, fb) \
p0 = a*v0.x - b*v0.y; \
p1 = a*v1.x - b*v1.y; \
minimum = physx::intrinsics::selectMin(p0, p1); \
maximum = physx::intrinsics::selectMax(p0, p1); \
rad = fa * extents.x + fb * extents.y; \
if(minimum>rad || maximum<-rad) return PxIntFalse;
namespace Gu
{
template <const bool bDoVertexChecks = false>
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxIntBool intersectTriangleBox_RefImpl(const PxVec3& boxcenter, const PxVec3& extents, const PxVec3& tp0, const PxVec3& tp1, const PxVec3& tp2)
{
/* use separating axis theorem to test overlap between triangle and box */
/* need to test for overlap in these directions: */
/* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
/* we do not even need to test these) */
/* 2) normal of the triangle */
/* 3) crossproduct(edge from tri, {x,y,z}-directin) */
/* this gives 3x3=9 more tests */
// This is the fastest branch on Sun - move everything so that the boxcenter is in (0,0,0)
const PxVec3 v0 = tp0 - boxcenter;
const PxVec3 v1 = tp1 - boxcenter;
const PxVec3 v2 = tp2 - boxcenter;
if (bDoVertexChecks)
{
if (PxAbs(v0.x) <= extents.x && PxAbs(v0.y) <= extents.y && PxAbs(v0.z) <= extents.z)
return PxIntTrue;
if (PxAbs(v1.x) <= extents.x && PxAbs(v1.y) <= extents.y && PxAbs(v1.z) <= extents.z)
return PxIntTrue;
if (PxAbs(v2.x) <= extents.x && PxAbs(v2.y) <= extents.y && PxAbs(v2.z) <= extents.z)
return PxIntTrue;
}
// compute triangle edges
const PxVec3 e0 = v1 - v0; // tri edge 0
const PxVec3 e1 = v2 - v1; // tri edge 1
const PxVec3 e2 = v0 - v2; // tri edge 2
float minimum, maximum, rad, p0, p1, p2;
// Bullet 3: test the 9 tests first (this was faster)
float fex = PxAbs(e0.x);
float fey = PxAbs(e0.y);
float fez = PxAbs(e0.z);
AXISTEST_X01(e0.z, e0.y, fez, fey);
AXISTEST_Y02(e0.z, e0.x, fez, fex);
AXISTEST_Z12(e0.y, e0.x, fey, fex);
fex = PxAbs(e1.x);
fey = PxAbs(e1.y);
fez = PxAbs(e1.z);
AXISTEST_X01(e1.z, e1.y, fez, fey);
AXISTEST_Y02(e1.z, e1.x, fez, fex);
AXISTEST_Z0(e1.y, e1.x, fey, fex);
fex = PxAbs(e2.x);
fey = PxAbs(e2.y);
fez = PxAbs(e2.z);
AXISTEST_X2(e2.z, e2.y, fez, fey);
AXISTEST_Y1(e2.z, e2.x, fez, fex);
AXISTEST_Z12(e2.y, e2.x, fey, fex);
// Bullet 1:
// first test overlap in the {x,y,z}-directions
// find minimum, maximum of the triangle each direction, and test for overlap in
// that direction -- this is equivalent to testing a minimal AABB around
// the triangle against the AABB
// test in X-direction
FINDMINMAX(v0.x, v1.x, v2.x, minimum, maximum);
if(minimum>extents.x || maximum<-extents.x)
return PxIntFalse;
// test in Y-direction
FINDMINMAX(v0.y, v1.y, v2.y, minimum, maximum);
if(minimum>extents.y || maximum<-extents.y)
return PxIntFalse;
// test in Z-direction
FINDMINMAX(v0.z, v1.z, v2.z, minimum, maximum);
if(minimum>extents.z || maximum<-extents.z)
return PxIntFalse;
// Bullet 2:
// test if the box intersects the plane of the triangle
// compute plane equation of triangle: normal*x+d=0
PxVec3 normal;
CROSS(normal, e0, e1);
const float d = -DOT(normal, v0); // plane eq: normal.x+d=0
if(!planeBoxOverlap(normal, d, extents))
return PxIntFalse;
return PxIntTrue; // box and triangle overlaps
}
}
#undef CROSS
#undef DOT
#undef FINDMINMAX
#undef AXISTEST_X01
#undef AXISTEST_X2
#undef AXISTEST_Y02
#undef AXISTEST_Y1
#undef AXISTEST_Z12
#undef AXISTEST_Z0
}
#endif
| 9,123 | C | 33.560606 | 185 | 0.612737 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuFactory.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_FACTORY_H
#define GU_FACTORY_H
#include "foundation/PxSimpleTypes.h"
#include "common/PxPhysXCommonConfig.h"
#include "GuPrunerTypedef.h"
namespace physx
{
namespace Gu
{
class Pruner;
PX_C_EXPORT PX_PHYSX_COMMON_API Gu::Pruner* createBucketPruner(PxU64 contextID);
PX_C_EXPORT PX_PHYSX_COMMON_API Gu::Pruner* createAABBPruner(PxU64 contextID, bool dynamic, Gu::CompanionPrunerType type, Gu::BVHBuildStrategy buildStrategy, PxU32 nbObjectsPerNode);
PX_C_EXPORT PX_PHYSX_COMMON_API Gu::Pruner* createIncrementalPruner(PxU64 contextID);
}
}
#endif
| 2,263 | C | 45.204081 | 183 | 0.771984 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPrunerTypedef.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_PRUNER_TYPEDEF_H
#define GU_PRUNER_TYPEDEF_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
namespace Gu
{
typedef PxU32 PrunerHandle;
static const PrunerHandle INVALID_PRUNERHANDLE = 0xffffffff;
typedef PxU32 PoolIndex;
static const PxU32 INVALID_POOL_ID = 0xffffffff;
typedef PxU32 TreeNodeIndex;
static const PxU32 INVALID_NODE_ID = 0xffffffff;
enum CompanionPrunerType
{
COMPANION_PRUNER_NONE,
COMPANION_PRUNER_BUCKET,
COMPANION_PRUNER_INCREMENTAL,
COMPANION_PRUNER_AABB_TREE
};
enum BVHBuildStrategy
{
BVH_SPLATTER_POINTS,
BVH_SPLATTER_POINTS_SPLIT_GEOM_CENTER,
BVH_SAH
};
}
}
#endif
| 2,362 | C | 35.353846 | 74 | 0.759102 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuPrunerMergeData.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_PRUNER_MERGE_DATA_H
#define GU_PRUNER_MERGE_DATA_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
namespace physx
{
namespace Gu
{
struct BVHNode;
// PT: TODO: refactor with BVHCoreData ?
struct AABBPrunerMergeData
{
AABBPrunerMergeData()
{
// PT: it's important to NOT initialize anything by default (for binary serialization)
}
PxU32 mNbNodes; // Nb nodes in AABB tree
BVHNode* mAABBTreeNodes; // AABB tree runtime nodes
PxU32 mNbObjects; // Nb objects in AABB tree
PxU32* mAABBTreeIndices; // AABB tree indices
void init(PxU32 nbNodes=0, BVHNode* nodes=NULL, PxU32 nbObjects=0, PxU32* indices=NULL)
{
mNbNodes = nbNodes;
mAABBTreeNodes = nodes;
mNbObjects = nbObjects;
mAABBTreeIndices = indices;
}
};
}
}
/** @} */
#endif
| 2,537 | C | 36.880596 | 90 | 0.735514 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuDistancePointTriangle.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_TRIANGLE_H
#define GU_DISTANCE_POINT_TRIANGLE_H
#include "foundation/PxVec3.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Gu
{
// PT: special version:
// - inlined
// - doesn't compute (s,t) output params
// - expects precomputed edges in input
PX_FORCE_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTriangle2(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& ab, const PxVec3& ac)
{
// 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)
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)
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);
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)
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);
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));
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;
return a + ab*v + ac*w;
}
//Scales and translates triangle and query points to fit into the unit box to make calculations less prone to numerical cancellation.
//The returned point will still be in the same space as the input points.
PX_FORCE_INLINE PX_CUDA_CALLABLE PxVec3 closestPtPointTriangle2UnitBox(const PxVec3& queryPoint, const PxVec3& triA, const PxVec3& triB, const PxVec3& triC)
{
const PxVec3 min = queryPoint.minimum(triA.minimum(triB.minimum(triC)));
const PxVec3 max = queryPoint.maximum(triA.maximum(triB.maximum(triC)));
const PxVec3 size = max - min;
PxReal invScaling = PxMax(PxMax(size.x, size.y), PxMax(1e-12f, size.z));
PxReal scaling = 1.0f / invScaling;
PxVec3 p = (queryPoint - min) * scaling;
PxVec3 a = (triA - min) * scaling;
PxVec3 b = (triB - min) * scaling;
PxVec3 c = (triC - min) * scaling;
PxVec3 result = closestPtPointTriangle2(p, a, b, c, b - a, c - a);
return result * invScaling + min;
}
PX_PHYSX_COMMON_API PxVec3 closestPtPointTriangle(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& s, float& t);
PX_FORCE_INLINE PxReal distancePointTriangleSquared(const PxVec3& point,
const PxVec3& triangleOrigin, const PxVec3& triangleEdge0, const PxVec3& triangleEdge1,
PxReal* param0=NULL, PxReal* param1=NULL)
{
const PxVec3 pt0 = triangleEdge0 + triangleOrigin;
const PxVec3 pt1 = triangleEdge1 + triangleOrigin;
float s,t;
const PxVec3 cp = closestPtPointTriangle(point, triangleOrigin, pt0, pt1, s, t);
if(param0)
*param0 = s;
if(param1)
*param1 = t;
return (cp - point).magnitudeSquared();
}
PX_PHYSX_COMMON_API aos::FloatV distancePointTriangleSquared( const aos::Vec3VArg point,
const aos::Vec3VArg a,
const aos::Vec3VArg b,
const aos::Vec3VArg c,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP);
//Scales and translates triangle and query points to fit into the unit box to make calculations less prone to numerical cancellation.
//The returned point and squared distance will still be in the same space as the input points.
PX_PHYSX_COMMON_API aos::FloatV distancePointTriangleSquared2UnitBox(
const aos::Vec3VArg point,
const aos::Vec3VArg a,
const aos::Vec3VArg b,
const aos::Vec3VArg c,
aos::FloatV& u,
aos::FloatV& v,
aos::Vec3V& closestP);
} // namespace Gu
}
#endif
| 6,285 | C | 38.043478 | 168 | 0.684964 |
NVIDIA-Omniverse/PhysX/physx/source/geomutils/include/GuBounds.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_BOUNDS_H
#define GU_BOUNDS_H
#include "foundation/PxBounds3.h"
#include "foundation/PxFlags.h"
#include "foundation/PxVecMath.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include <stddef.h>
#include "GuBox.h"
#include "GuCenterExtents.h"
#include "GuSphere.h"
#include "GuCapsule.h"
// PT: the PX_MAX_BOUNDS_EXTENTS value is too large and produces INF floats when the box values are squared in
// some collision routines. Thus, for the SQ subsystem we use this alternative (smaller) value to mark empty bounds.
// See PX-954 for details.
#define GU_EMPTY_BOUNDS_EXTENTS PxSqrt(0.25f * 1e33f)
namespace physx
{
class PxMeshScale;
namespace Gu
{
PX_FORCE_INLINE void computeCapsuleBounds(PxBounds3& bounds, const PxCapsuleGeometry& capsuleGeom, const PxTransform& pose, float contactOffset=0.0f, float inflation=1.0f)
{
const PxVec3 d = pose.q.getBasisVector0();
PxVec3 extents;
for(PxU32 ax = 0; ax<3; ax++)
extents[ax] = (PxAbs(d[ax]) * capsuleGeom.halfHeight + capsuleGeom.radius + contactOffset)*inflation;
bounds.minimum = pose.p - extents;
bounds.maximum = pose.p + extents;
}
//'contactOffset' and 'inflation' should not be used at the same time, i.e. either contactOffset==0.0f, or inflation==1.0f
PX_PHYSX_COMMON_API void computeBounds(PxBounds3& bounds, const PxGeometry& geometry, const PxTransform& transform, float contactOffset, float inflation); //AABB in world space.
PX_FORCE_INLINE PxBounds3 computeBounds(const PxGeometry& geometry, const PxTransform& pose)
{
PxBounds3 bounds;
computeBounds(bounds, geometry, pose, 0.0f, 1.0f);
return bounds;
}
void computeGlobalBox(PxBounds3& bounds, PxU32 nbPrims, const PxBounds3* PX_RESTRICT boxes, const PxU32* PX_RESTRICT primitives);
PX_PHYSX_COMMON_API void computeBoundsAroundVertices(PxBounds3& bounds, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts);
PX_PHYSX_COMMON_API void computeTightBounds(PxBounds3& bounds, PxU32 nbVerts, const PxVec3* PX_RESTRICT verts, const PxTransform& pose, const PxMeshScale& scale, float contactOffset, float inflation);
PX_PHYSX_COMMON_API void computeLocalBoundsAndGeomEpsilon(const PxVec3* vertices, PxU32 nbVerties, PxBounds3& localBounds, PxReal& geomEpsilon);
#define StoreBounds(bounds, minV, maxV) \
V4StoreU(minV, &bounds.minimum.x); \
PX_ALIGN(16, PxVec4) max4; \
V4StoreA(maxV, &max4.x); \
bounds.maximum = PxVec3(max4.x, max4.y, max4.z);
// PT: TODO: - refactor with "inflateBounds" in GuBounds.cpp if possible
template<const bool useSIMD>
PX_FORCE_INLINE void inflateBounds(PxBounds3& dst, const PxBounds3& src, float enlargement)
{
const float coeff = 0.5f * enlargement;
if(useSIMD)
{
using namespace physx::aos;
Vec4V minV = V4LoadU(&src.minimum.x);
Vec4V maxV = V4LoadU(&src.maximum.x);
const Vec4V eV = V4Scale(V4Sub(maxV, minV), FLoad(coeff));
minV = V4Sub(minV, eV);
maxV = V4Add(maxV, eV);
StoreBounds(dst, minV, maxV);
}
else
{
// PT: this clumsy but necessary second codepath is used to read the last bound of the array
// (making sure we don't V4LoadU invalid memory). Implementation must stay in sync with the
// main codepath above. No, this is not very nice.
const PxVec3& minV = src.minimum;
const PxVec3& maxV = src.maximum;
const PxVec3 eV = (maxV - minV) * coeff;
dst.minimum = minV - eV;
dst.maximum = maxV + eV;
}
}
class ShapeData
{
public:
PX_PHYSX_COMMON_API ShapeData(const PxGeometry& g, const PxTransform& t, PxReal inflation);
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxVec3& getPrunerBoxGeomExtentsInflated() const { return mPrunerBoxGeomExtents; }
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxVec3& getPrunerWorldPos() const { return mGuBox.center; }
PX_FORCE_INLINE const PxBounds3& getPrunerInflatedWorldAABB() const { return mPrunerInflatedAABB; }
// PT: used by overlaps (box, capsule, convex)
PX_FORCE_INLINE const PxMat33& getPrunerWorldRot33() const { return mGuBox.rot; }
// PT: this one only used by overlaps so far (for sphere shape, pruner level)
PX_FORCE_INLINE const Gu::Sphere& getGuSphere() const
{
PX_ASSERT(mType == PxGeometryType::eSPHERE);
return reinterpret_cast<const Gu::Sphere&>(mGuSphere);
}
// PT: this one only used by sweeps so far (for box shape, NP level)
PX_FORCE_INLINE const Gu::Box& getGuBox() const
{
PX_ASSERT(mType == PxGeometryType::eBOX);
return mGuBox;
}
// PT: this one used by sweeps (NP level) and overlaps (pruner level) - for capsule shape
PX_FORCE_INLINE const Gu::Capsule& getGuCapsule() const
{
PX_ASSERT(mType == PxGeometryType::eCAPSULE);
return reinterpret_cast<const Gu::Capsule&>(mGuCapsule);
}
PX_FORCE_INLINE float getCapsuleHalfHeight() const
{
PX_ASSERT(mType == PxGeometryType::eCAPSULE);
return mGuBox.extents.x;
}
PX_FORCE_INLINE PxU32 isOBB() const { return PxU32(mIsOBB); }
PX_FORCE_INLINE PxGeometryType::Enum getType() const { return PxGeometryType::Enum(mType); }
PX_NOCOPY(ShapeData)
private:
// PT: box: pre-inflated box extents
// capsule: pre-inflated extents of box-around-capsule
// convex: pre-inflated extents of box-around-convex
// sphere: not used
PxVec3 mPrunerBoxGeomExtents; // used for pruners. This volume encloses but can differ from the original shape
// PT:
//
// box center = unchanged copy of initial shape's position, except for convex (position of box around convex)
// SIMD code will load it as a V4 (safe because member is not last of Gu structure)
//
// box rot = precomputed PxMat33 version of initial shape's rotation, except for convex (rotation of box around convex)
// SIMD code will load it as V4s (safe because member is not last of Gu structure)
//
// box extents = non-inflated initial box extents for box shape, half-height for capsule, otherwise not used
Gu::Box mGuBox;
PxBounds3 mPrunerInflatedAABB; // precomputed AABB for the pruner shape
PxU16 mIsOBB; // true for OBB, false for AABB. Also used as padding for mPrunerInflatedAABB, don't move.
PxU16 mType; // shape's type
// these union Gu shapes are only precomputed for narrow phase (not pruners), can be different from mPrunerVolume
// so need separate storage
union
{
PxU8 mGuCapsule[sizeof(Gu::Capsule)]; // 28
PxU8 mGuSphere[sizeof(Gu::Sphere)]; // 16
};
};
// PT: please make sure it fits in "one" cache line
PX_COMPILE_TIME_ASSERT(sizeof(ShapeData)==128);
} // namespace Gu
}
#endif
| 8,329 | C | 39.833333 | 201 | 0.728419 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleDriveNW.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 "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleSDK.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "PxScene.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "foundation/PxUtilities.h"
#include "CmUtils.h"
namespace physx
{
extern PxF32 gToleranceScaleLength;
void PxVehicleDriveSimDataNW::setDiffData(const PxVehicleDifferentialNWData& diff)
{
PX_CHECK_AND_RETURN(diff.isValid(), "Invalid PxVehicleCoreSimulationData.mDiff");
mDiff=diff;
}
bool PxVehicleDriveSimDataNW::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mDiff.isValid(), "Invalid PxVehicleDifferentialNWData", false);
PX_CHECK_AND_RETURN_VAL(PxVehicleDriveSimData::isValid(), "Invalid PxVehicleDriveSimDataNW", false);
return true;
}
///////////////////////////////////
bool PxVehicleDriveNW::isValid() const
{
PX_CHECK_AND_RETURN_VAL(PxVehicleDrive::isValid(), "invalid PxVehicleDrive", false);
PX_CHECK_AND_RETURN_VAL(mDriveSimData.isValid(), "Invalid PxVehicleNW.mCoreSimData", false);
return true;
}
PxVehicleDriveNW* PxVehicleDriveNW::allocate(const PxU32 numWheels)
{
PX_CHECK_AND_RETURN_NULL(numWheels>0, "Cars with zero wheels are illegal");
PX_CHECK_AND_RETURN_NULL(gToleranceScaleLength > 0, "PxVehicleDriveNW::allocate - need to call PxInitVehicleSDK");
//Compute the bytes needed.
const PxU32 byteSize = sizeof(PxVehicleDriveNW) + PxVehicleDrive::computeByteSize(numWheels);
//Allocate the memory.
PxVehicleDriveNW* veh = static_cast<PxVehicleDriveNW*>(PX_ALLOC(byteSize, "PxVehicleDriveNW"));
PxMarkSerializedMemory(veh, byteSize);
PX_PLACEMENT_NEW(veh, PxVehicleDriveNW());
//Patch up the pointers.
PxU8* ptr = reinterpret_cast<PxU8*>(veh) + sizeof(PxVehicleDriveNW);
ptr=PxVehicleDrive::patchupPointers(numWheels, veh, ptr);
//Initialise
veh->init(numWheels);
//Set the vehicle type.
veh->mType = PxVehicleTypes::eDRIVENW;
return veh;
}
void PxVehicleDriveNW::free()
{
PxVehicleDrive::free();
}
void PxVehicleDriveNW::setup
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 numWheels)
{
PX_CHECK_AND_RETURN(driveData.isValid(), "PxVehicleDriveNW::setup - invalid driveData");
//Set up the wheels.
PxVehicleDrive::setup(physics,vehActor,wheelsData,numWheels,0);
//Start setting up the drive.
PX_CHECK_MSG(driveData.isValid(), "PxVehicleNWDrive - invalid driveData");
//Copy the simulation data.
mDriveSimData = driveData;
}
PxVehicleDriveNW* PxVehicleDriveNW::create
(PxPhysics* physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
const PxU32 numWheels)
{
PxVehicleDriveNW* vehNW=PxVehicleDriveNW::allocate(numWheels);
vehNW->setup(physics,vehActor,wheelsData,driveData,numWheels);
return vehNW;
}
void PxVehicleDriveNW::setToRestState()
{
//Set core to rest state.
PxVehicleDrive::setToRestState();
}
} //namespace physx
| 4,743 | C++ | 31.49315 | 115 | 0.767236 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleUpdate.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/PxQuat.h"
#include "foundation/PxBitMap.h"
#include "common/PxProfileZone.h"
#include "common/PxTolerancesScale.h"
#include "vehicle/PxVehicleUpdate.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveNW.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "extensions/PxRigidBodyExt.h"
#include "extensions/PxSceneQueryExt.h"
#include "PxShape.h"
#include "PxRigidDynamic.h"
#include "PxMaterial.h"
#include "PxContactModifyCallback.h"
#include "PxScene.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleLinearMath.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxFPU.h"
#include "CmUtils.h"
using namespace physx;
using namespace Cm;
//TODO: lsd - handle case where wheels are spinning in different directions.
//TODO: ackermann - use faster approximate functions for PxTan/PxATan because the results don't need to be too accurate here.
//TODO: tire lat slip - do we really use PxAbs(vz) as denominator, that's not in the paper?
//TODO: toe vs jounce table.
//TODO: pneumatic trail.
//TODO: we probably need to have a graphics jounce and a physics jounce and
//TODO: expose sticky friction values in api.
//TODO: blend the graphics jounce towards the physics jounce to avoid graphical pops at kerbs etc.
//TODO: better graph of friction vs slip. Need to account for negative slip and positive slip differences.
namespace physx
{
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetBasisVectors
////////////////////////////////////////////////////////////////////////////
static PxVehicleContext gVehicleContextDefault;
void PxVehicleSetBasisVectors(const PxVec3& up, const PxVec3& forward)
{
gVehicleContextDefault.upAxis = up;
gVehicleContextDefault.forwardAxis = forward;
gVehicleContextDefault.computeSideAxis();
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetUpdateMode
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetUpdateMode(PxVehicleUpdateMode::Enum vehicleUpdateMode)
{
gVehicleContextDefault.updateMode = vehicleUpdateMode;
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetSweepHitRejectionAngles
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetSweepHitRejectionAngles(const PxF32 pointRejectAngle, const PxF32 normalRejectAngle)
{
PX_CHECK_AND_RETURN(pointRejectAngle > 0.0f && pointRejectAngle < PxPi, "PxVehicleSetSweepHitRejectionAngles - pointRejectAngle must be in range (0, Pi)");
PX_CHECK_AND_RETURN(normalRejectAngle > 0.0f && normalRejectAngle < PxPi, "PxVehicleSetSweepHitRejectionAngles - normalRejectAngle must be in range (0, Pi)");
gVehicleContextDefault.pointRejectAngleThresholdCosine = PxCos(pointRejectAngle);
gVehicleContextDefault.normalRejectAngleThresholdCosine = PxCos(normalRejectAngle);
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleSetSweepHitRejectionAngles
////////////////////////////////////////////////////////////////////////////
void PxVehicleSetMaxHitActorAcceleration(const PxF32 maxHitActorAcceleration)
{
PX_CHECK_AND_RETURN(maxHitActorAcceleration >= 0.0f, "PxVehicleSetMaxHitActorAcceleration - maxHitActorAcceleration must be greater than or equal to zero");
gVehicleContextDefault.maxHitActorAcceleration = maxHitActorAcceleration;
}
////////////////////////////////////////////////////////////////////////////
//Implementation of public api function PxVehicleGetDefaultContext
////////////////////////////////////////////////////////////////////////////
const PxVehicleContext& PxVehicleGetDefaultContext()
{
return gVehicleContextDefault;
}
////////////////////////////////////////////////////////////////////////////
//Set all defaults from PxVehicleInitSDK
////////////////////////////////////////////////////////////////////////////
void setVehicleDefaults()
{
gVehicleContextDefault.setToDefault();
}
////////////////////////////////////////////////////////////////////////////
//Called from PxVehicleInitSDK/PxCloseVehicleSDK
////////////////////////////////////////////////////////////////////////////
//***********************
PxF32 gThresholdForwardSpeedForWheelAngleIntegration=0;
PxF32 gRecipThresholdForwardSpeedForWheelAngleIntegration=0;
PxF32 gMinLatSpeedForTireModel=0;
PxF32 gStickyTireFrictionThresholdSpeed=0;
PxF32 gToleranceScaleLength=0;
PxF32 gMinimumSlipThreshold=0;
void setVehicleToleranceScale(const PxTolerancesScale& ts)
{
gThresholdForwardSpeedForWheelAngleIntegration=5.0f*ts.length;
gRecipThresholdForwardSpeedForWheelAngleIntegration=1.0f/gThresholdForwardSpeedForWheelAngleIntegration;
gMinLatSpeedForTireModel=1.0f*ts.length;
gStickyTireFrictionThresholdSpeed=0.2f*ts.length;
gToleranceScaleLength=ts.length;
gMinimumSlipThreshold = 1e-5f;
}
void resetVehicleToleranceScale()
{
gThresholdForwardSpeedForWheelAngleIntegration=0;
gRecipThresholdForwardSpeedForWheelAngleIntegration=0;
gMinLatSpeedForTireModel=0;
gStickyTireFrictionThresholdSpeed=0;
gToleranceScaleLength=0;
gMinimumSlipThreshold=0;
}
//***********************
const PxSerializationRegistry* gSerializationRegistry=NULL;
void setSerializationRegistryPtr(const PxSerializationRegistry* sr)
{
gSerializationRegistry = sr;
}
const PxSerializationRegistry* resetSerializationRegistryPtr()
{
const PxSerializationRegistry* tmp = gSerializationRegistry;
gSerializationRegistry = NULL;
return tmp;
}
////////////////////////////////////////////////////////////////////////////
//Global values used to trigger and control sticky tire friction constraints.
////////////////////////////////////////////////////////////////////////////
const PxF32 gStickyTireFrictionForwardDamping=0.01f;
const PxF32 gStickyTireFrictionSideDamping=0.1f;
const PxF32 gLowForwardSpeedThresholdTime=1.0f;
const PxF32 gLowSideSpeedThresholdTime=1.0f;
////////////////////////////////////////////////////////////////////////////
//Global values used to control max iteration count if estimate mode is chosen
////////////////////////////////////////////////////////////////////////////
const PxF32 gSolverTolerance = 1e-10f;
////////////////////////////////////////////////////////////////////////////
//Compute the sprung masses that satisfy the centre of mass and sprung mass coords.
////////////////////////////////////////////////////////////////////////////
#define DETERMINANT_THRESHOLD (1e-6f)
void computeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxVec3& centreOfMass, const PxReal totalMass, const PxU32 gravityDirection, PxReal* sprungMasses)
{
#if PX_CHECKED
PX_CHECK_AND_RETURN(numSprungMasses > 0, "PxVehicleComputeSprungMasses: numSprungMasses must be greater than zero");
PX_CHECK_AND_RETURN(numSprungMasses <= PX_MAX_NB_WHEELS, "PxVehicleComputeSprungMasses: numSprungMasses must be less than or equal to 20");
for(PxU32 i=0;i<numSprungMasses;i++)
{
PX_CHECK_AND_RETURN(sprungMassCoordinates[i].isFinite(), "PxVehicleComputeSprungMasses: sprungMassCoordinates must all be valid coordinates");
}
PX_CHECK_AND_RETURN(totalMass > 0.0f, "PxVehicleComputeSprungMasses: totalMass must be greater than zero");
PX_CHECK_AND_RETURN(gravityDirection<=2, "PxVehicleComputeSprungMasses: gravityDirection must be 0 or 1 or 2");
PX_CHECK_AND_RETURN(sprungMasses, "PxVehicleComputeSprungMasses: sprungMasses must be a non-null pointer");
#endif
if(1==numSprungMasses)
{
sprungMasses[0]=totalMass;
}
else if(2==numSprungMasses)
{
PxVec3 v=sprungMassCoordinates[0];
v[gravityDirection]=0;
PxVec3 w=sprungMassCoordinates[1]-sprungMassCoordinates[0];
w[gravityDirection]=0;
w.normalize();
PxVec3 cm=centreOfMass;
cm[gravityDirection]=0;
PxF32 t=w.dot(cm-v);
PxVec3 p=v+w*t;
PxVec3 x0=sprungMassCoordinates[0];
x0[gravityDirection]=0;
PxVec3 x1=sprungMassCoordinates[1];
x1[gravityDirection]=0;
const PxF32 r0=(x0-p).dot(w);
const PxF32 r1=(x1-p).dot(w);
PX_CHECK_AND_RETURN(PxAbs(r0-r1) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
const PxF32 m0=totalMass*r1/(r1-r0);
const PxF32 m1=totalMass-m0;
sprungMasses[0]=m0;
sprungMasses[1]=m1;
}
else if(3==numSprungMasses)
{
const PxU32 d0=(gravityDirection+1)%3;
const PxU32 d1=(gravityDirection+2)%3;
MatrixNN A(3);
VectorN b(3);
A.set(0,0,sprungMassCoordinates[0][d0]);
A.set(0,1,sprungMassCoordinates[1][d0]);
A.set(0,2,sprungMassCoordinates[2][d0]);
A.set(1,0,sprungMassCoordinates[0][d1]);
A.set(1,1,sprungMassCoordinates[1][d1]);
A.set(1,2,sprungMassCoordinates[2][d1]);
A.set(2,0,1.f);
A.set(2,1,1.f);
A.set(2,2,1.f);
b[0]=totalMass*centreOfMass[d0];
b[1]=totalMass*centreOfMass[d1];
b[2]=totalMass;
VectorN result(3);
MatrixNNLUSolver solver;
solver.decomposeLU(A);
PX_CHECK_AND_RETURN(PxAbs(solver.getDet()) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
solver.solve(b,result);
sprungMasses[0]=result[0];
sprungMasses[1]=result[1];
sprungMasses[2]=result[2];
}
else if(numSprungMasses>=4)
{
const PxU32 d0=(gravityDirection+1)%3;
const PxU32 d1=(gravityDirection+2)%3;
const PxF32 mbar = totalMass/(numSprungMasses*1.0f);
//See http://en.wikipedia.org/wiki/Lagrange_multiplier
//particularly the section on multiple constraints.
//3 Constraint equations.
//g0 = sum_ xi*mi=xcm
//g1 = sum_ zi*mi=zcm
//g2 = sum_ mi = totalMass
//Minimisation function to achieve solution with minimum mass variance.
//f = sum_ (mi - mave)^2
//Lagrange terms (N equations, N+3 unknowns)
//2*mi - xi*lambda0 - zi*lambda1 - 1*lambda2 = 2*mave
MatrixNN A(numSprungMasses+3);
VectorN b(numSprungMasses+3);
//g0, g1, g2
for(PxU32 i=0;i<numSprungMasses;i++)
{
A.set(0,i,sprungMassCoordinates[i][d0]); //g0
A.set(1,i,sprungMassCoordinates[i][d1]); //g1
A.set(2,i,1.0f); //g2
}
for(PxU32 i=numSprungMasses;i<numSprungMasses+3;i++)
{
A.set(0,i,0); //g0 independent of lambda0,lambda1,lambda2
A.set(1,i,0); //g1 independent of lambda0,lambda1,lambda2
A.set(2,i,0); //g2 independent of lambda0,lambda1,lambda2
}
b[0] = totalMass*(centreOfMass[d0]); //g0
b[1] = totalMass*(centreOfMass[d1]); //g1
b[2] = totalMass; //g2
//Lagrange terms.
for(PxU32 i=0;i<numSprungMasses;i++)
{
//Off-diagonal terms from the derivative of f
for(PxU32 j=0;j<numSprungMasses;j++)
{
A.set(i+3,j,0);
}
//Diagonal term from the derivative of f
A.set(i+3,i,2.f);
//Derivative of g
A.set(i+3,numSprungMasses+0,sprungMassCoordinates[i][d0]);
A.set(i+3,numSprungMasses+1,sprungMassCoordinates[i][d1]);
A.set(i+3,numSprungMasses+2,1.0f);
//rhs.
b[i+3] = 2*mbar;
}
//Solve Ax=b
VectorN result(numSprungMasses+3);
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_CHECK_AND_RETURN(PxAbs(solver.getDet()) > DETERMINANT_THRESHOLD, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
for(PxU32 i=0;i<numSprungMasses;i++)
{
sprungMasses[i]=result[i];
}
}
#if PX_CHECKED
PxVec3 cm(0,0,0);
PxF32 m = 0;
for(PxU32 i=0;i<numSprungMasses;i++)
{
PX_CHECK_AND_RETURN(sprungMasses[i] >= 0, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
cm += sprungMassCoordinates[i]*sprungMasses[i];
m += sprungMasses[i];
}
cm *= (1.0f/totalMass);
PX_CHECK_AND_RETURN((PxAbs(totalMass - m)/totalMass) < 1e-3f, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
PxVec3 diff = cm - centreOfMass;
diff[gravityDirection]=0;
const PxF32 diffMag = diff.magnitude();
PX_CHECK_AND_RETURN(numSprungMasses <=2 || diffMag < 1e-3f, "PxVehicleComputeSprungMasses: Unable to determine sprung masses. Please check the values in sprungMassCoordinates.");
#endif
}
////////////////////////////////////////////////////////////////////////////
//Work out if all wheels are in the air.
////////////////////////////////////////////////////////////////////////////
bool PxVehicleIsInAir(const PxVehicleWheelQueryResult& vehWheelQueryResults)
{
if(!vehWheelQueryResults.wheelQueryResults)
{
return true;
}
for(PxU32 i=0;i<vehWheelQueryResults.nbWheelQueryResults;i++)
{
if(!vehWheelQueryResults.wheelQueryResults[i].isInAir)
{
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////
//Reject wheel contact points
////////////////////////////////////////////////////////////////////////////
PxU32 PxVehicleModifyWheelContacts
(const PxVehicleWheels& vehicle, const PxU32 wheelId,
const PxF32 wheelTangentVelocityMultiplier, const PxReal maxImpulse,
PxContactModifyPair& contactModifyPair, const PxVehicleContext& context)
{
const bool rejectPoints = true;
const bool rejectNormals = true;
PxU32 numIgnoredContacts = 0;
const PxRigidDynamic* vehActor = vehicle.getRigidDynamicActor();
//Is the vehicle represented by actor[0] or actor[1]?
PxTransform vehActorTransform;
PxTransform vehWheelTransform;
PxF32 normalMultiplier;
PxF32 targetVelMultiplier;
bool isOtherDynamic = false;
if(contactModifyPair.actor[0] == vehActor)
{
normalMultiplier = 1.0f;
targetVelMultiplier = 1.0f;
vehActorTransform = contactModifyPair.actor[0]->getGlobalPose();
vehWheelTransform = contactModifyPair.transform[0];
isOtherDynamic = contactModifyPair.actor[1] && contactModifyPair.actor[1]->is<PxRigidDynamic>();
}
else
{
PX_ASSERT(contactModifyPair.actor[1] == vehActor);
normalMultiplier = -1.0f;
targetVelMultiplier = -1.0f;
vehActorTransform = contactModifyPair.actor[1]->getGlobalPose();
vehWheelTransform = contactModifyPair.transform[1];
isOtherDynamic = contactModifyPair.actor[0] && contactModifyPair.actor[0]->is<PxRigidDynamic>();
}
//Compute the "right" vector of the transform.
const PxVec3 right = vehWheelTransform.q.rotate(context.sideAxis);
//The wheel transform includes rotation about the rolling axis.
//We want to compute the wheel transform at zero wheel rotation angle.
PxTransform correctedWheelShapeTransform;
{
const PxF32 wheelRotationAngle = vehicle.mWheelsDynData.getWheelRotationAngle(wheelId);
const PxQuat wheelRotateQuat(-wheelRotationAngle, right);
correctedWheelShapeTransform = PxTransform(vehWheelTransform.p, wheelRotateQuat*vehWheelTransform.q);
}
//Construct a plane for the wheel
const PxPlane wheelPlane(correctedWheelShapeTransform.p, right);
//Compute the suspension travel vector.
const PxVec3 suspTravelDir = correctedWheelShapeTransform.rotate(vehicle.mWheelsSimData.getSuspTravelDirection(wheelId));
//Get the wheel centre.
const PxVec3 wheelCentre = correctedWheelShapeTransform.p;
//Test each point.
PxContactSet& contactSet = contactModifyPair.contacts;
const PxU32 numContacts = contactSet.size();
for(PxU32 i = 0; i < numContacts; i++)
{
//Get the next contact point to analyse.
const PxVec3& contactPoint = contactSet.getPoint(i);
bool ignorePoint = false;
//Project the contact point on to the wheel plane.
const PxF32 distanceToPlane = wheelPlane.n.dot(contactPoint) + wheelPlane.d;
const PxVec3 contactPointOnPlane = contactPoint - wheelPlane.n*distanceToPlane;
//Construct a vector from the wheel centre to the contact point on the plane.
PxVec3 dir = contactPointOnPlane - wheelCentre;
const PxF32 effectiveRadius = dir.normalize();
if(!ignorePoint && rejectPoints)
{
//Work out the dot product of the suspension direction and the direction from wheel centre to contact point.
const PxF32 dotProduct = dir.dot(suspTravelDir);
if (dotProduct > context.pointRejectAngleThresholdCosine)
{
ignorePoint = true;
numIgnoredContacts++;
contactSet.ignore(i);
}
}
//Ignore contact normals that are near the raycast direction.
if(!ignorePoint && rejectNormals)
{
const PxVec3& contactNormal = contactSet.getNormal(i) * normalMultiplier;
const PxF32 dotProduct = -(contactNormal.dot(suspTravelDir));
if(dotProduct > context.normalRejectAngleThresholdCosine)
{
ignorePoint = true;
numIgnoredContacts++;
contactSet.ignore(i);
}
}
//For points that remain we want to modify the contact speed to account for the spinning wheel.
//We also want the applied impulse to go through the suspension geometry so we set the contact point to be the suspension force
//application point.
if(!ignorePoint)
{
//Compute the tangent velocity.
//Retain only the component that lies perpendicular to the contact normal.
const PxF32 wheelRotationSpeed = vehicle.mWheelsDynData.getWheelRotationSpeed(wheelId);
const PxVec3 tangentVelocityDir = right.cross(dir);
PxVec3 tangentVelocity = tangentVelocityDir*(effectiveRadius*wheelRotationSpeed);
tangentVelocity -= contactSet.getNormal(i)*(tangentVelocity.dot(contactSet.getNormal(i)));
//We want to add velocity in the opposite direction to the tangent velocity.
const PxVec3 targetTangentVelocity = -wheelTangentVelocityMultiplier*tangentVelocity;
//Relative velocity is computed from actor0 - actor1
//If vehicle is actor 0 we want to add to the target velocity: targetVelocity = [(vel0 + targetTangentVelocity) - vel1] = vel0 - vel1 + targetTangentVelocity
//If vehicle is actor 1 we want to subtract from the target velocity: targetVelocity = [vel0 - (vel1 + targetTangentVelocity)] = vel0 - vel1 - targetTangentVelocity
const PxVec3 targetVelocity = targetTangentVelocity*targetVelMultiplier;
//Add the target velocity.
contactSet.setTargetVelocity(i, targetVelocity);
//Set the max impulse that can be applied.
//Only apply this if the wheel has hit a dynamic.
if (isOtherDynamic)
{
contactSet.setMaxImpulse(i, maxImpulse);
}
//Set the contact point to be the suspension force application point because all forces applied through the wheel go through the suspension geometry.
const PxVec3 suspAppPoint = vehActorTransform.transform(vehActor->getCMassLocalPose().p + vehicle.mWheelsSimData.getSuspForceAppPointOffset(wheelId));
contactSet.setPoint(i, suspAppPoint);
}
}
return numIgnoredContacts;
}
////////////////////////////////////////////////////////////////////////////
//Enable a 4W vehicle in either tadpole or delta configuration.
////////////////////////////////////////////////////////////////////////////
void computeDirection(const PxVec3& up, const PxVec3& right,
PxU32& rightDirection, PxU32& upDirection)
{
//Work out the up and right vectors.
rightDirection = 0xffffffff;
if(right == PxVec3(1.f,0,0) || right == PxVec3(-1.f,0,0))
{
rightDirection = 0;
}
else if(right == PxVec3(0,1.f,0) || right == PxVec3(0,-1.f,0))
{
rightDirection = 1;
}
else if(right == PxVec3(0,0,1.f) || right == PxVec3(0,0,-1.f))
{
rightDirection = 2;
}
upDirection = 0xffffffff;
if(up == PxVec3(1.f,0,0) || up == PxVec3(-1.f,0,0))
{
upDirection = 0;
}
else if(up == PxVec3(0,1.f,0) || up == PxVec3(0,-1.f,0))
{
upDirection = 1;
}
else if(up == PxVec3(0,0,1.f) || up == PxVec3(0,0,-1.f))
{
upDirection = 2;
}
}
void enable3WMode(const PxU32 rightDirection, const PxU32 upDirection, const bool removeFrontWheel, PxVehicleWheelsSimData& wheelsSimData, PxVehicleWheelsDynData& wheelsDynData, PxVehicleDriveSimData4W& driveSimData)
{
PX_ASSERT(rightDirection < 3);
PX_ASSERT(upDirection < 3);
const PxU32 wheelToRemove = removeFrontWheel ? PxVehicleDrive4WWheelOrder::eFRONT_LEFT : PxVehicleDrive4WWheelOrder::eREAR_LEFT;
const PxU32 wheelToModify = removeFrontWheel ? PxVehicleDrive4WWheelOrder::eFRONT_RIGHT : PxVehicleDrive4WWheelOrder::eREAR_RIGHT;
//Disable the wheel.
wheelsSimData.disableWheel(wheelToRemove);
//Make sure the wheel's corresponding PxShape does not get posed again.
wheelsSimData.setWheelShapeMapping(wheelToRemove, -1);
//Set the angular speed to 0.0f
wheelsDynData.setWheelRotationSpeed(wheelToRemove, 0.0f);
//Disable Ackermann steering.
//If the front wheel is to be removed and the front wheels can steer then disable Ackermann correction.
//If the rear wheel is to be removed and the rear wheels can steer then disable Ackermann correction.
if(removeFrontWheel &&
(wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT).mMaxSteer!=0.0f ||
wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT).mMaxSteer!=0.0f))
{
PxVehicleAckermannGeometryData ackermannData=driveSimData.getAckermannGeometryData();
ackermannData.mAccuracy=0.0f;
driveSimData.setAckermannGeometryData(ackermannData);
}
if(!removeFrontWheel &&
(wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT).mMaxSteer!=0.0f ||
wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_LEFT).mMaxSteer!=0.0f))
{
PxVehicleAckermannGeometryData ackermannData=driveSimData.getAckermannGeometryData();
ackermannData.mAccuracy=0.0f;
driveSimData.setAckermannGeometryData(ackermannData);
}
//We need to set up the differential to make sure that no drive torque is delivered to the disabled wheel.
PxVehicleDifferential4WData diffData =driveSimData.getDiffData();
if(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT==wheelToModify)
{
diffData.mFrontBias=PX_MAX_F32;
diffData.mFrontLeftRightSplit=0.0f;
}
else
{
diffData.mRearBias=PX_MAX_F32;
diffData.mRearLeftRightSplit=0.0f;
}
driveSimData.setDiffData(diffData);
//Now reposition the disabled wheel so that it lies at the center of its axle.
//The following assumes that the front and rear axles lie along the x-axis.
{
PxVec3 wheelCentreOffset=wheelsSimData.getWheelCentreOffset(wheelToModify);
wheelCentreOffset[rightDirection]=0.0f;
wheelsSimData.setWheelCentreOffset(wheelToModify,wheelCentreOffset);
PxVec3 suspOffset=wheelsSimData.getSuspForceAppPointOffset(wheelToModify);
suspOffset[rightDirection]=0;
wheelsSimData.setSuspForceAppPointOffset(wheelToModify,suspOffset);
PxVec3 tireOffset=wheelsSimData.getTireForceAppPointOffset(wheelToModify);
tireOffset[rightDirection]=0;
wheelsSimData.setTireForceAppPointOffset(wheelToModify,tireOffset);
}
//Redistribute the mass supported by 4 wheels among the 3 remaining enabled wheels.
//Compute the total mass supported by all 4 wheels.
const PxF32 totalMass =
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eREAR_LEFT).mSprungMass +
wheelsSimData.getSuspensionData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT).mSprungMass;
//Get the wheel cm offsets of the 3 enabled wheels.
PxVec3 cmOffsets[3]=
{
wheelsSimData.getWheelCentreOffset((wheelToRemove+1) % 4),
wheelsSimData.getWheelCentreOffset((wheelToRemove+2) % 4),
wheelsSimData.getWheelCentreOffset((wheelToRemove+3) % 4),
};
//Re-compute the sprung masses.
PxF32 sprungMasses[3];
computeSprungMasses(3, cmOffsets, PxVec3(0,0,0), totalMass, upDirection, sprungMasses);
//Now set the new sprung masses.
//Do this in a way that preserves the natural frequency and damping ratio of the spring.
for(PxU32 i=0;i<3;i++)
{
PxVehicleSuspensionData suspData = wheelsSimData.getSuspensionData((wheelToRemove+1+i) % 4);
const PxF32 oldSprungMass = suspData.mSprungMass;
const PxF32 oldStrength = suspData.mSpringStrength;
const PxF32 oldDampingRate = suspData.mSpringDamperRate;
const PxF32 oldNaturalFrequency = PxSqrt(oldStrength/oldSprungMass);
const PxF32 newSprungMass = sprungMasses[i];
const PxF32 newStrength = oldNaturalFrequency*oldNaturalFrequency*newSprungMass;
const PxF32 newDampingRate = oldDampingRate;
suspData.mSprungMass = newSprungMass;
suspData.mSpringStrength = newStrength;
suspData.mSpringDamperRate = newDampingRate;
wheelsSimData.setSuspensionData((wheelToRemove+1+i) % 4, suspData);
}
}
////////////////////////////////////////////////////////////////////////////
//Maximum number of allowed blocks of 4 wheels
////////////////////////////////////////////////////////////////////////////
#define PX_MAX_NB_SUSPWHEELTIRE4 (PX_MAX_NB_WHEELS >>2)
////////////////////////////////////////////////////////////////////////////
//Pointers to telemetry data.
//Set to NULL if no telemetry data is to be recorded during a vehicle update.
//Functions used throughout vehicle update to record specific vehicle data.
////////////////////////////////////////////////////////////////////////////
#if PX_DEBUG_VEHICLE_ON
struct VehicleTelemetryDataContext
{
PxF32 wheelGraphData[PX_MAX_NB_WHEELS][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS];
PxF32 engineGraphData[PxVehicleDriveGraphChannel::eMAX_NB_DRIVE_CHANNELS];
PxVec3 suspForceAppPoints[PX_MAX_NB_WHEELS];
PxVec3 tireForceAppPoints[PX_MAX_NB_WHEELS];
};
PX_FORCE_INLINE void updateGraphDataInternalWheelDynamics(const PxU32 startIndex, const PxF32* carWheelSpeeds,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
//Grab the internal rotation speeds for graphing before we update them.
for(PxU32 i=0;i<4;i++)
{
PX_ASSERT((startIndex+i) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+i]);
carWheelGraphData[startIndex+i][PxVehicleWheelGraphChannel::eWHEEL_OMEGA]=carWheelSpeeds[i];
}
}
PX_FORCE_INLINE void updateGraphDataInternalEngineDynamics(const PxF32 carEngineSpeed, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eENGINE_REVS]=carEngineSpeed;
}
PX_FORCE_INLINE void updateGraphDataControlInputs(const PxF32 accel, const PxF32 brake, const PxF32 handbrake, const PxF32 steerLeft, const PxF32 steerRight,
PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eACCEL_CONTROL]=accel;
carEngineGraphData[PxVehicleDriveGraphChannel::eBRAKE_CONTROL]=brake;
carEngineGraphData[PxVehicleDriveGraphChannel::eHANDBRAKE_CONTROL]=handbrake;
carEngineGraphData[PxVehicleDriveGraphChannel::eSTEER_LEFT_CONTROL]=steerLeft;
carEngineGraphData[PxVehicleDriveGraphChannel::eSTEER_RIGHT_CONTROL]=steerRight;
}
PX_FORCE_INLINE void updateGraphDataGearRatio(const PxF32 G, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eGEAR_RATIO]=G;
}
PX_FORCE_INLINE void updateGraphDataEngineDriveTorque(const PxF32 engineDriveTorque, PxF32* carEngineGraphData)
{
carEngineGraphData[PxVehicleDriveGraphChannel::eENGINE_DRIVE_TORQUE]=engineDriveTorque;
}
PX_FORCE_INLINE void updateGraphDataClutchSlip(const PxF32* wheelSpeeds, const PxF32* aveWheelSpeedContributions, const PxF32 engineSpeed, const PxF32 G,
PxF32* carEngineGraphData)
{
PxF32 averageWheelSpeed=0;
for(PxU32 i=0;i<4;i++)
{
averageWheelSpeed+=wheelSpeeds[i]*aveWheelSpeedContributions[i];
}
averageWheelSpeed*=G;
carEngineGraphData[PxVehicleDriveGraphChannel::eCLUTCH_SLIP]=averageWheelSpeed-engineSpeed;
}
PX_FORCE_INLINE void updateGraphDataClutchSlipNW(const PxU32 numWheels4, const PxVehicleWheels4DynData* wheelsDynData, const PxF32* aveWheelSpeedContributions, const PxF32 engineSpeed, const PxF32 G,
PxF32* carEngineGraphData)
{
PxF32 averageWheelSpeed=0;
for(PxU32 i=0;i<numWheels4;i++)
{
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[0]*aveWheelSpeedContributions[4*i+0];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[1]*aveWheelSpeedContributions[4*i+1];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[2]*aveWheelSpeedContributions[4*i+2];
averageWheelSpeed+=wheelsDynData[i].mWheelSpeeds[3]*aveWheelSpeedContributions[4*i+3];
}
averageWheelSpeed*=G;
carEngineGraphData[PxVehicleDriveGraphChannel::eCLUTCH_SLIP]=averageWheelSpeed-engineSpeed;
}
PX_FORCE_INLINE void zeroGraphDataWheels(const PxU32 startIndex, const PxU32 type,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
for(PxU32 i=0;i<4;i++)
{
PX_ASSERT((startIndex+i) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+i]);
carWheelGraphData[startIndex+i][type]=0.0f;
}
}
PX_FORCE_INLINE void updateGraphDataSuspJounce(const PxU32 startIndex, const PxU32 wheel, const PxF32 jounce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eJOUNCE]=jounce;
}
PX_FORCE_INLINE void updateGraphDataSuspForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 springForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eSUSPFORCE]=springForce;
}
PX_FORCE_INLINE void updateGraphDataTireLoad(const PxU32 startIndex, const PxU32 wheel, const PxF32 filteredTireLoad,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRELOAD]=filteredTireLoad;
}
PX_FORCE_INLINE void updateGraphDataNormTireLoad(const PxU32 startIndex, const PxU32 wheel, const PxF32 filteredNormalisedTireLoad,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORMALIZED_TIRELOAD]=filteredNormalisedTireLoad;
}
PX_FORCE_INLINE void updateGraphDataNormLongTireForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 normForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_LONG_FORCE]=normForce;
}
PX_FORCE_INLINE void updateGraphDataNormLatTireForce(const PxU32 startIndex, const PxU32 wheel, const PxF32 normForce,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_LAT_FORCE]=normForce;
}
PX_FORCE_INLINE void updateGraphDataLatTireSlip(const PxU32 startIndex, const PxU32 wheel, const PxF32 latSlip,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_LAT_SLIP]=latSlip;
}
PX_FORCE_INLINE void updateGraphDataLongTireSlip(const PxU32 startIndex, const PxU32 wheel, const PxF32 longSlip,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_LONG_SLIP]=longSlip;
}
PX_FORCE_INLINE void updateGraphDataTireFriction(const PxU32 startIndex, const PxU32 wheel, const PxF32 friction,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eTIRE_FRICTION]=friction;
}
PX_FORCE_INLINE void updateGraphDataNormTireAligningMoment(const PxU32 startIndex, const PxU32 wheel, const PxF32 normAlignMoment,
PxF32 carWheelGraphData[][PxVehicleWheelGraphChannel::eMAX_NB_WHEEL_CHANNELS])
{
PX_ASSERT((startIndex+wheel) < PX_MAX_NB_WHEELS);
PX_ASSERT(carWheelGraphData[startIndex+wheel]);
carWheelGraphData[startIndex+wheel][PxVehicleWheelGraphChannel::eNORM_TIRE_ALIGNING_MOMENT]=normAlignMoment;
}
#else
struct VehicleTelemetryDataContext;
#endif //DEBUG_VEHICLE_ON
////////////////////////////////////////////////////////////////////////////
//Profile data structures.
////////////////////////////////////////////////////////////////////////////
#define PX_VEHICLE_PROFILE 0
enum
{
TIMER_ADMIN=0,
TIMER_GRAPHS,
TIMER_COMPONENTS_UPDATE,
TIMER_WHEELS,
TIMER_INTERNAL_DYNAMICS_SOLVER,
TIMER_POSTUPDATE1,
TIMER_POSTUPDATE2,
TIMER_POSTUPDATE3,
TIMER_ALL,
TIMER_RAYCASTS,
TIMER_SWEEPS,
MAX_NB_TIMERS
};
#if PX_VEHICLE_PROFILE
bool gTimerStates[MAX_NB_TIMERS]={false,false,false,false,false,false,false,false,false,false,false};
PxU64 gTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU64 gStartTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU64 gEndTimers[MAX_NB_TIMERS]={0,0,0,0,0,0,0,0,0,0,0};
PxU32 gTimerCount=0;
physx::PxTime gTimer;
PX_FORCE_INLINE void START_TIMER(const PxU32 id)
{
PX_ASSERT(!gTimerStates[id]);
gStartTimers[id]=gTimer.getCurrentCounterValue();
gTimerStates[id]=true;
}
PX_FORCE_INLINE void END_TIMER(const PxU32 id)
{
PX_ASSERT(gTimerStates[id]);
gTimerStates[id]=false;
gEndTimers[id]=gTimer.getCurrentCounterValue();
gTimers[id]+=(gEndTimers[id]-gStartTimers[id]);
}
PX_FORCE_INLINE PxF32 getTimerFraction(const PxU32 id)
{
return gTimers[id]/(1.0f*gTimers[TIMER_ALL]);
}
PX_FORCE_INLINE PxReal getTimerInMilliseconds(const PxU32 id)
{
const PxU64 time=gTimers[id];
const PxU64 timein10sOfNs = gTimer.getBootCounterFrequency().toTensOfNanos(time);
return (timein10sOfNs/(gTimerCount*100*1.0f));
}
#else
PX_FORCE_INLINE void START_TIMER(const PxU32)
{
}
PX_FORCE_INLINE void END_TIMER(const PxU32)
{
}
#endif
////////////////////////////////////////////////////////////////////////////
//Functions used to integrate rigid body transform and velocity.
//The sub-step system divides a specified timestep into N equal sub-steps
//and integrates the velocity and transform each sub-step.
//After all sub-steps are complete the velocity required to move the
//associated PxRigidBody from the start transform to the transform at the end
//of the timestep is computed and set. If the update mode is chosen to be
//acceleration then the acceleration is computed/set that will move the rigid body
//from the start to end transform. The PxRigidBody never actually has its transform
//updated and only has its velocity or acceleration set at the very end of the timestep.
////////////////////////////////////////////////////////////////////////////
PX_INLINE void integrateBody
(const PxF32 inverseMass, const PxVec3& invInertia, const PxVec3& force, const PxVec3& torque, const PxF32 dt,
PxVec3& v, PxVec3& w, PxTransform& t)
{
//Integrate linear velocity.
v+=force*(inverseMass*dt);
//Integrate angular velocity.
PxMat33 inverseInertia;
transformInertiaTensor(invInertia, PxMat33(t.q), inverseInertia);
w+=inverseInertia*(torque*dt);
//Integrate position.
t.p+=v*dt;
//Integrate quaternion.
PxQuat wq(w.x,w.y,w.z,0.0f);
PxQuat q=t.q;
PxQuat qdot=wq*q*(dt*0.5f);
q+=qdot;
q.normalize();
t.q=q;
}
/*
PX_INLINE void computeVelocity(const PxTransform& t1, const PxTransform& t2, const PxF32 invDT, PxVec3& v, PxVec3& w)
{
//Linear velocity.
v = (t2.p - t1.p)*invDT;
//Angular velocity.
PxQuat qw = (t2.q - t1.q)*t1.q.getConjugate()*(2.0f*invDT);
w.x=qw.x;
w.y=qw.y;
w.z=qw.z;
}
*/
/////////////////////////////////////////////////////////////////////////////////////////
//Use fsel to compute the sign of a float: +1 for positive values, -1 for negative values
/////////////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeSign(const PxF32 f)
{
return physx::intrinsics::fsel(f, physx::intrinsics::fsel(-f, 0.0f, 1.0f), -1.0f);
}
/////////////////////////////////////////////////////////////////////////////////////////
//Get the accel/brake/handbrake as floats in range (0,1) from the inputs stored in the vehicle.
//Equivalent for tank involving thrustleft/thrustright and brakeleft/brakeright.
/////////////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void getVehicle4WControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brake, PxF32& handbrake, PxF32& steerLeft, PxF32& steerRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
brake=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE];
handbrake=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE];
steerLeft=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT];
steerRight=driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT];
}
PX_FORCE_INLINE void getVehicleNWControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brake, PxF32& handbrake, PxF32& steerLeft, PxF32& steerRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL];
brake=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE];
handbrake=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE];
steerLeft=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT];
steerRight=driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT];
}
PX_FORCE_INLINE void getTankControlValues(const PxVehicleDriveDynData& driveDynData, PxF32& accel, PxF32& brakeLeft, PxF32& brakeRight, PxF32& thrustLeft, PxF32& thrustRight)
{
accel=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL];
brakeLeft=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT];
brakeRight=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT];
thrustLeft=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT];
thrustRight=driveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT];
}
////////////////////////////////////////////////////////////////////////////
//Process autobox to initiate automatic gear changes.
//The autobox can be turned off and simulated externally by setting
//the target gear as required prior to calling PxVehicleUpdates.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 processAutoBox(const PxU32 accelIndex, const PxF32 timestep, const PxVehicleDriveSimData& vehCoreSimData, PxVehicleDriveDynData& vehDynData)
{
PX_ASSERT(vehDynData.getUseAutoGears());
PxF32 autoboxCompensatedAnalogAccel = vehDynData.mControlAnalogVals[accelIndex];
//If still undergoing a gear change triggered by the autobox
//then turn off the accelerator pedal. This happens in autoboxes
//to stop the driver revving the engine crazily then damaging the
//clutch when the clutch re-engages at the end of the gear change.
const PxU32 currentGear=vehDynData.getCurrentGear();
const PxU32 targetGear=vehDynData.getTargetGear();
if(targetGear!=currentGear && PxVehicleGearsData::eNEUTRAL==currentGear)
{
autoboxCompensatedAnalogAccel = 0;
}
//Only process the autobox if no gear change is underway and the time passed since the last autobox
//gear change is greater than the autobox latency.
PxF32 autoBoxSwitchTime=vehDynData.getAutoBoxSwitchTime();
const PxF32 autoBoxLatencyTime=vehCoreSimData.getAutoBoxData().mDownRatios[PxVehicleGearsData::eREVERSE];
if(targetGear==currentGear && autoBoxSwitchTime > autoBoxLatencyTime)
{
//Work out if the autobox wants to switch up or down.
const PxF32 normalisedEngineOmega=vehDynData.getEngineRotationSpeed()*vehCoreSimData.getEngineData().getRecipMaxOmega();
const PxVehicleAutoBoxData& autoBoxData=vehCoreSimData.getAutoBoxData();
bool gearUp=false;
if(normalisedEngineOmega > autoBoxData.mUpRatios[currentGear] && PxVehicleGearsData::eREVERSE!=currentGear)
{
//If revs too high and not in reverse and not undergoing a gear change then switch up.
gearUp=true;
}
bool gearDown=false;
if(normalisedEngineOmega < autoBoxData.mDownRatios[currentGear] && currentGear > PxVehicleGearsData::eFIRST)
{
//If revs too low and in gear greater than first and not undergoing a gear change then change down.
gearDown=true;
}
//Start the gear change and reset the time since the last autobox gear change.
if(gearUp || gearDown)
{
vehDynData.setGearUp(gearUp);
vehDynData.setGearDown(gearDown);
vehDynData.setAutoBoxSwitchTime(0.f);
}
}
else
{
autoBoxSwitchTime+=timestep;
vehDynData.setAutoBoxSwitchTime(autoBoxSwitchTime);
}
return autoboxCompensatedAnalogAccel;
}
////////////////////////////////////////////////////////////////////////////
//Process gear changes.
//If target gear not equal to current gear then a gear change needs to start.
//The gear change process begins by switching immediately in neutral and
//staying there for a specified time. The process ends by setting current
//gear equal to target gear when the gear switch time has passed.
//This can be bypassed by always forcing target gear = current gear and then
//externally managing gear changes prior to calling PxVehicleUpdates.
////////////////////////////////////////////////////////////////////////////
void processGears(const PxF32 timestep, const PxVehicleGearsData& gears, PxVehicleDriveDynData& car)
{
//const PxVehicleGearsData& gears=car.mVehicleSimData.getGearsData();
//Process the gears.
if(car.getGearUp() && gears.mNbRatios-1!=car.getCurrentGear() && car.getCurrentGear()==car.getTargetGear())
{
//Car wants to go up a gear and can go up a gear and not already undergoing a gear change.
if(PxVehicleGearsData::eREVERSE==car.getCurrentGear())
{
//In reverse so switch to first through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eFIRST);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else if(PxVehicleGearsData::eNEUTRAL==car.getCurrentGear())
{
//In neutral so switch to first and stay in neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eFIRST);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else
{
//Switch up a gear through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(car.getCurrentGear() + 1);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
}
if(car.getGearDown() && PxVehicleGearsData::eREVERSE!=car.getCurrentGear() && car.getCurrentGear()==car.getTargetGear())
{
//Car wants to go down a gear and can go down a gear and not already undergoing a gear change
if(PxVehicleGearsData::eFIRST==car.getCurrentGear())
{
//In first so switch to reverse through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eREVERSE);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else if(PxVehicleGearsData::eNEUTRAL==car.getCurrentGear())
{
//In neutral so switch to reverse and stay in neutral.
car.setGearSwitchTime(0);
car.setTargetGear(PxVehicleGearsData::eREVERSE);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
else
{
//Switch down a gear through neutral.
car.setGearSwitchTime(0);
car.setTargetGear(car.getCurrentGear() - 1);
car.setCurrentGear(PxVehicleGearsData::eNEUTRAL);
}
}
if(car.getCurrentGear()!=car.getTargetGear())
{
if(car.getGearSwitchTime()>gears.mSwitchTime)
{
car.setCurrentGear(car.getTargetGear());
car.setGearSwitchTime(0);
car.setGearDown(false);
car.setGearUp(false);
}
else
{
car.setGearSwitchTime(car.getGearSwitchTime() + timestep);
}
}
}
////////////////////////////////////////////////////////////////////////////
//Helper functions to compute
//1. the gear ratio from the current gear.
//2. the drive torque from the state of the accelerator pedal and torque curve of available torque against engine speed.
//3. engine damping rate (a blend between a rate when not accelerating and a rate when fully accelerating).
//4. clutch strength (rate at which clutch will regulate difference between engine and averaged wheel speed).
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeGearRatio(const PxVehicleGearsData& gearsData, const PxU32 currentGear)
{
const PxF32 gearRatio=gearsData.mRatios[currentGear]*gearsData.mFinalRatio;
return gearRatio;
}
PX_FORCE_INLINE PxF32 computeEngineDriveTorque(const PxVehicleEngineData& engineData, const PxF32 omega, const PxF32 accel)
{
const PxF32 engineDriveTorque=accel*engineData.mPeakTorque*engineData.mTorqueCurve.getYVal(omega*engineData.getRecipMaxOmega());
return engineDriveTorque;
}
PX_FORCE_INLINE PxF32 computeEngineDampingRate(const PxVehicleEngineData& engineData, const PxU32 gear, const PxF32 accel)
{
const PxF32 fullThrottleDamping = engineData.mDampingRateFullThrottle;
const PxF32 zeroThrottleDamping = (PxVehicleGearsData::eNEUTRAL!=gear) ? engineData.mDampingRateZeroThrottleClutchEngaged : engineData.mDampingRateZeroThrottleClutchDisengaged;
const PxF32 engineDamping = zeroThrottleDamping + (fullThrottleDamping-zeroThrottleDamping)*accel;
return engineDamping;
}
PX_FORCE_INLINE PxF32 computeClutchStrength(const PxVehicleClutchData& clutchData, const PxU32 currentGear)
{
return ((PxVehicleGearsData::eNEUTRAL!=currentGear) ? clutchData.mStrength : 0.0f);
}
////////////////////////////////////////////////////////////////////////////
//Limited slip differential.
//Split the available drive torque as a fraction of the total between up to 4 driven wheels.
//Compute the fraction that each wheel contributes to the averages wheel speed at the clutch.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void splitTorque
(const PxF32 w1, const PxF32 w2, const PxF32 diffBias, const PxF32 defaultSplitRatio,
PxF32* t1, PxF32* t2)
{
PX_ASSERT(computeSign(w1)==computeSign(w2) && 0.0f!=computeSign(w1));
const PxF32 w1Abs=PxAbs(w1);
const PxF32 w2Abs=PxAbs(w2);
const PxF32 omegaMax=PxMax(w1Abs,w2Abs);
const PxF32 omegaMin=PxMin(w1Abs,w2Abs);
const PxF32 delta=omegaMax-diffBias*omegaMin;
const PxF32 deltaTorque=physx::intrinsics::fsel(delta, delta/omegaMax , 0.0f);
const PxF32 f1=physx::intrinsics::fsel(w1Abs-w2Abs, defaultSplitRatio*(1.0f-deltaTorque), defaultSplitRatio*(1.0f+deltaTorque));
const PxF32 f2=physx::intrinsics::fsel(w1Abs-w2Abs, (1.0f-defaultSplitRatio)*(1.0f+deltaTorque), (1.0f-defaultSplitRatio)*(1.0f-deltaTorque));
const PxF32 denom=1.0f/(f1+f2);
*t1=f1*denom;
*t2=f2*denom;
PX_ASSERT((*t1 + *t2) >=0.999f && (*t1 + *t2) <=1.001f);
}
PX_FORCE_INLINE void computeDiffTorqueRatios
(const PxVehicleDifferential4WData& diffData, const PxF32 handbrake, const PxF32* PX_RESTRICT wheelOmegas, PxF32* PX_RESTRICT diffTorqueRatios)
{
//If the handbrake is on only deliver torque to the front wheels.
PxU32 type=diffData.mType;
if(handbrake>0)
{
switch(diffData.mType)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
case PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES:
break;
}
}
const PxF32 wfl=wheelOmegas[PxVehicleDrive4WWheelOrder::eFRONT_LEFT];
const PxF32 wfr=wheelOmegas[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT];
const PxF32 wrl=wheelOmegas[PxVehicleDrive4WWheelOrder::eREAR_LEFT];
const PxF32 wrr=wheelOmegas[PxVehicleDrive4WWheelOrder::eREAR_RIGHT];
const PxF32 centreBias=diffData.mCentreBias;
const PxF32 frontBias=diffData.mFrontBias;
const PxF32 rearBias=diffData.mRearBias;
const PxF32 frontRearSplit=diffData.mFrontRearSplit;
const PxF32 frontLeftRightSplit=diffData.mFrontLeftRightSplit;
const PxF32 rearLeftRightSplit=diffData.mRearLeftRightSplit;
const PxF32 oneMinusFrontRearSplit=1.0f-diffData.mFrontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit=1.0f-diffData.mFrontLeftRightSplit;
const PxF32 oneMinusRearLeftRightSplit=1.0f-diffData.mRearLeftRightSplit;
const PxF32 swfl=computeSign(wfl);
//Split a torque of 1 between front and rear.
//Then split that torque between left and right.
PxF32 torqueFrontLeft=0;
PxF32 torqueFrontRight=0;
PxF32 torqueRearLeft=0;
PxF32 torqueRearRight=0;
switch(type)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
if(0.0f!=swfl && swfl==computeSign(wfr) && swfl==computeSign(wrl) && swfl==computeSign(wrr))
{
PxF32 torqueFront,torqueRear;
const PxF32 omegaFront=PxAbs(wfl+wfr);
const PxF32 omegaRear=PxAbs(wrl+wrr);
splitTorque(omegaFront,omegaRear,centreBias,frontRearSplit,&torqueFront,&torqueRear);
splitTorque(wfl,wfr,frontBias,frontLeftRightSplit,&torqueFrontLeft,&torqueFrontRight);
splitTorque(wrl,wrr,rearBias,rearLeftRightSplit,&torqueRearLeft,&torqueRearRight);
torqueFrontLeft*=torqueFront;
torqueFrontRight*=torqueFront;
torqueRearLeft*=torqueRear;
torqueRearRight*=torqueRear;
}
else
{
//TODO: need to handle this case.
torqueFrontLeft=frontRearSplit*frontLeftRightSplit;
torqueFrontRight=frontRearSplit*oneMinusFrontLeftRightSplit;
torqueRearLeft=oneMinusFrontRearSplit*rearLeftRightSplit;
torqueRearRight=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
if(0.0f!=swfl && swfl==computeSign(wfr))
{
splitTorque(wfl,wfr,frontBias,frontLeftRightSplit,&torqueFrontLeft,&torqueFrontRight);
}
else
{
torqueFrontLeft=frontLeftRightSplit;
torqueFrontRight=oneMinusFrontLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
if(0.0f!=computeSign(wrl) && computeSign(wrl)==computeSign(wrr))
{
splitTorque(wrl,wrr,rearBias,rearLeftRightSplit,&torqueRearLeft,&torqueRearRight);
}
else
{
torqueRearLeft=rearLeftRightSplit;
torqueRearRight=oneMinusRearLeftRightSplit;
}
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
torqueFrontLeft=frontRearSplit*frontLeftRightSplit;
torqueFrontRight=frontRearSplit*oneMinusFrontLeftRightSplit;
torqueRearLeft=oneMinusFrontRearSplit*rearLeftRightSplit;
torqueRearRight=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
torqueFrontLeft=frontLeftRightSplit;
torqueFrontRight=oneMinusFrontLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
torqueRearLeft=rearLeftRightSplit;
torqueRearRight=oneMinusRearLeftRightSplit;
break;
default:
PX_ASSERT(false);
break;
}
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=torqueFrontLeft;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=torqueFrontRight;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=torqueRearLeft;
diffTorqueRatios[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=torqueRearRight;
PX_ASSERT(((torqueFrontLeft+torqueFrontRight+torqueRearLeft+torqueRearRight) >= 0.999f) && ((torqueFrontLeft+torqueFrontRight+torqueRearLeft+torqueRearRight) <= 1.001f));
}
PX_FORCE_INLINE void computeDiffAveWheelSpeedContributions
(const PxVehicleDifferential4WData& diffData, const PxF32 handbrake, PxF32* PX_RESTRICT diffAveWheelSpeedContributions)
{
PxU32 type=diffData.mType;
//If the handbrake is on only deliver torque to the front wheels.
if(handbrake>0)
{
switch(diffData.mType)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
type=PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
case PxVehicleDifferential4WData::eMAX_NB_DIFF_TYPES:
break;
}
}
const PxF32 frontRearSplit=diffData.mFrontRearSplit;
const PxF32 frontLeftRightSplit=diffData.mFrontLeftRightSplit;
const PxF32 rearLeftRightSplit=diffData.mRearLeftRightSplit;
const PxF32 oneMinusFrontRearSplit=1.0f-diffData.mFrontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit=1.0f-diffData.mFrontLeftRightSplit;
const PxF32 oneMinusRearLeftRightSplit=1.0f-diffData.mRearLeftRightSplit;
switch(type)
{
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_4WD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_4WD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=frontRearSplit*frontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=frontRearSplit*oneMinusFrontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=oneMinusFrontRearSplit*rearLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=oneMinusFrontRearSplit*oneMinusRearLeftRightSplit;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_FRONTWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_FRONTWD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=frontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=oneMinusFrontLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=0.0f;
break;
case PxVehicleDifferential4WData::eDIFF_TYPE_LS_REARWD:
case PxVehicleDifferential4WData::eDIFF_TYPE_OPEN_REARWD:
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=0.0f;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=rearLeftRightSplit;
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=oneMinusRearLeftRightSplit;
break;
default:
PX_ASSERT(false);
break;
}
PX_ASSERT((diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]) >= 0.999f &&
(diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_LEFT] +
diffAveWheelSpeedContributions[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]) <= 1.001f);
}
///////////////////////////////////////////////////////
//Tank differential
///////////////////////////////////////////////////////
void computeTankDiff
(const PxF32 thrustLeft, const PxF32 thrustRight,
const PxU32 numActiveWheels, const bool* activeWheelStates,
PxF32* aveWheelSpeedContributions, PxF32* diffTorqueRatios, PxF32* wheelGearings)
{
const PxF32 thrustLeftAbs=PxAbs(thrustLeft);
const PxF32 thrustRightAbs=PxAbs(thrustRight);
//Work out now many left wheels are enabled.
PxF32 numLeftWheels=0.0f;
for(PxU32 i=0;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
numLeftWheels+=1.0f;
}
}
const PxF32 invNumEnabledWheelsLeft = numLeftWheels > 0 ? 1.0f/numLeftWheels : 0.0f;
//Work out now many right wheels are enabled.
PxF32 numRightWheels=0.0f;
for(PxU32 i=1;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
numRightWheels+=1.0f;
}
}
const PxF32 invNumEnabledWheelsRight = numRightWheels > 0 ? 1.0f/numRightWheels : 0.0f;
//Split the diff torque between left and right.
PxF32 diffTorqueRatioLeft=0.5f;
PxF32 diffTorqueRatioRight=0.5f;
if((thrustLeftAbs + thrustRightAbs) > 1e-3f)
{
const PxF32 thrustDiff = 0.5f*(thrustLeftAbs - thrustRightAbs)/(thrustLeftAbs + thrustRightAbs);
diffTorqueRatioLeft += thrustDiff;
diffTorqueRatioRight -= thrustDiff;
}
diffTorqueRatioLeft *= invNumEnabledWheelsLeft;
diffTorqueRatioRight *= invNumEnabledWheelsRight;
//Compute the per wheel gearing.
PxF32 wheelGearingLeft=1.0f;
PxF32 wheelGearingRight=1.0f;
if((thrustLeftAbs + thrustRightAbs) > 1e-3f)
{
wheelGearingLeft=computeSign(thrustLeft);
wheelGearingRight=computeSign(thrustRight);
}
//Compute the contribution of each wheel to the average speed at the clutch.
const PxF32 aveWheelSpeedContributionLeft = 0.5f*invNumEnabledWheelsLeft;
const PxF32 aveWheelSpeedContributionRight = 0.5f*invNumEnabledWheelsRight;
//Set all the left wheels.
for(PxU32 i=0;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
aveWheelSpeedContributions[i]=aveWheelSpeedContributionLeft;
diffTorqueRatios[i]=diffTorqueRatioLeft;
wheelGearings[i]=wheelGearingLeft;
}
}
//Set all the right wheels.
for(PxU32 i=1;i<numActiveWheels;i+=2)
{
if(activeWheelStates[i])
{
aveWheelSpeedContributions[i]=aveWheelSpeedContributionRight;
diffTorqueRatios[i]=diffTorqueRatioRight;
wheelGearings[i]=wheelGearingRight;
}
}
}
////////////////////////////////////////////////////////////////////////////
//Compute a per-wheel accelerator pedal value.
//These values are to blend the denominator normalised longitudinal slip at low speed
//between a low value for wheels under drive torque and a high value for wheels with no
//drive torque.
//Using a high value allows the vehicle to come to rest smoothly.
//Using a low value gives better thrust.
////////////////////////////////////////////////////////////////////////////
void computeIsAccelApplied(const PxF32* aveWheelSpeedContributions, bool* isAccelApplied)
{
isAccelApplied[0] = aveWheelSpeedContributions[0] != 0.0f ? true : false;
isAccelApplied[1] = aveWheelSpeedContributions[1] != 0.0f ? true : false;
isAccelApplied[2] = aveWheelSpeedContributions[2] != 0.0f ? true : false;
isAccelApplied[3] = aveWheelSpeedContributions[3] != 0.0f ? true : false;
}
////////////////////////////////////////////////////////////////////////////
//Ackermann correction to steer angles.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeAckermannSteerAngles
(const PxF32 steer, const PxF32 steerGain,
const PxF32 ackermannAccuracy, const PxF32 width, const PxF32 axleSeparation,
PxF32* PX_RESTRICT leftAckermannSteerAngle, PxF32* PX_RESTRICT rightAckermannSteerAngle)
{
PX_ASSERT(steer>=-1.01f && steer<=1.01f);
PX_ASSERT(steerGain<PxPi);
const PxF32 steerAngle=steer*steerGain;
if(0==steerAngle)
{
*leftAckermannSteerAngle=0;
*rightAckermannSteerAngle=0;
return;
}
//Work out the ackermann steer for +ve steer then swap and negate the steer angles if the steer is -ve.
//TODO: use faster approximate functions for PxTan/PxATan because the results don't need to be too accurate here.
const PxF32 rightSteerAngle=PxAbs(steerAngle);
const PxF32 dz=axleSeparation;
const PxF32 dx=width + dz/PxTan(rightSteerAngle);
const PxF32 leftSteerAnglePerfect=PxAtan(dz/dx);
const PxF32 leftSteerAngle=rightSteerAngle + ackermannAccuracy*(leftSteerAnglePerfect-rightSteerAngle);
*rightAckermannSteerAngle=physx::intrinsics::fsel(steerAngle, rightSteerAngle, -leftSteerAngle);
*leftAckermannSteerAngle=physx::intrinsics::fsel(steerAngle, leftSteerAngle, -rightSteerAngle);
}
PX_FORCE_INLINE void computeAckermannCorrectedSteerAngles
(const PxVehicleDriveSimData4W& driveSimData, const PxVehicleWheels4SimData& wheelsSimData, const PxF32 steer,
PxF32* PX_RESTRICT steerAngles)
{
const PxVehicleAckermannGeometryData& ackermannData=driveSimData.getAckermannGeometryData();
const PxF32 ackermannAccuracy=ackermannData.mAccuracy;
const PxF32 axleSeparation=ackermannData.mAxleSeparation;
{
const PxVehicleWheelData& wheelDataFL=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_LEFT);
const PxVehicleWheelData& wheelDataFR=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT);
const PxF32 steerGainFront=PxMax(wheelDataFL.mMaxSteer,wheelDataFR.mMaxSteer);
const PxF32 frontWidth=ackermannData.mFrontWidth;
PxF32 frontLeftSteer,frontRightSteer;
computeAckermannSteerAngles(steer,steerGainFront,ackermannAccuracy,frontWidth,axleSeparation,&frontLeftSteer,&frontRightSteer);
steerAngles[PxVehicleDrive4WWheelOrder::eFRONT_LEFT]=wheelDataFL.mToeAngle+frontLeftSteer;
steerAngles[PxVehicleDrive4WWheelOrder::eFRONT_RIGHT]=wheelDataFR.mToeAngle+frontRightSteer;
}
{
const PxVehicleWheelData& wheelDataRL=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_LEFT);
const PxVehicleWheelData& wheelDataRR=wheelsSimData.getWheelData(PxVehicleDrive4WWheelOrder::eREAR_RIGHT);
const PxF32 steerGainRear=PxMax(wheelDataRL.mMaxSteer,wheelDataRR.mMaxSteer);
const PxF32 rearWidth=ackermannData.mRearWidth;
PxF32 rearLeftSteer,rearRightSteer;
computeAckermannSteerAngles(steer,steerGainRear,ackermannAccuracy,rearWidth,axleSeparation,&rearLeftSteer,&rearRightSteer);
steerAngles[PxVehicleDrive4WWheelOrder::eREAR_LEFT]=wheelDataRL.mToeAngle-rearLeftSteer;
steerAngles[PxVehicleDrive4WWheelOrder::eREAR_RIGHT]=wheelDataRR.mToeAngle-rearRightSteer;
}
}
////////////////////////////////////////////////////////////////////////////
//Compute the wheel active states
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeWheelActiveStates(const PxU32 startId, PxU32* bitmapBuffer, bool* activeStates)
{
PX_ASSERT(!activeStates[0] && !activeStates[1] && !activeStates[2] && !activeStates[3]);
PxBitMap bm;
bm.setWords(bitmapBuffer, ((PX_MAX_NB_WHEELS + 31) & ~31) >> 5);
if(bm.test(startId + 0))
{
activeStates[0]=true;
}
if(bm.test(startId + 1))
{
activeStates[1]=true;
}
if(bm.test(startId + 2))
{
activeStates[2]=true;
}
if(bm.test(startId + 3))
{
activeStates[3]=true;
}
}
////////////////////////////////////////////////////////////////////////////
//Compute the brake and handbrake torques for different vehicle types.
//Also compute a boolean for each tire to know if the brake is applied or not.
//Can't use a single function for all types because not all vehicle types have
//handbrakes and the brake control mechanism is different for different vehicle
//types.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void computeNoDriveBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32* PX_RESTRICT rawBrakeTroques,
PxF32* PX_RESTRICT brakeTorques, bool* PX_RESTRICT isBrakeApplied)
{
PX_UNUSED(wheelDatas);
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-sign0*rawBrakeTroques[0]);
isBrakeApplied[0]=(rawBrakeTroques[0]!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-sign1*rawBrakeTroques[1]);
isBrakeApplied[1]=(rawBrakeTroques[1]!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-sign2*rawBrakeTroques[2]);
isBrakeApplied[2]=(rawBrakeTroques[2]!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-sign3*rawBrakeTroques[3]);
isBrakeApplied[3]=(rawBrakeTroques[3]!=0);
}
PX_FORCE_INLINE void computeBrakeAndHandBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32 brake, const PxF32 handbrake,
PxF32* PX_RESTRICT brakeTorques, bool* isBrakeApplied)
{
//At zero speed offer no brake torque allowed.
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-brake*sign0*wheelDatas[0].mMaxBrakeTorque-handbrake*sign0*wheelDatas[0].mMaxHandBrakeTorque);
isBrakeApplied[0]=((brake*wheelDatas[0].mMaxBrakeTorque+handbrake*wheelDatas[0].mMaxHandBrakeTorque)!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-brake*sign1*wheelDatas[1].mMaxBrakeTorque-handbrake*sign1*wheelDatas[1].mMaxHandBrakeTorque);
isBrakeApplied[1]=((brake*wheelDatas[1].mMaxBrakeTorque+handbrake*wheelDatas[1].mMaxHandBrakeTorque)!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-brake*sign2*wheelDatas[2].mMaxBrakeTorque-handbrake*sign2*wheelDatas[2].mMaxHandBrakeTorque);
isBrakeApplied[2]=((brake*wheelDatas[2].mMaxBrakeTorque+handbrake*wheelDatas[2].mMaxHandBrakeTorque)!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-brake*sign3*wheelDatas[3].mMaxBrakeTorque-handbrake*sign3*wheelDatas[3].mMaxHandBrakeTorque);
isBrakeApplied[3]=((brake*wheelDatas[3].mMaxBrakeTorque+handbrake*wheelDatas[3].mMaxHandBrakeTorque)!=0);
}
PX_FORCE_INLINE void computeTankBrakeTorques
(const PxVehicleWheelData* PX_RESTRICT wheelDatas, const PxF32* PX_RESTRICT wheelOmegas, const PxF32 brakeLeft, const PxF32 brakeRight,
PxF32* PX_RESTRICT brakeTorques, bool* isBrakeApplied)
{
//At zero speed offer no brake torque allowed.
const PxF32 sign0=computeSign(wheelOmegas[0]);
brakeTorques[0]=(-brakeLeft*sign0*wheelDatas[0].mMaxBrakeTorque);
isBrakeApplied[0]=((brakeLeft*wheelDatas[0].mMaxBrakeTorque)!=0);
const PxF32 sign1=computeSign(wheelOmegas[1]);
brakeTorques[1]=(-brakeRight*sign1*wheelDatas[1].mMaxBrakeTorque);
isBrakeApplied[1]=((brakeRight*wheelDatas[1].mMaxBrakeTorque)!=0);
const PxF32 sign2=computeSign(wheelOmegas[2]);
brakeTorques[2]=(-brakeLeft*sign2*wheelDatas[2].mMaxBrakeTorque);
isBrakeApplied[2]=((brakeLeft*wheelDatas[2].mMaxBrakeTorque)!=0);
const PxF32 sign3=computeSign(wheelOmegas[3]);
brakeTorques[3]=(-brakeRight*sign3*wheelDatas[3].mMaxBrakeTorque);
isBrakeApplied[3]=((brakeRight*wheelDatas[3].mMaxBrakeTorque)!=0);
}
////////////////////////////////////////////////////////////////////////////
//Functions to compute inputs to tire force calculation.
//1. Filter the normalised tire load to smooth any spikes in load.
//2. Compute the tire lat and long directions in the ground plane.
//3. Compute the tire lat and long slips.
//4. Compute the friction from a graph of friction vs slip.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE PxF32 computeFilteredNormalisedTireLoad(const PxVehicleTireLoadFilterData& filterData, const PxF32 normalisedLoad)
{
if(normalisedLoad <= filterData.mMinNormalisedLoad)
{
return filterData.mMinFilteredNormalisedLoad;
}
else if(normalisedLoad >= filterData.mMaxNormalisedLoad)
{
return filterData.mMaxFilteredNormalisedLoad;
}
else
{
const PxF32 x=normalisedLoad;
const PxF32 xmin=filterData.mMinNormalisedLoad;
const PxF32 ymin=filterData.mMinFilteredNormalisedLoad;
const PxF32 ymax=filterData.mMaxFilteredNormalisedLoad;
const PxF32 recipXmaxMinusXMin=filterData.getDenominator();
return (ymin + (x-xmin)*(ymax-ymin)*recipXmaxMinusXMin);
}
}
PX_FORCE_INLINE void computeTireDirs(const PxVec3& chassisLatDir, const PxVec3& hitNorm, const PxF32 wheelSteerAngle, PxVec3& tireLongDir, PxVec3& tireLatDir)
{
PX_ASSERT(chassisLatDir.magnitude()>0.999f && chassisLatDir.magnitude()<1.001f);
PX_ASSERT(hitNorm.magnitude()>0.999f && hitNorm.magnitude()<1.001f);
//Compute the tire axes in the ground plane.
PxVec3 tzRaw=chassisLatDir.cross(hitNorm);
PxVec3 txRaw=hitNorm.cross(tzRaw);
tzRaw.normalize();
txRaw.normalize();
//Rotate the tire using the steer angle.
const PxF32 cosWheelSteer=PxCos(wheelSteerAngle);
const PxF32 sinWheelSteer=PxSin(wheelSteerAngle);
const PxVec3 tz=tzRaw*cosWheelSteer + txRaw*sinWheelSteer;
const PxVec3 tx=txRaw*cosWheelSteer - tzRaw*sinWheelSteer;
tireLongDir=tz;
tireLatDir=tx;
}
PX_FORCE_INLINE void computeTireSlips
(const PxF32 longSpeed, const PxF32 latSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 maxDenominator,
const bool isAccelApplied, const bool isBrakeApplied,
const bool isTank,
PxF32& longSlip, PxF32& latSlip)
{
PX_ASSERT(maxDenominator>=0.0f);
const PxF32 longSpeedAbs=PxAbs(longSpeed);
const PxF32 wheelSpeed=wheelOmega*wheelRadius;
const PxF32 wheelSpeedAbs=PxAbs(wheelSpeed);
//Lateral slip is easy.
latSlip = PxAtan(latSpeed/(longSpeedAbs+gMinLatSpeedForTireModel));//TODO: do we really use PxAbs(vz) as denominator?
//If nothing is moving just avoid a divide by zero and set the long slip to zero.
if(longSpeed==0 && wheelOmega==0)
{
longSlip=0.0f;
return;
}
//Longitudinal slip is a bit harder because we can end up wtih zero on the denominator.
if(isTank)
{
if(isBrakeApplied || isAccelApplied)
{
//Wheel experiencing an applied torque.
//Use the raw denominator value plus an offset to avoid anything approaching a divide by zero.
//When accelerating from rest the small denominator will generate really quite large
//slip values, which will, in turn, generate large longitudinal forces. With large
//time-steps this might lead to a temporary oscillation in longSlip direction and an
//oscillation in wheel speed direction. The amplitude of the oscillation should be low
//unless the timestep is really large.
//There's not really an obvious solution to this without setting the denominator offset higher
//(or decreasing the timestep). Setting the denominator higher affects handling everywhere so
//settling for a potential temporary oscillation is probably the least worst compromise.
//Note that we always use longSpeedAbs as denominator because in order to turn on the spot the
//tank needs to get strong longitudinal force when it isn't moving but the wheels are slipping.
longSlip = (wheelSpeed - longSpeed)/(longSpeedAbs + 0.1f*gToleranceScaleLength);
}
else
{
//Wheel not experiencing an applied torque.
//If the denominator becomes too small then the longSlip becomes large and the longitudinal force
//can overshoot zero at large timesteps. This can be really noticeable so it's harder to justify
//not taking action. Further, the car isn't being actually driven so there is a strong case to fiddle
//with the denominator because it doesn't really affect active handling.
//Don't let the denominator fall below a user-specified value. This can be tuned upwards until the
//oscillation in the sign of longSlip disappears.
longSlip = (wheelSpeed - longSpeed)/(PxMax(maxDenominator, PxMax(longSpeedAbs,wheelSpeedAbs)));
}
}
else
{
if(isBrakeApplied || isAccelApplied)
{
//Wheel experiencing an applied torque.
//Use the raw denominator value plus an offset to avoid anything approaching a divide by zero.
//When accelerating from rest the small denominator will generate really quite large
//slip values, which will, in turn, generate large longitudinal forces. With large
//time-steps this might lead to a temporary oscillation in longSlip direction and an
//oscillation in wheel speed direction. The amplitude of the oscillation should be low
//unless the timestep is really large.
//There's not really an obvious solution to this without setting the denominator offset higher
//(or decreasing the timestep). Setting the denominator higher affects handling everywhere so
//settling for a potential temporary oscillation is probably the least worst compromise.
longSlip = (wheelSpeed - longSpeed)/(PxMax(longSpeedAbs,wheelSpeedAbs)+0.1f*gToleranceScaleLength);
}
else
{
//Wheel not experiencing an applied torque.
//If the denominator becomes too small then the longSlip becomes large and the longitudinal force
//can overshoot zero at large timesteps. This can be really noticeable so it's harder to justify
//not taking action. Further, the car isn't being actually driven so there is a strong case to fiddle
//with the denominator because it doesn't really affect active handling.
//Don't let the denominator fall below a user-specified value. This can be tuned upwards until the
//oscillation in the sign of longSlip disappears.
longSlip = (wheelSpeed - longSpeed)/(PxMax(maxDenominator,PxMax(longSpeedAbs,wheelSpeedAbs)));
}
}
}
PX_FORCE_INLINE void computeTireFriction(const PxVehicleTireData& tireData, const PxF32 longSlip, const PxF32 frictionMultiplier, PxF32& friction)
{
const PxF32 x0=tireData.mFrictionVsSlipGraph[0][0];
const PxF32 y0=tireData.mFrictionVsSlipGraph[0][1];
const PxF32 x1=tireData.mFrictionVsSlipGraph[1][0];
const PxF32 y1=tireData.mFrictionVsSlipGraph[1][1];
const PxF32 x2=tireData.mFrictionVsSlipGraph[2][0];
const PxF32 y2=tireData.mFrictionVsSlipGraph[2][1];
const PxF32 recipx1Minusx0=tireData.getFrictionVsSlipGraphRecipx1Minusx0();
const PxF32 recipx2Minusx1=tireData.getFrictionVsSlipGraphRecipx2Minusx1();
const PxF32 longSlipAbs=PxAbs(longSlip);
PxF32 mu;
if(longSlipAbs<x1)
{
mu=y0 + (y1-y0)*(longSlipAbs-x0)*recipx1Minusx0;
}
else if(longSlipAbs<x2)
{
mu=y1 + (y2-y1)*(longSlipAbs-x1)*recipx2Minusx1;
}
else
{
mu=y2;
}
PX_ASSERT(mu>=0);
friction=mu*frictionMultiplier;
}
////////////////////////////////////////////////////////////////////////////
//Sticky tire constraints.
//Increment a timer each update that a tire has a very low longitudinal speed.
//Activate a sticky constraint when the tire has had an unbroken low long speed
//for at least a threshold time.
//The longer the sticky constraint is active, the slower the target constraint speed
//along the long dir. Quickly tends towards zero.
//When the sticky constraint is activated set the long slip to zero and let
//the sticky constraint take over.
////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void updateLowForwardSpeedTimer
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 recipWheelRadius, const bool isIntentionToAccelerate,
const PxF32 timestep, PxF32& lowForwardSpeedTime)
{
PX_UNUSED(wheelRadius);
PX_UNUSED(recipWheelRadius);
//If the tire is rotating slowly and the forward speed is slow then increment the slow forward speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 longSpeedAbs=PxAbs(longSpeed);
if((longSpeedAbs<gStickyTireFrictionThresholdSpeed) && (PxAbs(wheelOmega)< gStickyTireFrictionThresholdSpeed*recipWheelRadius) && !isIntentionToAccelerate)
{
lowForwardSpeedTime+=timestep;
}
else
{
lowForwardSpeedTime=0;
}
}
PX_FORCE_INLINE void updateLowSideSpeedTimer
(const PxF32 latSpeed, const bool isIntentionToAccelerate, const PxF32 timestep, PxF32& lowSideSpeedTime)
{
//If the side speed is slow then increment the slow side speed timer.
//If the intention of the driver is to accelerate the vehicle then reset the timer because the intention has been signalled NOT to bring
//the wheel to rest.
PxF32 latSpeedAbs=PxAbs(latSpeed);
if((latSpeedAbs<gStickyTireFrictionThresholdSpeed) && !isIntentionToAccelerate)
{
lowSideSpeedTime+=timestep;
}
else
{
lowSideSpeedTime=0;
}
}
PX_FORCE_INLINE void activateStickyFrictionForwardConstraint
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 lowForwardSpeedTime, const bool isIntentionToAccelerate,
bool& stickyTireActiveFlag, PxF32& stickyTireTargetSpeed)
{
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//The idea here is to resolve the singularity of the tire long slip at low vz by replacing the long force with a velocity constraint.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//Smoothly reduce error to zero to avoid bringing car immediately to rest. This avoids graphical glitchiness.
//We're going to replace the longitudinal tire force with the sticky friction so set the long slip to zero to ensure zero long force.
//Apply sticky friction to this tire if
//(1) the wheel is locked (this means the brake/handbrake must be on) and the forward speed at the tire contact point is vanishingly small and
// the drive of vehicle has no intention to accelerate the vehicle.
//(2) the accumulated time of low forward speed is greater than a threshold.
PxF32 longSpeedAbs=PxAbs(longSpeed);
stickyTireActiveFlag=false;
stickyTireTargetSpeed=0.0f;
if((longSpeedAbs < gStickyTireFrictionThresholdSpeed && 0.0f==wheelOmega && !isIntentionToAccelerate) || lowForwardSpeedTime>gLowForwardSpeedThresholdTime)
{
stickyTireActiveFlag=true;
stickyTireTargetSpeed=longSpeed*gStickyTireFrictionForwardDamping;
}
}
PX_FORCE_INLINE void activateStickyFrictionSideConstraint
(const PxF32 latSpeed, const PxF32 lowSpeedForwardTimer, const PxF32 lowSideSpeedTimer, const bool isIntentionToAccelerate,
bool& stickyTireActiveFlag, PxF32& stickyTireTargetSpeed)
{
PX_UNUSED(latSpeed);
PX_UNUSED(isIntentionToAccelerate);
//Setup the sticky friction constraint to bring the vehicle to rest at the tire contact point.
//Only do this if we can guarantee that the intention is to bring the car to rest (no accel pedal applied).
//Smoothly reduce error to zero to avoid bringing car immediately to rest. This avoids graphical glitchiness.
//We're going to replace the lateral tire force with the sticky friction so set the lat slip to zero to ensure zero lat force.
//Apply sticky friction to this tire if
//(1) the low forward speed timer is > 0.
//(2) the accumulated time of low forward speed is greater than a threshold.
stickyTireActiveFlag=false;
stickyTireTargetSpeed=0.0f;
if((lowSpeedForwardTimer > 0) && lowSideSpeedTimer>gLowSideSpeedThresholdTime)
{
stickyTireActiveFlag=true;
stickyTireTargetSpeed=latSpeed*gStickyTireFrictionSideDamping;
}
}
////////////////////////////////////////////////////////////////////////////
//Default tire force shader function.
//Taken from Michigan tire model.
//Computes tire long and lat forces plus the aligning moment arising from
//the lat force and the torque to apply back to the wheel arising from the
//long force (application of Newton's 3rd law).
////////////////////////////////////////////////////////////////////////////
#define ONE_TWENTYSEVENTH 0.037037f
#define ONE_THIRD 0.33333f
PX_FORCE_INLINE PxF32 smoothingFunction1(const PxF32 K)
{
//Equation 20 in CarSimEd manual Appendix F.
//Looks a bit like a curve of sqrt(x) for 0<x<1 but reaching 1.0 on y-axis at K=3.
PX_ASSERT(K>=0.0f);
return PxMin(1.0f, K - ONE_THIRD*K*K + ONE_TWENTYSEVENTH*K*K*K);
}
PX_FORCE_INLINE PxF32 smoothingFunction2(const PxF32 K)
{
//Equation 21 in CarSimEd manual Appendix F.
//Rises to a peak at K=0.75 and falls back to zero by K=3
PX_ASSERT(K>=0.0f);
return (K - K*K + ONE_THIRD*K*K*K - ONE_TWENTYSEVENTH*K*K*K*K);
}
void PxVehicleComputeTireForceDefault
(const void* tireShaderData,
const PxF32 tireFriction,
const PxF32 longSlipUnClamped, const PxF32 latSlipUnClamped, const PxF32 camberUnclamped,
const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 recipWheelRadius,
const PxF32 restTireLoad, const PxF32 normalisedTireLoad, const PxF32 tireLoad,
const PxF32 gravity, const PxF32 recipGravity,
PxF32& wheelTorque, PxF32& tireLongForceMag, PxF32& tireLatForceMag, PxF32& tireAlignMoment)
{
PX_UNUSED(wheelOmega);
PX_UNUSED(recipWheelRadius);
const PxVehicleTireData& tireData=*reinterpret_cast<const PxVehicleTireData*>(tireShaderData);
PX_ASSERT(tireFriction>0);
PX_ASSERT(tireLoad>0);
wheelTorque=0.0f;
tireLongForceMag=0.0f;
tireLatForceMag=0.0f;
tireAlignMoment=0.0f;
//Clamp the slips to a minimum value.
const PxF32 latSlip = PxAbs(latSlipUnClamped) >= gMinimumSlipThreshold ? latSlipUnClamped : 0.0f;
const PxF32 longSlip = PxAbs(longSlipUnClamped) >= gMinimumSlipThreshold ? longSlipUnClamped : 0.0f;
const PxF32 camber = PxAbs(camberUnclamped) >= gMinimumSlipThreshold ? camberUnclamped : 0.0f;
//If long slip/lat slip/camber are all zero than there will be zero tire force.
if((0==latSlip)&&(0==longSlip)&&(0==camber))
{
return;
}
//Compute the lateral stiffness
const PxF32 latStiff=restTireLoad*tireData.mLatStiffY*smoothingFunction1(normalisedTireLoad*3.0f/tireData.mLatStiffX);
//Get the longitudinal stiffness
const PxF32 longStiff=tireData.mLongitudinalStiffnessPerUnitGravity*gravity;
const PxF32 recipLongStiff=tireData.getRecipLongitudinalStiffnessPerUnitGravity()*recipGravity;
//Get the camber stiffness.
const PxF32 camberStiff=tireData.mCamberStiffnessPerUnitGravity*gravity;
//Carry on and compute the forces.
const PxF32 TEff = PxTan(latSlip - camber*camberStiff/latStiff);
const PxF32 K = PxSqrt(latStiff*TEff*latStiff*TEff + longStiff*longSlip*longStiff*longSlip) /(tireFriction*tireLoad);
//const PxF32 KAbs=PxAbs(K);
PxF32 FBar = smoothingFunction1(K);//K - ONE_THIRD*PxAbs(K)*K + ONE_TWENTYSEVENTH*K*K*K;
PxF32 MBar = smoothingFunction2(K); //K - KAbs*K + ONE_THIRD*K*K*K - ONE_TWENTYSEVENTH*KAbs*K*K*K;
//Mbar = PxMin(Mbar, 1.0f);
PxF32 nu=1;
if(K <= 2.0f*PxPi)
{
const PxF32 latOverlLong=latStiff*recipLongStiff;
nu = 0.5f*(1.0f + latOverlLong - (1.0f - latOverlLong)*PxCos(K*0.5f));
}
const PxF32 FZero = tireFriction*tireLoad / (PxSqrt(longSlip*longSlip + nu*TEff*nu*TEff));
const PxF32 fz = longSlip*FBar*FZero;
const PxF32 fx = -nu*TEff*FBar*FZero;
//TODO: pneumatic trail.
const PxF32 pneumaticTrail=1.0f;
const PxF32 fMy= nu * pneumaticTrail * TEff * MBar * FZero;
//We can add the torque to the wheel.
wheelTorque=-fz*wheelRadius;
tireLongForceMag=fz;
tireLatForceMag=fx;
tireAlignMoment=fMy;
}
////////////////////////////////////////////////////////////////////////////
//Compute the suspension line raycast start point and direction.
////////////////////////////////////////////////////////////////////////////
static PX_INLINE void computeSuspensionRaycast
(const PxTransform& carChassisTrnsfm, const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 radius, const PxF32 maxBounce,
PxVec3& suspLineStart, PxVec3& suspLineDir)
{
//Direction of raycast.
suspLineDir=carChassisTrnsfm.rotate(bodySpaceSuspTravelDir);
//Position at top of wheel at maximum compression.
suspLineStart=carChassisTrnsfm.transform(bodySpaceWheelCentreOffset);
suspLineStart-=suspLineDir*(radius+maxBounce);
}
static PX_INLINE void computeSuspensionSweep
(const PxTransform& carChassisTrnsfm,
const PxQuat& wheelLocalPoseRotation,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 radius, const PxF32 maxBounce,
PxTransform& suspStartPose, PxVec3& suspLineDir)
{
//Direction of raycast.
suspLineDir=carChassisTrnsfm.rotate(bodySpaceSuspTravelDir);
//Position of wheel at maximum compression.
suspStartPose.p = carChassisTrnsfm.transform(bodySpaceWheelCentreOffset);
suspStartPose.p -= suspLineDir*(radius + maxBounce);
//Rotation in world frame.
suspStartPose.q = carChassisTrnsfm.q*wheelLocalPoseRotation;
}
////////////////////////////////////////////////////////////////////////////
//Functions required to intersect the wheel with the hit plane
//We support raycasts and sweeps.
////////////////////////////////////////////////////////////////////////////
static bool intersectRayPlane
(const PxTransform& carChassisTrnsfm,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir,
const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
PxF32& jounce, PxVec3& wheelBottomPos)
{
PX_UNUSED(width);
//Compute the raycast start pos and direction.
PxVec3 v, w;
computeSuspensionRaycast(carChassisTrnsfm, bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, radius, maxCompression, v, w);
//If the raycast starts inside the hit plane then return false
if((hitPlane.n.dot(v) + hitPlane.d) < 0.0f)
{
return false;
}
//Store a point through the centre of the wheel.
//We'll use this later to compute a position at the bottom of the wheel.
const PxVec3 pos = v;
//Remove this code because we handle tire width with sweeps now.
//Work out if the inner or outer disc is deeper in the plane.
//const PxVec3 latDir = carChassisTrnsfm.rotate(gRight);
//const PxF32 signDot = computeSign(hitNorm.dot(latDir));
//v -= latDir*(signDot*0.5f*width);
//Work out the point on the susp line that touches the intersection plane.
//n.(v+wt)+d=0 where n,d describe the plane; v,w describe the susp ray; t is the point on the susp line.
//t=-(n.v + d)/n.w
const PxF32 hitD = hitPlane.d;
const PxVec3 n = hitPlane.n;
const PxF32 d = hitD;
const PxF32 T=-(n.dot(v) + d)/(n.dot(w));
//The rest pos of the susp line is 2*radius + maxBounce.
const PxF32 restT = 2.0f*radius+maxCompression;
//Compute the spring compression ie the difference between T and restT.
//+ve means that the spring is compressed
//-ve means that the spring is elongated.
jounce = restT-T;
//Compute the bottom of the wheel.
//Always choose a point through the centre of the wheel.
wheelBottomPos = pos + w*(restT - jounce);
return true;
}
static bool intersectPlanes(const PxPlane& a, const PxPlane& b, PxVec3& v, PxVec3& w)
{
const PxF32 n1x = a.n.x;
const PxF32 n1y = a.n.y;
const PxF32 n1z = a.n.z;
const PxF32 n1d = a.d;
const PxF32 n2x = b.n.x;
const PxF32 n2y = b.n.y;
const PxF32 n2z = b.n.z;
const PxF32 n2d = b.d;
PxF32 dx = (n1y * n2z) - (n1z * n2y);
PxF32 dy = (n1z * n2x) - (n1x * n2z);
PxF32 dz = (n1x * n2y) - (n1y * n2x);
const PxF32 dx2 = dx * dx;
const PxF32 dy2 = dy * dy;
const PxF32 dz2 = dz * dz;
PxF32 px, py, pz;
bool success = true;
if ((dz2 > dy2) && (dz2 > dx2) && (dz2 > 0))
{
px = ((n1y * n2d) - (n2y * n1d)) / dz;
py = ((n2x * n1d) - (n1x * n2d)) / dz;
pz = 0;
}
else if ((dy2 > dx2) && (dy2 > 0))
{
px = -((n1z * n2d) - (n2z * n1d)) / dy;
py = 0;
pz = -((n2x * n1d) - (n1x * n2d)) / dy;
}
else if (dx2 > 0)
{
px = 0;
py = ((n1z * n2d) - (n2z * n1d)) / dx;
pz = ((n2y * n1d) - (n1y * n2d)) / dx;
}
else
{
px=0;
py=0;
pz=0;
success=false;
}
const PxF32 ld = PxSqrt(dx2 + dy2 + dz2);
dx /= ld;
dy /= ld;
dz /= ld;
w = PxVec3(dx,dy,dz);
v = PxVec3(px,py,pz);
return success;
}
static bool intersectCylinderPlane
(const PxTransform& wheelPoseAtZeroJounce, const PxVec3 suspDir,
const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
const PxVec3& sideAxis,
const bool rejectFromThresholds,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
PxF32& jounce, PxVec3& wheelBottomPos,
const PxVec3& contactPt, float hitDist, bool useDirectSweepResults)
{
//Reject based on the contact normal.
if(rejectFromThresholds)
{
if(suspDir.dot(-hitPlane.n) < normalRejectAngleThresholdCosine)
return false;
}
//Construct the wheel plane that contains the wheel disc.
const PxPlane wheelPlane(wheelPoseAtZeroJounce.p, wheelPoseAtZeroJounce.rotate(sideAxis));
if(useDirectSweepResults)
{
// PT: this codepath fixes PX-2184 / PX-2170 / PX-2297
// We start from the results we want to obtain, i.e. the data provided by the sweeps:
jounce = maxCompression + radius - hitDist;
wheelBottomPos = wheelPlane.project(contactPt);
// PT: and then we re-derive other variables from them, to do the culling.
// This is only needed for touching hits.
if(rejectFromThresholds)
{
// Derive t & pos from above data
const PxF32 t = -jounce; // From "jounce = -t;" in original codepath
const PxVec3 pos = wheelBottomPos - suspDir*t; // From "wheelBottomPos = pos + suspDir*t;" in original codepath
//If the sweep started inside the hit plane then return false
const PxVec3 startPos = pos - suspDir*(radius + maxCompression);
if(hitPlane.n.dot(startPos) + hitPlane.d < 0.0f)
return false;
// PT: derive dir from "const PxVec3 pos = wheelPoseAtZeroJounce.p + dir*radius;" in original codepath.
// We need a normalized dir though so we skip the division by radius.
PxVec3 dir = (pos - wheelPoseAtZeroJounce.p);
dir.normalize();
//Now work out if we accept the hit.
//Compare dir with the suspension direction.
if(suspDir.dot(dir) < pointRejectAngleThresholdCosine)
return false;
}
}
else
{
//Intersect the plane of the wheel with the hit plane.
//This generates an intersection edge.
PxVec3 intersectionEdgeV, intersectionEdgeW;
const bool intersectPlaneSuccess = intersectPlanes(wheelPlane, hitPlane, intersectionEdgeV, intersectionEdgeW);
if(!intersectPlaneSuccess)
{
jounce = 0.0f;
wheelBottomPos = PxVec3(0,0,0);
return false;
}
//Compute the position on the intersection edge that is closest to the wheel centre.
PxVec3 closestPointOnIntersectionEdge;
{
const PxVec3& p = wheelPoseAtZeroJounce.p;
const PxVec3& w = intersectionEdgeW;
const PxVec3& v = intersectionEdgeV;
const PxF32 t = (p - v).dot(w);
closestPointOnIntersectionEdge = v + w*t;
}
//Compute the vector that joins the wheel centre to the intersection edge;
PxVec3 dir;
{
const PxF32 wheelCentreD = hitPlane.n.dot(wheelPoseAtZeroJounce.p) + hitPlane.d;
dir = ((wheelCentreD >= 0) ? closestPointOnIntersectionEdge - wheelPoseAtZeroJounce.p : wheelPoseAtZeroJounce.p - closestPointOnIntersectionEdge);
dir.normalize();
}
//Now work out if we accept the hit.
//Compare dir with the suspension direction.
if(rejectFromThresholds)
{
if(suspDir.dot(dir) < pointRejectAngleThresholdCosine)
return false;
}
//Compute the point on the disc diameter that will be the closest to the hit plane or the deepest inside the hit plane.
const PxVec3 pos = wheelPoseAtZeroJounce.p + dir*radius;
//If the sweep started inside the hit plane then return false
const PxVec3 startPos = pos - suspDir*(radius + maxCompression);
if(hitPlane.n.dot(startPos) + hitPlane.d < 0.0f)
return false;
//Now compute the maximum depth of the inside and outside discs against the plane.
PxF32 depth;
{
const PxVec3 latDir = wheelPoseAtZeroJounce.rotate(sideAxis);
const PxF32 signDot = computeSign(hitPlane.n.dot(latDir));
const PxVec3 deepestPos = pos - latDir*(signDot*0.5f*width);
depth = hitPlane.n.dot(deepestPos) + hitPlane.d;
}
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
const PxF32 t = -depth/(hitPlane.n.dot(suspDir));
//+ve means that the spring is compressed
//-ve means that the spring is elongated.
jounce = -t;
//Compute a point at the bottom of the wheel that is at the centre.
wheelBottomPos = pos + suspDir*t;
}
return true;
}
static bool intersectCylinderPlane
(const PxTransform& carChassisTrnsfm,
const PxQuat& wheelLocalPoseRotation,
const PxVec3& bodySpaceWheelCentreOffset, const PxVec3& bodySpaceSuspTravelDir, const PxF32 width, const PxF32 radius, const PxF32 maxCompression,
const PxPlane& hitPlane,
const PxVec3& sideAxis,
const bool rejectFromThresholds,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
PxF32& jounce, PxVec3& wheelBottomPos,
const PxVec3& contactPt, float hitDist, bool useDirectSweepResults)
{
//Compute the pose of the wheel
PxTransform wheelPostsAtZeroJounce;
PxVec3 suspDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, 0.0f, 0.0f,
wheelPostsAtZeroJounce, suspDir);
//Perform the intersection.
return intersectCylinderPlane
(wheelPostsAtZeroJounce, suspDir,
width, radius, maxCompression,
hitPlane,
sideAxis,
rejectFromThresholds, pointRejectAngleThresholdCosine, normalRejectAngleThresholdCosine,
jounce, wheelBottomPos, contactPt, hitDist, useDirectSweepResults);
}
////////////////////////////////////////////////////////////////////////////
//Structures used to process blocks of 4 wheels: process the raycast result,
//compute the suspension and tire force, store a number of report variables
//such as tire slip, hit shape, hit material, friction etc.
////////////////////////////////////////////////////////////////////////////
class PxVehicleTireForceCalculator4
{
public:
const void* mShaderData[4];
PxVehicleComputeTireForce mShader;
private:
};
//This data structure is passed to processSuspTireWheels
//and represents the data that is logically constant across all sub-steps of each dt update.
struct ProcessSuspWheelTireConstData
{
//We are integrating dt over N sub-steps.
//timeFraction is 1/N.
PxF32 timeFraction;
//We are integrating dt over N sub-steps.
//subTimeStep is dt/N.
PxF32 subTimeStep;
PxF32 recipSubTimeStep;
//Gravitational acceleration vector
PxVec3 gravity;
//Length of gravitational acceleration vector (saves a square root each time we need it)
PxF32 gravityMagnitude;
//Reciprocal length of gravitational acceleration vector (saves a square root and divide each time we need it).
PxF32 recipGravityMagnitude;
//True for tanks, false for all other vehicle types.
//Used when computing the longitudinal and lateral slips.
bool isTank;
//Minimum denominator allowed in longitudinal slip computation.
PxF32 minLongSlipDenominator;
//Pointer to physx actor that represents the vehicle.
const PxRigidDynamic* vehActor;
//Pointer to table of friction values for each combination of material and tire type.
const PxVehicleDrivableSurfaceToTireFrictionPairs* frictionPairs;
//Flags related to wheel simulation (see PxVehicleWheelsSimFlags)
PxU32 wheelsSimFlags;
};
//This data structure is passed to processSuspTireWheels
//and represents the data that is physically constant across each sub-steps of each dt update.
struct ProcessSuspWheelTireInputData
{
public:
//True if the driver intends to pass drive torque to any wheel of the vehicle,
//even if none of the wheels in the block of 4 wheels processed in processSuspTireWheels are given drive torque.
//False if the driver does not intend the vehicle to accelerate.
//If the player intends to accelerate then no wheel will be given a sticky tire constraint.
//This data is actually logically constant.
bool isIntentionToAccelerate;
//True if a wheel has a non-zero diff torque, false if a wheel has zero diff torque.
//This data is actually logically constant.
const bool* isAccelApplied;
//True if a wheel has a non-zero brake torque, false if a wheel has zero brake torque.
//This data is actually logically constant.
const bool* isBrakeApplied;
//Steer angles of each wheel in radians.
//This data is actually logically constant.
const PxF32* steerAngles;
//True if the wheel is not disabled, false if wheel is disabled.
//This data is actually logically constant.
bool* activeWheelStates;
//Properties of the rigid body - transform.
//This data is actually logically constant.
PxTransform carChassisTrnsfm;
//Properties of the rigid body - linear velocity.
//This data is actually logically constant.
PxVec3 carChassisLinVel;
//Properties of the rigid body - angular velocity
//This data is actually logically constant.
PxVec3 carChassisAngVel;
//Properties of the wheel shapes at the last sweep.
const PxQuat* wheelLocalPoseRotations;
//Simulation data for the 4 wheels being processed in processSuspTireWheels
//This data is actually logically constant.
const PxVehicleWheels4SimData* vehWheels4SimData;
//Dynamics data for the 4 wheels being processed in processSuspTireWheels
//This data is a mixture of logically and physically constant.
//We could update some of the data in vehWheels4DynData in processSuspTireWheels
//but we choose to do it after. By specifying the non-constant data members explicitly
//in ProcessSuspWheelTireOutputData we are able to more easily keep a track of the
//constant and non-constant data members. After processSuspTireWheels is complete
//we explicitly transfer the updated data in ProcessSuspWheelTireOutputData to vehWheels4DynData.
//Examples are low long and lat forward speed timers.
const PxVehicleWheels4DynData* vehWheels4DynData;
//Shaders to calculate the tire forces.
//This data is actually logically constant.
const PxVehicleTireForceCalculator4* vehWheels4TireForceCalculator;
//Filter function to filter tire load.
//This data is actually logically constant.
const PxVehicleTireLoadFilterData* vehWheels4TireLoadFilterData;
//How many of the 4 wheels are real wheels (eg a 6-wheeled car has a
//block of 4 wheels then a 2nd block of 4 wheels with only 2 active wheels)
//This data is actually logically constant.
PxU32 numActiveWheels;
};
struct ProcessSuspWheelTireOutputData
{
public:
ProcessSuspWheelTireOutputData()
{
PxMemZero(this, sizeof(ProcessSuspWheelTireOutputData));
for(PxU32 i=0;i<4;i++)
{
isInAir[i]=true;
tireSurfaceTypes[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//The following data is stored so that it may be later passed to PxVehicleWheelQueryResult
/////////////////////////////////////////////////////////////////////////////////////////////
//Raycast start [most recent raycast start coord or (0,0,0) if using a cached raycast]
PxVec3 suspLineStarts[4];
//Raycast start [most recent raycast direction or (0,0,0) if using a cached raycast]
PxVec3 suspLineDirs[4];
//Raycast start [most recent raycast length or 0 if using a cached raycast]
PxF32 suspLineLengths[4];
//False if wheel cannot touch the ground.
bool isInAir[4];
//Actor hit by most recent raycast, NULL if using a cached raycast.
PxActor* tireContactActors[4];
//Shape hit by most recent raycast, NULL if using a cached raycast.
PxShape* tireContactShapes[4];
//Material hit by most recent raycast, NULL if using a cached raycast.
PxMaterial* tireSurfaceMaterials[4];
//Surface type of material hit by most recent raycast, eSURFACE_TYPE_UNKNOWN if using a cached raycast.
PxU32 tireSurfaceTypes[4];
//Contact point of raycast against either fresh contact plane from fresh raycast or cached contact plane.
PxVec3 tireContactPoints[4];
//Contact normal of raycast against either fresh contact plane from fresh raycast or cached contact plane.
PxVec3 tireContactNormals[4];
//Friction experienced by tire (value from friction table for surface/tire type combos multiplied by friction vs slip graph)
PxF32 frictions[4];
//Jounce experienced by suspension against fresh or cached contact plane.
PxF32 jounces[4];
//Suspension force to be applied to rigid body.
PxF32 suspensionSpringForces[4];
//Longitudinal direction of tire in the ground contact plane.
PxVec3 tireLongitudinalDirs[4];
//Lateral direction of tire in the ground contact plane.
PxVec3 tireLateralDirs[4];
//Longitudinal slip.
PxF32 longSlips[4];
//Lateral slip.
PxF32 latSlips[4];
//Forward speed of rigid body along tire longitudinal direction at tire base.
//Used later to blend the integrated wheel rotation angle between rolling speed and computed speed
//when the wheel rotation speeds become unreliable at low forward speeds.
PxF32 forwardSpeeds[4];
//Torque to be applied to wheel as 1d rigid body. Taken from the longitudinal tire force.
//(Newton's 3rd law means the longitudinal tire force must have an equal and opposite force).
//(The lateral tire force is assumed to be absorbed by the suspension geometry).
PxF32 tireTorques[4];
//Force to be applied to rigid body (accumulated across all 4 wheels/tires/suspensions).
PxVec3 chassisForce;
//Torque to be applied to rigid body (accumulated across all 4 wheels/tires/suspensions).
PxVec3 chassisTorque;
//Updated time spend at low forward speed.
//Needs copied back to vehWheels4DynData
PxF32 newLowForwardSpeedTimers[4];
//Updated time spend at low lateral speed.
//Needs copied back to vehWheels4DynData
PxF32 newLowSideSpeedTimers[4];
//Constraint data for sticky tire constraints and suspension limit constraints.
//Needs copied back to vehWheels4DynData
PxVehicleConstraintShader::VehicleConstraintData vehConstraintData;
//Store the details of the raycast hit results so that they may be re-used
//next update in the event that no raycast is performed.
//If no raycast was performed then the cached values are just re-copied here
//so that they can be recycled without having to do further tests on whether
//raycasts were performed or not.
//Needs copied back to vehWheels4DynData after the last call to processSuspTireWheels.
//The union of cached hit data and susp raycast data means we don't want to overwrite the
//raycast data until we don't need it any more.
PxU32 cachedHitCounts[4];
PxPlane cachedHitPlanes[4];
PxF32 cachedHitDistances[4];
PxF32 cachedFrictionMultipliers[4];
PxU16 cachedHitQueryTypes[4];
//Store the details of the force applied to any dynamic actor hit by wheel raycasts.
PxRigidDynamic* hitActors[4];
PxVec3 hitActorForces[4];
PxVec3 hitActorForcePositions[4];
};
////////////////////////////////////////////////////////////////////////////
//Monster function to
//1. compute the tire/susp forces
//2. compute the torque to apply to the 1D rigid body wheel arising from the long tire force
//3. process the sticky tire friction constraints
// (monitor and increment the low long + lat speed timers, compute data for the sticky tire constraint if necessary)
//4. process the suspension limit constraints
// (monitor the suspension jounce versus the suspension travel limit, compute the data for the suspension limit constraint if necessary).
//5. record the contact plane so that it may be re-used in future updates in the absence of fresh raycasts.
//6. record telemetry data (if necessary) and record data for reporting such as hit material, hit normal etc.
////////////////////////////////////////////////////////////////////////////
namespace
{
struct LocalHitData
{
template<class T>
void setFrom(const T& hit)
{
actor = hit.actor;
shape = hit.shape;
position = hit.position;
normal = hit.normal;
distance = hit.distance;
faceIndex = hit.faceIndex;
}
PxRigidActor* actor;
PxShape* shape;
PxVec3 position;
PxVec3 normal;
PxF32 distance;
PxU32 faceIndex;
};
}
static void storeHit
(const ProcessSuspWheelTireConstData& constData, const ProcessSuspWheelTireInputData& inputData,
const PxU16 hitQueryType,
const LocalHitData& hit, const PxPlane& hitPlane,
const PxU32 i,
PxU32* hitCounts4,
PxF32* hitDistances4,
PxPlane* hitPlanes4,
PxF32* hitFrictionMultipliers4,
PxU16* hitQueryTypes4,
PxShape** hitContactShapes4,
PxRigidActor** hitContactActors4,
PxMaterial** hitContactMaterials4,
PxU32* hitSurfaceTypes4,
PxVec3* hitContactPoints4,
PxVec3* hitContactNormals4,
PxU32* cachedHitCounts,
PxPlane* cachedHitPlanes,
PxF32* cachedHitDistances,
PxF32* cachedFrictionMultipliers,
PxU16* cachedHitQueryTypes)
{
//Hit count.
hitCounts4[i] = 1;
//Hit distance.
hitDistances4[i] = hit.distance;
//Hit plane.
hitPlanes4[i] = hitPlane;
//Hit friction.
PxMaterial* material = NULL;
{
//Only get the material if the raycast started outside the hit shape.
PxBaseMaterial* baseMaterial = (hit.distance != 0.0f) ? hit.shape->getMaterialFromInternalFaceIndex(hit.faceIndex) : NULL;
PX_ASSERT(!baseMaterial || baseMaterial->getConcreteType()==PxConcreteType::eMATERIAL);
material = static_cast<PxMaterial*>(baseMaterial);
}
const PxVehicleDrivableSurfaceToTireFrictionPairs* PX_RESTRICT frictionPairs = constData.frictionPairs;
const PxU32 surfaceType = material ? frictionPairs->getSurfaceType(*material) : 0;
const PxVehicleTireData& tire = inputData.vehWheels4SimData->getTireData(i);
const PxU32 tireType = tire.mType;
const PxF32 frictionMultiplier = frictionPairs->getTypePairFriction(surfaceType, tireType);
PX_ASSERT(frictionMultiplier >= 0);
hitFrictionMultipliers4[i] = frictionMultiplier;
//Hit type.
hitQueryTypes4[i] = hitQueryType;
//Hit report.
hitContactShapes4[i] = hit.shape;
hitContactActors4[i] = hit.actor;
hitContactMaterials4[i] = material;
hitSurfaceTypes4[i] = surfaceType;
hitContactPoints4[i] = hit.position;
hitContactNormals4[i] = hit.normal;
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i] = 1;
cachedHitPlanes[i] = hitPlane;
cachedHitDistances[i] = hit.distance;
cachedFrictionMultipliers[i] = frictionMultiplier;
cachedHitQueryTypes[i] = hitQueryType;
}
static void processSuspTireWheels
(const PxU32 startWheelIndex,
const ProcessSuspWheelTireConstData& constData, const ProcessSuspWheelTireInputData& inputData,
const PxVec3& sideAxis,
const PxF32 pointRejectAngleThresholdCosine,
const PxF32 normalRejectAngleThresholdCosine,
const PxF32 maxHitActorAcceleration,
ProcessSuspWheelTireOutputData& outputData,
VehicleTelemetryDataContext* vehTelemetryDataContext)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(startWheelIndex);
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; //tzRaw.normalize(); in computeTireDirs threw a denorm exception on osx
#if PX_DEBUG_VEHICLE_ON
PX_ASSERT(0==(startWheelIndex & 3));
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eJOUNCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eSUSPFORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRELOAD, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORMALIZED_TIRELOAD, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORM_TIRE_LONG_FORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eNORM_TIRE_LAT_FORCE, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_LONG_SLIP, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_LAT_SLIP, vehTelemetryDataContext->wheelGraphData);
zeroGraphDataWheels(startWheelIndex,PxVehicleWheelGraphChannel::eTIRE_FRICTION, vehTelemetryDataContext->wheelGraphData);
}
#endif
//Unpack the logically constant data.
const PxVec3& gravity=constData.gravity;
const PxF32 timeFraction=constData.timeFraction;
const PxF32 timeStep=constData.subTimeStep;
const PxF32 recipTimeStep=constData.recipSubTimeStep;
const PxF32 recipGravityMagnitude=constData.recipGravityMagnitude;
const PxF32 gravityMagnitude=constData.gravityMagnitude;
const bool isTank=constData.isTank;
const PxF32 minLongSlipDenominator=constData.minLongSlipDenominator;
const PxU32 wheelsSimFlags = constData.wheelsSimFlags;
//Unpack the input data (physically constant data).
const PxVehicleWheels4SimData& wheelsSimData=*inputData.vehWheels4SimData;
const PxVehicleWheels4DynData& wheelsDynData=*inputData.vehWheels4DynData;
const PxVehicleTireForceCalculator4& tireForceCalculator=*inputData.vehWheels4TireForceCalculator;
const PxVehicleTireLoadFilterData& tireLoadFilterData=*inputData.vehWheels4TireLoadFilterData;
//More constant data describing the 4 wheels under consideration.
const PxF32* PX_RESTRICT tireRestLoads=wheelsSimData.getTireRestLoadsArray();
const PxF32* PX_RESTRICT recipTireRestLoads=wheelsSimData.getRecipTireRestLoadsArray();
//Compute the right direction for later.
const PxTransform& carChassisTrnsfm=inputData.carChassisTrnsfm;
const PxVec3 latDir=inputData.carChassisTrnsfm.rotate(sideAxis);
//Unpack the linear and angular velocity of the rigid body.
const PxVec3& carChassisLinVel=inputData.carChassisLinVel;
const PxVec3& carChassisAngVel=inputData.carChassisAngVel;
//Wheel local poses
const PxQuat* PX_RESTRICT wheelLocalPoseRotations = inputData.wheelLocalPoseRotations;
//Inputs (accel, steer, brake).
const bool isIntentionToAccelerate=inputData.isIntentionToAccelerate;
const PxF32* steerAngles=inputData.steerAngles;
const bool* isBrakeApplied=inputData.isBrakeApplied;
const bool* isAccelApplied=inputData.isAccelApplied;
//Disabled/enabled wheel states.
const bool* activeWheelStates=inputData.activeWheelStates;
//Current low forward/side speed timers. Note that the updated timers
//are stored in newLowForwardSpeedTimers and newLowSideSpeedTimers.
const PxF32* PX_RESTRICT lowForwardSpeedTimers=wheelsDynData.mTireLowForwardSpeedTimers;
const PxF32* PX_RESTRICT lowSideSpeedTimers=wheelsDynData.mTireLowSideSpeedTimers;
//Susp jounces and speeds from previous call to processSuspTireWheels.
const PxF32* PX_RESTRICT prevJounces=wheelsDynData.mJounces;
//Unpack the output data (the data we are going to compute).
//Start with the data stored for reporting to PxVehicleWheelQueryResult.
//PxVec3* suspLineStarts=outputData.suspLineStarts;
//PxVec3* suspLineDirs=outputData.suspLineDirs;
//PxF32* suspLineLengths=outputData.suspLineLengths;
bool* isInAirs=outputData.isInAir;
PxActor** tireContactActors=outputData.tireContactActors;
PxShape** tireContactShapes=outputData.tireContactShapes;
PxMaterial** tireSurfaceMaterials=outputData.tireSurfaceMaterials;
PxU32* tireSurfaceTypes=outputData.tireSurfaceTypes;
PxVec3* tireContactPoints=outputData.tireContactPoints;
PxVec3* tireContactNormals=outputData.tireContactNormals;
PxF32* frictions=outputData.frictions;
PxF32* jounces=outputData.jounces;
PxF32* suspensionSpringForces=outputData.suspensionSpringForces;
PxVec3* tireLongitudinalDirs=outputData.tireLongitudinalDirs;
PxVec3* tireLateralDirs=outputData.tireLateralDirs;
PxF32* longSlips=outputData.longSlips;
PxF32* latSlips=outputData.latSlips;
//Now unpack the forward speeds that are used later to blend the integrated wheel
//rotation angle between rolling speed and computed speed when the wheel rotation
//speeds become unreliable at low forward speeds.
PxF32* forwardSpeeds=outputData.forwardSpeeds;
//Unpack the real outputs of this function (wheel torques to apply to 1d rigid body wheel and forces/torques
//to apply to 3d rigid body chassis).
PxF32* tireTorques=outputData.tireTorques;
PxVec3& chassisForce=outputData.chassisForce;
PxVec3& chassisTorque=outputData.chassisTorque;
//Unpack the low speed timers that will be computed.
PxF32* newLowForwardSpeedTimers=outputData.newLowForwardSpeedTimers;
PxF32* newLowSideSpeedTimers=outputData.newLowSideSpeedTimers;
//Unpack the constraint data for suspensions limit and sticky tire constraints.
//Susp limits.
bool* suspLimitActiveFlags=outputData.vehConstraintData.mSuspLimitData.mActiveFlags;
PxVec3* suspLimitDirs=outputData.vehConstraintData.mSuspLimitData.mDirs;
PxVec3* suspLimitCMOffsets=outputData.vehConstraintData.mSuspLimitData.mCMOffsets;
PxF32* suspLimitErrors=outputData.vehConstraintData.mSuspLimitData.mErrors;
//Longitudinal sticky tires.
bool* stickyTireForwardActiveFlags=outputData.vehConstraintData.mStickyTireForwardData.mActiveFlags;
PxVec3* stickyTireForwardDirs=outputData.vehConstraintData.mStickyTireForwardData.mDirs;
PxVec3* stickyTireForwardCMOffsets=outputData.vehConstraintData.mStickyTireForwardData.mCMOffsets;
PxF32* stickyTireForwardTargetSpeeds=outputData.vehConstraintData.mStickyTireForwardData.mTargetSpeeds;
//Lateral sticky tires.
bool* stickyTireSideActiveFlags=outputData.vehConstraintData.mStickyTireSideData.mActiveFlags;
PxVec3* stickyTireSideDirs=outputData.vehConstraintData.mStickyTireSideData.mDirs;
PxVec3* stickyTireSideCMOffsets=outputData.vehConstraintData.mStickyTireSideData.mCMOffsets;
PxF32* stickyTireSideTargetSpeeds=outputData.vehConstraintData.mStickyTireSideData.mTargetSpeeds;
//Hit data. Store the contact data so it can be reused.
PxU32* cachedHitCounts=outputData.cachedHitCounts;
PxPlane* cachedHitPlanes=outputData.cachedHitPlanes;
PxF32* cachedHitDistances=outputData.cachedHitDistances;
PxF32* cachedFrictionMultipliers=outputData.cachedFrictionMultipliers;
PxU16* cachedHitQueryTypes=outputData.cachedHitQueryTypes;
//Hit actor data.
PxRigidDynamic** hitActors=outputData.hitActors;
PxVec3* hitActorForces=outputData.hitActorForces;
PxVec3* hitActorForcePositions=outputData.hitActorForcePositions;
//Set the cmass rotation straight away (we might need this, we might not but we don't know that yet so just set it).
outputData.vehConstraintData.mCMassRotation = constData.vehActor->getCMassLocalPose().q;
//Compute all the hit data (counts, distances, planes, frictions, actors, shapes, materials etc etc).
//If we just did a raycast/sweep then we need to compute all this from the hit reports.
//If we are using cached raycast/sweep results then just copy the cached hit result data.
PxU32 hitCounts4[4];
PxF32 hitDistances4[4];
PxPlane hitPlanes4[4];
PxF32 hitFrictionMultipliers4[4];
PxU16 hitQueryTypes4[4];
PxShape* hitContactShapes4[4];
PxRigidActor* hitContactActors4[4];
PxMaterial* hitContactMaterials4[4];
PxU32 hitSurfaceTypes4[4];
PxVec3 hitContactPoints4[4];
PxVec3 hitContactNormals4[4];
const PxRaycastBuffer* PX_RESTRICT raycastResults=inputData.vehWheels4DynData->mRaycastResults;
const PxSweepBuffer* PX_RESTRICT sweepResults=inputData.vehWheels4DynData->mSweepResults;
if(raycastResults || sweepResults)
{
const PxU16 queryType = raycastResults ? 0u : 1u;
//If we have a blocking hit then always take that.
//If we don't have a blocking hit then search for the "best" hit from all the touches.
for(PxU32 i=0;i<inputData.numActiveWheels;i++)
{
//Test that raycasts issue blocking hits.
PX_CHECK_AND_RETURN(!raycastResults || (0 == raycastResults[i].nbTouches), "Raycasts must generate blocking hits");
PX_CHECK_MSG(!sweepResults || (PxBatchQueryStatus::getStatus(sweepResults[i]) != PxBatchQueryStatus::eOVERFLOW), "PxVehicleUpdate::suspensionSweeps - batched sweep touch array not large enough to perform sweep.");
PxU32 hitCount = 0;
if ((raycastResults && raycastResults[i].hasBlock) || (sweepResults && sweepResults[i].hasBlock))
{
//We have a blocking hit so use that.
LocalHitData hit;
if(raycastResults)
hit.setFrom(raycastResults[i].block);
else
hit.setFrom(sweepResults[i].block);
//Test that the hit actor isn't the vehicle itself.
PX_CHECK_AND_RETURN(constData.vehActor != hit.actor, "Vehicle raycast has hit itself. Please check the filter data to avoid this.");
//Reject if the sweep started inside the hit shape.
if (hit.distance != 0)
{
//Compute the plane of the hit.
const PxPlane hitPlane(hit.position, hit.normal);
//Store the hit data in the various arrays.
storeHit(constData, inputData,
queryType,
hit, hitPlane,
i,
hitCounts4,
hitDistances4,
hitPlanes4,
hitFrictionMultipliers4,
hitQueryTypes4,
hitContactShapes4,
hitContactActors4,
hitContactMaterials4,
hitSurfaceTypes4,
hitContactPoints4,
hitContactNormals4,
cachedHitCounts,
cachedHitPlanes,
cachedHitDistances,
cachedFrictionMultipliers,
cachedHitQueryTypes);
hitCount = 1;
}
}
else if (sweepResults && sweepResults[i].nbTouches)
{
//We need wheel info so that we can analyse the hit and reject/accept it.
//Get what we need now.
const PxVehicleWheelData& wheel = wheelsSimData.getWheelData(i);
const PxVehicleSuspensionData& susp = wheelsSimData.getSuspensionData(i);
const PxVec3& bodySpaceWheelCentreOffset = wheelsSimData.getWheelCentreOffset(i);
const PxVec3& bodySpaceSuspTravelDir = wheelsSimData.getSuspTravelDirection(i);
const PxQuat& wheelLocalPoseRotation = wheelLocalPoseRotations[i];
const PxF32 width = wheel.mWidth;
const PxF32 radius = wheel.mRadius;
const PxF32 maxBounce = susp.mMaxCompression;
//Compute the global pose of the wheel at zero jounce.
PxTransform suspPose;
PxVec3 suspDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, 0.0f, 0.0f,
suspPose, suspDir);
//Iterate over all touches and cache the deepest hit that we accept.
PxF32 bestTouchDistance = -PX_MAX_F32;
for (PxU32 j = 0; j < sweepResults[i].nbTouches; j++)
{
//Get the next candidate hit.
LocalHitData hit;
hit.setFrom(sweepResults[i].touches[j]);
//Test that the hit actor isn't the vehicle itself.
PX_CHECK_AND_RETURN(constData.vehActor != hit.actor, "Vehicle raycast has hit itself. Please check the filter data to avoid this.");
//Reject if the sweep started inside the hit shape.
if (hit.distance != 0.0f)
{
//Compute the plane of the hit.
const PxPlane hitPlane(hit.position, hit.normal);
const bool useDirectSweepResults = (wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST)!=0;
//Intersect the wheel disc with the hit plane and compute the jounce required to move the wheel free of the hit plane.
PxF32 dx;
PxVec3 wheelBottomPos;
const bool successIntersection =
intersectCylinderPlane
(suspPose, suspDir,
width, radius, maxBounce,
hitPlane,
sideAxis,
true, pointRejectAngleThresholdCosine, normalRejectAngleThresholdCosine,
dx, wheelBottomPos, hit.position, hit.distance, useDirectSweepResults);
//If we accept the intersection and it requires more jounce than previously encountered then
//store the hit.
if (successIntersection && dx > bestTouchDistance)
{
storeHit(constData, inputData,
queryType,
hit, hitPlane,
i,
hitCounts4,
hitDistances4,
hitPlanes4,
hitFrictionMultipliers4,
hitQueryTypes4,
hitContactShapes4,
hitContactActors4,
hitContactMaterials4,
hitSurfaceTypes4,
hitContactPoints4,
hitContactNormals4,
cachedHitCounts,
cachedHitPlanes,
cachedHitDistances,
cachedFrictionMultipliers,
cachedHitQueryTypes);
bestTouchDistance = dx;
hitCount = 1;
}
}
}
}
if(0 == hitCount)
{
hitCounts4[i]=0;
hitDistances4[i]=0;
hitPlanes4[i]=PxPlane(PxVec3(0,0,0),0);
hitFrictionMultipliers4[i]=0;
hitQueryTypes4[i]=0u;
hitContactShapes4[i]=NULL;
hitContactActors4[i]=NULL;
hitContactMaterials4[i]=NULL;
hitSurfaceTypes4[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
hitContactPoints4[i]=PxVec3(0,0,0);
hitContactNormals4[i]=PxVec3(0,0,0);
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i]=0;
cachedHitPlanes[i]= PxPlane(PxVec3(0,0,0),0);
cachedHitDistances[i]=0;
cachedFrictionMultipliers[i]=0;
cachedHitQueryTypes[i] = 0u;
}
}
}
else
{
//If we have no sq results then we must have a cached raycast hit result.
const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult& cachedHitResult =
reinterpret_cast<const PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult&>(inputData.vehWheels4DynData->mQueryOrCachedHitResults);
for(PxU32 i=0;i<inputData.numActiveWheels;i++)
{
hitCounts4[i]=cachedHitResult.mCounts[i];
hitDistances4[i]=cachedHitResult.mDistances[i];
hitPlanes4[i]=cachedHitResult.mPlanes[i];
hitFrictionMultipliers4[i]=cachedHitResult.mFrictionMultipliers[i];
hitQueryTypes4[i] = cachedHitResult.mQueryTypes[i];
hitContactShapes4[i]=NULL;
hitContactActors4[i]=NULL;
hitContactMaterials4[i]=NULL;
hitSurfaceTypes4[i]=PxU32(PxVehicleDrivableSurfaceType::eSURFACE_TYPE_UNKNOWN);
hitContactPoints4[i]=PxVec3(0,0,0);
hitContactNormals4[i]=PxVec3(0,0,0);
//When we're finished here we need to copy this back to the vehicle.
cachedHitCounts[i]=cachedHitResult.mCounts[i];
cachedHitPlanes[i]=cachedHitResult.mPlanes[i];
cachedHitDistances[i]=cachedHitResult.mDistances[i];
cachedFrictionMultipliers[i]=cachedHitResult.mFrictionMultipliers[i];
cachedHitQueryTypes[i]=cachedHitResult.mQueryTypes[i];
}
}
//Iterate over all 4 wheels.
for(PxU32 i=0;i<4;i++)
{
//Constant data of the ith wheel.
const PxVehicleWheelData& wheel=wheelsSimData.getWheelData(i);
const PxVehicleSuspensionData& susp=wheelsSimData.getSuspensionData(i);
const PxVehicleTireData& tire=wheelsSimData.getTireData(i);
const PxVec3& bodySpaceWheelCentreOffset=wheelsSimData.getWheelCentreOffset(i);
const PxVec3& bodySpaceSuspTravelDir=wheelsSimData.getSuspTravelDirection(i);
//Take a copy of the low forward/side speed timer of the ith wheel (time spent at low forward/side speed)
//Do this so we can quickly tell if the low/side forward speed timer changes.
newLowForwardSpeedTimers[i]=lowForwardSpeedTimers[i];
newLowSideSpeedTimers[i]=lowSideSpeedTimers[i];
//Reset the graph of the jounce to max droop.
//This will get updated as we learn more about the suspension.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspJounce(startWheelIndex, i,-susp.mMaxDroop, vehTelemetryDataContext->wheelGraphData);
#endif
//Reset the jounce to max droop.
//This will get updated as we learn more about the suspension and tire.
PxF32 jounce=-susp.mMaxDroop;
jounces[i]=jounce;
//Deactivate the sticky tire and susp limit constraint.
//These will get updated as we learn more about the suspension and tire.
suspLimitActiveFlags[i]=false;
suspLimitErrors[i]=0.0f;
stickyTireForwardActiveFlags[i]=false;
stickyTireForwardTargetSpeeds[i]=0;
stickyTireSideActiveFlags[i]=false;
stickyTireSideTargetSpeeds[i]=0;
//The vehicle is in the air until we know otherwise.
isInAirs[i]=true;
//If there has been a hit then compute the suspension force and tire load.
//Ignore the hit if the raycast starts inside the hit shape (eg wheel completely underneath surface of a heightfield).
const bool activeWheelState=activeWheelStates[i];
const PxU32 numHits=hitCounts4[i];
const PxVec3 hitNorm(hitPlanes4[i].n);
const PxVec3 w = carChassisTrnsfm.q.rotate(bodySpaceSuspTravelDir);
if(activeWheelState && numHits > 0 && hitDistances4[i] != 0.0f && hitNorm.dot(w) < 0.0f)
{
//Get the friction multiplier from the combination of surface type and tire type.
const PxF32 frictionMultiplier=hitFrictionMultipliers4[i];
PX_ASSERT(frictionMultiplier>=0);
PxF32 dx;
PxVec3 wheelBottomPos;
bool successIntersection = true;
if(0 == hitQueryTypes4[i])
{
successIntersection = intersectRayPlane
(carChassisTrnsfm,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, wheel.mWidth, wheel.mRadius, susp.mMaxCompression,
hitPlanes4[i],
dx, wheelBottomPos);
}
else
{
const bool useDirectSweepResults = (wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_INTERNAL_CYLINDER_PLANE_INTERSECTION_TEST)!=0;
PX_ASSERT(1 == hitQueryTypes4[i]);
successIntersection = intersectCylinderPlane
(carChassisTrnsfm,
wheelLocalPoseRotations[i],
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, wheel.mWidth, wheel.mRadius, susp.mMaxCompression,
hitPlanes4[i],
sideAxis,
false, 0.0f, 0.0f,
dx, wheelBottomPos, hitContactPoints4[i], hitDistances4[i], useDirectSweepResults);
}
//If the spring is elongated past its max droop then the wheel isn't touching the ground.
//In this case the spring offers zero force and provides no support for the chassis/sprung mass.
//Only carry on computing the spring force if the wheel is touching the ground.
PX_ASSERT(susp.mMaxCompression>=0);
PX_ASSERT(susp.mMaxDroop>=0);
if(dx > -susp.mMaxDroop && successIntersection)
{
//We can record the hit shape, hit actor, hit material, hit surface type, hit point, and hit normal now because we've got a hit.
tireContactShapes[i]=hitContactShapes4[i];
tireContactActors[i]=hitContactActors4[i];
tireSurfaceMaterials[i]=hitContactMaterials4[i];
tireSurfaceTypes[i]=hitSurfaceTypes4[i];
tireContactPoints[i]=hitContactPoints4[i];
tireContactNormals[i]=hitContactNormals4[i];
//Clamp the spring compression so that it is never greater than the max bounce.
//Apply the susp limit constraint if the spring compression is greater than the max bounce.
suspLimitErrors[i] = (w.dot(hitNorm))*(-dx + susp.mMaxCompression);
suspLimitActiveFlags[i] = (dx > susp.mMaxCompression);
suspLimitCMOffsets[i] = bodySpaceWheelCentreOffset;
suspLimitDirs[i] = bodySpaceSuspTravelDir;
jounce=PxMin(dx,susp.mMaxCompression);
//Store the jounce (having a local copy avoids lhs).
jounces[i]=jounce;
//Store the jounce in the graph.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspJounce(startWheelIndex, i,jounce, vehTelemetryDataContext->wheelGraphData);
#endif
//Compute the speed of the rigid body along the suspension travel dir at the
//bottom of the wheel.
const PxVec3 r=wheelBottomPos-carChassisTrnsfm.p;
PxVec3 wheelBottomVel=carChassisLinVel;
wheelBottomVel+=carChassisAngVel.cross(r);
//Modify the relative velocity at the wheel contact point if the hit actor is a dynamic.
PxRigidDynamic* dynamicHitActor=NULL;
PxVec3 hitActorVelocity(0,0,0);
if(hitContactActors4[i] && ((dynamicHitActor = hitContactActors4[i]->is<PxRigidDynamic>()) != NULL))
{
hitActorVelocity = PxRigidBodyExt::getVelocityAtPos(*dynamicHitActor,wheelBottomPos);
wheelBottomVel -= hitActorVelocity;
}
//Get the speed of the jounce.
PxF32 jounceSpeed;
PxF32 previousJounce;
if (PX_MAX_F32 != prevJounces[i])
{
jounceSpeed = (jounce - prevJounces[i])*recipTimeStep;
previousJounce = prevJounces[i];
}
else
{
jounceSpeed = 0.0f;
previousJounce = jounce;
}
const PxF32 gravitySuspDir = gravity.dot(w);
bool computeSuspensionForce = true;
if ((wheelsSimFlags & PxVehicleWheelsSimFlag::eLIMIT_SUSPENSION_EXPANSION_VELOCITY) && (jounceSpeed < 0.0f) && (jounce <= 0.0f))
{
//Suspension is expanding and not compressed (the latter helps to avoid the suspension not being able to carry the sprung mass
//when many substeps are used because the expected velocity from the suspension spring might always be slightly below the velocity
//needed to reach the new jounce).
//Check if the suspension can expand fast enough to keep pushing the wheel to the ground.
const PxF32 distToMaxDroop = previousJounce + susp.mMaxDroop; // signs chosen to point along the suspension travel direction
//The vehicle is considered to be in air until the suspension expands to the ground, thus the max droop is used
//as the rest length of the spring.
//Without the suspension elongating, the wheel would end up in the air. Compute the force that pushes the
//wheel towards the ground. Note that gravity is ignored here as it applies to chassis and wheel equally.
//Furthermore, the suspension start point (sprung mass) and the wheel are assumed to move with roughly the
//same velocity, hence, damping is ignored too.
const PxF32 springForceAlongSuspDir = distToMaxDroop * susp.mSpringStrength;
const PxF32 suspDirVelWheel = ((springForceAlongSuspDir / wheel.mMass) + gravitySuspDir) * timeStep;
if (jounceSpeed < (-suspDirVelWheel))
{
//The suspension can not push the wheel fast enough onto the ground, so the vehicle will leave the ground.
//Hence, no spring forces should get applied.
//note: could consider applying -springForceAlongSuspDir to the chassis but this is not done in the other
// scenarios where the vehicle is in the air either.
computeSuspensionForce = false;
jounce = PxMin(previousJounce - (suspDirVelWheel * timeStep), susp.mMaxCompression);
}
}
if (computeSuspensionForce)
{
//We know that the vehicle is not in the air.
isInAirs[i]=false;
//Decompose gravity into a term along w and a term perpendicular to w
//gravity = w*alpha + T*beta
//where T is a unit vector perpendicular to w; alpha and beta are scalars.
//The vector w*alpha*mass is the component of gravitational force that acts along the spring direction.
//The vector T*beta*mass is the component of gravitational force that will be resisted by the spring
//because the spring only supports a single degree of freedom along w.
//We only really need to know T*beta so don't bother calculating T or beta.
const PxF32 alpha = PxMax(0.0f, gravitySuspDir);
const PxVec3 TTimesBeta = (0.0f != alpha) ? gravity - w*alpha : PxVec3(0,0,0);
//Compute the magnitude of the force along w.
PxF32 suspensionForceW =
PxMax(0.0f,
susp.mSprungMass*alpha + //force to support sprung mass at zero jounce
susp.mSpringStrength*jounce); //linear spring
suspensionForceW += jounceSpeed * susp.mSpringDamperRate; //damping
//Compute the total force acting on the suspension.
//Remember that the spring force acts along -w.
//Remember to account for the term perpendicular to w and that it acts along -TTimesBeta
PxF32 suspensionForceMag;
if(wheelsSimFlags & PxVehicleWheelsSimFlag::eDISABLE_SUSPENSION_FORCE_PROJECTION)
suspensionForceMag = suspensionForceW - hitNorm.dot(TTimesBeta*susp.mSprungMass);
else
suspensionForceMag = hitNorm.dot(-w*suspensionForceW - TTimesBeta*susp.mSprungMass);
//Apply the opposite force to the hit object.
//Clamp suspensionForceMag if required.
if (dynamicHitActor && !(dynamicHitActor->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC))
{
const PxF32 dynamicActorInvMass = dynamicHitActor->getInvMass();
const PxF32 dynamicActorMass = dynamicHitActor->getMass();
const PxF32 forceSign = computeSign(suspensionForceMag);
const PxF32 forceMag = PxAbs(suspensionForceMag);
const PxF32 clampedAccelMag = PxMin(forceMag*dynamicActorInvMass, maxHitActorAcceleration);
const PxF32 clampedForceMag = clampedAccelMag*dynamicActorMass*forceSign;
PX_ASSERT(clampedForceMag*suspensionForceMag >= 0.0f);
suspensionForceMag = clampedForceMag;
hitActors[i] = dynamicHitActor;
hitActorForces[i] = hitNorm*(-clampedForceMag*timeFraction);
hitActorForcePositions[i] = hitContactPoints4[i];
}
//Store the spring force now (having a local copy avoids lhs).
suspensionSpringForces[i] = suspensionForceMag;
//Store the spring force in the graph.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataSuspForce(startWheelIndex, i, suspensionForceMag, vehTelemetryDataContext->wheelGraphData);
#endif
//Suspension force can be computed now.
const PxVec3 suspensionForce = hitNorm*suspensionForceMag;
//Torque from spring force.
const PxVec3 suspForceCMOffset = carChassisTrnsfm.rotate(wheelsSimData.getSuspForceAppPointOffset(i));
const PxVec3 suspensionTorque = suspForceCMOffset.cross(suspensionForce);
//Add the suspension force/torque to the chassis force/torque.
chassisForce+=suspensionForce;
chassisTorque+=suspensionTorque;
//Now compute the tire load.
const PxF32 tireLoad = suspensionForceMag;
//Normalize the tire load
//Now work out the normalized tire load.
const PxF32 normalisedTireLoad=tireLoad*recipGravityMagnitude*recipTireRestLoads[i];
//Filter the normalized tire load and compute the filtered tire load too.
const PxF32 filteredNormalisedTireLoad=computeFilteredNormalisedTireLoad(tireLoadFilterData,normalisedTireLoad);
const PxF32 filteredTireLoad=filteredNormalisedTireLoad*gravityMagnitude*tireRestLoads[i];
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
updateGraphDataTireLoad(startWheelIndex,i,filteredTireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormTireLoad(startWheelIndex,i,filteredNormalisedTireLoad, vehTelemetryDataContext->wheelGraphData);
}
#endif
//Compute the lateral and longitudinal tire axes in the ground plane.
PxVec3 tireLongDir;
PxVec3 tireLatDir;
computeTireDirs(latDir,hitNorm,steerAngles[i],tireLongDir,tireLatDir);
//Store the tire long and lat dirs now (having a local copy avoids lhs).
tireLongitudinalDirs[i]= tireLongDir;
tireLateralDirs[i]=tireLatDir;
//Now compute the speeds along each of the tire axes.
const PxF32 tireLongSpeed=wheelBottomVel.dot(tireLongDir);
const PxF32 tireLatSpeed=wheelBottomVel.dot(tireLatDir);
//Store the forward speed (having a local copy avoids lhs).
forwardSpeeds[i]=tireLongSpeed;
//Now compute the slips along each axes.
const bool hasAccel=isAccelApplied[i];
const bool hasBrake=isBrakeApplied[i];
const PxF32 wheelOmega=wheelsDynData.mWheelSpeeds[i];
const PxF32 wheelRadius=wheel.mRadius;
PxF32 longSlip;
PxF32 latSlip;
computeTireSlips
(tireLongSpeed,tireLatSpeed,wheelOmega,wheelRadius,minLongSlipDenominator,
hasAccel,hasBrake,
isTank,
longSlip,latSlip);
//Store the lat and long slip (having local copies avoids lhs).
longSlips[i]=longSlip;
latSlips[i]=latSlip;
//Camber angle.
PxF32 camber=susp.mCamberAtRest;
if(jounce>0)
{
camber += jounce*susp.mCamberAtMaxCompression*susp.getRecipMaxCompression();
}
else
{
camber -= jounce*susp.mCamberAtMaxDroop*susp.getRecipMaxDroop();
}
//Compute the friction that will be experienced by the tire.
PxF32 friction;
computeTireFriction(tire,longSlip,frictionMultiplier,friction);
//Store the friction (having a local copy avoids lhs).
frictions[i]=friction;
if(filteredTireLoad*frictionMultiplier>0)
{
//Either tire forces or sticky tire friction constraint will be applied here.
const PxVec3 tireForceCMOffset = carChassisTrnsfm.rotate(wheelsSimData.getTireForceAppPointOffset(i));
PxF32 newLowForwardSpeedTimer;
{
//check the accel value here
//Update low forward speed timer.
const PxF32 recipWheelRadius=wheel.getRecipRadius();
newLowForwardSpeedTimer=newLowForwardSpeedTimers[i];
updateLowForwardSpeedTimer(tireLongSpeed,wheelOmega,wheelRadius,recipWheelRadius,isIntentionToAccelerate,timeStep,newLowForwardSpeedTimer);
//Activate sticky tire forward friction constraint if required.
//If sticky tire friction is active then set the longitudinal slip to zero because
//the sticky tire constraint will take care of the longitudinal component of motion.
bool stickyTireForwardActiveFlag=false;
PxF32 stickyTireForwardTargetSpeed=0.0f;
activateStickyFrictionForwardConstraint(tireLongSpeed,wheelOmega,newLowForwardSpeedTimer,isIntentionToAccelerate,stickyTireForwardActiveFlag,stickyTireForwardTargetSpeed);
stickyTireForwardTargetSpeed += hitActorVelocity.dot(tireLongDir);
//Store the sticky tire data (having local copies avoids lhs).
newLowForwardSpeedTimers[i] = newLowForwardSpeedTimer;
stickyTireForwardActiveFlags[i]=stickyTireForwardActiveFlag;
stickyTireForwardTargetSpeeds[i]=stickyTireForwardTargetSpeed;
stickyTireForwardDirs[i]=tireLongDir;
stickyTireForwardCMOffsets[i]=tireForceCMOffset;
//Deactivate the long slip if sticky tire constraint is active.
longSlip=(!stickyTireForwardActiveFlag ? longSlip : 0.0f);
//Store the long slip (having local copies avoids lhs).
longSlips[i]=longSlip;
}
PxF32 newLowSideSpeedTimer;
{
//check the accel value here
//Update low side speed timer.
newLowSideSpeedTimer=newLowSideSpeedTimers[i];
updateLowSideSpeedTimer(tireLatSpeed,isIntentionToAccelerate,timeStep,newLowSideSpeedTimer);
//Activate sticky tire side friction constraint if required.
//If sticky tire friction is active then set the lateral slip to zero because
//the sticky tire constraint will take care of the lateral component of motion.
bool stickyTireSideActiveFlag=false;
PxF32 stickyTireSideTargetSpeed=0.0f;
activateStickyFrictionSideConstraint(tireLatSpeed,newLowForwardSpeedTimer,newLowSideSpeedTimer,isIntentionToAccelerate,stickyTireSideActiveFlag,stickyTireSideTargetSpeed);
stickyTireSideTargetSpeed += hitActorVelocity.dot(tireLatDir);
//Store the sticky tire data (having local copies avoids lhs).
newLowSideSpeedTimers[i] = newLowSideSpeedTimer;
stickyTireSideActiveFlags[i]=stickyTireSideActiveFlag;
stickyTireSideTargetSpeeds[i]=stickyTireSideTargetSpeed;
stickyTireSideDirs[i]=tireLatDir;
stickyTireSideCMOffsets[i]=tireForceCMOffset;
//Deactivate the lat slip if sticky tire constraint is active.
latSlip=(!stickyTireSideActiveFlag ? latSlip : 0.0f);
//Store the long slip (having local copies avoids lhs).
latSlips[i]=latSlip;
}
//Compute the various tire torques.
PxF32 wheelTorque=0;
PxF32 tireLongForceMag=0;
PxF32 tireLatForceMag=0;
PxF32 tireAlignMoment=0;
const PxF32 restTireLoad=gravityMagnitude*tireRestLoads[i];
const PxF32 recipWheelRadius=wheel.getRecipRadius();
tireForceCalculator.mShader(
tireForceCalculator.mShaderData[i],
friction,
longSlip,latSlip,camber,
wheelOmega,wheelRadius,recipWheelRadius,
restTireLoad,filteredNormalisedTireLoad,filteredTireLoad,
gravityMagnitude, recipGravityMagnitude,
wheelTorque,tireLongForceMag,tireLatForceMag,tireAlignMoment);
//Store the tire torque ((having a local copy avoids lhs).
tireTorques[i]=wheelTorque;
//Apply the torque to the chassis.
//Compute the tire force to apply to the chassis.
const PxVec3 tireLongForce=tireLongDir*tireLongForceMag;
const PxVec3 tireLatForce=tireLatDir*tireLatForceMag;
const PxVec3 tireForce=tireLongForce+tireLatForce;
//Compute the torque to apply to the chassis.
const PxVec3 tireTorque=tireForceCMOffset.cross(tireForce);
//Add all the forces/torques together.
chassisForce+=tireForce;
chassisTorque+=tireTorque;
//Graph all the data we just computed.
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
vehTelemetryDataContext->tireForceAppPoints[i] = carChassisTrnsfm.p + tireForceCMOffset;
vehTelemetryDataContext->suspForceAppPoints[i] = carChassisTrnsfm.p + suspForceCMOffset;
updateGraphDataNormLongTireForce(startWheelIndex, i, PxAbs(tireLongForceMag)*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormLatTireForce(startWheelIndex, i, PxAbs(tireLatForceMag)*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataNormTireAligningMoment(startWheelIndex, i, tireAlignMoment*normalisedTireLoad/tireLoad, vehTelemetryDataContext->wheelGraphData);
updateGraphDataLongTireSlip(startWheelIndex, i,longSlips[i], vehTelemetryDataContext->wheelGraphData);
updateGraphDataLatTireSlip(startWheelIndex, i,latSlips[i], vehTelemetryDataContext->wheelGraphData);
updateGraphDataTireFriction(startWheelIndex, i,frictions[i], vehTelemetryDataContext->wheelGraphData);
}
#endif
}//filteredTireLoad*frictionMultiplier>0
}//if(computeSuspensionForce)
}//if(dx > -susp.mMaxCompression)
}//if(numHits>0)
}//i
}
void procesAntiRollSuspension
(const PxVehicleWheelsSimData& wheelsSimData,
const PxTransform& carChassisTransform, const PxWheelQueryResult* wheelQueryResults,
PxVec3& chassisTorque)
{
const PxU32 numAntiRollBars = wheelsSimData.getNbAntiRollBars();
for(PxU32 i = 0; i < numAntiRollBars; i++)
{
const PxVehicleAntiRollBarData& antiRoll = wheelsSimData.getAntiRollBarData(i);
const PxU32 w0 = antiRoll.mWheel0;
const PxU32 w1 = antiRoll.mWheel1;
//At least one wheel must be on the ground for the anti-roll to work.
const bool w0InAir = wheelQueryResults[w0].isInAir;
const bool w1InAir = wheelQueryResults[w1].isInAir;
if(!w0InAir || !w1InAir)
{
//Compute the difference in jounce and compute the force.
const PxF32 w0Jounce = wheelQueryResults[w0].suspJounce;
const PxF32 w1Jounce = wheelQueryResults[w1].suspJounce;
const PxF32 antiRollForceMag = (w0Jounce - w1Jounce)*antiRoll.mStiffness;
//Apply the antiRollForce postiviely to wheel0, negatively to wheel 1
PxU32 wheelIds[2] = {0xffffffff, 0xffffffff};
PxF32 antiRollForceMags[2];
PxU32 numWheelIds = 0;
if(!w0InAir)
{
wheelIds[numWheelIds] = w0;
antiRollForceMags[numWheelIds] = -antiRollForceMag;
numWheelIds++;
}
if(!w1InAir)
{
wheelIds[numWheelIds] = w1;
antiRollForceMags[numWheelIds] = +antiRollForceMag;
numWheelIds++;
}
for(PxU32 j = 0; j < numWheelIds; j++)
{
const PxU32 wheelId = wheelIds[j];
//Force
const PxVec3 suspDir = carChassisTransform.q.rotate(wheelsSimData.getSuspTravelDirection(wheelId));
const PxVec3 antiRollForce = suspDir*antiRollForceMags[j];
//Torque
const PxVec3 r = carChassisTransform.q.rotate(wheelsSimData.getSuspForceAppPointOffset(wheelId));
const PxVec3 antiRollTorque = r.cross(antiRollForce);
chassisTorque += antiRollTorque;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
//Set the low long speed timers computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateLowSpeedTimers(const PxF32* PX_RESTRICT newLowSpeedTimers, PxF32* PX_RESTRICT lowSpeedTimers)
{
for(PxU32 i=0;i<4;i++)
{
lowSpeedTimers[i]=(newLowSpeedTimers[i]!=lowSpeedTimers[i] ? newLowSpeedTimers[i] : 0.0f);
}
}
////////////////////////////////////////////////////////////////////////////
//Set the jounce values computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateJounces(const PxF32* PX_RESTRICT jounces, PxF32* PX_RESTRICT prevJounces)
{
for(PxU32 i=0;i<4;i++)
{
prevJounces[i] = jounces[i];
}
}
void updateSteers(const PxF32* PX_RESTRICT steerAngles, PxF32* PX_RESTRICT prevSteers)
{
for (PxU32 i = 0; i < 4; i++)
{
prevSteers[i] = steerAngles[i];
}
}
///////////////////////////////////////////////////////////////////////////////
//Set the hit plane, hit distance and hit friction multplier computed in processSuspTireWheels
//Call immediately after completing processSuspTireWheels.
////////////////////////////////////////////////////////////////////////////
void updateCachedHitData
(const PxU32* PX_RESTRICT cachedHitCounts, const PxPlane* PX_RESTRICT cachedHitPlanes, const PxF32* PX_RESTRICT cachedHitDistances, const PxF32* PX_RESTRICT cachedFrictionMultipliers, const PxU16* cachedQueryTypes,
PxVehicleWheels4DynData* wheels4DynData)
{
if(wheels4DynData->mRaycastResults || wheels4DynData->mSweepResults)
{
wheels4DynData->mHasCachedRaycastHitPlane = true;
}
PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult* cachedRaycastHitResults =
reinterpret_cast<PxVehicleWheels4DynData::CachedSuspLineSceneQuerytHitResult*>(wheels4DynData->mQueryOrCachedHitResults);
for(PxU32 i=0;i<4;i++)
{
cachedRaycastHitResults->mCounts[i]=PxTo16(cachedHitCounts[i]);
cachedRaycastHitResults->mPlanes[i]=cachedHitPlanes[i];
cachedRaycastHitResults->mDistances[i]=cachedHitDistances[i];
cachedRaycastHitResults->mFrictionMultipliers[i]=cachedFrictionMultipliers[i];
cachedRaycastHitResults->mQueryTypes[i] = cachedQueryTypes[i];
}
}
////////////////////////////////////////////////////////////////////////////
//Solve the system of engine speed + wheel rotation speeds using an implicit integrator.
//The following functions only compute the speed of wheels connected to the diff.
//Worth going to the length of the implicit integrator because after gear changes
//the difference in speed at the clutch can be hard to integrate.
//Separate functions for 4W, NW and tank because the differential works in slightly
//different ways. With driveNW we end up with (N+1)*(N+1) problem, with drive4W we end up
//with 5*5 and with tanks we end up with just 3*3. Tanks use the method of least squares
//to apply the rule that all left/right wheels have the same speed.
//Remember that the following functions don't integrate wheels not connected to the diff
//so these need integrated separately.
////////////////////////////////////////////////////////////////////////////
#if PX_CHECKED
bool isValid(const MatrixNN& A, const VectorN& b, const VectorN& result)
{
PX_ASSERT(A.getSize()==b.getSize());
PX_ASSERT(A.getSize()==result.getSize());
const PxU32 size=A.getSize();
//r=A*result-b
VectorN r(size);
for(PxU32 i=0;i<size;i++)
{
r[i]=-b[i];
for(PxU32 j=0;j<size;j++)
{
r[i]+=A.get(i,j)*result[j];
}
}
PxF32 rLength=0;
PxF32 bLength=0;
for(PxU32 i=0;i<size;i++)
{
rLength+=r[i]*r[i];
bLength+=b[i]*b[i];
}
const PxF32 error=PxSqrt(rLength/(bLength+1e-5f));
return (error<1e-5f);
}
#endif
struct ImplicitSolverInput
{
//dt/numSubSteps
PxF32 subTimeStep;
//Brake control value in range (0,1)
PxF32 brake;
//Handbrake control value in range (0,1)
PxF32 handBrake;
//Clutch strength
PxF32 K;
//Gear ratio.
PxF32 G;
PxVehicleClutchAccuracyMode::Enum accuracyMode;
PxU32 maxNumIterations;
//Engine drive torque
PxF32 engineDriveTorque;
//Engine damping rate.
PxF32 engineDampingRate;
//Fraction of available clutch torque to be delivered to each wheel.
const PxF32* diffTorqueRatios;
//Fractional contribution of each wheel to average wheel speed at clutch.
const PxF32* aveWheelSpeedContributions;
//Braking torque at each wheel (inlcudes handbrake torque).
const PxF32* brakeTorques;
//True per wheel brakeTorques[i] > 0, false if brakeTorques[i]==0
const bool* isBrakeApplied;
//Tire torques to apply to each 1d rigid body wheel.
const PxF32* tireTorques;
//Sim and dyn data.
PxU32 numWheels4;
PxU32 numActiveWheels;
const PxVehicleWheels4SimData* wheels4SimData;
const PxVehicleDriveSimData* driveSimData;
};
struct ImplicitSolverOutput
{
PxVehicleWheels4DynData* wheelsDynData;
PxVehicleDriveDynData* driveDynData;
};
void solveDrive4WInternaDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, ImplicitSolverOutput* output)
{
const PxF32 subTimestep = input.subTimeStep;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxVehicleClutchAccuracyMode::Enum accuracyMode = input.accuracyMode;
const PxU32 maxIterations = input.maxNumIterations;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
const PxVehicleWheels4SimData& wheels4SimData = *input.wheels4SimData;
const PxVehicleDriveSimData4W& driveSimData = *static_cast<const PxVehicleDriveSimData4W*>(input.driveSimData);
PxVehicleDriveDynData* driveDynData = output->driveDynData;
PxVehicleWheels4DynData* wheels4DynData = output->wheelsDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
MatrixNN A(4+1);
VectorN b(4+1);
VectorN result(4+1);
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32* PX_RESTRICT wheelSpeeds=wheels4DynData->mWheelSpeeds;
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque]/IEng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//A*w(t+dt)=b(t);
//Wheels.
{
for(PxU32 i=0;i<4;i++)
{
const PxF32 dt=subTimestep*wheels4SimData.getWheelData(i).getRecipMOI();
const PxF32 R=diffTorqueRatios[i];
const PxF32 dtKGGR=dt*KGG*R;
A.set(i,0,dtKGGR*aveWheelSpeedContributions[0]);
A.set(i,1,dtKGGR*aveWheelSpeedContributions[1]);
A.set(i,2,dtKGGR*aveWheelSpeedContributions[2]);
A.set(i,3,dtKGGR*aveWheelSpeedContributions[3]);
A.set(i,i,1.0f+dtKGGR*aveWheelSpeedContributions[i]+dt*wheels4SimData.getWheelData(i).mDampingRate);
A.set(i,4,-dt*KG*R);
b[i] = wheelSpeeds[i] + dt*(brakeTorques[i]+tireTorques[i]);
result[i] = wheelSpeeds[i];
}
}
//Engine.
{
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
A.set(4,0,-dtKG*aveWheelSpeedContributions[0]);
A.set(4,1,-dtKG*aveWheelSpeedContributions[1]);
A.set(4,2,-dtKG*aveWheelSpeedContributions[2]);
A.set(4,3,-dtKG*aveWheelSpeedContributions[3]);
A.set(4,4,1.0f + dt*(K+engineDampingRate));
b[4] = engineOmega + dt*engineDriveTorque;
result[4] = engineOmega;
}
//Solve Aw=b
if(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode)
{
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_WARN_ONCE_IF(!isValid(A,b,result), "Unable to compute new PxVehicleDrive4W internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
}
else
{
MatrixNGaussSeidelSolver solver;
solver.solve(maxIterations, gSolverTolerance, A, b, result);
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
result[0]=(isBrakeApplied[0] && (wheelSpeeds[0]*result[0]<=0)) ? 0.0f : result[0];
result[1]=(isBrakeApplied[1] && (wheelSpeeds[1]*result[1]<=0)) ? 0.0f : result[1];
result[2]=(isBrakeApplied[2] && (wheelSpeeds[2]*result[2]<=0)) ? 0.0f : result[2];
result[3]=(isBrakeApplied[3] && (wheelSpeeds[3]*result[3]<=0)) ? 0.0f : result[3];
//Clamp the engine revs.
//Again, this is not physically or mathematically correct but the loss in behaviour will be hard to notice.
//The alternative would be to add constraints to the solver, which would be much more expensive.
result[4]=PxClamp(result[4],0.0f,engineData.mMaxOmega);
//Copy back to the car's internal rotation speeds.
wheels4DynData->mWheelSpeeds[0]=result[0];
wheels4DynData->mWheelSpeeds[1]=result[1];
wheels4DynData->mWheelSpeeds[2]=result[2];
wheels4DynData->mWheelSpeeds[3]=result[3];
driveDynData->setEngineRotationSpeed(result[4]);
}
void solveDriveNWInternalDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, ImplicitSolverOutput* output)
{
const PxF32 subTimestep = input.subTimeStep;
//const PxF32 brake = input.brake;
//const PxF32 handbrake = input.handBrake;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxVehicleClutchAccuracyMode::Enum accuracyMode = input.accuracyMode;
const PxU32 maxIterations = input.maxNumIterations;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
//const PxU32 numWheels4 = input.numWheels4;
const PxU32 numActiveWheels = input.numActiveWheels;
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimDatas = input.wheels4SimData;
const PxVehicleDriveSimDataNW& driveSimData = *static_cast<const PxVehicleDriveSimDataNW*>(input.driveSimData);
PxVehicleDriveDynData* driveDynData = output->driveDynData;
PxVehicleWheels4DynData* wheels4DynDatas = output->wheelsDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
MatrixNN A(numActiveWheels+1);
VectorN b(numActiveWheels+1);
VectorN result(numActiveWheels+1);
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel.
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque/Ieng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//A*w(t+dt)=b(t);
//Wheels.
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 dt=subTimestep*wheels4SimDatas[i>>2].getWheelData(i&3).getRecipMOI();
const PxF32 R=diffTorqueRatios[i];
const PxF32 dtKGGR=dt*KGG*R;
for(PxU32 j=0;j<numActiveWheels;j++)
{
A.set(i,j,dtKGGR*aveWheelSpeedContributions[j]);
}
A.set(i,i,1.0f+dtKGGR*aveWheelSpeedContributions[i]+dt*wheels4SimDatas[i>>2].getWheelData(i&3).mDampingRate);
A.set(i,numActiveWheels,-dt*KG*R);
b[i] = wheels4DynDatas[i>>2].mWheelSpeeds[i&3] + dt*(brakeTorques[i]+tireTorques[i]);
result[i] = wheels4DynDatas[i>>2].mWheelSpeeds[i&3];
}
//Engine.
{
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
for(PxU32 i=0;i<numActiveWheels;i++)
{
A.set(numActiveWheels,i,-dtKG*aveWheelSpeedContributions[i]);
}
A.set(numActiveWheels,numActiveWheels,1.0f + dt*(K+engineDampingRate));
b[numActiveWheels] = engineOmega + dt*engineDriveTorque;
result[numActiveWheels] = engineOmega;
}
//Solve Aw=b
if(PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == accuracyMode)
{
MatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b,result);
PX_WARN_ONCE_IF(!isValid(A,b,result), "Unable to compute new PxVehicleDriveNW internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
}
else
{
MatrixNGaussSeidelSolver solver;
solver.solve(maxIterations, gSolverTolerance, A, b, result);
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
for(PxU32 i=0;i<numActiveWheels;i++)
{
result[i]=(isBrakeApplied[i] && (wheels4DynDatas[i>>2].mWheelSpeeds[i&3]*result[i]<=0)) ? 0.0f : result[i];
}
//Clamp the engine revs.
//Again, this is not physically or mathematically correct but the loss in behaviour will be hard to notice.
result[numActiveWheels]=PxClamp(result[numActiveWheels],0.0f,engineData.mMaxOmega);
//Copy back to the car's internal rotation speeds.
for(PxU32 i=0;i<numActiveWheels;i++)
{
wheels4DynDatas[i>>2].mWheelSpeeds[i&3]=result[i];
}
driveDynData->setEngineRotationSpeed(result[numActiveWheels]);
}
void solveTankInternaDynamicsEnginePlusDrivenWheels
(const ImplicitSolverInput& input, const bool* PX_RESTRICT activeWheelStates, const PxF32* PX_RESTRICT wheelGearings, ImplicitSolverOutput* output)
{
PX_SIMD_GUARD; // denormal exception triggered at oldOmega*newOmega on osx
const PxF32 subTimestep = input.subTimeStep;
const PxF32 K = input.K;
const PxF32 G = input.G;
const PxF32 engineDriveTorque = input.engineDriveTorque;
const PxF32 engineDampingRate = input.engineDampingRate;
const PxF32* PX_RESTRICT diffTorqueRatios = input.diffTorqueRatios;
const PxF32* PX_RESTRICT aveWheelSpeedContributions = input.aveWheelSpeedContributions;
const PxF32* PX_RESTRICT brakeTorques = input.brakeTorques;
const bool* PX_RESTRICT isBrakeApplied = input.isBrakeApplied;
const PxF32* PX_RESTRICT tireTorques = input.tireTorques;
const PxU32 numWheels4 = input.numWheels4;
const PxU32 numActiveWheels = input.numActiveWheels;
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimDatas = input.wheels4SimData;
const PxVehicleDriveSimData& driveSimData = *input.driveSimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynDatas = output->wheelsDynData;
PxVehicleDriveDynData* driveDynData = output->driveDynData;
const PxF32 KG=K*G;
const PxF32 KGG=K*G*G;
//Rearrange data in a single array rather than scattered in blocks of 4.
//This makes it easier later on.
PxF32 recipMOI[PX_MAX_NB_WHEELS];
PxF32 dampingRates[PX_MAX_NB_WHEELS];
PxF32 wheelSpeeds[PX_MAX_NB_WHEELS];
PxF32 wheelRecipRadii[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4-1;i++)
{
const PxVehicleWheelData& wheelData0=wheels4SimDatas[i].getWheelData(0);
const PxVehicleWheelData& wheelData1=wheels4SimDatas[i].getWheelData(1);
const PxVehicleWheelData& wheelData2=wheels4SimDatas[i].getWheelData(2);
const PxVehicleWheelData& wheelData3=wheels4SimDatas[i].getWheelData(3);
recipMOI[4*i+0]=wheelData0.getRecipMOI();
recipMOI[4*i+1]=wheelData1.getRecipMOI();
recipMOI[4*i+2]=wheelData2.getRecipMOI();
recipMOI[4*i+3]=wheelData3.getRecipMOI();
dampingRates[4*i+0]=wheelData0.mDampingRate;
dampingRates[4*i+1]=wheelData1.mDampingRate;
dampingRates[4*i+2]=wheelData2.mDampingRate;
dampingRates[4*i+3]=wheelData3.mDampingRate;
wheelRecipRadii[4*i+0]=wheelData0.getRecipRadius();
wheelRecipRadii[4*i+1]=wheelData1.getRecipRadius();
wheelRecipRadii[4*i+2]=wheelData2.getRecipRadius();
wheelRecipRadii[4*i+3]=wheelData3.getRecipRadius();
const PxVehicleWheels4DynData& suspWheelTire4=wheels4DynDatas[i];
wheelSpeeds[4*i+0]=suspWheelTire4.mWheelSpeeds[0];
wheelSpeeds[4*i+1]=suspWheelTire4.mWheelSpeeds[1];
wheelSpeeds[4*i+2]=suspWheelTire4.mWheelSpeeds[2];
wheelSpeeds[4*i+3]=suspWheelTire4.mWheelSpeeds[3];
}
const PxU32 numInLastBlock = 4 - (4*numWheels4 - numActiveWheels);
for(PxU32 i=0;i<numInLastBlock;i++)
{
const PxVehicleWheelData& wheelData=wheels4SimDatas[numWheels4-1].getWheelData(i);
recipMOI[4*(numWheels4-1)+i]=wheelData.getRecipMOI();
dampingRates[4*(numWheels4-1)+i]=wheelData.mDampingRate;
wheelRecipRadii[4*(numWheels4-1)+i]=wheelData.getRecipRadius();
const PxVehicleWheels4DynData& suspWheelTire4=wheels4DynDatas[numWheels4-1];
wheelSpeeds[4*(numWheels4-1)+i]=suspWheelTire4.mWheelSpeeds[i];
}
const PxF32 wheelRadius0=wheels4SimDatas[0].getWheelData(0).mRadius;
const PxF32 wheelRadius1=wheels4SimDatas[0].getWheelData(1).mRadius;
//
//torque at clutch:
//tc = K*{G*[alpha0*w0 + alpha1*w1 + alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}
//where
//(i) G is the gearing ratio,
//(ii) alphai is the fractional contribution of the ith wheel to the average wheel speed at the clutch (alpha(i) is zero for undriven wheels)
//(iii) wi is the angular speed of the ith wheel
//(iv) K is the clutch strength
//(v) wEng is the angular speed of the engine
//torque applied to ith wheel is
//ti = G*gammai*tc + bt(i) + tt(i)
//where
//gammai is the fractional proportion of the clutch torque that the differential delivers to the ith wheel
//bt(i) is the brake torque applied to the ith wheel
//tt(i) is the tire torque applied to the ith wheel
//acceleration applied to ith wheel is
//ai = G*gammai*K*{G*[alpha0*w0 + alpha1*w1 alpha2*w2 + ..... alpha(N-1)*w(N-1)] - wEng}/Ii + (bt(i) + tt(i))/Ii
//wheer Ii is the moi of the ith wheel.
//express ai as
//ai = [wi(t+dt) - wi(t)]/dt
//and rearrange
//wi(t+dt) - wi(t)] = dt*G*gammai*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1)(t+dt)] - wEng(t+dt)}/Ii + dt*(bt(i) + tt(i))/Ii
//Do the same for tEng (torque applied to engine)
//tEng = -tc + engineDriveTorque
//where engineDriveTorque is the drive torque applied to the engine
//Assuming the engine has unit mass then
//wEng(t+dt) -wEng(t) = -dt*K*{G*[alpha0*w0(t+dt) + alpha1*w1(t+dt) + alpha2*w2(t+dt) + ..... alpha(N-1)*w(N-1(t+dt))] - wEng(t+dt)}/Ieng + dt*engineDriveTorque/Ieng
//Introduce the vector w=(w0,w1,w2....w(N-1), wEng)
//and re-express as a matrix after collecting all unknowns at (t+dt) and knowns at time t.
//M*w(t+dt)=b(t);
//Matrix M and rhs vector b that we use to solve Mw=b.
MatrixNN M(numActiveWheels+1);
VectorN b(numActiveWheels+1);
//Wheels.
{
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 dt=subTimestep*recipMOI[i];
const PxF32 R=diffTorqueRatios[i];
const PxF32 g=wheelGearings[i];
const PxF32 dtKGGRg=dt*KGG*R*g;
for(PxU32 j=0;j<numActiveWheels;j++)
{
M.set(i,j,dtKGGRg*aveWheelSpeedContributions[j]*wheelGearings[j]);
}
M.set(i,i,1.0f+dtKGGRg*aveWheelSpeedContributions[i]*wheelGearings[i]+dt*dampingRates[i]);
M.set(i,numActiveWheels,-dt*KG*R*g);
b[i] = wheelSpeeds[i] + dt*(brakeTorques[i]+tireTorques[i]);
}
}
//Engine.
{
const PxF32 engineOmega=driveDynData->getEngineRotationSpeed();
const PxF32 dt=subTimestep*driveSimData.getEngineData().getRecipMOI();
const PxF32 dtKG=dt*K*G;
for(PxU32 i=0;i<numActiveWheels;i++)
{
M.set(numActiveWheels,i,-dtKG*aveWheelSpeedContributions[i]*wheelGearings[i]);
}
M.set(numActiveWheels,numActiveWheels,1.0f + dt*(K+engineDampingRate));
b[numActiveWheels] = engineOmega + dt*engineDriveTorque;
}
//Now apply the constraints that all the odd numbers are equal and all the even numbers are equal.
//ie w2,w4,w6 are all equal to w0 and w3,w5,w7 are all equal to w1.
//That leaves (4*N+1) equations but only 3 unknowns: two wheels speeds and the engine speed.
//Substitute these extra constraints into the matrix.
MatrixNN A(numActiveWheels+1);
for(PxU32 i=0;i<numActiveWheels+1;i++)
{
PxF32 sum0=M.get(i,0+0);
PxF32 sum1=M.get(i,0+1);
for(PxU32 j=2;j<numActiveWheels;j+=2)
{
sum0+=M.get(i,j+0)*wheelRadius0*wheelRecipRadii[j+0];
sum1+=M.get(i,j+1)*wheelRadius1*wheelRecipRadii[j+1];
}
A.set(i,0,sum0);
A.set(i,1,sum1);
A.set(i,2,M.get(i,numActiveWheels));
}
//We have an over-determined problem because of the extra constraints
//on equal wheel speeds. Solve using the least squares method as in
//http://s-mat-pcs.oulu.fi/~mpa/matreng/ematr5_5.htm
//Compute A^T*A
//No longer using M.
MatrixNN& ATA = M;
ATA.setSize(3);
for(PxU32 i=0;i<3;i++)
{
for(PxU32 j=0;j<3;j++)
{
PxF32 sum=0.0f;
for(PxU32 k=0;k<numActiveWheels+1;k++)
{
//sum+=AT.get(i,k)*A.get(k,j);
sum+=A.get(k,i)*A.get(k,j);
}
ATA.set(i,j,sum);
}
}
//Compute A^T*b;
VectorN ATb(3);
for(PxU32 i=0;i<3;i++)
{
PxF32 sum=0;
for(PxU32 j=0;j<numActiveWheels+1;j++)
{
//sum+=AT.get(i,j)*b[j];
sum+=A.get(j,i)*b[j];
}
ATb[i]=sum;
}
//Solve (A^T*A)*x = A^T*b
VectorN result(3);
Matrix33Solver solver;
bool successfulSolver = solver.solve(ATA, ATb, result);
if(!successfulSolver)
{
PX_WARN_ONCE("Unable to compute new PxVehicleDriveTank internal rotation speeds. Please check vehicle sim data, especially clutch strength; engine moi and damping; wheel moi and damping");
return;
}
//Clamp the engine revs between zero and maxOmega
const PxF32 maxEngineOmega=driveSimData.getEngineData().mMaxOmega;
const PxF32 newEngineOmega=PxClamp(result[2],0.0f,maxEngineOmega);
//Apply the constraints on each of the equal wheel speeds.
PxF32 wheelSpeedResults[PX_MAX_NB_WHEELS];
wheelSpeedResults[0]=result[0];
wheelSpeedResults[1]=result[1];
for(PxU32 i=2;i<numActiveWheels;i+=2)
{
wheelSpeedResults[i+0]=result[0];
wheelSpeedResults[i+1]=result[1];
}
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//A consequence of this quick fix is that locked wheels remain locked until the brake is entirely released.
//This isn't strictly mathematically or physically correct - a more accurate solution would either formulate the
//brake as a lcp problem or repeatedly solve with constraints that locked wheels remain at zero rotation speed.
//The physically correct solution will certainly be more expensive so let's live with the restriction that
//locked wheels remain locked until the brake is released.
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxF32 oldOmega=wheelSpeeds[i];
const PxF32 newOmega=wheelSpeedResults[i];
const bool hasBrake=isBrakeApplied[i];
if(hasBrake && (oldOmega*newOmega <= 0))
{
wheelSpeedResults[i]=0.0f;
}
}
//Copy back to the car's internal rotation speeds.
for(PxU32 i=0;i<numWheels4-1;i++)
{
wheels4DynDatas[i].mWheelSpeeds[0] = activeWheelStates[4*i+0] ? wheelSpeedResults[4*i+0] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[1] = activeWheelStates[4*i+1] ? wheelSpeedResults[4*i+1] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[2] = activeWheelStates[4*i+2] ? wheelSpeedResults[4*i+2] : 0.0f;
wheels4DynDatas[i].mWheelSpeeds[3] = activeWheelStates[4*i+3] ? wheelSpeedResults[4*i+3] : 0.0f;
}
for(PxU32 i=0;i<numInLastBlock;i++)
{
wheels4DynDatas[numWheels4-1].mWheelSpeeds[i] = activeWheelStates[4*(numWheels4-1)+i] ? wheelSpeedResults[4*(numWheels4-1)+i] : 0.0f;
}
driveDynData->setEngineRotationSpeed(newEngineOmega);
}
////////////////////////////////////////////////////////////////////////////
//Integrate wheel rotation speeds of wheels not connected to the differential.
//Obviously, no wheels in a PxVehicleNoDrive are connected to a diff so all require
//direct integration.
//Only the first 4 wheels of a PxVehicleDrive4W are connected to the diff so
//any extra wheels need direct integration.
//All tank wheels are connected to the diff so none need integrated in a separate pass.
//What about undriven wheels in a PxVehicleDriveNW? This vehicle type treats all
//wheels as being connected to the diff but sets the diff contribution to zero for
//all undriven wheels. No wheels from a PxVehicleNW need integrated in a separate pass.
////////////////////////////////////////////////////////////////////////////
void integrateNoDriveWheelSpeeds
(const PxF32 subTimestep,
const PxF32* PX_RESTRICT brakeTorques, const bool* PX_RESTRICT isBrakeApplied, const PxF32* driveTorques, const PxF32* PX_RESTRICT tireTorques, const PxF32* PX_RESTRICT dampingRates,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
//w(t+dt) = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt - (1/inertia)*damping*w(t)*dt ) (1)
//Apply implicit trick and rearrange.
//w(t+dt)[1 + (1/inertia)*damping*dt] = w(t) + (1/inertia)*(brakeTorque + driveTorque + tireTorque)*dt (2)
//Introduce (1/inertia)*dt to avoid duplication in (2)
PxF32 subTimeSteps[4] =
{
subTimestep*vehSuspWheelTire4SimData.getWheelData(0).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(1).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(2).getRecipMOI(),
subTimestep*vehSuspWheelTire4SimData.getWheelData(3).getRecipMOI()
};
//Integrate.
//w += torque*dt/inertia - damping*dt*w
//Use implicit integrate trick and rearrange
//w(t+dt) = [w(t) + torque*dt/inertia]/[1 + damping*dt]
const PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32 result[4]=
{
(wheelSpeeds[0] + subTimeSteps[0]*(tireTorques[0] + driveTorques[0] + brakeTorques[0]))/(1.0f + dampingRates[0]*subTimeSteps[0]),
(wheelSpeeds[1] + subTimeSteps[1]*(tireTorques[1] + driveTorques[1] + brakeTorques[1]))/(1.0f + dampingRates[1]*subTimeSteps[1]),
(wheelSpeeds[2] + subTimeSteps[2]*(tireTorques[2] + driveTorques[2] + brakeTorques[2]))/(1.0f + dampingRates[2]*subTimeSteps[2]),
(wheelSpeeds[3] + subTimeSteps[3]*(tireTorques[3] + driveTorques[3] + brakeTorques[3]))/(1.0f + dampingRates[3]*subTimeSteps[3]),
};
//Check for sanity in the resultant internal rotation speeds.
//If the brakes are on and the wheels have switched direction then lock them at zero.
//newOmega=result[i], oldOmega=wheelSpeeds[i], if newOmega*oldOmega<=0 and isBrakeApplied then lock wheel.
result[0]=(isBrakeApplied[0] && (wheelSpeeds[0]*result[0]<=0)) ? 0.0f : result[0];
result[1]=(isBrakeApplied[1] && (wheelSpeeds[1]*result[1]<=0)) ? 0.0f : result[1];
result[2]=(isBrakeApplied[2] && (wheelSpeeds[2]*result[2]<=0)) ? 0.0f : result[2];
result[3]=(isBrakeApplied[3] && (wheelSpeeds[3]*result[3]<=0)) ? 0.0f : result[3];
//Copy back to the car's internal rotation speeds.
vehSuspWheelTire4.mWheelSpeeds[0]=result[0];
vehSuspWheelTire4.mWheelSpeeds[1]=result[1];
vehSuspWheelTire4.mWheelSpeeds[2]=result[2];
vehSuspWheelTire4.mWheelSpeeds[3]=result[3];
}
void integrateUndriveWheelRotationSpeeds
(const PxF32 subTimestep,
const PxF32 brake, const PxF32 handbrake, const PxF32* PX_RESTRICT tireTorques, const PxF32* PX_RESTRICT brakeTorques,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
for(PxU32 i=0;i<4;i++)
{
//Compute the new angular speed of the wheel.
const PxF32 oldOmega=vehSuspWheelTire4.mWheelSpeeds[i];
const PxF32 dtI = subTimestep*vehSuspWheelTire4SimData.getWheelData(i).getRecipMOI();
const PxF32 gamma = vehSuspWheelTire4SimData.getWheelData(i).mDampingRate;
const PxF32 newOmega=(oldOmega+dtI*(tireTorques[i]+brakeTorques[i]))/(1.0f + gamma*dtI);
//Has the brake been applied? It's hard to tell from brakeTorques[j] because that
//will be zero if the wheel is locked. Work it out from the brake and handbrake data.
const PxF32 brakeGain=vehSuspWheelTire4SimData.getWheelData(i).mMaxBrakeTorque;
const PxF32 handbrakeGain=vehSuspWheelTire4SimData.getWheelData(i).mMaxHandBrakeTorque;
//Work out if the wheel should be locked.
const bool brakeApplied=((brake*brakeGain + handbrake*handbrakeGain)!=0.0f);
const bool wheelReversed=(oldOmega*newOmega <=0);
const bool wheelLocked=(brakeApplied && wheelReversed);
//Lock the wheel or apply its new angular speed.
if(!wheelLocked)
{
vehSuspWheelTire4.mWheelSpeeds[i]=newOmega;
}
else
{
vehSuspWheelTire4.mWheelSpeeds[i]=0.0f;
}
}
}
////////////////////////////////////////////////////////////////////////////
//Pose the wheels.
//First integrate the wheel rotation angles and clamp them to a range (-10*pi, 10*pi)
//PxVehicleNoDrive has a different way of telling if a wheel is driven by a drive torque so has a separate function.
//Use the wheel steer/rotation/camber angle and suspension jounce to compute the local transform of each wheel.
////////////////////////////////////////////////////////////////////////////
void integrateWheelRotationAngles
(const PxF32 timestep,
const PxF32 K, const PxF32 G, const PxF32 engineDriveTorque,
const PxF32* PX_RESTRICT jounces, const PxF32* PX_RESTRICT diffTorqueRatios, const PxF32* PX_RESTRICT forwardSpeeds, const bool* isBrakeApplied,
const PxVehicleDriveSimData& vehCoreSimData, const PxVehicleWheels4SimData& vehSuspWheelTire4SimData,
PxVehicleDriveDynData& vehCore, PxVehicleWheels4DynData& vehSuspWheelTire4)
{
PX_SIMD_GUARD; //denorm exception on newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep; on osx
PX_UNUSED(vehCore);
PX_UNUSED(vehCoreSimData);
const PxF32 KG=K*G;
PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32* PX_RESTRICT wheelRotationAngles=vehSuspWheelTire4.mWheelRotationAngles;
PxF32* PX_RESTRICT correctedWheelSpeeds = vehSuspWheelTire4.mCorrectedWheelSpeeds;
for(PxU32 j=0;j<4;j++)
{
//At low vehicle forward speeds we have some numerical difficulties getting the
//wheel rotation speeds to be correct due to the tire model's difficulties at low vz.
//The solution is to blend between the rolling speed at the wheel and the wheel's actual rotation speed.
//If the wheel is
//(i) in the air or,
//(ii) under braking torque or,
//(iii) driven by the engine through the gears and diff
//then always use the wheel's actual rotation speed.
//Just to be clear, this means we will blend when the wheel
//(i) is on the ground and
//(ii) has no brake applied and
//(iii) has no drive torque applied from the clutch and
//(iv) is at low forward speed
PxF32 wheelOmega=wheelSpeeds[j];
if(jounces[j] > -vehSuspWheelTire4SimData.getSuspensionData(j).mMaxDroop && //(i) wheel touching ground
false==isBrakeApplied[j] && //(ii) no brake applied
0.0f==diffTorqueRatios[j]*KG*engineDriveTorque && //(iii) no drive torque applied
PxAbs(forwardSpeeds[j])<gThresholdForwardSpeedForWheelAngleIntegration) //(iv) low speed
{
const PxF32 recipWheelRadius=vehSuspWheelTire4SimData.getWheelData(j).getRecipRadius();
const PxF32 alpha=PxAbs(forwardSpeeds[j])*gRecipThresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (forwardSpeeds[j]*recipWheelRadius)*(1.0f-alpha) + wheelOmega*alpha;
}
PxF32 newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep;
//Clamp the wheel rotation angle to a range (-10*pi,10*pi) to stop it getting crazily big.
newRotAngle=physx::intrinsics::fsel(newRotAngle-10*PxPi, newRotAngle-10*PxPi, physx::intrinsics::fsel(-newRotAngle-10*PxPi, newRotAngle + 10*PxPi, newRotAngle));
wheelRotationAngles[j]=newRotAngle;
correctedWheelSpeeds[j]=wheelOmega;
}
}
void integrateNoDriveWheelRotationAngles
(const PxF32 timestep,
const PxF32* PX_RESTRICT driveTorques,
const PxF32* PX_RESTRICT jounces, const PxF32* PX_RESTRICT forwardSpeeds, const bool* isBrakeApplied,
const PxVehicleWheels4SimData& vehSuspWheelTire4SimData,
PxVehicleWheels4DynData& vehSuspWheelTire4)
{
PxF32* PX_RESTRICT wheelSpeeds=vehSuspWheelTire4.mWheelSpeeds;
PxF32* PX_RESTRICT wheelRotationAngles=vehSuspWheelTire4.mWheelRotationAngles;
PxF32* PX_RESTRICT correctedWheelSpeeds=vehSuspWheelTire4.mCorrectedWheelSpeeds;
for(PxU32 j=0;j<4;j++)
{
//At low vehicle forward speeds we have some numerical difficulties getting the
//wheel rotation speeds to be correct due to the tire model's difficulties at low vz.
//The solution is to blend between the rolling speed at the wheel and the wheel's actual rotation speed.
//If the wheel is
//(i) in the air or,
//(ii) under braking torque or,
//(iii) driven by a drive torque
//then always use the wheel's actual rotation speed.
//Just to be clear, this means we will blend when the wheel
//(i) is on the ground and
//(ii) has no brake applied and
//(iii) has no drive torque and
//(iv) is at low forward speed
PxF32 wheelOmega=wheelSpeeds[j];
if(jounces[j] > -vehSuspWheelTire4SimData.getSuspensionData(j).mMaxDroop && //(i) wheel touching ground
false==isBrakeApplied[j] && //(ii) no brake applied
0.0f==driveTorques[j] && //(iii) no drive torque applied
PxAbs(forwardSpeeds[j])<gThresholdForwardSpeedForWheelAngleIntegration) //(iv) low speed
{
const PxF32 recipWheelRadius=vehSuspWheelTire4SimData.getWheelData(j).getRecipRadius();
const PxF32 alpha=PxAbs(forwardSpeeds[j])*gRecipThresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (forwardSpeeds[j]*recipWheelRadius)*(1.0f-alpha) + wheelOmega*alpha;
//TODO: maybe just set the car wheel omega to the blended value?
//Not sure about this bit.
//Turned this off because it added energy to the car at very small timesteps.
//wheelSpeeds[j]=wheelOmega;
}
PxF32 newRotAngle=wheelRotationAngles[j]+wheelOmega*timestep;
//Clamp the wheel rotation angle to a range (-10*pi,10*pi) to stop it getting crazily big.
newRotAngle=physx::intrinsics::fsel(newRotAngle-10*PxPi, newRotAngle-10*PxPi, physx::intrinsics::fsel(-newRotAngle-10*PxPi, newRotAngle + 10*PxPi, newRotAngle));
wheelRotationAngles[j]=newRotAngle;
correctedWheelSpeeds[j]=wheelOmega;
}
}
PxQuat computeWheelLocalQuat(
const PxVec3& forwardAxis, const PxVec3& sideAxis, const PxVec3& upAxis,
const float jounce, const PxVehicleSuspensionData& suspData, const PxF32 rotationAngle, const PxF32 steerAngle)
{
PX_ASSERT(jounce != PX_MAX_F32);
//Compute the camber angle.
PxF32 camberAngle = suspData.mCamberAtRest;
if (jounce > 0.0f)
{
camberAngle += jounce*suspData.mCamberAtMaxCompression*suspData.getRecipMaxCompression();
}
else
{
camberAngle -= jounce*suspData.mCamberAtMaxDroop*suspData.getRecipMaxDroop();
}
const PxQuat quat(steerAngle, upAxis);
const PxQuat quat2(camberAngle, quat.rotate(forwardAxis));
const PxQuat quat3 = quat2*quat;
const PxQuat quat4(rotationAngle, quat3.rotate(sideAxis));
const PxQuat result = quat4*quat3;
return result;
}
void computeWheelLocalPoses
(const PxVehicleWheels4SimData& wheelsSimData,
const PxVehicleWheels4DynData& wheelsDynData,
const PxWheelQueryResult* wheelQueryResults,
const PxU32 numWheelsToPose,
const PxTransform& vehChassisCMLocalPose,
const PxVec3& upAxis,
const PxVec3& sideAxis,
const PxVec3& forwardAxis,
PxTransform* localPoses)
{
const PxF32* PX_RESTRICT rotAngles=wheelsDynData.mWheelRotationAngles;
const PxVec3 cmOffset=vehChassisCMLocalPose.p;
for(PxU32 i=0;i<numWheelsToPose;i++)
{
const PxF32 jounce=wheelQueryResults[i].suspJounce;
PX_ASSERT(jounce != PX_MAX_F32);
const PxQuat quat = computeWheelLocalQuat(forwardAxis, sideAxis, upAxis, jounce, wheelsSimData.getSuspensionData(i), rotAngles[i], wheelQueryResults[i].steerAngle);
const PxVec3 pos=cmOffset+wheelsSimData.getWheelCentreOffset(i)-wheelsSimData.getSuspTravelDirection(i)*jounce;
localPoses[i] = PxTransform(pos, quat);
}
}
void computeWheelLocalPoseRotations
(const PxVehicleWheels4DynData* wheels4DynDatas, const PxVehicleWheels4SimData* wheels4SimDatas, const PxU32 numWheels4,
const PxVehicleContext& context,
const float* steerAngles,
PxQuat* wheelLocalPoseRotations)
{
for (PxU32 i = 0; i < numWheels4; i++)
{
for (PxU32 j = 0; j < 4; j++)
{
const PxF32 jounce = (wheels4DynDatas[i].mJounces[j] != PX_MAX_F32) ? wheels4DynDatas[i].mJounces[j] : 0.0f;
const PxVehicleSuspensionData& suspData = wheels4SimDatas[i].getSuspensionData(j);
const PxF32 steerAngle = steerAngles[4 * i + j];
const PxQuat q = computeWheelLocalQuat(context.forwardAxis, context.sideAxis, context.upAxis, jounce, suspData, 0.0f, steerAngle);
wheelLocalPoseRotations[4 * i + j] = q;
}
}
}
void poseWheels
(const PxVehicleWheels4SimData& wheelsSimData,
const PxTransform* localPoses,
const PxU32 numWheelsToPose,
PxRigidDynamic* vehActor)
{
PxShape* shapeBuffer[128];
vehActor->getShapes(shapeBuffer,128,0);
for(PxU32 i=0;i<numWheelsToPose;i++)
{
const PxI32 shapeIndex = wheelsSimData.getWheelShapeMapping(i);
if(shapeIndex != -1)
{
PxShape* currShape = NULL;
if(shapeIndex < 128)
{
currShape = shapeBuffer[shapeIndex];
}
else
{
PxShape* shapeBuffer2[1];
vehActor->getShapes(shapeBuffer2,1,PxU32(shapeIndex));
currShape = shapeBuffer2[0];
}
PX_ASSERT(currShape);
currShape->setLocalPose(localPoses[i]);
}
}
}
////////////////////////////////////////////////////////////////////////////
//Update each vehicle type with a special function
////////////////////////////////////////////////////////////////////////////
class PxVehicleUpdate
{
public:
#if PX_DEBUG_VEHICLE_ON
static void updateSingleVehicleAndStoreTelemetryData(
const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* focusVehicle, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxVehicleContext&);
#endif
static void update(
const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* wheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
VehicleTelemetryDataContext* vehicleTelemetryDataContext, const PxVehicleContext&);
static void updatePost(
const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext&);
static void suspensionRaycasts(
PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const bool* vehiclesToRaycast, const PxQueryFlags queryFlags);
static void suspensionSweeps(
PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToRaycast,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation, const PxQueryFlags queryFlags,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis);
static void updateDrive4W(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDrive4W* vehDrive4W, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateDriveNW(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveNW* vehDriveNW, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateTank(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveTank* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static void updateNoDrive(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleNoDrive* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext*, const PxVehicleContext&);
static PxU32 computeNumberOfSubsteps(const PxVehicleWheelsSimData& wheelsSimData, const PxVec3& linVel, const PxTransform& globalPose, const PxVec3& forward)
{
const PxVec3 z=globalPose.q.rotate(forward);
const PxF32 vz=PxAbs(linVel.dot(z));
const PxF32 thresholdVz=wheelsSimData.mThresholdLongitudinalSpeed;
const PxU32 lowCount=wheelsSimData.mLowForwardSpeedSubStepCount;
const PxU32 highCount=wheelsSimData.mHighForwardSpeedSubStepCount;
const PxU32 count=(vz<thresholdVz ? lowCount : highCount);
return count;
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleWheelsDynData& wheels)
{
const PxU32 nbWheels4 = (wheels.mNbActiveWheels + 3) >> 2;
PxVehicleWheels4DynData* wheels4 = wheels.getWheel4DynData();
for(PxU32 i = 0; i < nbWheels4; i++)
{
wheels4[i].setInternalDynamicsToZero();
}
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveDynData& drive)
{
drive.setEngineRotationSpeed(0.0f);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleNoDrive* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDrive4W* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveNW* veh)
{
veh->mDriveDynData.setEngineRotationSpeed(0.0f);
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static void setInternalDynamicsToZero(PxVehicleDriveTank* veh)
{
setInternalDynamicsToZero(veh->mWheelsDynData);
setInternalDynamicsToZero(veh->mDriveDynData);
}
PX_INLINE static bool isOnDynamicActor(const PxVehicleWheelsSimData& wheelsSimData, const PxVehicleWheelsDynData& wheelsDynData)
{
const PxU32 numWheels4 = wheelsSimData.mNbWheels4;
const PxVehicleWheels4DynData* PX_RESTRICT wheels4DynDatas = wheelsDynData.mWheels4DynData;
for(PxU32 i=0;i<numWheels4;i++)
{
const PxRaycastBuffer* raycastResults = wheels4DynDatas[i].mRaycastResults;
const PxSweepBuffer* sweepResults = wheels4DynDatas[i].mSweepResults;
for(PxU32 j=0;j<4;j++)
{
if (!wheelsSimData.getIsWheelDisabled(4 * i + j) && (raycastResults || sweepResults))
{
const PxU32 hitCount = PxU32(raycastResults ? raycastResults[j].hasBlock : sweepResults[j].hasBlock);
PxRigidActor* hitActor = raycastResults ? raycastResults[j].block.actor : sweepResults[j].block.actor;
if(hitCount && hitActor && hitActor->is<PxRigidDynamic>())
return true;
}
}
}
return false;
}
PX_INLINE static void storeRaycasts(const PxVehicleWheels4DynData& dynData, PxWheelQueryResult* wheelQueryResults)
{
if(dynData.mRaycastResults)
{
for(PxU32 i=0;i<4;i++)
{
const PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<const PxVehicleWheels4DynData::SuspLineRaycast&>(dynData.mQueryOrCachedHitResults);
wheelQueryResults[i].suspLineStart=raycast.mStarts[i];
wheelQueryResults[i].suspLineDir=raycast.mDirs[i];
wheelQueryResults[i].suspLineLength=raycast.mLengths[i];
}
}
else if(dynData.mSweepResults)
{
for(PxU32 i=0;i<4;i++)
{
const PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<const PxVehicleWheels4DynData::SuspLineSweep&>(dynData.mQueryOrCachedHitResults);
wheelQueryResults[i].suspLineStart=sweep.mStartPose[i].p;
wheelQueryResults[i].suspLineDir=sweep.mDirs[i];
wheelQueryResults[i].suspLineLength=sweep.mLengths[i];
}
}
else
{
for(PxU32 i=0;i<4;i++)
{
wheelQueryResults[i].suspLineStart=PxVec3(0,0,0);
wheelQueryResults[i].suspLineDir=PxVec3(0,0,0);
wheelQueryResults[i].suspLineLength=0;
}
}
}
PX_INLINE static void storeSuspWheelTireResults
(const ProcessSuspWheelTireOutputData& outputData, const PxF32* steerAngles, PxWheelQueryResult* wheelQueryResults, const PxU32 numWheels)
{
for(PxU32 i=0;i<numWheels;i++)
{
wheelQueryResults[i].isInAir=outputData.isInAir[i];
wheelQueryResults[i].tireContactActor=outputData.tireContactActors[i];
wheelQueryResults[i].tireContactShape=outputData.tireContactShapes[i];
wheelQueryResults[i].tireSurfaceMaterial=outputData.tireSurfaceMaterials[i];
wheelQueryResults[i].tireSurfaceType=outputData.tireSurfaceTypes[i];
wheelQueryResults[i].tireContactPoint=outputData.tireContactPoints[i];
wheelQueryResults[i].tireContactNormal=outputData.tireContactNormals[i];
wheelQueryResults[i].tireFriction=outputData.frictions[i];
wheelQueryResults[i].suspJounce=outputData.jounces[i];
wheelQueryResults[i].suspSpringForce=outputData.suspensionSpringForces[i];
wheelQueryResults[i].tireLongitudinalDir=outputData.tireLongitudinalDirs[i];
wheelQueryResults[i].tireLateralDir=outputData.tireLateralDirs[i];
wheelQueryResults[i].longitudinalSlip=outputData.longSlips[i];
wheelQueryResults[i].lateralSlip=outputData.latSlips[i];
wheelQueryResults[i].steerAngle=steerAngles[i];
}
}
PX_INLINE static void storeHitActorForces(const ProcessSuspWheelTireOutputData& outputData, PxVehicleWheelConcurrentUpdateData* wheelConcurrentUpdates, const PxU32 numWheels)
{
for(PxU32 i=0;i<numWheels;i++)
{
wheelConcurrentUpdates[i].hitActor=outputData.hitActors[i];
wheelConcurrentUpdates[i].hitActorForce+=outputData.hitActorForces[i];
wheelConcurrentUpdates[i].hitActorForcePosition=outputData.hitActorForcePositions[i];
}
}
static void shiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles);
};
void PxVehicleUpdate::updateDrive4W(
const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDrive4W* vehDrive4W, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor() on osx
START_TIMER(TIMER_ADMIN);
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal vehicle control value - accel must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_BRAKE]<1.01f,
"Illegal vehicle control value - brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]>-0.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_HANDBRAKE]<1.01f,
"Illegal vehicle control value - handbrake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT]>-1.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT]<1.01f,
"Illegal vehicle control value - left steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]>-1.01f &&
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]<1.01f,
"Illegal vehicle control value - right steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxAbs(vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT]-
vehDrive4W->mDriveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT])<1.01f,
"Illegal vehicle control value - right steer value minus left steer value must be in range (-1,1)");
PX_CHECK_AND_RETURN(
!(vehDrive4W->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a drive4W with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDrive4W->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
PX_CHECK_AND_RETURN(
NULL==vehConcurrentUpdates || vehConcurrentUpdates->nbConcurrentWheelUpdates >= vehDrive4W->mWheelsSimData.getNbWheels(),
"vehConcurrentUpdates->nbConcurrentWheelUpdates must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
{
//Check that the sense of left/right and forward/rear is true.
const PxVec3 fl=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eFRONT_LEFT);
const PxVec3 fr=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eFRONT_RIGHT);
const PxVec3 rl=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eREAR_LEFT);
const PxVec3 rr=vehDrive4W->mWheelsSimData.mWheels4SimData[0].getWheelCentreOffset(PxVehicleDrive4WWheelOrder::eREAR_RIGHT);
const PxVec3 right=context.sideAxis;
const PxF32 s0=computeSign((fr-fl).dot(right));
const PxF32 s1=computeSign((rr-rl).dot(right));
PX_CHECK_AND_RETURN(0==s0 || 0==s1 || s0==s1, "PxVehicle4W does not obey the rule that the eFRONT_RIGHT/eREAR_RIGHT wheels are to the right of the eFRONT_LEFT/eREAR_LEFT wheels");
}
#endif
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_GRAPHS);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDrive4W->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDrive4W->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDrive4W->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
END_TIMER(TIMER_GRAPHS);
START_TIMER(TIMER_ADMIN);
//Unpack the vehicle.
//Unpack the 4W simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDrive4W->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDrive4W->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDrive4W->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDrive4W->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDrive4W->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
const PxVehicleDriveSimData4W driveSimData=vehDrive4W->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDrive4W->mDriveDynData;
PxRigidDynamic* vehActor=vehDrive4W->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDrive4W->mWheelsSimData, vehDrive4W->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to zero.
setInternalDynamicsToZero(vehDrive4W);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDrive4W->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//We need to store data to pose the wheels at the end.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Update the auto-box and decide whether to change gear up or down.
PxF32 autoboxCompensatedAnalogAccel = driveDynData.mControlAnalogVals[PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL];
if(driveDynData.getUseAutoGears())
{
autoboxCompensatedAnalogAccel = processAutoBox(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength;
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Clutch accuracy
PxVehicleClutchAccuracyMode::Enum clutchAccuracyMode;
PxU32 clutchMaxIterations;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
clutchAccuracyMode = clutchData.mAccuracyMode;
clutchMaxIterations = clutchData.mEstimateIterations;
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
//Retrieve control values from vehicle controls.
PxF32 accel,brake,handbrake,steerLeft,steerRight;
PxF32 steer;
bool isIntentionToAccelerate;
{
getVehicle4WControlValues(driveDynData,accel,brake,handbrake,steerLeft,steerRight);
steer=steerRight-steerLeft;
accel=autoboxCompensatedAnalogAccel;
isIntentionToAccelerate = (accel>0.0f && 0.0f==brake && 0.0f==handbrake && PxVehicleGearsData::eNEUTRAL != currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brake,handbrake,steerLeft,steerRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Active wheels (wheels which have not been disabled).
bool activeWheelStates[4]={false,false,false,false};
{
computeWheelActiveStates(4*0, vehDrive4W->mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
}
//Get the drive wheels (the first 4 wheels are the drive wheels).
const PxVehicleWheels4SimData& wheels4SimData=wheels4SimDatas[0];
PxVehicleWheels4DynData& wheels4DynData=wheels4DynDatas[0];
const PxVehicleTireForceCalculator4& tires4ForceCalculator=tires4ForceCalculators[0];
//Contribution of each driven wheel to average wheel speed at clutch.
//With 4 driven wheels the average wheel speed at clutch is
//wAve = alpha0*w0 + alpha1*w1 + alpha2*w2 + alpha3*w3.
//This next bit of code computes alpha0,alpha1,alpha2,alpha3.
//For rear wheel drive alpha0=alpha1=0
//For front wheel drive alpha2=alpha3=0
PxF32 aveWheelSpeedContributions[4]={0.0f,0.0f,0.0f,0.0f};
{
const PxVehicleDifferential4WData& diffData=driveSimData.getDiffData();
computeDiffAveWheelSpeedContributions(diffData,handbrake,aveWheelSpeedContributions);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlip(wheels4DynData.mWheelSpeeds,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
PX_CHECK_AND_RETURN(
(activeWheelStates[0] || 0.0f==aveWheelSpeedContributions[0]) &&
(activeWheelStates[1] || 0.0f==aveWheelSpeedContributions[1]) &&
(activeWheelStates[2] || 0.0f==aveWheelSpeedContributions[2]) &&
(activeWheelStates[3] || 0.0f==aveWheelSpeedContributions[3]),
"PxVehicleDifferential4WData must be configured so that no torque is delivered to a disabled wheel");
}
//Compute a per-wheel accelerator pedal value.
bool isAccelApplied[4]={false,false,false,false};
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
computeIsAccelApplied(aveWheelSpeedContributions, isAccelApplied);
}
//Ackermann-corrected steering angles for 1st block of 4 wheels.
//http://en.wikipedia.org/wiki/Ackermann_steering_geometry
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemZero(steerAngles, sizeof(steerAngles));
{
computeAckermannCorrectedSteerAngles(driveSimData,wheels4SimData,steer,steerAngles);
}
//All other wheels need a steer angle too.
for(PxU32 i = 1; i < numWheels4; i++)
{
for(PxU32 j = 0; j < 4; j++)
{
const PxF32 steerAngle = wheels4SimDatas[i].getWheelData(j).mToeAngle;
steerAngles[4*i + j] = steerAngle;
}
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_ADMIN);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDrive4W->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDrive4W->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDrive4W->mWheelsSimData.mFlags};
END_TIMER(TIMER_ADMIN);
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Update the drive/steer wheels and engine.
{
//Compute the brake torques.
PxF32 brakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool isBrakeApplied[4]={false,false,false,false};
computeBrakeAndHandBrakeTorques
(&wheels4SimData.getWheelData(0),wheels4DynData.mWheelSpeeds,brake,handbrake,
brakeTorques,isBrakeApplied);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_WHEELS);
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, isAccelApplied, isBrakeApplied, steerAngles, activeWheelStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
wheelLocalPoseRotations, &wheels4SimData, &wheels4DynData, &tires4ForceCalculator, &tireLoadFilterData, numActiveWheelsPerBlock4[0]
};
ProcessSuspWheelTireOutputData outputData;
processSuspTireWheels(0, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData, vehTelemetryDataContext);
updateLowSpeedTimers(outputData.newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData.newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData.jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(steerAngles, const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData.cachedHitCounts, outputData.cachedHitPlanes, outputData.cachedHitDistances, outputData.cachedFrictionMultipliers, outputData.cachedHitQueryTypes, &wheels4DynData);
}
chassisForce+=outputData.chassisForce;
chassisTorque+=outputData.chassisTorque;
if(0 == k)
{
wheels4DynData.mVehicleConstraints->mData=outputData.vehConstraintData;
}
storeSuspWheelTireResults(outputData, inputData.steerAngles, &wheelQueryResults[4*0], numActiveWheelsPerBlock4[0]);
storeHitActorForces(outputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*0], numActiveWheelsPerBlock4[0]);
END_TIMER(TIMER_WHEELS);
START_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
//Diff torque ratios needed (how we split the torque between the drive wheels).
//The sum of the torque ratios is always 1.0f.
//The drive torque delivered to each wheel is the total available drive torque multiplied by the
//diff torque ratio for each wheel.
PxF32 diffTorqueRatios[4]={0.0f,0.0f,0.0f,0.0f};
computeDiffTorqueRatios(driveSimData.getDiffData(),handbrake,wheels4DynData.mWheelSpeeds,diffTorqueRatios);
PX_CHECK_AND_RETURN(
(activeWheelStates[0] || 0.0f==diffTorqueRatios[0]) &&
(activeWheelStates[1] || 0.0f==diffTorqueRatios[1]) &&
(activeWheelStates[2] || 0.0f==diffTorqueRatios[2]) &&
(activeWheelStates[3] || 0.0f==diffTorqueRatios[3]),
"PxVehicleDifferential4WData must be configured so that no torque is delivered to a disabled wheel");
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - 5x5 matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput=
{
subTimestep,
brake, handbrake,
K, G,
clutchAccuracyMode, clutchMaxIterations,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, outputData.tireTorques,
1, 4,
&wheels4SimData, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput=
{
&wheels4DynData, &driveDynData
};
solveDrive4WInternaDynamicsEnginePlusDrivenWheels(implicitSolverInput, &implicitSolverOutput);
END_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
START_TIMER(TIMER_POSTUPDATE1);
//Integrate wheel rotation angle (theta += omega*dt)
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData.jounces,diffTorqueRatios,outputData.forwardSpeeds,isBrakeApplied,
driveSimData,wheels4SimData,
driveDynData,wheels4DynData);
}
END_TIMER(TIMER_POSTUPDATE1);
//////////////////////////////////////////////////////////////////////////
//susp and tire forces from extra wheels (non-driven wheels)
//////////////////////////////////////////////////////////////////////////
for(PxU32 j=1;j<numWheels4;j++)
{
//We already computed the steer angles above.
PxF32* extraWheelSteerAngles= steerAngles + 4*j;
//Only the driven wheels are connected to the diff.
PxF32 extraWheelsDiffTorqueRatios[4]={0.0f,0.0f,0.0f,0.0f};
bool extraIsAccelApplied[4]={false,false,false,false};
//The extra wheels do have brakes.
PxF32 extraWheelBrakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool extraIsBrakeApplied[4]={false,false,false,false};
computeBrakeAndHandBrakeTorques
(&wheels4SimDatas[j].getWheelData(0),wheels4DynDatas[j].mWheelSpeeds,brake,handbrake,
extraWheelBrakeTorques,extraIsBrakeApplied);
//The extra wheels can be disabled or enabled.
bool extraWheelActiveStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, vehDrive4W->mWheelsSimData.mActiveWheelsBitmapBuffer, extraWheelActiveStates);
ProcessSuspWheelTireInputData extraInputData=
{
isIntentionToAccelerate, extraIsAccelApplied, extraIsBrakeApplied, extraWheelSteerAngles, extraWheelActiveStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[j], &wheels4SimDatas[j], &wheels4DynDatas[j], &tires4ForceCalculators[j], &tireLoadFilterData, numActiveWheelsPerBlock4[j],
};
ProcessSuspWheelTireOutputData extraOutputData;
processSuspTireWheels(4*j, constData, extraInputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
extraOutputData, vehTelemetryDataContext);
updateLowSpeedTimers(extraOutputData.newLowForwardSpeedTimers, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(extraOutputData.newLowSideSpeedTimers, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(extraOutputData.jounces, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mJounces));
updateSteers(extraWheelSteerAngles, const_cast<PxF32*>(extraInputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(extraOutputData.cachedHitCounts, extraOutputData.cachedHitPlanes, extraOutputData.cachedHitDistances, extraOutputData.cachedFrictionMultipliers, extraOutputData.cachedHitQueryTypes, &wheels4DynDatas[j]);
}
chassisForce+=extraOutputData.chassisForce;
chassisTorque+=extraOutputData.chassisTorque;
if(0 == k)
{
wheels4DynDatas[j].mVehicleConstraints->mData=extraOutputData.vehConstraintData;
}
storeSuspWheelTireResults(extraOutputData, extraInputData.steerAngles, &wheelQueryResults[4*j], numActiveWheelsPerBlock4[j]);
storeHitActorForces(extraOutputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*j], numActiveWheelsPerBlock4[j]);
//Integrate the tire torques (omega += (tireTorque + brakeTorque)*dt)
integrateUndriveWheelRotationSpeeds(subTimestep, brake, handbrake, extraOutputData.tireTorques, extraWheelBrakeTorques, wheels4SimDatas[j], wheels4DynDatas[j]);
//Integrate wheel rotation angle (theta += omega*dt)
integrateWheelRotationAngles
(subTimestep,
0,0,0,
extraOutputData.jounces,extraWheelsDiffTorqueRatios,extraOutputData.forwardSpeeds,extraIsBrakeApplied,
driveSimData,wheels4SimDatas[j],
driveDynData,wheels4DynDatas[j]);
}
START_TIMER(TIMER_POSTUPDATE2);
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDrive4W->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate one sustep.
integrateBody(inverseChassisMass, inverseInertia ,chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
END_TIMER(TIMER_POSTUPDATE2);
}
START_TIMER(TIMER_POSTUPDATE3);
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;;
}
//Compute and pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
//Copy the poses to the wheelQueryResults
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
//Copy the poses to the concurrent update data.
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
//Copy the poses to the wheelQueryResults
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
//Copy the poses to the concurrent update data.
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDrive4W};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
END_TIMER(TIMER_POSTUPDATE3);
}
void PxVehicleUpdate::updateDriveNW
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveNW* vehDriveNW, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception triggered in transformInertiaTensor() on osx
START_TIMER(TIMER_ADMIN);
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal vehicle control value - accel must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_BRAKE]<1.01f,
"Illegal vehicle control value - brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE]>-0.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_HANDBRAKE]<1.01f,
"Illegal vehicle control value - handbrake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT]>-1.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT]<1.01f,
"Illegal vehicle control value - left steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]>-1.01f &&
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]<1.01f,
"Illegal vehicle control value - right steer must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxAbs(vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_RIGHT]-
vehDriveNW->mDriveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_STEER_LEFT])<1.01f,
"Illegal vehicle control value - right steer value minus left steer value must be in range (-1,1)");
PX_CHECK_AND_RETURN(
!(vehDriveNW->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a drive4W with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDriveNW->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
for(PxU32 i=0;i<vehDriveNW->mWheelsSimData.getNbWheels();i++)
{
PX_CHECK_AND_RETURN(!vehDriveNW->mWheelsSimData.getIsWheelDisabled(i) || !vehDriveNW->mDriveSimData.getDiffData().getIsDrivenWheel(i),
"PxVehicleDifferentialNWData must be configured so that no torque is delivered to a disabled wheel");
}
#endif
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_GRAPHS);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDriveNW->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDriveNW->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDriveNW->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
END_TIMER(TIMER_GRAPHS);
START_TIMER(TIMER_ADMIN);
//Unpack the vehicle.
//Unpack the NW simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDriveNW->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDriveNW->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDriveNW->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDriveNW->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDriveNW->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
const PxVehicleDriveSimDataNW driveSimData=vehDriveNW->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDriveNW->mDriveDynData;
PxRigidDynamic* vehActor=vehDriveNW->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_STEER_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDrive4WControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDriveNW->mWheelsSimData, vehDriveNW->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehDriveNW);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDriveNW->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
END_TIMER(TIMER_ADMIN);
START_TIMER(TIMER_COMPONENTS_UPDATE);
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Update the auto-box and decide whether to change gear up or down.
PxF32 autoboxCompensatedAnalogAccel = driveDynData.mControlAnalogVals[PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL];
if(driveDynData.getUseAutoGears())
{
autoboxCompensatedAnalogAccel = processAutoBox(PxVehicleDriveNWControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength.
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Clutch accuracy.
PxVehicleClutchAccuracyMode::Enum clutchAccuracyMode;
PxU32 clutchMaxIterations;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
clutchAccuracyMode=clutchData.mAccuracyMode;
clutchMaxIterations=clutchData.mEstimateIterations;
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
//Retrieve control values from vehicle controls.
PxF32 accel,brake,handbrake,steerLeft,steerRight;
PxF32 steer;
bool isIntentionToAccelerate;
{
getVehicleNWControlValues(driveDynData,accel,brake,handbrake,steerLeft,steerRight);
steer=steerRight-steerLeft;
accel=autoboxCompensatedAnalogAccel;
isIntentionToAccelerate = (accel>0.0f && 0.0f==brake && 0.0f==handbrake && PxVehicleGearsData::eNEUTRAL != currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brake,handbrake,steerLeft,steerRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Compute the wheels that are disabled or enabled.
bool activeWheelStates[PX_MAX_NB_WHEELS];
PxMemSet(activeWheelStates, 0, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeWheelActiveStates(4*i, vehDriveNW->mWheelsSimData.mActiveWheelsBitmapBuffer, &activeWheelStates[4*i]);
}
//Contribution of each driven wheel to average wheel speed at clutch.
//For NW drive equal torque split is supported.
const PxVehicleDifferentialNWData diffData=driveSimData.getDiffData();
const PxF32 invNumDrivenWheels=diffData.mInvNbDrivenWheels;
PxF32 aveWheelSpeedContributions[PX_MAX_NB_WHEELS];
PxMemSet(aveWheelSpeedContributions, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
aveWheelSpeedContributions[i] = diffData.getIsDrivenWheel(i) ? invNumDrivenWheels : 0;
}
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlipNW(numWheels4,wheels4DynDatas,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
//Compute a per-wheel accelerator pedal value.
bool isAccelApplied[PX_MAX_NB_WHEELS];
PxMemSet(isAccelApplied, 0, sizeof(bool)*PX_MAX_NB_WHEELS);
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
for(PxU32 i=0;i<numWheels4;i++)
{
computeIsAccelApplied(&aveWheelSpeedContributions[4*i],&isAccelApplied[4*i]);
}
}
//Steer angles.
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemSet(steerAngles, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
const PxVehicleWheelData& wheelData=vehDriveNW->mWheelsSimData.getWheelData(i);
const PxF32 steerGain=wheelData.mMaxSteer;
const PxF32 toe=wheelData.mToeAngle;
steerAngles[i]=steerGain*steer + toe;
}
//Diff torque ratios needed (how we split the torque between the drive wheels).
//The sum of the torque ratios is always 1.0f.
//The drive torque delivered to each wheel is the total available drive torque multiplied by the
//diff torque ratio for each wheel.
PxF32 diffTorqueRatios[PX_MAX_NB_WHEELS];
PxMemSet(diffTorqueRatios, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numActiveWheels;i++)
{
diffTorqueRatios[i] = diffData.getIsDrivenWheel(i) ? invNumDrivenWheels : 0.0f;
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_ADMIN);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDriveNW->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDriveNW->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDriveNW->mWheelsSimData.mFlags};
END_TIMER(TIMER_ADMIN);
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
START_TIMER(TIMER_COMPONENTS_UPDATE);
PxF32 brakeTorques[PX_MAX_NB_WHEELS];
bool isBrakeApplied[PX_MAX_NB_WHEELS];
PxMemSet(brakeTorques, 0, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemSet(isBrakeApplied, false, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeBrakeAndHandBrakeTorques(&wheels4SimDatas[i].getWheelData(0),wheels4DynDatas[i].mWheelSpeeds,brake,handbrake,&brakeTorques[4*i],&isBrakeApplied[4*i]);
}
END_TIMER(TIMER_COMPONENTS_UPDATE);
START_TIMER(TIMER_WHEELS);
ProcessSuspWheelTireOutputData outputData[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, &isAccelApplied[4*i], &isBrakeApplied[4*i], &steerAngles[4*i], &activeWheelStates[4*i],
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimDatas[i], &wheels4DynDatas[i], &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i]
};
processSuspTireWheels(4*i, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData[i], vehTelemetryDataContext);
updateLowSpeedTimers(outputData[i].newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData[i].newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData[i].jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(&steerAngles[4*i], const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData[i].cachedHitCounts, outputData[i].cachedHitPlanes, outputData[i].cachedHitDistances, outputData[i].cachedFrictionMultipliers, outputData[i].cachedHitQueryTypes, &wheels4DynDatas[i]);
}
chassisForce+=outputData[i].chassisForce;
chassisTorque+=outputData[i].chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData[i].vehConstraintData;
}
storeSuspWheelTireResults(outputData[i], inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData[i], &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
}
//Store the tire torques in a single array.
PxF32 tireTorques[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4;i++)
{
tireTorques[4*i+0]=outputData[i].tireTorques[0];
tireTorques[4*i+1]=outputData[i].tireTorques[1];
tireTorques[4*i+2]=outputData[i].tireTorques[2];
tireTorques[4*i+3]=outputData[i].tireTorques[3];
}
END_TIMER(TIMER_WHEELS);
START_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - (N+1)*(N+1) matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput=
{
subTimestep,
brake, handbrake,
K, G,
clutchAccuracyMode, clutchMaxIterations,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, tireTorques,
numWheels4, numActiveWheels,
wheels4SimDatas, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput=
{
wheels4DynDatas, &driveDynData
};
solveDriveNWInternalDynamicsEnginePlusDrivenWheels(implicitSolverInput, &implicitSolverOutput);
END_TIMER(TIMER_INTERNAL_DYNAMICS_SOLVER);
START_TIMER(TIMER_POSTUPDATE1);
//Integrate wheel rotation angle (theta += omega*dt)
for(PxU32 i=0;i<numWheels4;i++)
{
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData[i].jounces,&diffTorqueRatios[4*i],outputData[i].forwardSpeeds,&isBrakeApplied[4*i],
driveSimData,wheels4SimDatas[i],
driveDynData,wheels4DynDatas[i]);
}
END_TIMER(TIMER_POSTUPDATE1);
START_TIMER(TIMER_POSTUPDATE2);
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDriveNW->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
END_TIMER(TIMER_POSTUPDATE2);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
START_TIMER(TIMER_POSTUPDATE3);
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDriveNW};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
END_TIMER(TIMER_POSTUPDATE3);
}
void PxVehicleUpdate::updateTank
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleDriveTank* vehDriveTank, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor()
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL]<1.01f,
"Illegal tank control value - accel must be in range (0,1)" );
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT]<1.01f,
"Illegal tank control value - left brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT]<1.01f,
"Illegal tank control right value - right brake must be in range (0,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]>-1.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]<1.01f,
"Illegal tank control value - left thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]>-1.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]<1.01f,
"Illegal tank control value - right thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
(vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]<1.01f),
"Illegal tank control value - left thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
(vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]>-0.01f &&
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]<1.01f),
"Illegal tank control value - right thrust must be in range (-1,1)");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
0.0f==
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT]*
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_LEFT],
"Illegal tank control value - thrust left and brake left simultaneously non-zero in standard drive mode");
PX_CHECK_AND_RETURN(
PxVehicleDriveTankControlModel::eSPECIAL==vehDriveTank->mDriveModel ||
0.0f==
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT]*
vehDriveTank->mDriveDynData.mControlAnalogVals[PxVehicleDriveTankControl::eANALOG_INPUT_BRAKE_RIGHT],
"Illegal tank control value - thrust right and brake right simultaneously non-zero in standard drive mode");
PX_CHECK_AND_RETURN(
!(vehDriveTank->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a tank with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehDriveTank->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
{
PxVec3 fl=vehDriveTank->mWheelsSimData.getWheelCentreOffset(PxVehicleDriveTankWheelOrder::eFRONT_LEFT);
PxVec3 fr=vehDriveTank->mWheelsSimData.getWheelCentreOffset(PxVehicleDriveTankWheelOrder::eFRONT_RIGHT);
const PxVec3 right=context.sideAxis;
const PxF32 s0=computeSign((fr-fl).dot(right));
for(PxU32 i=PxVehicleDriveTankWheelOrder::e1ST_FROM_FRONT_LEFT;i<vehDriveTank->mWheelsSimData.getNbWheels();i+=2)
{
PxVec3 rl=vehDriveTank->mWheelsSimData.getWheelCentreOffset(i);
PxVec3 rr=vehDriveTank->mWheelsSimData.getWheelCentreOffset(i+1);
const PxF32 t0=computeSign((rr-rl).dot(right));
PX_CHECK_AND_RETURN(s0==t0 || 0==s0 || 0==t0, "Tank wheels must be ordered with odd wheels on one side and even wheels on the other side");
}
}
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehDriveTank->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehDriveTank->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
updateGraphDataInternalEngineDynamics(vehDriveTank->mDriveDynData.getEngineRotationSpeed(), vehTelemetryDataContext->engineGraphData);
}
#endif
//Unpack the tank simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehDriveTank->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehDriveTank->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehDriveTank->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehDriveTank->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehDriveTank->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4-numActiveWheels);
const PxVehicleDriveSimData driveSimData=vehDriveTank->mDriveSimData;
PxVehicleDriveDynData& driveDynData=vehDriveTank->mDriveDynData;
PxRigidDynamic* vehActor=vehDriveTank->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
if(0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_LEFT) ||
0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_THRUST_RIGHT) ||
0!=driveDynData.getAnalogInput(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL) ||
driveDynData.getGearDown() || driveDynData.getGearUp())
{
finiteInputApplied=true;
}
//Awake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehDriveTank->mWheelsSimData, vehDriveTank->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehDriveTank);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehDriveTank->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the suspension/tire constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Retrieve control values from vehicle controls.
PxF32 accel,brakeLeft,brakeRight,thrustLeft,thrustRight;
{
getTankControlValues(driveDynData,accel,brakeLeft,brakeRight,thrustLeft,thrustRight);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataControlInputs(accel,brakeLeft,brakeRight,thrustLeft,thrustRight, vehTelemetryDataContext->engineGraphData);
#endif
}
//Update the auto-box and decide whether to change gear up or down.
//If the tank is supposed to turn sharply don't process the auto-box.
bool useAutoGears;
if(vehDriveTank->getDriveModel()==PxVehicleDriveTankControlModel::eSPECIAL)
{
useAutoGears = driveDynData.getUseAutoGears() ? ((((thrustRight*thrustLeft) >= 0.0f) || (0.0f==thrustLeft && 0.0f==thrustRight)) ? true : false) : false;
}
else
{
useAutoGears = driveDynData.getUseAutoGears() ? (thrustRight*brakeLeft>0 || thrustLeft*brakeRight>0 ? false : true) : false;
}
if(useAutoGears)
{
processAutoBox(PxVehicleDriveTankControl::eANALOG_INPUT_ACCEL,timestep,driveSimData,driveDynData);
}
//Process gear-up/gear-down commands.
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
processGears(timestep,gearsData,driveDynData);
}
//Clutch strength;
PxF32 K;
{
const PxVehicleClutchData& clutchData=driveSimData.getClutchData();
const PxU32 currentGear=driveDynData.getCurrentGear();
K=computeClutchStrength(clutchData, currentGear);
}
//Gear ratio.
PxF32 G;
PxU32 currentGear;
{
const PxVehicleGearsData& gearsData=driveSimData.getGearsData();
currentGear=driveDynData.getCurrentGear();
G=computeGearRatio(gearsData,currentGear);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataGearRatio(G, vehTelemetryDataContext->engineGraphData);
#endif
}
bool isIntentionToAccelerate;
{
const PxF32 thrustLeftAbs=PxAbs(thrustLeft);
const PxF32 thrustRightAbs=PxAbs(thrustRight);
isIntentionToAccelerate = (accel*(thrustLeftAbs+thrustRightAbs)>0 && PxVehicleGearsData::eNEUTRAL != currentGear);
}
//Compute the wheels that are enabled/disabled.
bool activeWheelStates[PX_MAX_NB_WHEELS];
PxMemZero(activeWheelStates, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeWheelActiveStates(4*i, vehDriveTank->mWheelsSimData.mActiveWheelsBitmapBuffer, &activeWheelStates[4*i]);
}
//Set up contribution of each wheel to the average wheel speed at the clutch
//Set up the torque ratio delivered by the diff to each wheel.
//Set the sign of the gearing applied to the left and right wheels.
PxF32 aveWheelSpeedContributions[PX_MAX_NB_WHEELS];
PxF32 diffTorqueRatios[PX_MAX_NB_WHEELS];
PxF32 wheelGearings[PX_MAX_NB_WHEELS];
PxMemZero(aveWheelSpeedContributions, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(diffTorqueRatios, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(wheelGearings, sizeof(PxF32)*PX_MAX_NB_WHEELS);
computeTankDiff
(thrustLeft, thrustRight,
numActiveWheels, activeWheelStates,
aveWheelSpeedContributions, diffTorqueRatios, wheelGearings);
//Compute an accelerator pedal value per wheel.
bool isAccelApplied[PX_MAX_NB_WHEELS];
PxMemZero(isAccelApplied, sizeof(bool)*PX_MAX_NB_WHEELS);
if(isIntentionToAccelerate)
{
PX_ASSERT(accel>0);
for(PxU32 i=0;i<numWheels4;i++)
{
computeIsAccelApplied(&aveWheelSpeedContributions[4*i], &isAccelApplied[4*i]);
}
}
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataClutchSlip(wheels4DynDatas[0].mWheelSpeeds,aveWheelSpeedContributions,driveDynData.getEngineRotationSpeed(),G, vehTelemetryDataContext->engineGraphData);
#endif
//Ackermann-corrected steer angles
//For tanks this is always zero because they turn by torque delivery rather than a steering mechanism.
PxF32 steerAngles[PX_MAX_NB_WHEELS];
PxMemZero(steerAngles, sizeof(PxF32)*PX_MAX_NB_WHEELS);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, steerAngles, wheelLocalPoseRotations);
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehDriveTank->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehDriveTank->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, true, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehDriveTank->mWheelsSimData.mFlags};
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
//Compute the brake torques.
PxF32 brakeTorques[PX_MAX_NB_WHEELS];
bool isBrakeApplied[PX_MAX_NB_WHEELS];
PxMemZero(brakeTorques, sizeof(PxF32)*PX_MAX_NB_WHEELS);
PxMemZero(isBrakeApplied, sizeof(bool)*PX_MAX_NB_WHEELS);
for(PxU32 i=0;i<numWheels4;i++)
{
computeTankBrakeTorques
(&wheels4SimDatas[i].getWheelData(0),wheels4DynDatas[i].mWheelSpeeds,brakeLeft,brakeRight,
&brakeTorques[i*4],&isBrakeApplied[i*4]);
}
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireOutputData outputData[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, &isAccelApplied[i*4], &isBrakeApplied[i*4], &steerAngles[i*4], &activeWheelStates[4*i],
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimDatas[i], &wheels4DynDatas[i], &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i],
};
processSuspTireWheels(i*4, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData[i], vehTelemetryDataContext);
updateLowSpeedTimers(outputData[i].newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData[i].newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData[i].jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(&steerAngles[i*4], const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData[i].cachedHitCounts, outputData[i].cachedHitPlanes, outputData[i].cachedHitDistances, outputData[i].cachedFrictionMultipliers, outputData[i].cachedHitQueryTypes, &wheels4DynDatas[i]);
}
chassisForce+=outputData[i].chassisForce;
chassisTorque+=outputData[i].chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData[i].vehConstraintData;
}
storeSuspWheelTireResults(outputData[i], inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData[i], &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
}
//Copy the tire torques to a single array.
PxF32 tireTorques[PX_MAX_NB_WHEELS];
for(PxU32 i=0;i<numWheels4;i++)
{
tireTorques[4*i+0]=outputData[i].tireTorques[0];
tireTorques[4*i+1]=outputData[i].tireTorques[1];
tireTorques[4*i+2]=outputData[i].tireTorques[2];
tireTorques[4*i+3]=outputData[i].tireTorques[3];
}
PxF32 engineDriveTorque;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
const PxF32 engineOmega=driveDynData.getEngineRotationSpeed();
engineDriveTorque=computeEngineDriveTorque(engineData,engineOmega,accel);
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
updateGraphDataEngineDriveTorque(engineDriveTorque, vehTelemetryDataContext->engineGraphData);
#endif
}
PxF32 engineDampingRate;
{
const PxVehicleEngineData& engineData=driveSimData.getEngineData();
engineDampingRate=computeEngineDampingRate(engineData,currentGear,accel);
}
//Update the wheel and engine speeds - 5x5 matrix coupling engine and wheels.
ImplicitSolverInput implicitSolverInput =
{
subTimestep,
0.0f, 0.0f,
K, G,
PxVehicleClutchAccuracyMode::eBEST_POSSIBLE, 0,
engineDriveTorque, engineDampingRate,
diffTorqueRatios, aveWheelSpeedContributions,
brakeTorques, isBrakeApplied, tireTorques,
numWheels4, numActiveWheels,
wheels4SimDatas, &driveSimData
};
ImplicitSolverOutput implicitSolverOutput =
{
wheels4DynDatas, &driveDynData
};
solveTankInternaDynamicsEnginePlusDrivenWheels(implicitSolverInput, activeWheelStates, wheelGearings, &implicitSolverOutput);
//Integrate wheel rotation angle (theta += omega*dt)
for(PxU32 i=0;i<numWheels4;i++)
{
integrateWheelRotationAngles
(subTimestep,
K,G,engineDriveTorque,
outputData[i].jounces,diffTorqueRatios,outputData[i].forwardSpeeds,isBrakeApplied,
driveSimData,wheels4SimDatas[i],
driveDynData,wheels4DynDatas[i]);
}
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehDriveTank->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehDriveTank};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
}
void PxVehicleUpdate::updateNoDrive
(const PxF32 timestep,
const PxVec3& gravity, const PxF32 gravityMagnitude, const PxF32 recipGravityMagnitude,
const PxVehicleDrivableSurfaceToTireFrictionPairs& drivableSurfaceToTireFrictionPairs,
PxVehicleNoDrive* vehNoDrive, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleConcurrentUpdateData* vehConcurrentUpdates,
VehicleTelemetryDataContext* vehTelemetryDataContext, const PxVehicleContext& context)
{
#if !PX_DEBUG_VEHICLE_ON
PX_UNUSED(vehTelemetryDataContext);
#endif
PX_SIMD_GUARD; // denorm exception in transformInertiaTensor() on osx
PX_CHECK_AND_RETURN(
!(vehNoDrive->getRigidDynamicActor()->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC),
"Attempting to update a PxVehicleNoDrive with a kinematic actor - this isn't allowed");
PX_CHECK_AND_RETURN(
NULL==vehWheelQueryResults || vehWheelQueryResults->nbWheelQueryResults >= vehNoDrive->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
#if PX_CHECKED
for(PxU32 i=0;i<vehNoDrive->mWheelsSimData.getNbWheels();i++)
{
PX_CHECK_AND_RETURN(
!vehNoDrive->mWheelsSimData.getIsWheelDisabled(i) || 0==vehNoDrive->getDriveTorque(i),
"Disabled wheels should have zero drive torque applied to them.");
}
#endif
#if PX_DEBUG_VEHICLE_ON
if (vehTelemetryDataContext)
{
for(PxU32 i=0;i<vehNoDrive->mWheelsSimData.mNbWheels4;i++)
{
updateGraphDataInternalWheelDynamics(4*i,vehNoDrive->mWheelsDynData.mWheels4DynData[i].mWheelSpeeds, vehTelemetryDataContext->wheelGraphData);
}
}
#endif
//Unpack the tank simulation and instanced dynamics components.
const PxVehicleWheels4SimData* wheels4SimDatas=vehNoDrive->mWheelsSimData.mWheels4SimData;
const PxVehicleTireLoadFilterData& tireLoadFilterData=vehNoDrive->mWheelsSimData.mNormalisedLoadFilter;
PxVehicleWheels4DynData* wheels4DynDatas=vehNoDrive->mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=vehNoDrive->mWheelsSimData.mNbWheels4;
const PxU32 numActiveWheels=vehNoDrive->mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4-numActiveWheels);
PxRigidDynamic* vehActor=vehNoDrive->mActor;
//We need to store that data we are going to write to actors so we can do this at the end in one go with fewer write locks.
PxVehicleWheelConcurrentUpdateData wheelConcurrentUpdates[PX_MAX_NB_WHEELS];
PxVehicleConcurrentUpdateData vehicleConcurrentUpdates;
vehicleConcurrentUpdates.nbConcurrentWheelUpdates = numActiveWheels;
vehicleConcurrentUpdates.concurrentWheelUpdates = wheelConcurrentUpdates;
//Test if a non-zero drive torque was applied or if a non-zero steer angle was applied.
bool finiteInputApplied=false;
for(PxU32 i=0;i<numActiveWheels;i++)
{
if(vehNoDrive->getDriveTorque(i) != 0.0f)
{
finiteInputApplied=true;
break;
}
if(vehNoDrive->getSteerAngle(i)!=0.0f)
{
finiteInputApplied=true;
break;
}
}
//Wake or sleep.
{
if(vehActor->getScene() && vehActor->isSleeping()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
if(finiteInputApplied)
{
//Driving inputs so we need the actor to start moving.
vehicleConcurrentUpdates.wakeup = true;
}
else if(isOnDynamicActor(vehNoDrive->mWheelsSimData, vehNoDrive->mWheelsDynData))
{
//Driving on dynamic so we need to keep moving.
vehicleConcurrentUpdates.wakeup = true;
}
else
{
//No driving inputs and the actor is asleep.
//Set internal dynamics to sleep.
setInternalDynamicsToZero(vehNoDrive);
if(vehConcurrentUpdates) vehConcurrentUpdates->staySleeping = true;
return;
}
}
}
//In each block of 4 wheels record how many wheels are active.
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 i=1;i<numWheels4-1;i++)
{
numActiveWheelsPerBlock4[i]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Organise the shader data in blocks of 4.
PxVehicleTireForceCalculator4 tires4ForceCalculators[PX_MAX_NB_SUSPWHEELTIRE4];
for(PxU32 i=0;i<numWheels4;i++)
{
tires4ForceCalculators[i].mShaderData[0]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+0];
tires4ForceCalculators[i].mShaderData[1]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+1];
tires4ForceCalculators[i].mShaderData[2]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+2];
tires4ForceCalculators[i].mShaderData[3]=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShaderData[4*i+3];
tires4ForceCalculators[i].mShader=vehNoDrive->mWheelsDynData.mTireForceCalculators->mShader;
}
//Mark the suspension/tire constraints as dirty to force them to be updated in the sdk.
for(PxU32 i=0;i<numWheels4;i++)
{
wheels4DynDatas[i].getVehicletConstraintShader().mConstraint->markDirty();
}
//Need to store report data to pose the wheels.
PxWheelQueryResult wheelQueryResults[PX_MAX_NB_WHEELS];
//Center of mass local pose.
PxTransform carChassisCMLocalPose;
//Compute the transform of the center of mass.
PxTransform origCarChassisTransform;
PxTransform carChassisTransform;
//Inverse mass and inertia to apply the tire/suspension forces as impulses.
PxF32 inverseChassisMass;
PxVec3 inverseInertia;
//Linear and angular velocity.
PxVec3 carChassisLinVel;
PxVec3 carChassisAngVel;
{
carChassisCMLocalPose = vehActor->getCMassLocalPose();
carChassisCMLocalPose.q = PxQuat(PxIdentity);
origCarChassisTransform = vehActor->getGlobalPose().transform(carChassisCMLocalPose);
carChassisTransform = origCarChassisTransform;
const PxF32 chassisMass = vehActor->getMass();
inverseChassisMass = 1.0f/chassisMass;
inverseInertia = vehActor->getMassSpaceInvInertiaTensor();
carChassisLinVel = vehActor->getLinearVelocity();
carChassisAngVel = vehActor->getAngularVelocity();
}
//Get the local rotations of the wheel shapes with the latest steer.
//These should be very close to the poses at the most recent scene query.
PxQuat wheelLocalPoseRotations[PX_MAX_NB_WHEELS];
computeWheelLocalPoseRotations(wheels4DynDatas, wheels4SimDatas, numWheels4, context, vehNoDrive->mSteerAngles, wheelLocalPoseRotations);
PxF32 maxAccel=0;
PxF32 maxBrake=0;
for(PxU32 i=0;i<numActiveWheels;i++)
{
maxAccel = PxMax(PxAbs(vehNoDrive->mDriveTorques[i]), maxAccel);
maxBrake = PxMax(PxAbs(vehNoDrive->mBrakeTorques[i]), maxBrake);
}
const bool isIntentionToAccelerate = (maxAccel>0.0f && 0.0f==maxBrake);
//Store the susp line raycast data.
for(PxU32 i=0;i<numWheels4;i++)
{
storeRaycasts(wheels4DynDatas[i], &wheelQueryResults[4*i]);
}
//Ready to do the update.
PxVec3 carChassisLinVelOrig=carChassisLinVel;
PxVec3 carChassisAngVelOrig=carChassisAngVel;
const PxU32 numSubSteps=computeNumberOfSubsteps(vehNoDrive->mWheelsSimData,carChassisLinVel,carChassisTransform,
context.forwardAxis);
const PxF32 timeFraction=1.0f/(1.0f*numSubSteps);
const PxF32 subTimestep=timestep*timeFraction;
const PxF32 recipSubTimeStep=1.0f/subTimestep;
const PxF32 recipTimestep=1.0f/timestep;
const PxF32 minLongSlipDenominator=vehNoDrive->mWheelsSimData.mMinLongSlipDenominator;
ProcessSuspWheelTireConstData constData={timeFraction, subTimestep, recipSubTimeStep, gravity, gravityMagnitude, recipGravityMagnitude, false, minLongSlipDenominator,
vehActor, &drivableSurfaceToTireFrictionPairs, vehNoDrive->mWheelsSimData.mFlags};
for(PxU32 k=0;k<numSubSteps;k++)
{
//Set the force and torque for the current update to zero.
PxVec3 chassisForce(0,0,0);
PxVec3 chassisTorque(0,0,0);
for(PxU32 i=0;i<numWheels4;i++)
{
//Get the raw input torques.
const PxF32* PX_RESTRICT rawBrakeTorques=&vehNoDrive->mBrakeTorques[4*i];
const PxF32* PX_RESTRICT rawSteerAngles=&vehNoDrive->mSteerAngles[4*i];
const PxF32* PX_RESTRICT rawDriveTorques=&vehNoDrive->mDriveTorques[4*i];
//Work out which wheels are enabled.
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*i, vehNoDrive->mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxVehicleWheels4SimData& wheels4SimData=wheels4SimDatas[i];
PxVehicleWheels4DynData& wheels4DynData=wheels4DynDatas[i];
//Compute the brake torques.
PxF32 brakeTorques[4]={0.0f,0.0f,0.0f,0.0f};
bool isBrakeApplied[4]={false,false,false,false};
computeNoDriveBrakeTorques
(wheels4SimData.mWheels,wheels4DynData.mWheelSpeeds,rawBrakeTorques,
brakeTorques,isBrakeApplied);
//Compute the per wheel accel pedal values.
bool isAccelApplied[4]={false,false,false,false};
if(isIntentionToAccelerate)
{
computeIsAccelApplied(rawDriveTorques, isAccelApplied);
}
//Compute jounces, slips, tire forces, suspension forces etc.
ProcessSuspWheelTireInputData inputData=
{
isIntentionToAccelerate, isAccelApplied, isBrakeApplied, rawSteerAngles, activeWheelStates,
carChassisTransform, carChassisLinVel, carChassisAngVel,
&wheelLocalPoseRotations[i], &wheels4SimData, &wheels4DynData, &tires4ForceCalculators[i], &tireLoadFilterData, numActiveWheelsPerBlock4[i]
};
ProcessSuspWheelTireOutputData outputData;
processSuspTireWheels(4*i, constData, inputData, context.sideAxis,
context.pointRejectAngleThresholdCosine, context.normalRejectAngleThresholdCosine,
context.maxHitActorAcceleration,
outputData, vehTelemetryDataContext);
updateLowSpeedTimers(outputData.newLowForwardSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowForwardSpeedTimers));
updateLowSpeedTimers(outputData.newLowSideSpeedTimers, const_cast<PxF32*>(inputData.vehWheels4DynData->mTireLowSideSpeedTimers));
updateJounces(outputData.jounces, const_cast<PxF32*>(inputData.vehWheels4DynData->mJounces));
updateSteers(rawSteerAngles, const_cast<PxF32*>(inputData.vehWheels4DynData->mSteerAngles));
if((numSubSteps-1) == k)
{
updateCachedHitData(outputData.cachedHitCounts, outputData.cachedHitPlanes, outputData.cachedHitDistances, outputData.cachedFrictionMultipliers, outputData.cachedHitQueryTypes, &wheels4DynData);
}
chassisForce+=outputData.chassisForce;
chassisTorque+=outputData.chassisTorque;
if(0 == k)
{
wheels4DynDatas[i].mVehicleConstraints->mData=outputData.vehConstraintData;
}
storeSuspWheelTireResults(outputData, inputData.steerAngles, &wheelQueryResults[4*i], numActiveWheelsPerBlock4[i]);
storeHitActorForces(outputData, &vehicleConcurrentUpdates.concurrentWheelUpdates[4*i], numActiveWheelsPerBlock4[i]);
//Integrate wheel speeds.
const PxF32 wheelDampingRates[4]=
{
wheels4SimData.getWheelData(0).mDampingRate,
wheels4SimData.getWheelData(1).mDampingRate,
wheels4SimData.getWheelData(2).mDampingRate,
wheels4SimData.getWheelData(3).mDampingRate
};
integrateNoDriveWheelSpeeds(
subTimestep,
brakeTorques,isBrakeApplied,rawDriveTorques,outputData.tireTorques,wheelDampingRates,
wheels4SimData,wheels4DynData);
integrateNoDriveWheelRotationAngles(
subTimestep,
rawDriveTorques,
outputData.jounces, outputData.forwardSpeeds, isBrakeApplied,
wheels4SimData,
wheels4DynData);
}
//Apply the anti-roll suspension.
procesAntiRollSuspension(vehNoDrive->mWheelsSimData, carChassisTransform, wheelQueryResults, chassisTorque);
//Integrate the chassis velocity by applying the accumulated force and torque.
integrateBody(inverseChassisMass, inverseInertia, chassisForce, chassisTorque, subTimestep, carChassisLinVel, carChassisAngVel, carChassisTransform);
}
//Set the new chassis linear/angular velocity.
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehicleConcurrentUpdates.linearMomentumChange = carChassisLinVel;
vehicleConcurrentUpdates.angularMomentumChange = carChassisAngVel;
}
else
{
//integration steps are:
//v = v0 + a*dt (1)
//x = x0 + v*dt (2)
//Sub (2) into (1.
//x = x0 + v0*dt + a*dt*dt;
//Rearrange for a
//a = (x -x0 - v0*dt)/(dt*dt) = [(x-x0)/dt - v0/dt]
//Rearrange again with v = (x-x0)/dt
//a = (v - v0)/dt
vehicleConcurrentUpdates.linearMomentumChange = (carChassisLinVel-carChassisLinVelOrig)*recipTimestep;
vehicleConcurrentUpdates.angularMomentumChange = (carChassisAngVel-carChassisAngVelOrig)*recipTimestep;
}
//Pose the wheels from jounces, rotations angles, and steer angles.
PxTransform localPoses0[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[0],wheels4DynDatas[0],&wheelQueryResults[4*0],numActiveWheelsPerBlock4[0],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses0);
wheelQueryResults[4*0 + 0].localPose = localPoses0[0];
wheelQueryResults[4*0 + 1].localPose = localPoses0[1];
wheelQueryResults[4*0 + 2].localPose = localPoses0[2];
wheelQueryResults[4*0 + 3].localPose = localPoses0[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 0].localPose = localPoses0[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 1].localPose = localPoses0[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 2].localPose = localPoses0[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*0 + 3].localPose = localPoses0[3];
for(PxU32 i=1;i<numWheels4;i++)
{
PxTransform localPoses[4] = {PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity), PxTransform(PxIdentity)};
computeWheelLocalPoses(wheels4SimDatas[i],wheels4DynDatas[i],&wheelQueryResults[4*i],numActiveWheelsPerBlock4[i],carChassisCMLocalPose,
context.upAxis, context.sideAxis, context.forwardAxis, localPoses);
wheelQueryResults[4*i + 0].localPose = localPoses[0];
wheelQueryResults[4*i + 1].localPose = localPoses[1];
wheelQueryResults[4*i + 2].localPose = localPoses[2];
wheelQueryResults[4*i + 3].localPose = localPoses[3];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 0].localPose = localPoses[0];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 1].localPose = localPoses[1];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 2].localPose = localPoses[2];
vehicleConcurrentUpdates.concurrentWheelUpdates[4*i + 3].localPose = localPoses[3];
}
if(vehWheelQueryResults && vehWheelQueryResults->wheelQueryResults)
{
PxMemCopy(vehWheelQueryResults->wheelQueryResults, wheelQueryResults, sizeof(PxWheelQueryResult)*numActiveWheels);
}
if(vehConcurrentUpdates)
{
//Copy across to input data structure so that writes can be applied later.
PxMemCopy(vehConcurrentUpdates->concurrentWheelUpdates, vehicleConcurrentUpdates.concurrentWheelUpdates, sizeof(PxVehicleWheelConcurrentUpdateData)*numActiveWheels);
vehConcurrentUpdates->linearMomentumChange = vehicleConcurrentUpdates.linearMomentumChange;
vehConcurrentUpdates->angularMomentumChange = vehicleConcurrentUpdates.angularMomentumChange;
vehConcurrentUpdates->staySleeping = vehicleConcurrentUpdates.staySleeping;
vehConcurrentUpdates->wakeup = vehicleConcurrentUpdates.wakeup;
}
else
{
//Apply the writes immediately.
PxVehicleWheels* vehWheels[1]={vehNoDrive};
PxVehicleUpdate::updatePost(&vehicleConcurrentUpdates, 1, vehWheels, context);
}
}
void PxVehicleUpdate::shiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles)
{
for(PxU32 i=0; i < numVehicles; i++)
{
//Get the current car.
PxVehicleWheels& veh = *vehicles[i];
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=veh.mWheelsSimData.mNbWheels4;
//Blocks of 4 wheels.
for(PxU32 j=0; j < numWheels4; j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
if (wheels4DynData[j].mRaycastResults) // this is set when a query has been scheduled
{
PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineRaycast&>(wheels4DynData[j].mQueryOrCachedHitResults);
for(PxU32 k=0; k < 4; k++)
{
if (activeWheelStates[k])
{
raycast.mStarts[k] -= shift;
if (wheels4DynData[j].mRaycastResults[k].hasBlock)
const_cast<PxVec3&>(wheels4DynData[j].mRaycastResults[k].block.position) -= shift;
}
}
}
else if(wheels4DynData[i].mSweepResults)
{
PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineSweep&>(wheels4DynData[j].mQueryOrCachedHitResults);
for(PxU32 k=0; k < 4; k++)
{
if (activeWheelStates[k])
{
sweep.mStartPose[k].p -= shift;
if (wheels4DynData[j].mSweepResults[k].hasBlock)
const_cast<PxVec3&>(wheels4DynData[j].mSweepResults[k].block.position) -= shift;
}
}
}
}
}
}
}//namespace physx
#if PX_DEBUG_VEHICLE_ON
/////////////////////////////////////////////////////////////////////////////////
//Update a single vehicle of any type and record the associated telemetry data.
/////////////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void PxVehicleUpdate::updateSingleVehicleAndStoreTelemetryData
(const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* vehWheels, PxVehicleWheelQueryResult* vehWheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehConcurrentUpdates, const PxVehicleContext& context)
{
START_TIMER(TIMER_ALL);
PX_CHECK_MSG(vehWheels->mWheelsSimData.getNbWheels()==telemetryData.getNbWheelGraphs(), "vehicle and telemetry data need to have the same number of wheels");
VehicleTelemetryDataContext vehicleTelemetryDataContext;
PxMemZero(vehicleTelemetryDataContext.wheelGraphData, sizeof(vehicleTelemetryDataContext.wheelGraphData));
PxMemZero(vehicleTelemetryDataContext.engineGraphData, sizeof(vehicleTelemetryDataContext.engineGraphData));
PxMemZero(vehicleTelemetryDataContext.suspForceAppPoints, sizeof(vehicleTelemetryDataContext.suspForceAppPoints));
PxMemZero(vehicleTelemetryDataContext.tireForceAppPoints, sizeof(vehicleTelemetryDataContext.tireForceAppPoints));
update(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, 1, &vehWheels, vehWheelQueryResults, vehConcurrentUpdates,
&vehicleTelemetryDataContext, context);
for(PxU32 i=0;i<vehWheels->mWheelsSimData.mNbActiveWheels;i++)
{
telemetryData.mWheelGraphs[i].updateTimeSlice(vehicleTelemetryDataContext.wheelGraphData[i]);
telemetryData.mSuspforceAppPoints[i]=vehicleTelemetryDataContext.suspForceAppPoints[i];
telemetryData.mTireforceAppPoints[i]=vehicleTelemetryDataContext.tireForceAppPoints[i];
}
telemetryData.mEngineGraph->updateTimeSlice(vehicleTelemetryDataContext.engineGraphData);
END_TIMER(TIMER_ALL);
#if PX_VEHICLE_PROFILE
gTimerCount++;
if(10==gTimerCount)
{
/*
printf("%f %f %f %f %f %f %f %f %f\n",
localTimers[TIMER_ADMIN]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_GRAPHS]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_COMPONENTS_UPDATE]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_WHEELS]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_INTERNAL_DYNAMICS_SOLVER]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE1]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE2]/(1.0f*localTimers[TIMER_ALL]),
localTimers[TIMER_POSTUPDATE3]/(1.0f*localTimers[TIMER_ALL]),
floatTimeIn10sOfNs);
*/
printf("%f %f %f %f %f %f \n",
getTimerFraction(TIMER_WHEELS),
getTimerFraction(TIMER_INTERNAL_DYNAMICS_SOLVER),
getTimerFraction(TIMER_POSTUPDATE2),
getTimerFraction(TIMER_POSTUPDATE3),
getTimerInMilliseconds(TIMER_ALL),
getTimerInMilliseconds(TIMER_RAYCASTS));
gTimerCount=0;
for(PxU32 i=0;i<MAX_NB_TIMERS;i++)
{
gTimers[i]=0;
}
}
#endif
}
void physx::PxVehicleUpdateSingleVehicleAndStoreTelemetryData
(const PxReal timestep, const PxVec3& gravity, const physx::PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
PxVehicleWheels* focusVehicle, PxVehicleWheelQueryResult* wheelQueryResults, PxVehicleTelemetryData& telemetryData,
PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleUpdateSingleVehicleAndStoreTelemetryData: provided PxVehicleContext is not valid");
PxVehicleUpdate::updateSingleVehicleAndStoreTelemetryData
(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, focusVehicle, wheelQueryResults, telemetryData,
vehicleConcurrentUpdates, context);
}
#endif
////////////////////////////////////////////////////////////
//Update an array of vehicles of any type
////////////////////////////////////////////////////////////
void PxVehicleUpdate::update
(const PxF32 timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* vehicleWheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
VehicleTelemetryDataContext* vehicleTelemetryDataContext, const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(gravity.magnitude()>0, "gravity vector must have non-zero length");
PX_CHECK_AND_RETURN(timestep>0, "timestep must be greater than zero");
PX_CHECK_AND_RETURN(gThresholdForwardSpeedForWheelAngleIntegration>0, "PxInitVehicleSDK needs to be called before ever calling PxVehicleUpdates or PxVehicleUpdateSingleVehicleAndStoreTelemetryData");
#if PX_CHECKED
for(PxU32 i=0;i<numVehicles;i++)
{
const PxVehicleWheels* const vehWheels=vehicles[i];
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbWheels4;j++)
{
PX_CHECK_MSG(
vehWheels->mWheelsDynData.mWheels4DynData[j].mRaycastResults ||
vehWheels->mWheelsDynData.mWheels4DynData[j].mSweepResults ||
vehWheels->mWheelsDynData.mWheels4DynData[0].mHasCachedRaycastHitPlane ||
(vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+0) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+1) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+2) &&
vehWheels->mWheelsSimData.getIsWheelDisabled(4*j+3)),
"Need to call PxVehicleSuspensionRaycasts or PxVehicleSuspensionSweeps at least once before trying to update");
}
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_MSG(vehWheels->mWheelsDynData.mTireForceCalculators->mShaderData[j], "Need to set non-null tire force shader data ptr");
}
PX_CHECK_MSG(vehWheels->mWheelsDynData.mTireForceCalculators->mShader, "Need to set non-null tire force shader function");
PX_CHECK_AND_RETURN(NULL==vehicleWheelQueryResults || vehicleWheelQueryResults[i].nbWheelQueryResults >= vehicles[i]->mWheelsSimData.getNbWheels(),
"nbWheelQueryResults must always be greater than or equal to number of wheels in corresponding vehicle");
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || -1==vehWheels->mWheelsSimData.getWheelShapeMapping(j),
"Disabled wheels must not be associated with a PxShape: use setWheelShapeMapping to remove the association");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || 0==vehWheels->mWheelsDynData.getWheelRotationSpeed(j),
"Disabled wheels must have zero rotation speed: use setWheelRotationSpeed to set the wheel to zero rotation speed");
}
PX_CHECK_AND_RETURN(!vehicleConcurrentUpdates || (vehicleConcurrentUpdates[i].concurrentWheelUpdates && vehicleConcurrentUpdates[i].nbConcurrentWheelUpdates >= vehicles[i]->mWheelsSimData.getNbWheels()),
"vehicleConcurrentUpdates is illegally configured with either null pointers or with insufficient memory for successful concurrent updates.");
for(PxU32 j=0; j < vehWheels->mWheelsSimData.mNbActiveAntiRollBars; j++)
{
const PxVehicleAntiRollBarData antiRoll = vehWheels->mWheelsSimData.getAntiRollBarData(j);
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(antiRoll.mWheel0), "Wheel0 of antiroll bar is disabled. This is not supported.");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(antiRoll.mWheel1), "Wheel1 of antiroll bar is disabled. This is not supported.");
}
}
#endif
const PxF32 gravityMagnitude=gravity.magnitude();
const PxF32 recipGravityMagnitude=1.0f/gravityMagnitude;
for(PxU32 i=0;i<numVehicles;i++)
{
PxVehicleWheels* vehWheels=vehicles[i];
PxVehicleWheelQueryResult* vehWheelQueryResults = vehicleWheelQueryResults ? &vehicleWheelQueryResults[i] : NULL;
PxVehicleConcurrentUpdateData* vehConcurrentUpdateData = vehicleConcurrentUpdates ? &vehicleConcurrentUpdates[i] : NULL;
switch(vehWheels->mType)
{
case PxVehicleTypes::eDRIVE4W:
{
PxVehicleDrive4W* vehDrive4W=static_cast<PxVehicleDrive4W*>(vehWheels);
PxVehicleUpdate::updateDrive4W(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDrive4W, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eDRIVENW:
{
PxVehicleDriveNW* vehDriveNW=static_cast<PxVehicleDriveNW*>(vehWheels);
PxVehicleUpdate::updateDriveNW(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveNW, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eDRIVETANK:
{
PxVehicleDriveTank* vehDriveTank=static_cast<PxVehicleDriveTank*>(vehWheels);
PxVehicleUpdate::updateTank(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveTank, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
case PxVehicleTypes::eNODRIVE:
{
PxVehicleNoDrive* vehDriveNoDrive=static_cast<PxVehicleNoDrive*>(vehWheels);
PxVehicleUpdate::updateNoDrive(
timestep,
gravity,gravityMagnitude,recipGravityMagnitude,
vehicleDrivableSurfaceToTireFrictionPairs,
vehDriveNoDrive, vehWheelQueryResults, vehConcurrentUpdateData, vehicleTelemetryDataContext,
context);
}
break;
default:
PX_CHECK_MSG(false, "update - unsupported vehicle type");
break;
}
}
}
void PxVehicleUpdate::updatePost
(const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleUpdates::ePROFILE_POSTUPDATES",0);
PX_CHECK_AND_RETURN(vehicleConcurrentUpdates, "vehicleConcurrentUpdates must be non-null.");
#if PX_CHECKED
for(PxU32 i=0;i<numVehicles;i++)
{
PxVehicleWheels* vehWheels=vehicles[i];
for(PxU32 j=0;j<vehWheels->mWheelsSimData.mNbActiveWheels;j++)
{
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || -1==vehWheels->mWheelsSimData.getWheelShapeMapping(j),
"Disabled wheels must not be associated with a PxShape: use setWheelShapeMapping to remove the association");
PX_CHECK_AND_RETURN(!vehWheels->mWheelsSimData.getIsWheelDisabled(j) || 0==vehWheels->mWheelsDynData.getWheelRotationSpeed(j),
"Disabled wheels must have zero rotation speed: use setWheelRotationSpeed to set the wheel to zero rotation speed");
PX_CHECK_AND_RETURN(vehicleConcurrentUpdates[i].concurrentWheelUpdates && vehicleConcurrentUpdates[i].nbConcurrentWheelUpdates >= vehWheels->mWheelsSimData.getNbWheels(),
"vehicleConcurrentUpdates is illegally configured with either null pointers or insufficient memory for successful concurrent vehicle updates.");
}
}
#endif
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the ith vehicle and its actor.
PxVehicleWheels* vehWheels=vehicles[i];
PxRigidDynamic* vehActor = vehWheels->getRigidDynamicActor();
//Get the concurrent update data for the ith vehicle.
//This contains the data that couldn't get updated concurrently and now must be
//set sequentially.
const PxVehicleConcurrentUpdateData& vehicleConcurrentUpdate = vehicleConcurrentUpdates[i];
//Test if the actor is to remain sleeping.
//If the actor is to remain sleeping then do nothing.
if(!vehicleConcurrentUpdate.staySleeping)
{
//Wake the vehicle's actor up as required.
if(vehicleConcurrentUpdate.wakeup && vehActor->getScene()) //Support case where actor is not in a scene and constraints get solved via immediate mode
{
vehActor->wakeUp();
}
//Apply momentum changes to vehicle's actor
if(context.updateMode == PxVehicleUpdateMode::eVELOCITY_CHANGE)
{
vehActor->setLinearVelocity(vehicleConcurrentUpdate.linearMomentumChange, false);
vehActor->setAngularVelocity(vehicleConcurrentUpdate.angularMomentumChange, false);
}
else
{
vehActor->addForce(vehicleConcurrentUpdate.linearMomentumChange, PxForceMode::eACCELERATION, false);
vehActor->addTorque(vehicleConcurrentUpdate.angularMomentumChange, PxForceMode::eACCELERATION, false);
}
//In each block of 4 wheels record how many wheels are active.
const PxU32 numActiveWheels=vehWheels->mWheelsSimData.mNbActiveWheels;
const PxU32 numWheels4 = vehWheels->mWheelsSimData.getNbWheels4();
const PxU32 numActiveWheelsInLast4=4-(4*numWheels4 - numActiveWheels);
PxU32 numActiveWheelsPerBlock4[PX_MAX_NB_SUSPWHEELTIRE4]={0,0,0,0,0};
numActiveWheelsPerBlock4[0]=PxMin(numActiveWheels,PxU32(4));
for(PxU32 j=1;j<numWheels4-1;j++)
{
numActiveWheelsPerBlock4[j]=4;
}
numActiveWheelsPerBlock4[numWheels4-1]=numActiveWheelsInLast4;
PX_ASSERT(numActiveWheels == numActiveWheelsPerBlock4[0] + numActiveWheelsPerBlock4[1] + numActiveWheelsPerBlock4[2] + numActiveWheelsPerBlock4[3] + numActiveWheelsPerBlock4[4]);
//Apply the local poses to the shapes of the vehicle's actor that represent wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
PxTransform localPoses[4]=
{
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 0].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 1].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 2].localPose,
vehicleConcurrentUpdate.concurrentWheelUpdates[j*4 + 3].localPose
};
poseWheels(vehWheels->mWheelsSimData.mWheels4SimData[j],localPoses,numActiveWheelsPerBlock4[j],vehActor);
}
//Apply forces to dynamic actors hit by the wheels.
for(PxU32 j=0;j<numActiveWheels;j++)
{
PxRigidDynamic* hitActor=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActor;
if(hitActor)
{
const PxVec3& hitForce=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActorForce;
const PxVec3& hitForcePosition=vehicleConcurrentUpdate.concurrentWheelUpdates[j].hitActorForcePosition;
PxRigidBodyExt::addForceAtPos(*hitActor,hitForce,hitForcePosition);
}
}
}
}
}
void physx::PxVehicleUpdates
(const PxReal timestep, const PxVec3& gravity, const PxVehicleDrivableSurfaceToTireFrictionPairs& vehicleDrivableSurfaceToTireFrictionPairs,
const PxU32 numVehicles, PxVehicleWheels** vehicles, PxVehicleWheelQueryResult* vehicleWheelQueryResults, PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates,
const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleUpdates::ePROFILE_UPDATES",0);
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleUpdates: provided PxVehicleContext is not valid");
PxVehicleUpdate::update(timestep, gravity, vehicleDrivableSurfaceToTireFrictionPairs, numVehicles, vehicles, vehicleWheelQueryResults, vehicleConcurrentUpdates,
NULL, context);
}
void physx::PxVehiclePostUpdates
(const PxVehicleConcurrentUpdateData* vehicleConcurrentUpdates, const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxVehicleContext& context)
{
PX_CHECK_AND_RETURN(context.isValid(), "PxVehiclePostUpdates: provided PxVehicleContext is not valid");
PxVehicleUpdate::updatePost(vehicleConcurrentUpdates, numVehicles, vehicles, context);
}
void physx::PxVehicleShiftOrigin(const PxVec3& shift, const PxU32 numVehicles, PxVehicleWheels** vehicles)
{
PxVehicleUpdate::shiftOrigin(shift, numVehicles, vehicles);
}
///////////////////////////////////////////////////////////////////////////////////
//The following functions issue a single batch of suspension raycasts for an array of vehicles of any type.
//The buffer of sceneQueryResults is distributed among the vehicles in the array
//for use in the next PxVehicleUpdates call.
///////////////////////////////////////////////////////////////////////////////////
static const PxRaycastBuffer* vehicleWheels4SuspensionRaycasts
(PxBatchQueryExt* batchQuery,
const PxVehicleWheels4SimData& wheels4SimData, PxVehicleWheels4DynData& wheels4DynData,
const PxQueryFilterData* carFilterData, const bool* activeWheelStates, const PxU32 numActiveWheels,
PxRigidDynamic* vehActor)
{
const PxRaycastBuffer* buffer4 = NULL;
//Get the transform of the chassis.
PxTransform massXform = vehActor->getCMassLocalPose();
massXform.q = PxQuat(PxIdentity);
PxTransform carChassisTrnsfm = vehActor->getGlobalPose().transform(massXform);
//Add a raycast for each wheel.
for(PxU32 j=0;j<numActiveWheels;j++)
{
const PxVehicleSuspensionData& susp=wheels4SimData.getSuspensionData(j);
const PxVehicleWheelData& wheel=wheels4SimData.getWheelData(j);
const PxVec3& bodySpaceSuspTravelDir=wheels4SimData.getSuspTravelDirection(j);
PxVec3 bodySpaceWheelCentreOffset=wheels4SimData.getWheelCentreOffset(j);
PxF32 maxDroop=susp.mMaxDroop;
PxF32 maxBounce=susp.mMaxCompression;
PxF32 radius=wheel.mRadius;
PX_ASSERT(maxBounce>=0);
PX_ASSERT(maxDroop>=0);
if(!activeWheelStates[j])
{
//For disabled wheels just issue a raycast of almost zero length.
//This should be very cheap and ought to hit nothing.
bodySpaceWheelCentreOffset=PxVec3(0,0,0);
maxDroop=1e-5f*gToleranceScaleLength;
maxBounce=1e-5f*gToleranceScaleLength;
radius=1e-5f*gToleranceScaleLength;
}
PxVec3 suspLineStart;
PxVec3 suspLineDir;
computeSuspensionRaycast(carChassisTrnsfm,bodySpaceWheelCentreOffset,bodySpaceSuspTravelDir,radius,maxBounce,suspLineStart,suspLineDir);
//Total length from top of wheel at max compression to bottom of wheel at max droop.
PxF32 suspLineLength=radius + maxBounce + maxDroop + radius;
//Add another radius on for good measure.
suspLineLength+=radius;
//Store the susp line ray for later use.
PxVehicleWheels4DynData::SuspLineRaycast& raycast =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineRaycast&>(wheels4DynData.mQueryOrCachedHitResults);
raycast.mStarts[j]=suspLineStart;
raycast.mDirs[j]=suspLineDir;
raycast.mLengths[j]=suspLineLength;
//Add the raycast to the scene query.
const PxRaycastBuffer* raycastBuffer = batchQuery->raycast(
suspLineStart, suspLineDir, suspLineLength, 0,
PxHitFlag::ePOSITION|PxHitFlag::eNORMAL|PxHitFlag::eUV, carFilterData[j]);
if(0 == j)
buffer4 = raycastBuffer;
if (!raycastBuffer)
return buffer4 = NULL;
}
return buffer4;
}
void PxVehicleUpdate::suspensionRaycasts(PxBatchQueryExt* batchQuery, const PxU32 numVehicles, PxVehicleWheels** vehicles, const bool* vehiclesToRaycast, const PxQueryFlags queryFlags)
{
START_TIMER(TIMER_RAYCASTS);
//Work out the rays for the suspension line raycasts and perform all the raycasts.
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the current car.
PxVehicleWheels& veh=*vehicles[i];
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimData=veh.mWheelsSimData.mWheels4SimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=((veh.mWheelsSimData.mNbActiveWheels & ~3) >> 2);
const PxU32 numActiveWheels=veh.mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=numActiveWheels-4*numWheels4;
PxRigidDynamic* vehActor=veh.mActor;
//Set the results pointer and start the raycasts.
PX_ASSERT(numActiveWheelsInLast4<4);
//Blocks of 4 wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToRaycast || vehiclesToRaycast[i])
{
const PxQueryFilterData carFilterData[4] =
{
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(3), queryFlags)
};
const PxRaycastBuffer* buffer = vehicleWheels4SuspensionRaycasts(batchQuery, wheels4SimData[j], wheels4DynData[j], carFilterData, activeWheelStates, 4, vehActor);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionRaycasts - PxVehicleBatchUpdate raycast buffers not large enough to perform raycast.");
wheels4DynData[j].mRaycastResults = buffer;
}
}
//Remainder that don't make up a block of 4.
if(numActiveWheelsInLast4>0)
{
const PxU32 j=numWheels4;
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToRaycast || vehiclesToRaycast[i])
{
PxQueryFilterData carFilterData[4];
if (0 < numActiveWheelsInLast4)
carFilterData[0] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags);
if (1 < numActiveWheelsInLast4)
carFilterData[1] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags);
if (2 < numActiveWheelsInLast4)
carFilterData[2] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags);
const PxRaycastBuffer* buffer = vehicleWheels4SuspensionRaycasts(batchQuery,wheels4SimData[j],wheels4DynData[j],carFilterData,activeWheelStates,numActiveWheelsInLast4,vehActor);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionRaycasts - PxVehicleBatchUpdate raycast buffers not large enough to perform raycast.");
wheels4DynData[j].mRaycastResults = buffer;
}
}
}
batchQuery->execute();
END_TIMER(TIMER_RAYCASTS);
}
void physx::PxVehicleSuspensionRaycasts(PxBatchQueryExt* batchQuery, const PxU32 numVehicles, PxVehicleWheels** vehicles, const bool* vehiclesToRaycast, const PxQueryFlags queryFlags)
{
PX_PROFILE_ZONE("PxVehicleSuspensionRaycasts::ePROFILE_RAYCASTS",0);
PxVehicleUpdate::suspensionRaycasts(batchQuery, numVehicles, vehicles, vehiclesToRaycast, queryFlags);
}
static const PxSweepBuffer* vehicleWheels4SuspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxVehicleWheels4SimData& wheels4SimData, PxVehicleWheels4DynData& wheels4DynData,
const PxQueryFilterData* carFilterData, const bool* activeWheelStates, const PxU32 numActiveWheels,
const PxU16 nbHitsPerQuery,
const PxI32* wheelShapeIds,
PxRigidDynamic* vehActor,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis)
{
PX_UNUSED(sweepWidthScale);
PX_UNUSED(sweepRadiusScale);
//Get the transform of the chassis.
PxTransform carChassisTrnsfm=vehActor->getGlobalPose().transform(vehActor->getCMassLocalPose());
const PxSweepBuffer* buffer4 = NULL;
//Add a raycast for each wheel.
for(PxU32 j=0;j<numActiveWheels;j++)
{
const PxVehicleSuspensionData& susp = wheels4SimData.getSuspensionData(j);
const PxVehicleWheelData& wheel = wheels4SimData.getWheelData(j);
PxShape* wheelShape;
vehActor->getShapes(&wheelShape, 1, PxU32(wheelShapeIds[j]));
PxGeometryHolder suspGeometry;
const PxGeometry& geom = wheelShape->getGeometry();
const PxGeometryType::Enum geomType = geom.getType();
if (PxGeometryType::eCONVEXMESH == geomType)
{
PxConvexMeshGeometry convMeshGeom = static_cast<const PxConvexMeshGeometry&>(geom);
convMeshGeom.scale.scale = convMeshGeom.scale.scale.multiply(
PxVec3(
PxAbs(sideAxis.x*sweepWidthScale + (upAxis.x + forwardAxis.x)*sweepRadiusScale),
PxAbs(sideAxis.y*sweepWidthScale + (upAxis.y + forwardAxis.y)*sweepRadiusScale),
PxAbs(sideAxis.z*sweepWidthScale + (upAxis.z + forwardAxis.z)*sweepRadiusScale))
);
suspGeometry.storeAny(convMeshGeom);
}
else if (PxGeometryType::eCAPSULE == geomType)
{
PxCapsuleGeometry capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom);
capsuleGeom.halfHeight *= sweepWidthScale;
capsuleGeom.radius *= sweepRadiusScale;
suspGeometry.storeAny(capsuleGeom);
}
else
{
PX_ASSERT(PxGeometryType::eSPHERE == geomType);
PxSphereGeometry sphereGeom = static_cast<const PxSphereGeometry&>(geom);
sphereGeom.radius *= sweepRadiusScale;
suspGeometry.storeAny(sphereGeom);
}
const float jounce = wheels4DynData.mJounces[j] != PX_MAX_F32 ? wheels4DynData.mJounces[j] : 0.0f;
const float steerAngle = wheels4DynData.mSteerAngles[j];
const PxVehicleSuspensionData& suspData = wheels4SimData.getSuspensionData(j);
const PxQuat wheelLocalPoseRotation = computeWheelLocalQuat(forwardAxis, sideAxis, upAxis, jounce, suspData, 0.0f, steerAngle);
const PxVec3& bodySpaceSuspTravelDir = wheels4SimData.getSuspTravelDirection(j);
PxVec3 bodySpaceWheelCentreOffset = wheels4SimData.getWheelCentreOffset(j);
PxF32 maxDroop = susp.mMaxDroop;
PxF32 maxBounce = susp.mMaxCompression;
PxF32 radius = wheel.mRadius;
PX_ASSERT(maxBounce >= 0);
PX_ASSERT(maxDroop >= 0);
if(!activeWheelStates[j])
{
//For disabled wheels just issue a raycast of almost zero length.
//This should be very cheap and ought to hit nothing.
bodySpaceWheelCentreOffset = PxVec3(0,0,0);
maxDroop = 1e-5f*gToleranceScaleLength;
maxBounce = 1e-5f*gToleranceScaleLength;
radius = 1e-5f*gToleranceScaleLength;
}
PxTransform suspPoseStart;
PxVec3 suspLineDir;
computeSuspensionSweep(
carChassisTrnsfm,
wheelLocalPoseRotation,
bodySpaceWheelCentreOffset, bodySpaceSuspTravelDir, radius, maxBounce,
suspPoseStart, suspLineDir);
const PxF32 suspLineLength = radius + maxBounce + maxDroop + radius;
//Store the susp line ray for later use.
PxVehicleWheels4DynData::SuspLineSweep& sweep =
reinterpret_cast<PxVehicleWheels4DynData::SuspLineSweep&>(wheels4DynData.mQueryOrCachedHitResults);
sweep.mStartPose[j] = suspPoseStart;
sweep.mDirs[j] = suspLineDir;
sweep.mLengths[j] = suspLineLength;
sweep.mGometries[j] = suspGeometry;
//Add the raycast to the scene query.
const PxSweepBuffer* buffer = batchQuery->sweep(sweep.mGometries[j].any(),
suspPoseStart, suspLineDir, suspLineLength, nbHitsPerQuery,
PxHitFlag::ePOSITION|PxHitFlag::eNORMAL|PxHitFlag::eUV,
carFilterData[j], NULL, sweepInflation);
if(0 == j)
buffer4 = buffer;
if(!buffer)
buffer4 = NULL;
}
return buffer4;
}
void PxVehicleUpdate::suspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxU32 numVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToSweep,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation, const PxQueryFlags queryFlags,
const PxVec3& upAxis, const PxVec3& forwardAxis, const PxVec3& sideAxis)
{
PX_CHECK_MSG(sweepWidthScale > 0.0f, "PxVehicleUpdate::suspensionSweeps - sweepWidthScale must be greater than 0.0");
PX_CHECK_MSG(sweepRadiusScale > 0.0f, "PxVehicleUpdate::suspensionSweeps - sweepRadiusScale must be greater than 0.0");
START_TIMER(TIMER_SWEEPS);
//Work out the rays for the suspension line raycasts and perform all the raycasts.
for(PxU32 i=0;i<numVehicles;i++)
{
//Get the current car.
PxVehicleWheels& veh=*vehicles[i];
const PxVehicleWheels4SimData* PX_RESTRICT wheels4SimData=veh.mWheelsSimData.mWheels4SimData;
PxVehicleWheels4DynData* PX_RESTRICT wheels4DynData=veh.mWheelsDynData.mWheels4DynData;
const PxU32 numWheels4=((veh.mWheelsSimData.mNbActiveWheels & ~3) >> 2);
const PxU32 numActiveWheels=veh.mWheelsSimData.mNbActiveWheels;
const PxU32 numActiveWheelsInLast4=numActiveWheels-4*numWheels4;
PxRigidDynamic* vehActor=veh.mActor;
//Set the results pointer and start the raycasts.
PX_ASSERT(numActiveWheelsInLast4<4);
//Get the shape ids for the wheels.
PxI32 wheelShapeIds[PX_MAX_NB_WHEELS];
PxMemSet(wheelShapeIds, 0xff, sizeof(PxI32)*PX_MAX_NB_WHEELS);
for(PxU32 j = 0; j < veh.mWheelsSimData.getNbWheels(); j++)
{
PX_CHECK_AND_RETURN(veh.mWheelsSimData.getWheelShapeMapping(j) != -1, "PxVehicleUpdate::suspensionSweeps - trying to sweep a shape that doesn't exist.");
wheelShapeIds[j] = veh.mWheelsSimData.getWheelShapeMapping(j);
}
//Blocks of 4 wheels.
for(PxU32 j=0;j<numWheels4;j++)
{
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxI32* wheelShapeIds4 = wheelShapeIds + 4*j;
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if (!vehiclesToSweep || vehiclesToSweep[i])
{
const PxQueryFilterData carFilterData[4] =
{
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags),
PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(3), queryFlags)
};
const PxSweepBuffer* buffer = vehicleWheels4SuspensionSweeps(
batchQuery,
wheels4SimData[j], wheels4DynData[j],
carFilterData, activeWheelStates, 4,
nbHitsPerQuery,
wheelShapeIds4,
vehActor,
sweepWidthScale, sweepRadiusScale, sweepInflation,
upAxis, forwardAxis, sideAxis);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionSweeps - batched sweep result array not large enough to perform sweep.");
wheels4DynData[j].mSweepResults = buffer;
}
}
//Remainder that don't make up a block of 4.
if(numActiveWheelsInLast4>0)
{
const PxU32 j=numWheels4;
bool activeWheelStates[4]={false,false,false,false};
computeWheelActiveStates(4*j, veh.mWheelsSimData.mActiveWheelsBitmapBuffer, activeWheelStates);
const PxI32* wheelShapeIds4 = wheelShapeIds + 4*j;
wheels4DynData[j].mRaycastResults=NULL;
wheels4DynData[j].mSweepResults=NULL;
if(!vehiclesToSweep || vehiclesToSweep[i])
{
PxQueryFilterData carFilterData[4];
if(0<numActiveWheelsInLast4)
carFilterData[0] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(0), queryFlags);
if(1<numActiveWheelsInLast4)
carFilterData[1] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(1), queryFlags);
if(2<numActiveWheelsInLast4)
carFilterData[2] = PxQueryFilterData(wheels4SimData[j].getSceneQueryFilterData(2), queryFlags);
const PxSweepBuffer* buffer = vehicleWheels4SuspensionSweeps(
batchQuery,
wheels4SimData[j], wheels4DynData[j],
carFilterData, activeWheelStates, numActiveWheelsInLast4,
nbHitsPerQuery,
wheelShapeIds4,
vehActor,
sweepWidthScale, sweepRadiusScale, sweepInflation,
upAxis, forwardAxis, sideAxis);
PX_CHECK_MSG(buffer, "PxVehicleUpdate::suspensionSweeps - batched sweep result array not large enough to perform sweep.");
wheels4DynData[j].mSweepResults = buffer;
}
}
}
batchQuery->execute();
END_TIMER(TIMER_SWEEPS);
}
namespace physx
{
void PxVehicleSuspensionSweeps
(PxBatchQueryExt* batchQuery,
const PxU32 nbVehicles, PxVehicleWheels** vehicles,
const PxU16 nbHitsPerQuery,
const bool* vehiclesToSweep,
const PxF32 sweepWidthScale, const PxF32 sweepRadiusScale, const PxF32 sweepInflation,
const PxQueryFlags queryFlags, const PxVehicleContext& context)
{
PX_PROFILE_ZONE("PxVehicleSuspensionSweeps::ePROFILE_SWEEPS",0);
PX_CHECK_AND_RETURN(context.isValid(), "PxVehicleSuspensionSweeps: provided PxVehicleContext is not valid");
PxVehicleUpdate::suspensionSweeps(batchQuery, nbVehicles, vehicles, nbHitsPerQuery, vehiclesToSweep,
sweepWidthScale, sweepRadiusScale, sweepInflation, queryFlags, context.upAxis, context.forwardAxis, context.sideAxis);
}
}
| 318,845 | C++ | 41.450539 | 227 | 0.757525 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle/src/PxVehicleSerialization.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxBase.h"
#include "common/PxCollection.h"
#include "extensions/PxRepXSimpleType.h"
#include "PxVehicleMetaDataObjects.h"
#include "PxVehicleSerialization.h"
#include "PxVehicleSuspWheelTire4.h"
#include "PxVehicleSuspLimitConstraintShader.h"
#include "SnRepXSerializerImpl.h"
#include "foundation/PxFPU.h"
namespace physx
{
using namespace Sn;
template<typename TVehicleType>
inline void* createVehicle( PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& driveDataNW,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PX_UNUSED(physics);
PX_UNUSED(vehActor);
PX_UNUSED(wheelsData);
PX_UNUSED(driveData);
PX_UNUSED(driveDataNW);
PX_UNUSED(numWheels);
PX_UNUSED(numNonDrivenWheels);
return NULL;
}
template<>
inline void* createVehicle<PxVehicleDrive4W>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDrive4W* vehDrive4W = PxVehicleDrive4W::allocate(numWheels);
vehDrive4W->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveData, numNonDrivenWheels);
return vehDrive4W;
}
template<>
inline void* createVehicle<PxVehicleDriveTank>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& driveData, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDriveTank* tank = PxVehicleDriveTank::allocate(numWheels);
tank->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveData, numWheels - numNonDrivenWheels);
return tank;
}
template<>
inline void* createVehicle<PxVehicleDriveNW>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& /*driveData*/, const PxVehicleDriveSimDataNW& driveDataNW,
const PxU32 numWheels, const PxU32 numNonDrivenWheels)
{
PxVehicleDriveNW* vehDriveNW = PxVehicleDriveNW::allocate(numWheels);
vehDriveNW->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData, driveDataNW, numWheels - numNonDrivenWheels);
return vehDriveNW;
}
template<>
inline void* createVehicle<PxVehicleNoDrive>(PxPhysics& physics, PxRigidDynamic* vehActor,
const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimData4W& /*driveData*/, const PxVehicleDriveSimDataNW& /*driveDataNW*/,
const PxU32 numWheels, const PxU32 /*numNonDrivenWheels*/)
{
PxVehicleNoDrive* vehNoDrive = PxVehicleNoDrive::allocate(numWheels);
vehNoDrive->setup(&physics, vehActor->is<PxRigidDynamic>(), wheelsData);
return vehNoDrive;
}
template<typename TVehicleType>
PxRepXObject PxVehicleRepXSerializer<TVehicleType>::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection )
{
PxRigidActor* vehActor = NULL;
readReference<PxRigidActor>( inReader, *inCollection, "PxRigidDynamicRef", vehActor );
if ( vehActor == NULL )
return PxRepXObject();
PxU32 numWheels = 0;
readProperty( inReader, "NumWheels", numWheels );
if( numWheels == 0)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::createCollectionFromXml: PxVehicleRepXSerializer: Xml field NumWheels is zero!");
return PxRepXObject();
}
PxU32 numNonDrivenWheels = 0;
readProperty( inReader, "NumNonDrivenWheels", numNonDrivenWheels );
//change to numwheel
PxVehicleWheelsSimData* wheelsSimData=PxVehicleWheelsSimData::allocate(numWheels);
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MWheelsSimData" ) )
{
readAllProperties( inArgs, inReader, wheelsSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
PxVehicleDriveSimData4W driveSimData;
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MDriveSimData" ) )
{
readAllProperties( inArgs, inReader, &driveSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
PxVehicleDriveSimDataNW nmSimData;
{
inReader.pushCurrentContext();
if ( inReader.gotoChild( "MDriveSimDataNW" ) )
{
readAllProperties( inArgs, inReader, &driveSimData, inAllocator, *inCollection );
}
inReader.popCurrentContext();
}
TVehicleType* drive = static_cast<TVehicleType*>(createVehicle<TVehicleType>(inArgs.physics, vehActor->is<PxRigidDynamic>(), *wheelsSimData, driveSimData, nmSimData, numWheels, numNonDrivenWheels));
readAllProperties( inArgs, inReader, drive, inAllocator, *inCollection );
PxVehicleWheels4DynData* wheel4DynData = drive->mWheelsDynData.getWheel4DynData();
PX_ASSERT( wheel4DynData );
for(PxU32 i=0;i<wheelsSimData->getNbWheels4();i++)
{
PxConstraint* constraint = wheel4DynData[i].getVehicletConstraintShader().getPxConstraint();
if( constraint )
inCollection->add(*constraint);
}
if( wheelsSimData )
wheelsSimData->free();
return PxCreateRepXObject(drive);
}
template<typename TVehicleType>
void PxVehicleRepXSerializer<TVehicleType>::objectToFileImpl( const TVehicleType* drive, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/ )
{
PX_SIMD_GUARD; // denorm exception triggered in PxVehicleGearsDataGeneratedInfo::visitInstanceProperties on osx
writeReference( inWriter, *inCollection, "PxRigidDynamicRef", drive->getRigidDynamicActor() );
writeProperty( inWriter, *inCollection, inTempBuffer, "NumWheels", drive->mWheelsSimData.getNbWheels() );
writeProperty( inWriter, *inCollection, inTempBuffer, "NumNonDrivenWheels", drive->getNbNonDrivenWheels());
writeAllProperties( drive, inWriter, inTempBuffer, *inCollection );
}
PxVehicleNoDrive::PxVehicleNoDrive()
: PxVehicleWheels(PxVehicleConcreteType::eVehicleNoDrive, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDrive4W::PxVehicleDrive4W()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDrive4W, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDriveNW::PxVehicleDriveNW()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDriveNW, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
{}
PxVehicleDriveTank::PxVehicleDriveTank()
: PxVehicleDrive(PxVehicleConcreteType::eVehicleDriveTank, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE)
, mDriveModel(PxVehicleDriveTankControlModel::eSTANDARD)
{}
// explicit template instantiations
template struct PxVehicleRepXSerializer<PxVehicleDrive4W>;
template struct PxVehicleRepXSerializer<PxVehicleDriveTank>;
template struct PxVehicleRepXSerializer<PxVehicleDriveNW>;
template struct PxVehicleRepXSerializer<PxVehicleNoDrive>;
}
| 8,733 | C++ | 41.813725 | 204 | 0.770068 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.