file_path
stringlengths 21
202
| content
stringlengths 13
1.02M
| size
int64 13
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 5.43
98.5
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmTransformUtils.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 CM_TRANSFORM_UTILS_H
#define CM_TRANSFORM_UTILS_H
#include "foundation/PxVecMath.h"
namespace
{
using namespace physx::aos;
// V3PrepareCross would help here, but it's not on all platforms yet...
PX_FORCE_INLINE void transformFast(const FloatVArg wa, const Vec3VArg va, const Vec3VArg pa,
const FloatVArg wb, const Vec3VArg vb, const Vec3VArg pb,
FloatV& wo, Vec3V& vo, Vec3V& po)
{
wo = FSub(FMul(wa, wb), V3Dot(va, vb));
vo = V3ScaleAdd(va, wb, V3ScaleAdd(vb, wa, V3Cross(va, vb)));
const Vec3V t1 = V3Scale(pb, FScaleAdd(wa, wa, FLoad(-0.5f)));
const Vec3V t2 = V3ScaleAdd(V3Cross(va, pb), wa, t1);
const Vec3V t3 = V3ScaleAdd(va, V3Dot(va, pb), t2);
po = V3ScaleAdd(t3, FLoad(2.f), pa);
}
PX_FORCE_INLINE void transformInvFast(const FloatVArg wa, const Vec3VArg va, const Vec3VArg pa,
const FloatVArg wb, const Vec3VArg vb, const Vec3VArg pb,
FloatV& wo, Vec3V& vo, Vec3V& po)
{
wo = FScaleAdd(wa, wb, V3Dot(va, vb));
vo = V3NegScaleSub(va, wb, V3ScaleAdd(vb, wa, V3Cross(vb, va)));
const Vec3V pt = V3Sub(pb, pa);
const Vec3V t1 = V3Scale(pt, FScaleAdd(wa, wa, FLoad(-0.5f)));
const Vec3V t2 = V3ScaleAdd(V3Cross(pt, va), wa, t1);
const Vec3V t3 = V3ScaleAdd(va, V3Dot(va, pt), t2);
po = V3Add(t3,t3);
}
}
namespace physx
{
namespace Cm
{
// PT: actor2World * shape2Actor
PX_FORCE_INLINE void getStaticGlobalPoseAligned(const PxTransform& actor2World, const PxTransform& shape2Actor, PxTransform& outTransform)
{
using namespace aos;
PX_ASSERT((size_t(&actor2World)&15) == 0);
PX_ASSERT((size_t(&shape2Actor)&15) == 0);
PX_ASSERT((size_t(&outTransform)&15) == 0);
const Vec3V actor2WorldPos = V3LoadA(actor2World.p);
const QuatV actor2WorldRot = QuatVLoadA(&actor2World.q.x);
const Vec3V shape2ActorPos = V3LoadA(shape2Actor.p);
const QuatV shape2ActorRot = QuatVLoadA(&shape2Actor.q.x);
Vec3V v,p;
FloatV w;
transformFast(V4GetW(actor2WorldRot), Vec3V_From_Vec4V(actor2WorldRot), actor2WorldPos,
V4GetW(shape2ActorRot), Vec3V_From_Vec4V(shape2ActorRot), shape2ActorPos,
w, v, p);
V3StoreA(p, outTransform.p);
V4StoreA(V4SetW(v,w), &outTransform.q.x);
}
// PT: body2World * body2Actor.getInverse() * shape2Actor
PX_FORCE_INLINE void getDynamicGlobalPoseAligned(const PxTransform& body2World, const PxTransform& shape2Actor, const PxTransform& body2Actor, PxTransform& outTransform)
{
PX_ASSERT((size_t(&body2World)&15) == 0);
PX_ASSERT((size_t(&shape2Actor)&15) == 0);
PX_ASSERT((size_t(&body2Actor)&15) == 0);
PX_ASSERT((size_t(&outTransform)&15) == 0);
using namespace aos;
const Vec3V shape2ActorPos = V3LoadA(shape2Actor.p);
const QuatV shape2ActorRot = QuatVLoadA(&shape2Actor.q.x);
const Vec3V body2ActorPos = V3LoadA(body2Actor.p);
const QuatV body2ActorRot = QuatVLoadA(&body2Actor.q.x);
const Vec3V body2WorldPos = V3LoadA(body2World.p);
const QuatV body2WorldRot = QuatVLoadA(&body2World.q.x);
Vec3V v1, p1, v2, p2;
FloatV w1, w2;
transformInvFast(V4GetW(body2ActorRot), Vec3V_From_Vec4V(body2ActorRot), body2ActorPos,
V4GetW(shape2ActorRot), Vec3V_From_Vec4V(shape2ActorRot), shape2ActorPos,
w1, v1, p1);
transformFast(V4GetW(body2WorldRot), Vec3V_From_Vec4V(body2WorldRot), body2WorldPos,
w1, v1, p1,
w2, v2, p2);
V3StoreA(p2, outTransform.p);
V4StoreA(V4SetW(v2, w2), &outTransform.q.x);
}
}
}
#endif
| 5,094 | C | 35.392857 | 169 | 0.726934 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmPool.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 CM_POOL_H
#define CM_POOL_H
#include "foundation/PxSort.h"
#include "foundation/PxMutex.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxBitMap.h"
namespace physx
{
namespace Cm
{
/*!
Allocator for pools of data structures
Also decodes indices (which can be computed from handles) into objects. To make this
faster, the EltsPerSlab must be a power of two
*/
template <class T, class ArgumentType>
class PoolList : public PxAllocatorTraits<T>::Type
{
typedef typename PxAllocatorTraits<T>::Type Alloc;
PX_NOCOPY(PoolList)
public:
PX_INLINE PoolList(const Alloc& alloc, ArgumentType* argument, PxU32 eltsPerSlab)
: Alloc(alloc),
mEltsPerSlab(eltsPerSlab),
mSlabCount(0),
mFreeList(0),
mFreeCount(0),
mSlabs(NULL),
mArgument(argument)
{
PX_ASSERT(mEltsPerSlab>0);
PX_ASSERT((mEltsPerSlab & (mEltsPerSlab-1)) == 0);
mLog2EltsPerSlab = 0;
for(mLog2EltsPerSlab=0; mEltsPerSlab!=PxU32(1<<mLog2EltsPerSlab); mLog2EltsPerSlab++)
;
}
PX_INLINE ~PoolList()
{
destroy();
}
PX_INLINE void destroy()
{
// Run all destructors
for(PxU32 i=0;i<mSlabCount;i++)
{
PX_ASSERT(mSlabs);
T* slab = mSlabs[i];
for(PxU32 j=0;j<mEltsPerSlab;j++)
{
slab[j].~T();
}
}
//Deallocate
for(PxU32 i=0;i<mSlabCount;i++)
{
Alloc::deallocate(mSlabs[i]);
mSlabs[i] = NULL;
}
mSlabCount = 0;
if(mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = NULL;
if(mSlabs)
{
Alloc::deallocate(mSlabs);
mSlabs = NULL;
}
}
PxU32 preallocate(const PxU32 nbRequired, T** elements)
{
//(1) Allocate and pull out an array of X elements
PxU32 nbToAllocate = nbRequired > mFreeCount ? nbRequired - mFreeCount : 0;
PxU32 nbElements = nbRequired - nbToAllocate;
PxMemCopy(elements, mFreeList + (mFreeCount - nbElements), sizeof(T*) * nbElements);
//PxU32 originalFreeCount = mFreeCount;
mFreeCount -= nbElements;
if (nbToAllocate)
{
PX_ASSERT(mFreeCount == 0);
PxU32 nbSlabs = (nbToAllocate + mEltsPerSlab - 1) / mEltsPerSlab; //The number of slabs we need to allocate...
//allocate our slabs...
PxU32 freeCount = mFreeCount;
for (PxU32 i = 0; i < nbSlabs; ++i)
{
//KS - would be great to allocate this using a single allocation but it will make releasing slabs fail later :(
T * mAddr = reinterpret_cast<T*>(Alloc::allocate(mEltsPerSlab * sizeof(T), PX_FL));
if (!mAddr)
return nbElements; //Allocation failed so only return the set of elements we could allocate from the free list
PxU32 newSlabCount = mSlabCount+1;
// Make sure the usage bitmap is up-to-size
if (mUseBitmap.size() < newSlabCount*mEltsPerSlab)
{
mUseBitmap.resize(2 * newSlabCount*mEltsPerSlab); //set last element as not used
if (mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = reinterpret_cast<T**>(Alloc::allocate(2 * newSlabCount * mEltsPerSlab * sizeof(T*), PX_FL));
T** slabs = reinterpret_cast<T**>(Alloc::allocate(2* newSlabCount *sizeof(T*), PX_FL));
if (mSlabs)
{
PxMemCopy(slabs, mSlabs, sizeof(T*)*mSlabCount);
Alloc::deallocate(mSlabs);
}
mSlabs = slabs;
}
mSlabs[mSlabCount++] = mAddr;
PxU32 baseIndex = (mSlabCount-1) * mEltsPerSlab;
//Now add all these to the mFreeList and elements...
PxI32 idx = PxI32(mEltsPerSlab - 1);
for (; idx >= PxI32(nbToAllocate); --idx)
{
mFreeList[freeCount++] = PX_PLACEMENT_NEW(mAddr + idx, T(mArgument, baseIndex + idx));
}
PxU32 origElements = nbElements;
T** writeIdx = elements + nbElements;
for (; idx >= 0; --idx)
{
writeIdx[idx] = PX_PLACEMENT_NEW(mAddr + idx, T(mArgument, baseIndex + idx));
nbElements++;
}
nbToAllocate -= (nbElements - origElements);
}
mFreeCount = freeCount;
}
PX_ASSERT(nbElements == nbRequired);
for (PxU32 a = 0; a < nbElements; ++a)
{
mUseBitmap.set(elements[a]->getIndex());
}
return nbRequired;
}
// TODO: would be nice to add templated construct/destroy methods like ObjectPool
PX_INLINE T* get()
{
if(mFreeCount == 0 && !extend())
return 0;
T* element = mFreeList[--mFreeCount];
mUseBitmap.set(element->getIndex());
return element;
}
PX_INLINE void put(T* element)
{
PxU32 i = element->getIndex();
mUseBitmap.reset(i);
mFreeList[mFreeCount++] = element;
}
/*
WARNING: Unlike findByIndexFast below, this method is NOT safe to use if another thread
is concurrently updating the pool (e.g. through put/get/extend/getIterator), since the
safety boundedTest uses mSlabCount and mUseBitmap.
*/
PX_FORCE_INLINE T* findByIndex(PxU32 index) const
{
if(index>=mSlabCount*mEltsPerSlab || !(mUseBitmap.boundedTest(index)))
return 0;
return mSlabs[index>>mLog2EltsPerSlab] + (index&(mEltsPerSlab-1));
}
/*
This call is safe to do while other threads update the pool.
*/
PX_FORCE_INLINE T* findByIndexFast(PxU32 index) const
{
return mSlabs[index>>mLog2EltsPerSlab] + (index&(mEltsPerSlab-1));
}
bool extend()
{
T * mAddr = reinterpret_cast<T*>(Alloc::allocate(mEltsPerSlab * sizeof(T), PX_FL));
if(!mAddr)
return false;
PxU32 newSlabCount = mSlabCount+1;
// Make sure the usage bitmap is up-to-size
if(mUseBitmap.size() < newSlabCount*mEltsPerSlab)
{
mUseBitmap.resize(2* newSlabCount*mEltsPerSlab); //set last element as not used
if(mFreeList)
Alloc::deallocate(mFreeList);
mFreeList = reinterpret_cast<T**>(Alloc::allocate(2* newSlabCount * mEltsPerSlab * sizeof(T*), PX_FL));
T** slabs = reinterpret_cast<T**>(Alloc::allocate(2 * newSlabCount * sizeof(T*), PX_FL));
if (mSlabs)
{
PxMemCopy(slabs, mSlabs, sizeof(T*)*mSlabCount);
Alloc::deallocate(mSlabs);
}
mSlabs = slabs;
}
mSlabs[mSlabCount++] = mAddr;
// Add to free list in descending order so that lowest indices get allocated first -
// the FW context code currently *relies* on this behavior to grab the zero-index volume
// which can't be allocated to the user. TODO: fix this
PxU32 baseIndex = (mSlabCount-1) * mEltsPerSlab;
PxU32 freeCount = mFreeCount;
for(PxI32 i=PxI32(mEltsPerSlab-1);i>=0;i--)
mFreeList[freeCount++] = PX_PLACEMENT_NEW(mAddr+i, T(mArgument, baseIndex+ i));
mFreeCount = freeCount;
return true;
}
PX_INLINE PxU32 getMaxUsedIndex() const
{
return mUseBitmap.findLast();
}
PX_INLINE PxBitMap::Iterator getIterator() const
{
return PxBitMap::Iterator(mUseBitmap);
}
private:
const PxU32 mEltsPerSlab;
PxU32 mSlabCount;
PxU32 mLog2EltsPerSlab;
T** mFreeList;
PxU32 mFreeCount;
T** mSlabs;
ArgumentType* mArgument;
PxBitMap mUseBitmap;
};
}
}
#endif
| 8,399 | C | 27.093645 | 115 | 0.692702 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmCollection.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 CM_COLLECTION_H
#define CM_COLLECTION_H
#include "common/PxCollection.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxAllocator.h"
namespace physx
{
namespace Cm
{
template <class Key,
class Value,
class HashFn = PxHash<Key>,
class Allocator = PxAllocator >
class CollectionHashMap : public PxCoalescedHashMap< Key, Value, HashFn, Allocator>
{
typedef physx::PxHashMapBase< Key, Value, HashFn, Allocator> MapBase;
typedef PxPair<const Key,Value> EntryData;
public:
CollectionHashMap(PxU32 initialTableSize = 64, float loadFactor = 0.75f):
PxCoalescedHashMap< Key, Value, HashFn, Allocator>(initialTableSize,loadFactor) {}
void insertUnique(const Key& k, const Value& v)
{
PX_PLACEMENT_NEW(MapBase::mBase.insertUnique(k), EntryData)(k,v);
}
};
class Collection : public PxCollection, public PxUserAllocated
{
public:
typedef CollectionHashMap<PxBase*, PxSerialObjectId> ObjectToIdMap;
typedef CollectionHashMap<PxSerialObjectId, PxBase*> IdToObjectMap;
virtual void add(PxBase& object, PxSerialObjectId ref);
virtual void remove(PxBase& object);
virtual bool contains(PxBase& object) const;
virtual void addId(PxBase& object, PxSerialObjectId id);
virtual void removeId(PxSerialObjectId id);
virtual PxBase* find(PxSerialObjectId ref) const;
virtual void add(PxCollection& collection);
virtual void remove(PxCollection& collection);
virtual PxU32 getNbObjects() const;
virtual PxBase& getObject(PxU32 index) const;
virtual PxU32 getObjects(PxBase** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const;
virtual PxU32 getNbIds() const;
virtual PxSerialObjectId getId(const PxBase& object) const;
virtual PxU32 getIds(PxSerialObjectId* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const;
void release() { PX_DELETE_THIS; }
// Only for internal use. Bypasses virtual calls, specialized behaviour.
PX_INLINE void internalAdd(PxBase* s, PxSerialObjectId id = PX_SERIAL_OBJECT_ID_INVALID) { mObjects.insertUnique(s, id); }
PX_INLINE PxU32 internalGetNbObjects() const { return mObjects.size(); }
PX_INLINE PxBase* internalGetObject(PxU32 i) const { PX_ASSERT(i<mObjects.size()); return mObjects.getEntries()[i].first; }
PX_INLINE const ObjectToIdMap::Entry* internalGetObjects() const { return mObjects.getEntries(); }
IdToObjectMap mIds;
ObjectToIdMap mObjects;
};
}
}
#endif
| 4,288 | C | 43.216494 | 130 | 0.735541 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmSerialize.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 CM_SERIALIZE_H
#define CM_SERIALIZE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxIO.h"
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxUtilities.h"
namespace physx
{
PX_INLINE void flip(PxU16& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[1];
b[1] = temp;
}
PX_INLINE void flip(PxI16& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
PxI8 temp = b[0];
b[0] = b[1];
b[1] = temp;
}
PX_INLINE void flip(PxU32& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[3];
b[3] = temp;
temp = b[1];
b[1] = b[2];
b[2] = temp;
}
// MS: It is important to modify the value directly and not use a temporary variable or a return
// value. The reason for this is that a flipped float might have a bit pattern which indicates
// an invalid float. If such a float is assigned to another float, the bit pattern
// can change again (maybe to map invalid floats to a common invalid pattern?).
// When reading the float and flipping again, the changed bit pattern will result in a different
// float than the original one.
PX_INLINE void flip(PxF32& v)
{
PxU8* b = reinterpret_cast<PxU8*>(&v);
PxU8 temp = b[0];
b[0] = b[3];
b[3] = temp;
temp = b[1];
b[1] = b[2];
b[2] = temp;
}
PX_INLINE void writeChunk(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxOutputStream& stream)
{
stream.write(&a, sizeof(PxI8));
stream.write(&b, sizeof(PxI8));
stream.write(&c, sizeof(PxI8));
stream.write(&d, sizeof(PxI8));
}
void readChunk(PxI8& a, PxI8& b, PxI8& c, PxI8& d, PxInputStream& stream);
PxU16 readWord(bool mismatch, PxInputStream& stream);
PxU32 readDword(bool mismatch, PxInputStream& stream);
PxF32 readFloat(bool mismatch, PxInputStream& stream);
void writeWord(PxU16 value, bool mismatch, PxOutputStream& stream);
void writeDword(PxU32 value, bool mismatch, PxOutputStream& stream);
void writeFloat(PxF32 value, bool mismatch, PxOutputStream& stream);
bool readFloatBuffer(PxF32* dest, PxU32 nbFloats, bool mismatch, PxInputStream& stream);
void writeFloatBuffer(const PxF32* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void writeWordBuffer(const PxU16* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void readWordBuffer(PxU16* dest, PxU32 nb, bool mismatch, PxInputStream& stream);
void writeWordBuffer(const PxI16* src, PxU32 nb, bool mismatch, PxOutputStream& stream);
void readWordBuffer(PxI16* dest, PxU32 nb, bool mismatch, PxInputStream& stream);
void writeByteBuffer(const PxU8* src, PxU32 nb, PxOutputStream& stream);
void readByteBuffer(PxU8* dest, PxU32 nb, PxInputStream& stream);
bool writeHeader(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxU32 version, bool mismatch, PxOutputStream& stream);
bool readHeader(PxI8 a, PxI8 b, PxI8 c, PxI8 d, PxU32& version, bool& mismatch, PxInputStream& stream);
PX_INLINE bool readIntBuffer(PxU32* dest, PxU32 nbInts, bool mismatch, PxInputStream& stream)
{
return readFloatBuffer(reinterpret_cast<PxF32*>(dest), nbInts, mismatch, stream);
}
PX_INLINE void writeIntBuffer(const PxU32* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
writeFloatBuffer(reinterpret_cast<const PxF32*>(src), nb, mismatch, stream);
}
PX_INLINE bool ReadDwordBuffer(PxU32* dest, PxU32 nb, bool mismatch, PxInputStream& stream)
{
return readFloatBuffer(reinterpret_cast<float*>(dest), nb, mismatch, stream);
}
PX_INLINE void WriteDwordBuffer(const PxU32* src, PxU32 nb, bool mismatch, PxOutputStream& stream)
{
writeFloatBuffer(reinterpret_cast<const float*>(src), nb, mismatch, stream);
}
PxU32 computeMaxIndex(const PxU32* indices, PxU32 nbIndices);
PxU16 computeMaxIndex(const PxU16* indices, PxU32 nbIndices);
void storeIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch);
void readIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch);
// PT: see PX-1163
PX_FORCE_INLINE bool readBigEndianVersionNumber(PxInputStream& stream, bool mismatch_, PxU32& fileVersion, bool& mismatch)
{
// PT: allright this is going to be subtle:
// - in version 1 the data was always saved in big-endian format
// - *including the version number*!
// - so we cannot just read the version "as usual" using the passed mismatch param
// PT: mismatch value for version 1
mismatch = (PxLittleEndian() == 1);
const PxU32 rawFileVersion = readDword(false, stream);
if(rawFileVersion==1)
{
// PT: this is a version-1 file with no flip
fileVersion = 1;
PX_ASSERT(!mismatch);
}
else
{
PxU32 fileVersionFlipped = rawFileVersion;
flip(fileVersionFlipped);
if(fileVersionFlipped==1)
{
// PT: this is a version-1 file with flip
fileVersion = 1;
PX_ASSERT(mismatch);
}
else
{
// PT: this is at least version 2 so we can process it "as usual"
mismatch = mismatch_;
fileVersion = mismatch_ ? fileVersionFlipped : rawFileVersion;
}
}
PX_ASSERT(fileVersion<=3);
if(fileVersion>3)
return false;
return true;
}
// PT: TODO: copied from IceSerialize.h, still needs to be refactored/cleaned up.
namespace Cm
{
bool WriteHeader(PxU8 a, PxU8 b, PxU8 c, PxU8 d, PxU32 version, bool mismatch, PxOutputStream& stream);
bool ReadHeader(PxU8 a_, PxU8 b_, PxU8 c_, PxU8 d_, PxU32& version, bool& mismatch, PxInputStream& stream);
void StoreIndices(PxU32 maxIndex, PxU32 nbIndices, const PxU32* indices, PxOutputStream& stream, bool platformMismatch);
void ReadIndices(PxU32 maxIndex, PxU32 nbIndices, PxU32* indices, PxInputStream& stream, bool platformMismatch);
void StoreIndices(PxU16 maxIndex, PxU32 nbIndices, const PxU16* indices, PxOutputStream& stream, bool platformMismatch);
void ReadIndices(PxU16 maxIndex, PxU32 nbIndices, PxU16* indices, PxInputStream& stream, bool platformMismatch);
}
}
#endif
| 7,710 | C | 37.944444 | 123 | 0.720233 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmConeLimitHelper.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 CM_CONE_LIMIT_HELPER_H
#define CM_CONE_LIMIT_HELPER_H
// This class contains methods for supporting the tan-quarter swing limit - that
// is the, ellipse defined by tanQ(theta)^2/tanQ(thetaMax)^2 + tanQ(phi)^2/tanQ(phiMax)^2 = 1
//
// Angles are passed as an PxVec3 swing vector with x = 0 and y and z the swing angles
// around the y and z axes
#include "foundation/PxMathUtils.h"
namespace physx
{
namespace Cm
{
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal tanAdd(PxReal tan1, PxReal tan2)
{
PX_ASSERT(PxAbs(1.0f-tan1*tan2)>1e-6f);
return (tan1+tan2)/(1.0f-tan1*tan2);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE float computeAxisAndError(const PxVec3& r, const PxVec3& d, const PxVec3& twistAxis, PxVec3& axis)
{
// the point on the cone defined by the tanQ swing vector r
// this code is equal to quatFromTanQVector(r).rotate(PxVec3(1.0f, 0.0f, 0.0f);
const PxVec3 p(1.0f, 0.0f, 0.0f);
const PxReal r2 = r.dot(r), a = 1.0f - r2, b = 1.0f/(1.0f+r2), b2 = b*b;
const PxReal v1 = 2.0f * a * b2;
const PxVec3 v2(a, 2.0f * r.z, -2.0f * r.y); // a*p + 2*r.cross(p);
const PxVec3 coneLine = v1 * v2 - p; // already normalized
// the derivative of coneLine in the direction d
const PxReal rd = r.dot(d);
const PxReal dv1 = -4.0f * rd * (3.0f - r2)*b2*b;
const PxVec3 dv2(-2.0f * rd, 2.0f * d.z, -2.0f * d.y);
const PxVec3 coneNormal = v1 * dv2 + dv1 * v2;
axis = coneLine.cross(coneNormal)/coneNormal.magnitude();
return coneLine.cross(axis).dot(twistAxis);
}
// this is here because it's used in both LL and Extensions. However, it
// should STAY IN THE SDK CODE BASE because it's SDK-specific
class ConeLimitHelper
{
public:
PX_CUDA_CALLABLE ConeLimitHelper(PxReal tanQSwingY, PxReal tanQSwingZ, PxReal tanQPadding)
: mTanQYMax(tanQSwingY), mTanQZMax(tanQSwingZ), mTanQPadding(tanQPadding) {}
// whether the point is inside the (inwardly) padded cone - if it is, there's no limit
// constraint
PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& tanQSwing) const
{
const PxReal tanQSwingYPadded = tanAdd(PxAbs(tanQSwing.y),mTanQPadding);
const PxReal tanQSwingZPadded = tanAdd(PxAbs(tanQSwing.z),mTanQPadding);
return PxSqr(tanQSwingYPadded/mTanQYMax)+PxSqr(tanQSwingZPadded/mTanQZMax) <= 1;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 clamp(const PxVec3& tanQSwing, PxVec3& normal) const
{
const PxVec3 p = PxEllipseClamp(tanQSwing, PxVec3(0.0f, mTanQYMax, mTanQZMax));
normal = PxVec3(0.0f, p.y/PxSqr(mTanQYMax), p.z/PxSqr(mTanQZMax));
#ifdef PX_PARANOIA_ELLIPSE_CHECK
PxReal err = PxAbs(PxSqr(p.y/mTanQYMax) + PxSqr(p.z/mTanQZMax) - 1);
PX_ASSERT(err<1e-3);
#endif
return p;
}
// input is a swing quat, such that swing.x = twist.y = twist.z = 0, q = swing * twist
// The routine is agnostic to the sign of q.w (i.e. we don't need the minimal-rotation swing)
// output is an axis such that positive rotation increases the angle outward from the
// limit (i.e. the image of the x axis), the error is the sine of the angular difference,
// positive if the twist axis is inside the cone
PX_CUDA_CALLABLE bool getLimit(const PxQuat& swing, PxVec3& axis, PxReal& error) const
{
PX_ASSERT(swing.w>0.0f);
const PxVec3 twistAxis = swing.getBasisVector0();
const PxVec3 tanQSwing = PxVec3(0.0f, PxTanHalf(swing.z,swing.w), -PxTanHalf(swing.y,swing.w));
if(contains(tanQSwing))
return false;
PxVec3 normal, clamped = clamp(tanQSwing, normal);
// rotation vector and ellipse normal
const PxVec3 r(0.0f, -clamped.z, clamped.y), d(0.0f, -normal.z, normal.y);
error = computeAxisAndError(r, d, twistAxis, axis);
PX_ASSERT(PxAbs(axis.magnitude()-1)<1e-5f);
#ifdef PX_PARANOIA_ELLIPSE_CHECK
bool inside = PxSqr(tanQSwing.y/mTanQYMax) + PxSqr(tanQSwing.z/mTanQZMax) <= 1;
PX_ASSERT(inside && error>-1e-4f || !inside && error<1e-4f);
#endif
return true;
}
private:
PxReal mTanQYMax, mTanQZMax, mTanQPadding;
};
class ConeLimitHelperTanLess
{
public:
PX_CUDA_CALLABLE ConeLimitHelperTanLess(PxReal swingY, PxReal swingZ)
: mYMax(swingY), mZMax(swingZ) {}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 clamp(const PxVec3& swing, PxVec3& normal) const
{
// finds the closest point on the ellipse to a given point
const PxVec3 p = PxEllipseClamp(swing, PxVec3(0.0f, mYMax, mZMax));
// normal to the point on ellipse
normal = PxVec3(0.0f, p.y/PxSqr(mYMax), p.z/PxSqr(mZMax));
#ifdef PX_PARANOIA_ELLIPSE_CHECK
PxReal err = PxAbs(PxSqr(p.y/mYMax) + PxSqr(p.z/mZMax) - 1);
PX_ASSERT(err<1e-3);
#endif
return p;
}
// input is a swing quat, such that swing.x = twist.y = twist.z = 0, q = swing * twist
// The routine is agnostic to the sign of q.w (i.e. we don't need the minimal-rotation swing)
// output is an axis such that positive rotation increases the angle outward from the
// limit (i.e. the image of the x axis), the error is the sine of the angular difference,
// positive if the twist axis is inside the cone
PX_CUDA_CALLABLE void getLimit(const PxQuat& swing, PxVec3& axis, PxReal& error) const
{
PX_ASSERT(swing.w>0.0f);
const PxVec3 twistAxis = swing.getBasisVector0();
// get the angles from the swing quaternion
const PxVec3 swingAngle(0.0f, 4.0f * PxAtan2(swing.y, 1.0f + swing.w), 4.0f * PxAtan2(swing.z, 1.0f + swing.w));
PxVec3 normal, clamped = clamp(swingAngle, normal);
// rotation vector and ellipse normal
const PxVec3 r(0.0f, PxTan(clamped.y/4.0f), PxTan(clamped.z/4.0f)), d(0.0f, normal.y, normal.z);
error = computeAxisAndError(r, d, twistAxis, axis);
PX_ASSERT(PxAbs(axis.magnitude()-1.0f)<1e-5f);
}
private:
PxReal mYMax, mZMax;
};
} // namespace Cm
}
#endif
| 7,434 | C | 38.338624 | 132 | 0.71025 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/CmRadixSort.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 CM_RADIX_SORT_H
#define CM_RADIX_SORT_H
#include "common/PxPhysXCommonConfig.h"
namespace physx
{
namespace Cm
{
enum RadixHint
{
RADIX_SIGNED, //!< Input values are signed
RADIX_UNSIGNED, //!< Input values are unsigned
RADIX_FORCE_DWORD = 0x7fffffff
};
#define INVALIDATE_RANKS mCurrentSize|=0x80000000
#define VALIDATE_RANKS mCurrentSize&=0x7fffffff
#define CURRENT_SIZE (mCurrentSize&0x7fffffff)
#define INVALID_RANKS (mCurrentSize&0x80000000)
class PX_PHYSX_COMMON_API RadixSort
{
PX_NOCOPY(RadixSort)
public:
RadixSort();
virtual ~RadixSort();
// Sorting methods
RadixSort& Sort(const PxU32* input, PxU32 nb, RadixHint hint=RADIX_SIGNED);
RadixSort& Sort(const float* input, PxU32 nb);
//! Access to results. mRanks is a list of indices in sorted order, i.e. in the order you may further process your data
PX_FORCE_INLINE const PxU32* GetRanks() const { return mRanks; }
//! mIndices2 gets trashed on calling the sort routine, but otherwise you can recycle it the way you want.
PX_FORCE_INLINE PxU32* GetRecyclable() const { return mRanks2; }
//! Returns the total number of calls to the radix sorter.
PX_FORCE_INLINE PxU32 GetNbTotalCalls() const { return mTotalCalls; }
//! Returns the number of eraly exits due to temporal coherence.
PX_FORCE_INLINE PxU32 GetNbHits() const { return mNbHits; }
PX_FORCE_INLINE void invalidateRanks() { INVALIDATE_RANKS; }
bool SetBuffers(PxU32* ranks0, PxU32* ranks1, PxU32* histogram1024, PxU32** links256);
protected:
PxU32 mCurrentSize; //!< Current size of the indices list
PxU32* mRanks; //!< Two lists, swapped each pass
PxU32* mRanks2;
PxU32* mHistogram1024;
PxU32** mLinks256;
// Stats
PxU32 mTotalCalls; //!< Total number of calls to the sort routine
PxU32 mNbHits; //!< Number of early exits due to coherence
// Stack-radix
bool mDeleteRanks; //!<
};
#define StackRadixSort(name, ranks0, ranks1) \
RadixSort name; \
PxU32 histogramBuffer[1024]; \
PxU32* linksBuffer[256]; \
name.SetBuffers(ranks0, ranks1, histogramBuffer, linksBuffer);
class PX_PHYSX_COMMON_API RadixSortBuffered : public RadixSort
{
public:
RadixSortBuffered();
~RadixSortBuffered();
void reset();
RadixSortBuffered& Sort(const PxU32* input, PxU32 nb, RadixHint hint=RADIX_SIGNED);
RadixSortBuffered& Sort(const float* input, PxU32 nb);
private:
RadixSortBuffered(const RadixSortBuffered& object);
RadixSortBuffered& operator=(const RadixSortBuffered& object);
// Internal methods
void CheckResize(PxU32 nb);
bool Resize(PxU32 nb);
};
}
}
#endif // CM_RADIX_SORT_H
| 4,476 | C | 36.940678 | 121 | 0.718275 |
NVIDIA-Omniverse/PhysX/physx/source/common/src/windows/CmWindowsModuleUpdateLoader.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.
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
#define NX_USE_SDK_DLLS
#include "PhysXUpdateLoader.h"
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
#include "windows/CmWindowsModuleUpdateLoader.h"
#include "windows/CmWindowsLoadLibrary.h"
#include "stdio.h"
namespace physx { namespace Cm {
#if PX_VC
#pragma warning(disable: 4191) //'operator/operation' : unsafe conversion from 'type of expression' to 'type required'
#endif
typedef HMODULE (*GetUpdatedModule_FUNC)(const char*, const char*);
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
typedef void (*setLogging_FUNC)(PXUL_ErrorCode, pt2LogFunc);
static void LogMessage(PXUL_ErrorCode messageType, char* message)
{
switch(messageType)
{
case PXUL_ERROR_MESSAGES:
getFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL,
"PhysX Update Loader Error: %s.", message);
break;
case PXUL_WARNING_MESSAGES:
getFoundation().error(PX_WARN, "PhysX Update Loader Warning: %s.", message);
break;
case PXUL_INFO_MESSAGES:
getFoundation().error(PX_INFO, "PhysX Update Loader Information: %s.", message);
break;
default:
getFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL,
"Unknown message type from update loader.");
break;
}
}
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
CmModuleUpdateLoader::CmModuleUpdateLoader(const char* updateLoaderDllName)
: mGetUpdatedModuleFunc(NULL)
{
mUpdateLoaderDllHandle = loadLibrary(updateLoaderDllName);
if (mUpdateLoaderDllHandle != NULL)
{
mGetUpdatedModuleFunc = GetProcAddress(mUpdateLoaderDllHandle, "GetUpdatedModule");
#ifdef SUPPORT_UPDATE_LOADER_LOGGING
#if PX_X86
setLogging_FUNC setLoggingFunc;
setLoggingFunc = (setLogging_FUNC)GetProcAddress(mUpdateLoaderDllHandle, "setLoggingFunction");
if(setLoggingFunc != NULL)
{
setLoggingFunc(PXUL_ERROR_MESSAGES, LogMessage);
}
#endif
#endif /* SUPPORT_UPDATE_LOADER_LOGGING */
}
}
CmModuleUpdateLoader::~CmModuleUpdateLoader()
{
if (mUpdateLoaderDllHandle != NULL)
{
FreeLibrary(mUpdateLoaderDllHandle);
mUpdateLoaderDllHandle = NULL;
}
}
HMODULE CmModuleUpdateLoader::LoadModule(const char* moduleName, const char* appGUID)
{
HMODULE result = NULL;
if (mGetUpdatedModuleFunc != NULL)
{
// Try to get the module through PhysXUpdateLoader
GetUpdatedModule_FUNC getUpdatedModuleFunc = (GetUpdatedModule_FUNC)mGetUpdatedModuleFunc;
result = getUpdatedModuleFunc(moduleName, appGUID);
}
else
{
// If no PhysXUpdateLoader, just load the DLL directly
result = loadLibrary(moduleName);
if (result == NULL)
{
const DWORD err = GetLastError();
printf("%s:%i: loadLibrary error when loading %s: %lu\n", PX_FL, moduleName, err);
}
}
return result;
}
}; // end of namespace
}; // end of namespace
| 4,455 | C++ | 32.007407 | 118 | 0.752413 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenCreateRegistrationStruct.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.
//
// The macro logic in this header (and the headers CmOmniPvdAutoGenRegisterData.h and
// and CmOmniPvdAutoGenSetData.h) is meant as a helper to automatically generate a
// structure that stores all PVD class and attribute handles for a module, handles the
// registration logic and adds methods for object creation, setting attribute
// values etc. At the core of the generation logic is a user defined header file
// that describes the classes and attributes as follows:
//
// OMNI_PVD_CLASS_BEGIN(MyClass1)
// OMNI_PVD_ATTRIBUTE(MyClass1, myAttr1, PxReal, OmniPvdDataType::eFLOAT32)
// OMNI_PVD_ATTRIBUTE(MyClass1, myAttr2, PxReal, OmniPvdDataType::eFLOAT32)
// OMNI_PVD_CLASS_END(MyClass1)
//
// OMNI_PVD_CLASS_UNTYPED_BEGIN(MyClass2)
// OMNI_PVD_ATTRIBUTE(MyClass2, myAttr1, PxU32, OmniPvdDataType::eUINT32)
// OMNI_PVD_CLASS_END(MyClass2)
//
// The structure to create from this description will look somewhat like this:
//
// struct MyModulePvdObjectsDescriptor
// {
//
// struct PvdMyClass1
// {
// typedef MyClass1 ObjectType;
// static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectRef) { return reinterpret_cast<OmniPvdObjectHandle>(&objectRef); }
//
// OmniPvdClassHandle classHandle;
//
// void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const
// {
// writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL);
// }
//
// static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef)
// {
// writer.destroyObject(contextHandle, getObjectHandle(objectRef));
// }
//
// OmniPvdAttributeHandle myAttr1;
// void set_myAttr1_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxReal& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr1, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>());
// }
//
// OmniPvdAttributeHandle myAttr2;
// void set_myAttr2_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxReal& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr2, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>());
// }
// };
// PvdMyClass1 pvdMyClass1;
//
//
// struct PvdMyClass2
// {
// typedef OmniPvdObjectHandle ObjectType;
// static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectHandle) { return objectHandle; }
//
// OmniPvdClassHandle classHandle;
//
// void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const
// {
// writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL);
// }
//
// static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef)
// {
// writer.destroyObject(contextHandle, getObjectHandle(objectRef));
// }
//
// OmniPvdAttributeHandle myAttr1;
// void set_myAttr1_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const PxU32& value) const
// {
// writer.setAttribute(contextHandle, getObjectHandle(objectRef), myAttr1, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>());
// }
// };
// PvdMyClass2 pvdMyClass2;
//
//
// void myRegisterDataMethod(OmniPvdWriter& writer)
// {
// pvdMyClass1.classHandle = writer.registerClass("MyClass1");
// pvdMyClass1.myAttr1 = writer.registerAttribute(pvdMyClass1.classHandle, "myAttr1", OmniPvdDataType::eFLOAT32, 1);
// pvdMyClass1.myAttr2 = writer.registerAttribute(pvdMyClass1.classHandle, "myAttr2", OmniPvdDataType::eFLOAT32, 1);
//
// pvdMyClass2.classHandle = writer.registerClass("MyClass2");
// pvdMyClass2.myAttr1 = writer.registerAttribute(pvdMyClass2.classHandle, "myAttr1", OmniPvdDataType::eUINT32, 1);
// }
//
// };
//
// Assuming the class and attribute definitions are in a file called MyModulePvdObjectDefinitions.h,
// the described structure can be generated like this:
//
// struct MyModulePvdObjectsDescriptor
// {
//
// #include "CmOmniPvdAutoGenCreateRegistrationStruct.h"
// #include "MyModulePvdObjectDefinitions.h"
// #include "CmOmniPvdAutoGenClearDefines.h"
//
// // custom registration data related members that are not auto-generated can go here, for example
//
//
// void myRegisterDataMethod(OmniPvdWriter& writer)
// {
// #define OMNI_PVD_WRITER_VAR writer
//
// #include "CmOmniPvdAutoGenRegisterData.h"
// #include "MyModulePvdObjectDefinitions.h"
// #include "CmOmniPvdAutoGenClearDefines.h"
//
// // custom registration code that is not auto-generated can go here too
//
// #undef OMNI_PVD_WRITER_VAR
// }
// };
//
// As can be seen, CmOmniPvdAutoGenCreateRegistrationStruct.h is responsible for generating the structs,
// members and setter methods. CmOmniPvdAutoGenRegisterData.h is responsible for generating the registration
// code (note that defining OMNI_PVD_WRITER_VAR is important in this context since it is used inside
// CmOmniPvdAutoGenRegisterData.h)
//
// Note that it is the user's responsibility to include the necessary headers before applying these helpers
// (for example, OmniPvdDefines.h etc.).
//
// Last but not least, the helpers in CmOmniPvdAutoGenSetData.h provide a way to use this structure to
// set values of attributes, create class instances etc. An example usage is shown below:
//
// OmniPvdContextHandle contextHandle; // assuming this holds the context the objects belong to
// MyClass1 myClass1Instance;
// PxReal value; // assuming this holds the value to set the attribute to
//
// OMNI_PVD_CREATE(contextHandle, MyClass1, myClass1Instance);
// OMNI_PVD_SET(contextHandle, MyClass1, myAttr1, myClass1Instance, value);
//
// To use these helper macros, the following things need to be defined before including CmOmniPvdAutoGenSetData.h:
//
// #define OMNI_PVD_GET_WRITER(writer)
// OmniPvdWriter* writer = GetPvdWriterForMyModule();
//
// #define OMNI_PVD_GET_REGISTRATION_DATA(regData)
// MyModulePvdObjectsDescriptor* regData = GetPvdObjectsDescForMyModule();
//
// #include "CmOmniPvdAutoGenSetData.h"
//
// GetPvdWriterForMyModule() and GetPvdObjectsDescForMyModule() just stand for the logic the user needs
// to provide to access the OmniPvdWriter object and the generated description structure. In the given example,
// the variables "writer" and "regData" need to be assigned but the code to do so will be user specific.
//
//
#define OMNI_PVD_CLASS_INTERNALS \
\
OmniPvdClassHandle classHandle; \
\
void createInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) const \
{ \
writer.createObject(contextHandle, classHandle, getObjectHandle(objectRef), NULL); \
} \
\
static void destroyInstance(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef) \
{ \
writer.destroyObject(contextHandle, getObjectHandle(objectRef)); \
}
//
// Define a PVD class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: name of the class to register in PVD (note: has to be an existing C++ class)
//
#define OMNI_PVD_CLASS_BEGIN(classID) \
\
struct Pvd##classID \
{ \
typedef classID ObjectType; \
\
static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectRef) { return reinterpret_cast<OmniPvdObjectHandle>(&objectRef); } \
\
OMNI_PVD_CLASS_INTERNALS
//
// Define a PVD class that is derived from another class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: see OMNI_PVD_CLASS_BEGIN
// baseClassID: the name of the class to derive from
//
#define OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_BEGIN(classID)
//
// Define a PVD class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: name of the class to register in PVD (note: the class does not need to match an actually existing
// class but still needs to follow C++ naming conventions)
//
#define OMNI_PVD_CLASS_UNTYPED_BEGIN(classID) \
\
struct Pvd##classID \
{ \
typedef OmniPvdObjectHandle ObjectType; \
\
static OmniPvdObjectHandle getObjectHandle(const ObjectType& objectHandle) { return objectHandle; } \
\
OMNI_PVD_CLASS_INTERNALS
//
// Define a PVD class that is derived from another class.
//
// Note: has to be paired with OMNI_PVD_CLASS_END
//
// classID: see OMNI_PVD_CLASS_UNTYPED_BEGIN
// baseClassID: the name of the class to derive from
//
#define OMNI_PVD_CLASS_UNTYPED_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_UNTYPED_BEGIN(classID)
//
// See OMNI_PVD_CLASS_BEGIN for more info.
//
#define OMNI_PVD_CLASS_END(classID) \
\
}; \
Pvd##classID pvd##classID;
//
// Define a PVD enum class.
//
// Note: has to be paired with OMNI_PVD_ENUM_END
//
// enumID: name of the enum class (has to follow C++ naming conventions)
//
#define OMNI_PVD_ENUM_BEGIN(enumID) \
\
struct Pvd##enumID \
{ \
OmniPvdClassHandle classHandle;
//
// See OMNI_PVD_ENUM_BEGIN
//
#define OMNI_PVD_ENUM_END(enumID) OMNI_PVD_CLASS_END(enumID)
//
// Define a simple PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// classID: name of the class to add the attribute to (see OMNI_PVD_CLASS_BEGIN)
// attributeID: name of the attribute (has to follow C++ naming conventions)
// valueType: attribute data type (int, float etc.)
// pvdDataType: PVD attribute data type (see OmniPvdDataType)
//
#define OMNI_PVD_ATTRIBUTE(classID, attributeID, valueType, pvdDataType) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
PX_ASSERT(sizeof(valueType) == getOmniPvdDataTypeSize<pvdDataType>()); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), getOmniPvdDataTypeSize<pvdDataType>()); \
}
//
// Define a fixed size multi-value PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// The attribute is a fixed size array of values of the given pvd data type.
//
// entryCount: number of entries the array will hold.
//
// See OMNI_PVD_ATTRIBUTE for the other parameters. Note that valueType is
// expected to hold a type that matches the size of the whole array, i.e.,
// sizeof(valueType) == entryCount * getOmniPvdDataTypeSize<pvdDataType>()
//
#define OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE(classID, attributeID, valueType, pvdDataType, entryCount) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const uint32_t byteSize = static_cast<uint32_t>(sizeof(valueType)); \
PX_ASSERT(byteSize == (entryCount * getOmniPvdDataTypeSize<pvdDataType>())); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), byteSize); \
}
//
// Define a variable size multi-value PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// The attribute is a variable size array of values of the given pvd data type.
//
// See OMNI_PVD_ATTRIBUTE for a parameter description. Note that valueType is expected
// to define the type of a single array element, for example, int for an integer array.
//
#define OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE(classID, attributeID, valueType, pvdDataType) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType* values, uint32_t valueCount) const \
{ \
const uint32_t byteSize = valueCount * getOmniPvdDataTypeSize<pvdDataType>(); \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(values), byteSize); \
}
//
// Define a string PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// See OMNI_PVD_ATTRIBUTE for a parameter description.
//
#define OMNI_PVD_ATTRIBUTE_STRING(classID, attributeID) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const char* values, uint32_t valueCount) const \
{ \
const uint32_t byteSize = valueCount; \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(values), byteSize); \
}
//
// Define a unique list PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// See OMNI_PVD_ATTRIBUTE for a parameter description. Note that valueType is expected
// to define the class the list will hold pointers to. If it shall hold pointers to
// instances of class MyClass, then the valueType is MyClass.
//
#define OMNI_PVD_ATTRIBUTE_UNIQUE_LIST(classID, attributeID, valueType) \
\
OmniPvdAttributeHandle attributeID; \
\
void addTo_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const OmniPvdObjectHandle objHandle = reinterpret_cast<OmniPvdObjectHandle>(&value); \
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&objHandle); \
writer.addToUniqueListAttribute(contextHandle, getObjectHandle(objectRef), attributeID, ptr, sizeof(OmniPvdObjectHandle)); \
} \
\
void removeFrom_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const valueType& value) const \
{ \
const OmniPvdObjectHandle objHandle = reinterpret_cast<OmniPvdObjectHandle>(&value); \
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&objHandle); \
writer.removeFromUniqueListAttribute(contextHandle, getObjectHandle(objectRef), attributeID, ptr, sizeof(OmniPvdObjectHandle)); \
}
//
// Define a flag PVD attribute.
//
// Note: needs to be placed between a OMNI_PVD_CLASS_BEGIN, OMNI_PVD_CLASS_END
// sequence
//
// enumType: the enum type this attribute refers to
// enumID: the name of the enum class that describes the enum (see OMNI_PVD_ENUM_BEGIN)
//
// See OMNI_PVD_ATTRIBUTE for the other parameters.
//
#define OMNI_PVD_ATTRIBUTE_FLAG(classID, attributeID, enumType, enumID) \
\
OmniPvdAttributeHandle attributeID; \
void set_##attributeID##_(OmniPvdWriter& writer, OmniPvdContextHandle contextHandle, const ObjectType& objectRef, const enumType& value) const \
{ \
writer.setAttribute(contextHandle, getObjectHandle(objectRef), attributeID, reinterpret_cast<const uint8_t*>(&value), sizeof(enumType)); \
}
//
// Define an enum entry.
//
// Note: needs to be placed between a OMNI_PVD_ENUM_BEGIN, OMNI_PVD_ENUM_END
// sequence
//
// enumID: name of the enum class to add an entry to (see OMNI_PVD_ENUM_BEGIN)
// enumEntryID: the name of the enum entry to add to the enum class (has to follow C++ naming conventions)
// value: the enum value
//
#define OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, value)
//
// Define an enum entry.
//
// Note: needs to be placed between a OMNI_PVD_ENUM_BEGIN, OMNI_PVD_ENUM_END
// sequence
//
// See OMNI_PVD_ENUM_VALUE_EXPLICIT for a description of the parameters. This shorter form expects the enum to
// have a C++ definition of the form:
//
// struct <enumID>
// {
// enum Enum
// {
// <enumEntryID> = ...
// }
// }
//
// such that the value can be derived using: <enumID>::<enumEntryID>
//
#define OMNI_PVD_ENUM_VALUE(enumID, enumEntryID) \
\
OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, enumID::enumEntryID)
| 25,110 | C | 54.067982 | 176 | 0.526245 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenSetData.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 header provides macros to register PVD object instances, to set PVD attribute
// values etc. This only works in combination with a registration structure that was
// defined using the logic in CmOmniPvdAutoGenCreateRegistrationStruct.h.
// OMNI_PVD_GET_WRITER and OMNI_PVD_GET_REGISTRATION_DATA have to be defined before
// including this header. These two macros need to fetch and assign the pointer to
// the OmniPvdWriter instance and the registration structure instance respectively.
// See CmOmniPvdAutoGenCreateRegistrationStruct.h for a more detailed overview of the
// whole approach.
//
#if PX_SUPPORT_OMNI_PVD
//
// It is recommended to use this macro when multiple PVD attributes get written
// in one go since the writer and registration structure is then fetched once only.
//
// Note: has to be paired with OMNI_PVD_WRITE_SCOPE_END
//
// writer: a pointer to the OmniPvdWriter instance will get assigned to a variable
// named "writer"
// regData: a pointer to the registration structure instance will get assigned to
// a variable named "regData"
//
// General usage would look like this:
//
// OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData)
// OMNI_PVD_SET_EXPLICIT(writer, regData, ...)
// OMNI_PVD_SET_EXPLICIT(writer, regData, ...)
// ...
// OMNI_PVD_WRITE_SCOPE_END
//
#define OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData) \
\
OMNI_PVD_GET_WRITER(writer) \
if (writer != NULL) \
{ \
OMNI_PVD_GET_REGISTRATION_DATA(regData)
//
// See OMNI_PVD_WRITE_SCOPE_BEGIN for more info.
//
#define OMNI_PVD_WRITE_SCOPE_END \
\
}
//
// Create a PVD object instance using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_CREATE_EXPLICIT(writer, regData, contextHandle, classID, objectRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.createInstance(*writer, contextHandle, objectRef);
//
// Create a PVD object instance.
//
// Note: if attribute values are to be set directly after the object instance registration,
// it is recommended to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_CREATE_EXPLICIT etc. instead
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_CREATE(contextHandle, classID, objectRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, objectRef); \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Destroy a PVD object instance using the provided pointer to the writer instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_DESTROY_EXPLICIT(writer, regData, contextHandle, classID, objectRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.destroyInstance(*writer, contextHandle, objectRef);
//
// Destroy a PVD object instance.
//
// See OMNI_PVD_SET_EXPLICIT and OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_DESTROY(contextHandle, classID, objectRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_DESTROY_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, objectRef); \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Set a PVD attribute value using the provided pointers to the writer and registration
// structure instance.
//
// writer: the variable named "writer" has to hold a pointer to the OmniPvdWriter instance
// regData: the variable named "regData" has to hold a pointer to the registration
// structure
//
// See OMNI_PVD_SET for a description of the other parameters.
//
#define OMNI_PVD_SET_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.set_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Set a PVD attribute value.
//
// Note: if multiple attribute values should get set in a row, it is recommended
// to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_SET_EXPLICIT etc. instead
//
// contextHandle: the handle of the context the object instance belongs to
// classID: the name of the class (as defined in OMNI_PVD_CLASS_BEGIN() etc.) the attribute
// belongs to
// attributeID: the name of the attribute (as defined in OMNI_PVD_ATTRIBUTE() etc.) to set the
// value for
// objectRef: reference to the class instance to set the attribute for (for untyped classes this shall be
// a reference to a OmniPvdObjectHandle. For typed classes, the pointer value will be used as the
// object handle value).
// valueRef: a reference to a variable that holds the value to set the attribute to
//
#define OMNI_PVD_SET(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Set PVD array attribute values (variable size array) using the provided pointers to the writer and registration
// structure instance.
//
// valuesPtr: pointer to the array data to set the attribute to
// valueCount: number of entries in valuePtr
//
// See OMNI_PVD_SET for a description of the other parameters.
//
#define OMNI_PVD_SET_ARRAY_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.set_##attributeID##_(*writer, contextHandle, objectRef, valuesPtr, valueCount);
//
// Set PVD array attribute values (variable size array).
//
// Note: if multiple attribute values should get set in a row, it is recommended
// to use OMNI_PVD_WRITE_SCOPE_BEGIN & OMNI_PVD_SET_EXPLICIT etc. instead
//
// See OMNI_PVD_SET_ARRAY_EXPLICIT for a description of the parameters.
//
#define OMNI_PVD_SET_ARRAY(contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Add an entry to a PVD unique list attribute using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_ADD_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.addTo_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Add an entry to a PVD unique list attribute.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_ADD(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
//
// Remove an entry from a PVD unique list attribute using the provided pointers to the writer and registration
// structure instance.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_REMOVE_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef) \
\
PX_ASSERT(writer); \
PX_ASSERT(regData); \
regData->pvd##classID.removeFrom_##attributeID##_(*writer, contextHandle, objectRef, valueRef);
//
// Remove an entry from a PVD unique list attribute.
//
// See OMNI_PVD_SET for a description of the parameters.
//
#define OMNI_PVD_REMOVE(contextHandle, classID, attributeID, objectRef, valueRef) \
\
{ \
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) \
OMNI_PVD_REMOVE_EXPLICIT(pvdWriter, pvdRegData, contextHandle, classID, attributeID, objectRef, valueRef) \
OMNI_PVD_WRITE_SCOPE_END \
}
#else
#define OMNI_PVD_WRITE_SCOPE_BEGIN(writer, regData)
#define OMNI_PVD_WRITE_SCOPE_END
#define OMNI_PVD_CREATE_EXPLICIT(writer, regData, contextHandle, classID, objectRef)
#define OMNI_PVD_CREATE(contextHandle, classID, objectRef)
#define OMNI_PVD_DESTROY_EXPLICIT(writer, regData, contextHandle, classID, objectRef)
#define OMNI_PVD_DESTROY(contextHandle, classID, objectRef)
#define OMNI_PVD_SET_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_SET(contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_SET_ARRAY_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount)
#define OMNI_PVD_SET_ARRAY(contextHandle, classID, attributeID, objectRef, valuesPtr, valueCount)
#define OMNI_PVD_ADD_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_ADD(contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_REMOVE_EXPLICIT(writer, regData, contextHandle, classID, attributeID, objectRef, valueRef)
#define OMNI_PVD_REMOVE(contextHandle, classID, attributeID, objectRef, valueRef)
#endif // PX_SUPPORT_OMNI_PVD
| 14,716 | C | 51.003533 | 125 | 0.552664 |
NVIDIA-Omniverse/PhysX/physx/source/common/include/omnipvd/CmOmniPvdAutoGenRegisterData.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.
//
// The macro logic in this header will generate the PVD class/attribute registration
// code based on a class/attribute definition file. OMNI_PVD_WRITER_VAR needs to be
// defined before including this header. OMNI_PVD_WRITER_VAR has to represent the
// variable that holds a reference to a OmniPvdWriter instance. See
// CmOmniPvdAutoGenCreateRegistrationStruct.h for a more detailed overview of the
// whole approach. The various parameters are described there too.
//
#define OMNI_PVD_CLASS_BEGIN(classID) \
\
pvd##classID.classHandle = OMNI_PVD_WRITER_VAR.registerClass(#classID);
#define OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID) \
\
pvd##classID.classHandle = OMNI_PVD_WRITER_VAR.registerClass(#classID, pvd##baseClassID.classHandle);
#define OMNI_PVD_CLASS_UNTYPED_BEGIN(classID) OMNI_PVD_CLASS_BEGIN(classID)
#define OMNI_PVD_CLASS_UNTYPED_DERIVED_BEGIN(classID, baseClassID) OMNI_PVD_CLASS_DERIVED_BEGIN(classID, baseClassID)
#define OMNI_PVD_CLASS_END(classID)
#define OMNI_PVD_ENUM_BEGIN(enumID) OMNI_PVD_CLASS_BEGIN(enumID)
#define OMNI_PVD_ENUM_END(enumID) OMNI_PVD_CLASS_END(enumID)
#define OMNI_PVD_ATTRIBUTE(classID, attributeID, valueType, pvdDataType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, 1);
#define OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE(classID, attributeID, valueType, pvdDataType, entryCount) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, entryCount);
#define OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE(classID, attributeID, valueType, pvdDataType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, pvdDataType, 0);
#define OMNI_PVD_ATTRIBUTE_STRING(classID, attributeID) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerAttribute(pvd##classID.classHandle, #attributeID, OmniPvdDataType::eSTRING, 1);
#define OMNI_PVD_ATTRIBUTE_UNIQUE_LIST(classID, attributeID, valueType) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerUniqueListAttribute(pvd##classID.classHandle, #attributeID, OmniPvdDataType::eOBJECT_HANDLE);
#define OMNI_PVD_ATTRIBUTE_FLAG(classID, attributeID, enumType, enumID) \
\
pvd##classID.attributeID = OMNI_PVD_WRITER_VAR.registerFlagsAttribute(pvd##classID.classHandle, #attributeID, pvd##enumID.classHandle);
#define OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, value) \
\
OMNI_PVD_WRITER_VAR.registerEnumValue(pvd##enumID.classHandle, #enumEntryID, value);
#define OMNI_PVD_ENUM_VALUE(enumID, enumEntryID) \
\
OMNI_PVD_ENUM_VALUE_EXPLICIT(enumID, enumEntryID, enumID::enumEntryID)
| 5,083 | C | 48.359223 | 148 | 0.674208 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxActor/VhPhysXActorFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandStates.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorFunctions.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
#include "PxRigidDynamic.h"
#include "PxArticulationLink.h"
#include "PxArticulationReducedCoordinate.h"
namespace physx
{
namespace vehicle2
{
void PxVehiclePhysxActorWakeup(
const PxVehicleCommandState& commands,
const PxVehicleEngineDriveTransmissionCommandState* transmissionCommands,
const PxVehicleGearboxParams* gearParams,
const PxVehicleGearboxState* gearState,
PxRigidBody& physxActor,
PxVehiclePhysXSteerState& physxSteerState)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorWakeup: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
PxArticulationLink* link = physxActor.is<PxArticulationLink>();
bool intentToChangeState = ((commands.throttle != 0.0f) || ((PX_VEHICLE_UNSPECIFIED_STEER_STATE != physxSteerState.previousSteerCommand) && (commands.steer != physxSteerState.previousSteerCommand)));
if (!intentToChangeState && transmissionCommands)
{
PX_ASSERT(gearParams);
PX_ASSERT(gearState);
// Manual gear switch (includes going from neutral or reverse to automatic)
intentToChangeState = (gearState->currentGear == gearState->targetGear) &&
(((transmissionCommands->targetGear != PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR) && (gearState->targetGear != transmissionCommands->targetGear)) ||
((transmissionCommands->targetGear == PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR) && (gearState->currentGear <= gearParams->neutralGear)));
}
if(rd && rd->isSleeping() && intentToChangeState)
{
rd->wakeUp();
}
else if(link && link->getArticulation().isSleeping() && intentToChangeState)
{
link->getArticulation().wakeUp();
}
physxSteerState.previousSteerCommand = commands.steer;
}
bool PxVehiclePhysxActorSleepCheck
(const PxVehicleAxleDescription& axleDescription,
const PxRigidBody& physxActor,
const PxVehicleEngineParams* engineParams,
PxVehicleRigidBodyState& rigidBodyState,
PxVehiclePhysXConstraints& physxConstraints,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
PxVehicleEngineState* engineState)
{
PX_CHECK_AND_RETURN_VAL(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorSleepCheck: physxActor is kinematic. This is not supported", false);
const PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
const PxArticulationLink* link = physxActor.is<PxArticulationLink>();
bool isSleeping = false;
if (rd && rd->isSleeping())
{
isSleeping = true;
}
else if (link && link->getArticulation().isSleeping())
{
isSleeping = true;
}
if (isSleeping)
{
// note: pose is not copied as isSleeping() implies that pose was not changed by the
// simulation step (see docu). If a user explicitly calls putToSleep or manually
// changes pose, it will only get reflected in the vehicle rigid body state once
// the body wakes up.
rigidBodyState.linearVelocity = PxVec3(PxZero);
rigidBodyState.angularVelocity = PxVec3(PxZero);
rigidBodyState.previousLinearVelocity = PxVec3(PxZero);
rigidBodyState.previousAngularVelocity = PxVec3(PxZero);
bool markConstraintsDirty = false;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
PxVehicleWheelRigidBody1dState& wheelState = wheelRigidBody1dStates[wheelId];
wheelState.rotationSpeed = 0.0f;
wheelState.correctedRotationSpeed = 0.0f;
// disable constraints if there are active ones. The idea is that if something
// is crashing into a sleeping vehicle and waking it up, then the vehicle should
// be able to move if the impact was large enough. Thus, there is also no logic
// to reset the sticky tire timers, for example. If the impact was small, the
// constraints should potentially kick in again in the subsequent sim step.
PxVehiclePhysXConstraintState& constraintState = physxConstraints.constraintStates[wheelId];
if (constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ||
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] ||
constraintState.suspActiveStatus)
{
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = false;
constraintState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] = false;
constraintState.suspActiveStatus = false;
markConstraintsDirty = true;
}
}
if (markConstraintsDirty)
PxVehicleConstraintsDirtyStateUpdate(physxConstraints);
if (engineState)
{
PX_ASSERT(engineParams);
engineState->rotationSpeed = engineParams->idleOmega;
}
}
return isSleeping;
}
PX_FORCE_INLINE static void setWakeCounter(const PxReal wakeCounter, PxRigidDynamic* rd, PxArticulationLink* link)
{
if (rd && (!(rd->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
rd->setWakeCounter(wakeCounter);
}
else if (link)
{
link->getArticulation().setWakeCounter(wakeCounter);
}
}
void PxVehiclePhysxActorKeepAwakeCheck
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxReal wakeCounterThreshold,
const PxReal wakeCounterResetValue,
const PxVehicleGearboxState* gearState,
const PxReal* throttle,
PxRigidBody& physxActor)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehiclePhysxActorKeepAwakeCheck: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
PxArticulationLink* link = physxActor.is<PxArticulationLink>();
PxReal wakeCounter = PX_MAX_REAL;
if (rd)
{
wakeCounter = rd->getWakeCounter();
}
else if (link)
{
wakeCounter = link->getArticulation().getWakeCounter();
}
if (wakeCounter < wakeCounterThreshold)
{
if ((throttle && ((*throttle) > 0.0f)) ||
(gearState && (gearState->currentGear != gearState->targetGear)))
{
setWakeCounter(wakeCounterResetValue, rd, link);
return;
}
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
const PxVehicleWheelParams& wheelParam = wheelParams[wheelId];
const PxVehicleWheelRigidBody1dState& wheelState = wheelRigidBody1dStates[wheelId];
// note: the translational part of the energy is ignored here as this is mainly for
// scenarios where there is almost no translation but the wheels are spinning
const PxReal normalizedEnergy = (0.5f * wheelState.correctedRotationSpeed * wheelState.correctedRotationSpeed *
wheelParam.moi) / wheelParam.mass;
PxReal sleepThreshold = PX_MAX_REAL;
if (rd)
{
sleepThreshold = rd->getSleepThreshold();
}
else if (link)
{
sleepThreshold = link->getArticulation().getSleepThreshold();
}
if (normalizedEnergy > sleepThreshold)
{
setWakeCounter(wakeCounterResetValue, rd, link);
return;
}
}
}
}
void PxVehicleReadRigidBodyStateFromPhysXActor
(const PxRigidBody& physxActor,
PxVehicleRigidBodyState& rigidBodyState)
{
PX_CHECK_AND_RETURN(!(physxActor.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleReadRigidBodyStateFromPhysXActor: physxActor is kinematic. This is not supported");
const PxRigidDynamic* rd = physxActor.is<PxRigidDynamic>();
const PxArticulationLink* link = physxActor.is<PxArticulationLink>();
PX_ASSERT(rd || link);
if(rd)
{
rigidBodyState.pose = physxActor.getGlobalPose()*physxActor.getCMassLocalPose();
rigidBodyState.angularVelocity = rd->getAngularVelocity();
rigidBodyState.linearVelocity = rd->getLinearVelocity();
}
else
{
rigidBodyState.pose = physxActor.getGlobalPose()*physxActor.getCMassLocalPose();
rigidBodyState.angularVelocity = link->getAngularVelocity();
rigidBodyState.linearVelocity = link->getLinearVelocity();
}
rigidBodyState.previousLinearVelocity = rigidBodyState.linearVelocity;
rigidBodyState.previousAngularVelocity = rigidBodyState.angularVelocity;
}
void PxVehicleWriteWheelLocalPoseToPhysXWheelShape
(const PxTransform& wheelLocalPose, const PxTransform& wheelShapeLocalPose, PxShape* shape)
{
if(!shape)
return;
PxRigidActor* ra = shape->getActor();
if(!ra)
return;
PxRigidBody* rb = ra->is<PxRigidBody>();
if(!rb)
return;
PX_CHECK_AND_RETURN(!(rb->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleWriteWheelLocalPoseToPhysXWheelShape: shape is attached to a kinematic actor. This is not supported");
//Local pose in actor frame.
const PxTransform& localPoseCMassFrame = wheelLocalPose*wheelShapeLocalPose;
const PxTransform cmassLocalPose = rb->getCMassLocalPose();
const PxTransform localPoseActorFrame = cmassLocalPose * localPoseCMassFrame;
//Apply the local pose to the shape.
shape->setLocalPose(localPoseActorFrame);
}
void PxVehicleWriteRigidBodyStateToPhysXActor
(const PxVehiclePhysXActorUpdateMode::Enum updateMode,
const PxVehicleRigidBodyState& rigidBodyState,
const PxReal dt,
PxRigidBody& rb)
{
PX_CHECK_AND_RETURN(!(rb.getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC), "PxVehicleWriteRigidBodyStateToPhysXActor: physxActor is kinematic. This is not supported");
PxRigidDynamic* rd = rb.is<PxRigidDynamic>();
PxArticulationLink* link = rb.is<PxArticulationLink>();
PX_ASSERT(rd || link);
if(rb.getScene() && // check for scene to support immediate mode style vehicles
((rd && rd->isSleeping()) || (link && link->getArticulation().isSleeping())))
{
// note: sort of a safety mechanism to be able to keep running the full vehicle pipeline
// even if the physx actor fell asleep. Without it, the vehicle state can drift from
// physx actor state in the course of multiple simulation steps up to the point
// where the physx actor suddenly wakes up.
return;
}
switch (updateMode)
{
case PxVehiclePhysXActorUpdateMode::eAPPLY_VELOCITY:
{
PX_ASSERT(rd);
rd->setLinearVelocity(rigidBodyState.linearVelocity, false);
rd->setAngularVelocity(rigidBodyState.angularVelocity, false);
}
break;
case PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION:
{
const PxVec3 linAccel = (rigidBodyState.linearVelocity - rigidBodyState.previousLinearVelocity)/dt;
const PxVec3 angAccel = (rigidBodyState.angularVelocity - rigidBodyState.previousAngularVelocity)/dt;
if (rd)
{
rd->addForce(linAccel, PxForceMode::eACCELERATION, false);
rd->addTorque(angAccel, PxForceMode::eACCELERATION, false);
}
else
{
PX_ASSERT(link);
link->addForce(linAccel, PxForceMode::eACCELERATION, false);
link->addTorque(angAccel, PxForceMode::eACCELERATION, false);
}
}
break;
default:
break;
}
}
} //namespace vehicle2
} //namespace physx
| 13,124 | C++ | 36.393162 | 200 | 0.770344 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxActor/VhPhysXActorHelpers.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorHelpers.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "cooking/PxCooking.h"
#include "PxPhysics.h"
#include "PxRigidDynamic.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxArticulationLink.h"
#include "PxScene.h"
#include "extensions/PxDefaultStreams.h"
namespace physx
{
namespace vehicle2
{
void createShapes(
const PxVehicleFrame& vehicleFrame,
const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams,
const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams,
PxRigidBody* rd,
PxPhysics& physics, const PxCookingParams& params,
PxVehiclePhysXActor& vehiclePhysXActor)
{
//Create a shape for the vehicle body.
{
PxShape* shape = physics.createShape(rigidActorShapeParams.geometry, rigidActorShapeParams.material, true);
shape->setLocalPose(rigidActorShapeParams.localPose);
shape->setFlags(rigidActorShapeParams.flags);
shape->setSimulationFilterData(rigidActorShapeParams.simulationFilterData);
shape->setQueryFilterData(rigidActorShapeParams.queryFilterData);
rd->attachShape(*shape);
shape->release();
}
//Create shapes for wheels.
for (PxU32 i = 0; i < wheelParams.axleDescription.nbWheels; i++)
{
const PxU32 wheelId = wheelParams.axleDescription.wheelIdsInAxleOrder[i];
const PxF32 radius = wheelParams.wheelParams[wheelId].radius;
const PxF32 halfWidth = wheelParams.wheelParams[wheelId].halfWidth;
PxVec3 verts[32];
for (PxU32 k = 0; k < 16; k++)
{
const PxF32 lng = radius * PxCos(k*2.0f*PxPi / 16.0f);
const PxF32 lat = halfWidth;
const PxF32 vrt = radius * PxSin(k*2.0f*PxPi / 16.0f);
const PxVec3 pos0 = vehicleFrame.getFrame()*PxVec3(lng, lat, vrt);
const PxVec3 pos1 = vehicleFrame.getFrame()*PxVec3(lng, -lat, vrt);
verts[2 * k + 0] = pos0;
verts[2 * k + 1] = pos1;
}
// Create descriptor for convex mesh
PxConvexMeshDesc convexDesc;
convexDesc.points.count = 32;
convexDesc.points.stride = sizeof(PxVec3);
convexDesc.points.data = verts;
convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX;
PxConvexMesh* convexMesh = NULL;
PxDefaultMemoryOutputStream buf;
if (PxCookConvexMesh(params, convexDesc, buf))
{
PxDefaultMemoryInputData id(buf.getData(), buf.getSize());
convexMesh = physics.createConvexMesh(id);
}
PxConvexMeshGeometry convexMeshGeom(convexMesh);
PxShape* wheelShape = physics.createShape(convexMeshGeom, wheelShapeParams.material, true);
wheelShape->setFlags(wheelShapeParams.flags);
wheelShape->setSimulationFilterData(wheelShapeParams.simulationFilterData);
wheelShape->setQueryFilterData(wheelShapeParams.queryFilterData);
rd->attachShape(*wheelShape);
wheelShape->release();
convexMesh->release();
vehiclePhysXActor.wheelShapes[wheelId] = wheelShape;
}
}
void PxVehiclePhysXActorCreate
(const PxVehicleFrame& vehicleFrame,
const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose,
const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams,
const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams,
PxPhysics& physics, const PxCookingParams& params,
PxVehiclePhysXActor& vehiclePhysXActor)
{
PxRigidDynamic* rd = physics.createRigidDynamic(PxTransform(PxIdentity));
vehiclePhysXActor.rigidBody = rd;
PxVehiclePhysXActorConfigure(rigidActorParams, rigidActorCmassLocalPose, *rd);
createShapes(vehicleFrame, rigidActorShapeParams, wheelParams, wheelShapeParams, rd, physics, params, vehiclePhysXActor);
}
void PxVehiclePhysXActorConfigure
(const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose,
PxRigidBody& rigidBody)
{
rigidBody.setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, false);
rigidBody.setCMassLocalPose(rigidActorCmassLocalPose);
rigidBody.setMass(rigidActorParams.rigidBodyParams.mass);
rigidBody.setMassSpaceInertiaTensor(rigidActorParams.rigidBodyParams.moi);
rigidBody.setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
rigidBody.setName(rigidActorParams.physxActorName);
}
void PxVehiclePhysXArticulationLinkCreate
(const PxVehicleFrame& vehicleFrame,
const PxVehiclePhysXRigidActorParams& rigidActorParams, const PxTransform& rigidActorCmassLocalPose,
const PxVehiclePhysXRigidActorShapeParams& rigidActorShapeParams,
const PxVehiclePhysXWheelParams& wheelParams, const PxVehiclePhysXWheelShapeParams& wheelShapeParams,
PxPhysics& physics, const PxCookingParams& params,
PxVehiclePhysXActor& vehiclePhysXActor)
{
PxArticulationReducedCoordinate* art = physics.createArticulationReducedCoordinate();
PxArticulationLink* link = art->createLink(NULL, PxTransform(PxIdentity));
vehiclePhysXActor.rigidBody = link;
PxVehiclePhysXActorConfigure(rigidActorParams, rigidActorCmassLocalPose, *link);
createShapes(vehicleFrame, rigidActorShapeParams, wheelParams, wheelShapeParams, link, physics, params, vehiclePhysXActor);
}
void PxVehiclePhysXActorDestroy
(PxVehiclePhysXActor& vehiclePhysXActor)
{
PxRigidDynamic* rd = vehiclePhysXActor.rigidBody->is<PxRigidDynamic>();
PxArticulationLink* link = vehiclePhysXActor.rigidBody->is<PxArticulationLink>();
if(rd)
{
rd->release();
vehiclePhysXActor.rigidBody = NULL;
}
else if(link)
{
PxArticulationReducedCoordinate& articulation = link->getArticulation();
PxScene* scene = articulation.getScene();
if(scene)
{
scene->removeArticulation(articulation);
}
articulation.release();
vehiclePhysXActor.rigidBody = NULL;
}
}
} //namespace vehicle2
} //namespace physx
| 7,572 | C++ | 39.068783 | 124 | 0.795695 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/rigidBody/VhRigidBodyFunctions.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/PxMat33.h"
#include "foundation/PxTransform.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyFunctions.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE void transformInertiaTensor(const PxVec3& invD, const PxMat33& M, PxMat33& mIInv)
{
const float axx = invD.x*M(0, 0), axy = invD.x*M(1, 0), axz = invD.x*M(2, 0);
const float byx = invD.y*M(0, 1), byy = invD.y*M(1, 1), byz = invD.y*M(2, 1);
const float czx = invD.z*M(0, 2), czy = invD.z*M(1, 2), czz = invD.z*M(2, 2);
mIInv(0, 0) = axx * M(0, 0) + byx * M(0, 1) + czx * M(0, 2);
mIInv(1, 1) = axy * M(1, 0) + byy * M(1, 1) + czy * M(1, 2);
mIInv(2, 2) = axz * M(2, 0) + byz * M(2, 1) + czz * M(2, 2);
mIInv(0, 1) = mIInv(1, 0) = axx * M(1, 0) + byx * M(1, 1) + czx * M(1, 2);
mIInv(0, 2) = mIInv(2, 0) = axx * M(2, 0) + byx * M(2, 1) + czx * M(2, 2);
mIInv(1, 2) = mIInv(2, 1) = axy * M(2, 0) + byy * M(2, 1) + czy * M(2, 2);
}
PX_FORCE_INLINE void integrateBody
(const PxF32 mass, const PxVec3& moi, const PxVec3& force, const PxVec3& torque, const PxF32 dt,
PxVec3& linvel, PxVec3& angvel, PxTransform& t)
{
const PxF32 inverseMass = 1.0f/mass;
const PxVec3 inverseMOI(1.0f/moi.x, 1.0f/moi.y, 1.0f/moi.z);
//Integrate linear velocity.
linvel += force * (inverseMass*dt);
//Integrate angular velocity.
PxMat33 inverseInertia;
transformInertiaTensor(inverseMOI, PxMat33(t.q), inverseInertia);
angvel += inverseInertia * (torque*dt);
//Integrate position.
t.p += linvel * dt;
//Integrate quaternion.
PxQuat wq(angvel.x, angvel.y, angvel.z, 0.0f);
PxQuat q = t.q;
PxQuat qdot = wq * q*(dt*0.5f);
q += qdot;
q.normalize();
t.q = q;
}
void PxVehicleRigidBodyUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleRigidBodyParams& rigidBodyParams,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxReal dt, const PxVec3& gravity,
PxVehicleRigidBodyState& rigidBodyState)
{
//Sum all the forces and torques.
const PxU32 nbAxles = axleDescription.getNbAxles();
PxVec3 force(PxZero);
PxVec3 torque(PxZero);
for (PxU32 i = 0; i < nbAxles; i++)
{
PxVec3 axleSuspForce(PxZero);
PxVec3 axleTireLongForce(PxZero);
PxVec3 axleTireLatForce(PxZero);
PxVec3 axleSuspTorque(PxZero);
PxVec3 axleTireLongTorque(PxZero);
PxVec3 axleTireLatTorque(PxZero);
for (PxU32 j = 0; j < axleDescription.getNbWheelsOnAxle(i); j++)
{
const PxU32 wheelId = axleDescription.getWheelOnAxle(j, i);
const PxVehicleSuspensionForce& suspForce = suspensionForces[wheelId];
const PxVehicleTireForce& tireForce = tireForces[wheelId];
axleSuspForce += suspForce.force;
axleTireLongForce += tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL];
axleTireLatForce += tireForce.forces[PxVehicleTireDirectionModes::eLATERAL];
axleSuspTorque += suspForce.torque;
axleTireLongTorque += tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL];
axleTireLatTorque += tireForce.torques[PxVehicleTireDirectionModes::eLATERAL];
}
const PxVec3 axleForce = axleSuspForce + axleTireLongForce + axleTireLatForce;
const PxVec3 axleTorque = axleSuspTorque + axleTireLongTorque + axleTireLatTorque;
force += axleForce;
torque += axleTorque;
}
force += gravity * rigidBodyParams.mass;
force += rigidBodyState.externalForce;
torque += rigidBodyState.externalTorque;
torque += (antiRollTorque ? antiRollTorque->antiRollTorque : PxVec3(PxZero));
//Rigid body params.
const PxF32 mass = rigidBodyParams.mass;
const PxVec3& moi = rigidBodyParams.moi;
//Perform the integration.
PxTransform& t = rigidBodyState.pose;
PxVec3& linvel = rigidBodyState.linearVelocity;
PxVec3& angvel = rigidBodyState.angularVelocity;
integrateBody(
mass, moi,
force, torque, dt,
linvel, angvel, t);
//Reset the accumulated external forces after using them.
rigidBodyState.externalForce = PxVec3(PxZero);
rigidBodyState.externalTorque = PxVec3(PxZero);
}
} //namespace vehicle2
} //namespace physx
| 6,054 | C++ | 39.099337 | 99 | 0.736373 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/wheel/VhWheelFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelFunctions.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleWheelRotationAngleUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleWheelActuationState& actState, const PxVehicleSuspensionState& suspState, const PxVehicleTireSpeedState& trSpeedState,
const PxReal thresholdForwardSpeedForWheelAngleIntegration, const PxReal dt,
PxVehicleWheelRigidBody1dState& whlRigidBody1dState)
{
//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
const PxF32 jounce = suspState.jounce;
const bool isBrakeApplied = actState.isBrakeApplied;
const bool isDriveApplied = actState.isDriveApplied;
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 absLngSpeed = PxAbs(lngSpeed);
PxF32 wheelOmega = whlRigidBody1dState.rotationSpeed;
if (jounce > 0 && //(i) wheel touching ground
!isBrakeApplied && //(ii) no brake applied
!isDriveApplied && //(iii) no drive torque applied
(absLngSpeed < thresholdForwardSpeedForWheelAngleIntegration)) //(iv) low speed
{
const PxF32 wheelRadius = whlParams.radius;
const PxF32 alpha = absLngSpeed / thresholdForwardSpeedForWheelAngleIntegration;
wheelOmega = (lngSpeed/wheelRadius)*(1.0f - alpha) + wheelOmega * alpha;
}
whlRigidBody1dState.correctedRotationSpeed = wheelOmega;
//Integrate angle.
PxF32 newRotAngle = whlRigidBody1dState.rotationAngle + wheelOmega * dt;
//Clamp in range (-2*Pi,2*Pi)
newRotAngle = newRotAngle - (PxI32(newRotAngle / PxTwoPi) * PxTwoPi);
//Set the angle.
whlRigidBody1dState.rotationAngle = newRotAngle;
}
} //namespace vehicle2
} //namespace physx
| 4,222 | C++ | 44.408602 | 134 | 0.763382 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/suspension/VhSuspensionFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionFunctions.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
namespace physx
{
namespace vehicle2
{
#define VH_SUSPENSION_NO_INTERSECTION_MARKER FLT_MIN
PX_FORCE_INLINE void computeJounceAndSeparation(const PxF32 depth, const PxF32 suspDirDotPlaneNormal,
const PxF32 suspTravelDist, const PxF32 previousJounce,
PxF32& jounce, PxF32& separation)
{
if (suspDirDotPlaneNormal != 0.0f)
{
if (depth <= 0.0f)
{
//There is overlap at max droop
const PxF32 suspDeltaToDepthZero = depth / suspDirDotPlaneNormal;
if ((suspDeltaToDepthZero > 0.0f) && (suspDeltaToDepthZero <= suspTravelDist))
{
//The wheel can be placed on the plane for a jounce between max droop and max compression.
jounce = suspDeltaToDepthZero;
separation = 0.0f;
}
else
{
if (suspDeltaToDepthZero > suspTravelDist)
{
//There is overlap even at max compression. Compute the depth at max
//compression.
jounce = suspTravelDist;
separation = (depth * (suspDeltaToDepthZero - suspTravelDist)) / suspDeltaToDepthZero;
}
else
{
PX_ASSERT(suspDeltaToDepthZero <= 0.0f);
//There is overlap at max droop and in addition, the suspension would have to expand
//beyond max droop to move out of plane contact. This scenario can be reached, for
//example, if a car rolls over or if something touches a wheel from "above".
jounce = 0.0f;
separation = depth;
}
}
}
else
{
//At max droop there is no overlap => let the suspension fully expand.
//Note that this check is important because without it, you can get unexpected
//behavior like the wheel compressing just so that it touches the plane again.
jounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
}
else
{
//The suspension direction and hit normal are perpendicular, thus no change to
//suspension jounce will change the distance to the plane.
if (depth >= 0.0f)
{
jounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
else
{
jounce = (previousJounce != PX_VEHICLE_UNSPECIFIED_JOUNCE) ? previousJounce : suspTravelDist;
separation = depth;
// note: since The suspension direction and hit normal are perpendicular, the
// depth will be the same for all jounce values
}
}
}
PX_FORCE_INLINE void intersectRayPlane
(const PxVehicleFrame& frame, const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 previousJounce,
PxVec3& suspDir, PxF32& jounce, PxF32& separation)
{
//Compute the position on the wheel surface along the suspension direction that is closest to
//the plane (for the purpose of computing the separation from the plane). The wheel center position
//is chosen at max droop (zero jounce).
PxVehicleSuspensionState suspState;
suspState.setToDefault(0.0f);
const PxTransform wheelPose = PxVehicleComputeWheelPose(frame, suspParams, suspState, 0.0f, 0.0f, steerAngle,
rigidBodyState.pose, 0.0f);
suspDir = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxPlane& hitPlane = roadGeomState.plane;
const PxF32 suspDirDotPlaneNormal = suspDir.dot(hitPlane.n);
PxVec3 wheelRefPoint;
if (suspDirDotPlaneNormal < 0.0f)
{
wheelRefPoint = wheelPose.p + (suspDir * wheelParams.radius);
//The "wheel bottom" has to be placed on the plane to resolve collision
}
else if (suspDirDotPlaneNormal > 0.0f)
{
wheelRefPoint = wheelPose.p - (suspDir * wheelParams.radius);
//The "wheel top" has to be placed on the plane to resolve collision
}
else
{
//The hit normal and susp dir are prependicular
//-> any point along the suspension direction will do to compute the depth
wheelRefPoint = wheelPose.p;
}
//Compute the penetration depth of the reference point with respect to the plane
const PxF32 depth = hitPlane.n.dot(wheelRefPoint) + hitPlane.d;
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
computeJounceAndSeparation(depth, suspDirDotPlaneNormal, suspParams.suspensionTravelDist, previousJounce,
jounce, separation);
}
PX_FORCE_INLINE 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;
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;
return 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 true;
}
// This method computes how much a wheel cylinder object at max droop (fully elongated suspension)
// has to be pushed along the suspension direction to end up just touching the plane provided in
// the road geometry state.
//
// output:
// suspDir: suspension direction in the world frame
// jounce: the suspension jounce.
// jounce=0 the wheel is at max droop
// jounce>0 the suspension is compressed by length jounce (up to max compression = suspensionTravelDist)
//
// The jounce value will be set to 0 (in the case of no overlap) or to the previous jounce
// (in the case of overlap) for the following special cases:
// - the plane normal and the wheel lateral axis are parallel
// - the plane normal and the suspension direction are perpendicular
// separation: 0 if the suspension can move between max droop and max compression to place
// the wheel on the ground.
// A negative value denotes by how much the wheel cylinder penetrates (along the hit
// plane normal) into the ground for the computed jounce.
// A positive value denotes that the wheel does not touch the ground.
//
PX_FORCE_INLINE void intersectCylinderPlane
(const PxVehicleFrame& frame,
const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 previousJounce,
PxVec3& suspDir, PxF32& jounce, PxF32& separation)
{
const PxPlane& hitPlane = roadGeomState.plane;
const PxF32 radius = whlParams.radius;
const PxF32 halfWidth = whlParams.halfWidth;
//Compute the wheel pose at zero jounce ie at max droop.
PxTransform wheelPoseAtZeroJounce;
{
PxTransform start;
PxF32 dist;
PxVehicleComputeSuspensionSweep(frame, suspParams, steerAngle, rigidBodyState.pose, start, suspDir, dist);
wheelPoseAtZeroJounce = PxTransform(start.p + suspDir*dist, start.q);
}
//Compute the plane of the wheel.
PxPlane wheelPlane;
{
wheelPlane = PxPlane(wheelPoseAtZeroJounce.p, wheelPoseAtZeroJounce.rotate(frame.getLatAxis()));
}
//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);
PxF32 depth;
if (intersectPlaneSuccess)
{
//Compute the position on the intersection edge that is closest to the wheel centre.
PxVec3 closestPointOnIntersectionEdge;
{
const PxVec3& p = wheelPoseAtZeroJounce.p;
const PxVec3& dir = intersectionEdgeW;
const PxVec3& v = intersectionEdgeV;
const PxF32 t = (p - v).dot(dir);
closestPointOnIntersectionEdge = v + dir * 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();
}
//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;
//Now compute the maximum depth of the inside and outside discs against the plane.
{
const PxVec3& latDir = wheelPlane.n;
const PxF32 signDot = PxVehicleComputeSign(hitPlane.n.dot(latDir));
const PxVec3 deepestPos = pos - latDir * (signDot*halfWidth);
depth = hitPlane.n.dot(deepestPos) + hitPlane.d;
}
}
else
{
//The hit plane normal and the wheel lateral axis are parallel
//Now compute the maximum depth of the inside and outside discs against the plane.
const PxVec3& latDir = wheelPlane.n;
const PxF32 signDot = PxVehicleComputeSign(hitPlane.n.dot(latDir));
depth = hitPlane.d - halfWidth - (signDot*wheelPlane.d);
// examples:
// halfWidth = 0.5
//
// wheelPlane.d hitplane.d depth
//=============================================
// -3 -> -3.5 -> -1
// 3 <- -3.5 -> -1
//
// -3 -> 3.5 <- 0
// 3 <- 3.5 <- 0
//
}
//How far along the susp dir do we have to move to place the wheel exactly on the plane.
const PxF32 suspDirDotPlaneNormal = hitPlane.n.dot(suspDir);
computeJounceAndSeparation(depth, suspDirDotPlaneNormal, suspParams.suspensionTravelDist, previousJounce,
jounce, separation);
}
static void limitSuspensionExpansionVelocity
(const PxReal jounceSpeed, const PxReal previousJounceSpeed, const PxReal previousJounce,
const PxReal suspStiffness, const PxReal suspDamping,
const PxVec3& suspDirWorld, const PxReal wheelMass,
const PxReal dt, const PxVec3& gravity, const bool hasGroundHit,
PxVehicleSuspensionState& suspState)
{
PX_ASSERT(jounceSpeed < 0.0f); // don't call this method if the suspension is not expanding
// The suspension is expanding. Check if the suspension can expand fast enough to actually reach the
// target jounce within the given time step.
// Without the suspension elongating, the wheel would end up in the air. Compute the suspension force
// that pushes the wheel towards the ground. Note that gravity is ignored here as it applies to sprung
// mass and wheel equally.
const PxReal springForceAlongSuspDir = (previousJounce * suspStiffness);
const PxReal suspDirVelSpring = (springForceAlongSuspDir / wheelMass) * dt;
const PxReal dampingForceAlongSuspDir = (previousJounceSpeed * suspDamping); // note: negative jounce speed = expanding
const PxReal suspDirVelDamping = (dampingForceAlongSuspDir / wheelMass) * dt;
PxReal suspDirVel = suspDirVelSpring - previousJounceSpeed;
// add damping part but such that it does not flip the velocity sign (covering case of
// crazily high damping values)
const PxReal suspDirVelTmp = suspDirVel + suspDirVelDamping;
if (suspDirVel >= 0.0f)
suspDirVel = PxMax(0.0f, suspDirVelTmp);
else
suspDirVel = PxMin(0.0f, suspDirVelTmp);
const PxReal gravitySuspDir = gravity.dot(suspDirWorld);
PxReal velocityThreshold;
if (hasGroundHit)
{
velocityThreshold = (gravitySuspDir > 0.0f) ? suspDirVel + (gravitySuspDir * dt) : suspDirVel;
// gravity is considered too as it affects the wheel and can close the distance to the ground
// too. External forces acting on the sprung mass are ignored as those propagate
// through the suspension to the wheel.
// If gravity points in the opposite direction of the suspension travel direction, it is
// ignored. The suspension should never elongate more than what's given by the current delta
// jounce (defined by jounceSpeed, i.e., jounceSpeed < -suspDirVel has to hold all the time
// for the clamping to take place).
}
else
{
velocityThreshold = suspDirVel;
// if there was no hit detected, the gravity will not be taken into account since there is no
// ground to move towards.
}
if (jounceSpeed < (-velocityThreshold))
{
// The suspension can not expand fast enough to place the wheel on the ground. As a result,
// the scenario is interpreted as if there was no hit and the wheels end up in air. The
// jounce is adjusted based on the clamped velocity to not have it snap to the target immediately.
// note: could consider applying the suspension force to the sprung mass too but the complexity
// seems high enough already.
const PxReal expansionDelta = suspDirVel * dt;
const PxReal clampedJounce = previousJounce - expansionDelta;
PX_ASSERT(clampedJounce >= 0.0f);
// No need to cover the case of a negative jounce as the input jounce speed is expected to make
// sure that no negative jounce would result (and the speed considered here is smaller than the
// non-clamped input jounce speed).
if (suspState.separation >= 0.0f) // do not adjust separation if ground penetration was detected
{
suspState.separation = clampedJounce - suspState.jounce;
}
suspState.jounce = clampedJounce;
suspState.jounceSpeed = -suspDirVel;
}
}
void PxVehicleSuspensionStateUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams, const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const PxReal suspStiffness, const PxReal suspDamping,
const PxF32 steerAngle, const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxReal dt, const PxVehicleFrame& frame, const PxVec3& gravity,
PxVehicleSuspensionState& suspState)
{
const PxReal prevJounce = suspState.jounce;
const PxReal prevJounceSpeed = suspState.jounceSpeed;
suspState.setToDefault(0.0f, VH_SUSPENSION_NO_INTERSECTION_MARKER);
if(!roadGeomState.hitState)
{
if (suspStateCalcParams.limitSuspensionExpansionVelocity && (prevJounce != PX_VEHICLE_UNSPECIFIED_JOUNCE))
{
if (prevJounce > 0.0f)
{
PX_ASSERT(suspState.jounce == 0.0f); // the expectation is that setToDefault() above does this
const PxReal jounceSpeed = (-prevJounce) / dt;
const PxVec3 suspDirWorld = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
limitSuspensionExpansionVelocity(jounceSpeed, prevJounceSpeed, prevJounce,
suspStiffness, suspDamping, suspDirWorld, whlParams.mass, dt, gravity, false,
suspState);
}
}
return;
}
PxVec3 suspDir;
PxF32 currJounce;
PxF32 separation;
switch(suspStateCalcParams.suspensionJounceCalculationType)
{
case PxVehicleSuspensionJounceCalculationType::eRAYCAST:
{
//Compute the distance along the suspension direction that places the wheel on the ground plane.
intersectRayPlane(frame, whlParams, suspParams, steerAngle, roadGeomState, rigidBodyState,
prevJounce,
suspDir, currJounce, separation);
}
break;
case PxVehicleSuspensionJounceCalculationType::eSWEEP:
{
//Compute the distance along the suspension direction that places the wheel on the ground plane.
intersectCylinderPlane(frame, whlParams, suspParams, steerAngle, roadGeomState, rigidBodyState,
prevJounce,
suspDir, currJounce, separation);
}
break;
default:
{
PX_ASSERT(false);
currJounce = 0.0f;
separation = VH_SUSPENSION_NO_INTERSECTION_MARKER;
}
break;
}
suspState.jounce = currJounce;
suspState.jounceSpeed = (PX_VEHICLE_UNSPECIFIED_JOUNCE != prevJounce) ? (currJounce - prevJounce) / dt : 0.0f;
suspState.separation = separation;
if (suspStateCalcParams.limitSuspensionExpansionVelocity && (suspState.jounceSpeed < 0.0f))
{
limitSuspensionExpansionVelocity(suspState.jounceSpeed, prevJounceSpeed, prevJounce,
suspStiffness, suspDamping, suspDir, whlParams.mass, dt, gravity, true,
suspState);
}
}
void PxVehicleSuspensionComplianceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionComplianceParams& compParams,
const PxVehicleSuspensionState& suspState,
PxVehicleSuspensionComplianceState& compState)
{
compState.setToDefault();
//Compliance is normalised in range (0,1) with:
//0 being fully elongated (ie jounce = 0)
//1 being fully compressed (ie jounce = maxTravelDist)
const PxF32 jounce = suspState.jounce;
const PxF32 maxTravelDist = suspParams.suspensionTravelDist;
const PxF32 r = jounce/maxTravelDist;
//Camber and toe relative the wheel reference pose.
{
compState.camber = compParams.wheelCamberAngle.interpolate(r);
compState.toe = compParams.wheelToeAngle.interpolate(r);
}
//Tire force application point as an offset from wheel reference pose.
{
compState.tireForceAppPoint = compParams.tireForceAppPoint.interpolate(r);
}
//Susp force application point as an offset from wheel reference pose.
{
compState.suspForceAppPoint = compParams.suspForceAppPoint.interpolate(r);
}
}
PX_FORCE_INLINE void setSuspensionForceAndTorque
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState,
const PxF32 suspForceMagnitude, const PxF32 normalForceMagnitude,
PxVehicleSuspensionForce& suspForce)
{
const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(suspComplianceState.suspForceAppPoint));
const PxVec3 f = roadGeomState.plane.n*suspForceMagnitude;
suspForce.force = f;
suspForce.torque = r.cross(f);
suspForce.normalForce = normalForceMagnitude;
}
void PxVehicleSuspensionForceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionForceParams& suspForceParams,
const PxVehicleRoadGeometryState& roadGeom, const PxVehicleSuspensionState& suspState,
const PxVehicleSuspensionComplianceState& compState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& gravity, const PxReal vehicleMass,
PxVehicleSuspensionForce& suspForces)
{
suspForces.setToDefault();
//If the wheel cannot touch the ground then carry on with zero force.
if (!PxVehicleIsWheelOnGround(suspState))
return;
//For the following computations, the external force Fe acting on the suspension
//is seen as the sum of two forces Fe0 and Fe1. Fe0 acts along the suspension
//direction while Fe1 is the part perpendicular to Fe0. The suspension spring
//force Fs0 works against Fe0, while the suspension "collision" force Fs1 works
//against Fe1 (can be seen as a force that is trying to push the suspension
//into the ground in a direction where the spring can not do anything against
//it because it's perpendicular to the spring direction).
//For the system to be at rest, we require Fs0 = -Fe0 and Fs1 = -Fe1
//The forces Fe0 and Fe1 can each be split further into parts that act along
//the ground patch normal and parts that act parallel to the ground patch.
//Fs0 and Fs1 work against the former as the ground prevents the suspension
//from penetrating. However, to work against the latter, friction would have
//to be considered. The current model does not do this (or rather: it is the
//tire model that deals with forces parallel to the ground patch). As a result,
//only the force parts of Fs0 and Fs1 perpendicular to the ground patch are
//considered here. Furthermore, Fs1 is set to zero, if the external force is
//not pushing the suspension towards the ground patch (imagine a vehicle with
//a "tilted" suspension direction "driving" up a wall. No "collision" force
//should be added in such a scenario).
PxF32 suspForceMagnitude = 0.0f;
{
const PxF32 jounce = suspState.jounce;
const PxF32 stiffness = suspForceParams.stiffness;
const PxF32 jounceSpeed = suspState.jounceSpeed;
const PxF32 damping = suspForceParams.damping;
const PxVec3 suspDirWorld = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxVec3 suspSpringForce = suspDirWorld * (-(jounce*stiffness + jounceSpeed*damping));
const PxF32 suspSpringForceProjected = roadGeom.plane.n.dot(suspSpringForce);
suspForceMagnitude = suspSpringForceProjected;
const PxVec3 comToSuspWorld = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.p);
const PxVec3 externalForceLin = (gravity * vehicleMass) + rigidBodyState.externalForce;
const PxReal comToSuspDistSqr = comToSuspWorld.magnitudeSquared();
PxVec3 externalForceAng;
if (comToSuspDistSqr > 0.0f)
{
// t = r x F
// t x r = (r x F) x r = -[r x (r x F)] = -[((r o F) * r) - ((r o r) * F)]
// r and F perpendicular (r o F = 0) => = (r o r) * F = |r|^2 * F
externalForceAng = (rigidBodyState.externalTorque.cross(comToSuspWorld)) / comToSuspDistSqr;
}
else
externalForceAng = PxVec3(PxZero);
const PxVec3 externalForce = externalForceLin + externalForceAng;
const PxVec3 externalForceSusp = externalForce * (suspForceParams.sprungMass / vehicleMass);
if (roadGeom.plane.n.dot(externalForceSusp) < 0.0f)
{
const PxF32 suspDirExternalForceMagn = suspDirWorld.dot(externalForceSusp);
const PxVec3 collisionForce = externalForceSusp - (suspDirWorld * suspDirExternalForceMagn);
const PxF32 suspCollisionForceProjected = -roadGeom.plane.n.dot(collisionForce);
suspForceMagnitude += suspCollisionForceProjected;
}
}
setSuspensionForceAndTorque(suspParams, roadGeom, compState, rigidBodyState, suspForceMagnitude, suspForceMagnitude, suspForces);
}
void PxVehicleSuspensionLegacyForceUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionForceLegacyParams& suspForceParamsLegacy,
const PxVehicleRoadGeometryState& roadGeomState, const PxVehicleSuspensionState& suspState,
const PxVehicleSuspensionComplianceState& compState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& gravity,
PxVehicleSuspensionForce& suspForces)
{
suspForces.setToDefault();
//If the wheel cannot touch the ground then carry on with zero force.
if (!PxVehicleIsWheelOnGround(suspState))
return;
PxF32 suspForceMagnitude = 0.0f;
{
//Get the params for the legacy model.
//const PxF32 restDistance = suspForceParamsLegacy.restDistance;
const PxF32 sprungMass = suspForceParamsLegacy.sprungMass;
const PxF32 restDistance = suspForceParamsLegacy.restDistance;
//Get the non-legacy params.
const PxF32 stiffness = suspForceParamsLegacy.stiffness;
const PxF32 damperRate = suspForceParamsLegacy.damping;
const PxF32 maxTravelDist = suspParams.suspensionTravelDist;
//Suspension state.
const PxF32 jounce = suspState.jounce;
const PxF32 jounceSpeed = suspState.jounceSpeed;
//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 PxVec3 w = PxVehicleComputeSuspensionDirection(suspParams, rigidBodyState.pose);
const PxF32 gravitySuspDir = gravity.dot(w);
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,
sprungMass*alpha + //force to support sprung mass at zero jounce
stiffness*(jounce + restDistance - maxTravelDist)); //linear spring
suspensionForceW += jounceSpeed * damperRate; //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
suspForceMagnitude = roadGeomState.plane.n.dot(-w * suspensionForceW - TTimesBeta * sprungMass);
}
setSuspensionForceAndTorque(suspParams, roadGeomState, compState, rigidBodyState, suspForceMagnitude, suspForceMagnitude, suspForces);
}
void PxVehicleAntiRollForceUpdate
(const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams,
const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& complianceStates,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehicleAntiRollTorque& antiRollTorque)
{
antiRollTorque.setToDefault();
for (PxU32 i = 0; i < antiRollParams.size; i++)
{
if (antiRollParams[i].stiffness != 0.0f)
{
const PxU32 w0 = antiRollParams[i].wheel0;
const PxU32 w1 = antiRollParams[i].wheel1;
const bool w0InAir = (0.0f == suspensionStates[w0].jounce);
const bool w1InAir = (0.0f == suspensionStates[w1].jounce);
if (!w0InAir || !w1InAir)
{
//Compute the difference in jounce and compute the force.
const PxF32 w0Jounce = suspensionStates[w0].jounce;
const PxF32 w1Jounce = suspensionStates[w1].jounce;
const PxF32 antiRollForceMag = (w0Jounce - w1Jounce) * antiRollParams[i].stiffness;
//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];
const PxVec3& antiRollForceDir = suspensionParams[wheelId].suspensionTravelDir;
const PxVec3 antiRollForce = antiRollForceDir * antiRollForceMags[j];
const PxVec3 r = suspensionParams[wheelId].suspensionAttachment.transform(complianceStates[wheelId].suspForceAppPoint);
antiRollTorque.antiRollTorque += rigidBodyState.pose.rotate(r.cross(antiRollForce));
}
}
}
}
}
} //namespace vehicle2
} //namespace physx
| 28,511 | C++ | 38.710306 | 160 | 0.746344 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/suspension/VhSuspensionHelpers.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
namespace physx
{
namespace vehicle2
{
#define DETERMINANT_THRESHOLD (1e-6f)
bool PxVehicleComputeSprungMasses(const PxU32 numSprungMasses, const PxVec3* sprungMassCoordinates, const PxReal totalMass, const PxVehicleAxes::Enum gravityDir, PxReal* sprungMasses)
{
if (numSprungMasses < 1)
return false;
if (numSprungMasses > PxVehicleLimits::eMAX_NB_WHEELS)
return false;
if (totalMass <= 0.0f)
return false;
if (!sprungMassCoordinates || !sprungMasses)
return false;
const PxVec3 centreOfMass(PxZero);
PxU32 gravityDirection = 0xffffffff;
switch (gravityDir)
{
case PxVehicleAxes::eNegX:
case PxVehicleAxes::ePosX:
gravityDirection = 0;
break;
case PxVehicleAxes::eNegY:
case PxVehicleAxes::ePosY:
gravityDirection = 1;
break;
case PxVehicleAxes::eNegZ:
case PxVehicleAxes::ePosZ:
gravityDirection = 2;
break;
default:
PX_ASSERT(false);
break;
}
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);
if (PxAbs(r0 - r1) <= DETERMINANT_THRESHOLD)
return false;
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;
PxVehicleMatrixNN A(3);
PxVehicleVectorN 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;
PxVehicleVectorN result(3);
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(A);
if (PxAbs(solver.getDet()) <= DETERMINANT_THRESHOLD)
return false;
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
PxVehicleMatrixNN A(numSprungMasses + 3);
PxVehicleVectorN 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
PxVehicleVectorN result(numSprungMasses + 3);
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(A);
solver.solve(b, result);
if (PxAbs(solver.getDet()) <= DETERMINANT_THRESHOLD)
return false;
for (PxU32 i = 0; i < numSprungMasses; i++)
{
sprungMasses[i] = result[i];
}
}
return true;
}
} //namespace vehicle2
} //namespace physx
| 6,768 | C++ | 30.483721 | 184 | 0.671395 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/tire/VhTireFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
#include "vehicle2/tire/PxVehicleTireFunctions.h"
#include "vehicle2/tire/PxVehicleTireParams.h"
#include "vehicle2/wheel/PxVehicleWheelHelpers.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE PxF32 computeFilteredNormalisedTireLoad
(const PxF32 xmin, const PxF32 ymin, const PxF32 xmax, const PxF32 ymax, const PxF32 x)
{
if (x <= xmin)
{
return ymin;
}
else if (x >= xmax)
{
return ymax;
}
else
{
return (ymin + (x - xmin)*(ymax - ymin)/ (xmax - xmin));
}
}
void PxVehicleTireDirsLegacyUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVehicleRoadGeometryState& rdGeomState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireDirectionState& trSlipDirs)
{
trSlipDirs.setToDefault();
//If there are no hits we'll have no ground plane.
if (!rdGeomState.hitState)
return;
//Compute wheel orientation with zero compliance, zero steer and zero
//rotation. Ignore rotation because it plays no role due to radial
//symmetry of wheel. Steer will be applied to the pose so we can
//ignore when computing the orientation. Compliance ought to be applied but
//we're not doing this in legacy code.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, 0.0f, 0.0f, 0.0f,
rigidBodyState.pose.q, 0.0f);
//We need lateral dir and hit norm to project wheel into ground plane.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
const PxVec3& hitNorm = rdGeomState.plane.n;
//Compute the tire axes in the ground plane.
PxVec3 tLongRaw = latDir.cross(hitNorm);
PxVec3 tLatRaw = hitNorm.cross(tLongRaw);
tLongRaw.normalize();
tLatRaw.normalize();
//Rotate the tire using the steer angle.
const PxF32 yawAngle = steerAngle;
const PxF32 cosWheelSteer = PxCos(yawAngle);
const PxF32 sinWheelSteer = PxSin(yawAngle);
const PxVec3 tLong = tLongRaw * cosWheelSteer + tLatRaw * sinWheelSteer;
const PxVec3 tLat = tLatRaw * cosWheelSteer - tLongRaw * sinWheelSteer;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL] = tLat;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] = tLong;
}
void PxVehicleTireDirsUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireDirectionState& trSlipDirs)
{
trSlipDirs.setToDefault();
//Skip if the suspension could not push the wheel to the ground.
if (!isWheelOnGround)
return;
//Compute the wheel quaternion in the world frame.
//Ignore rotation because it plays no role due to radial symmetry of wheel.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, compState.camber, compState.toe, steerAngle,
rigidBodyState.pose.q, 0.0f);
//We need lateral dir and hit norm to project wheel into ground plane.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
//Compute the tire axes in the ground plane.
PxVec3 lng = latDir.cross(groundNormal);
PxVec3 lat = groundNormal.cross(lng);
lng.normalize();
lat.normalize();
//Set the direction vectors.
trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL] = lat;
trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] = lng;
}
PX_FORCE_INLINE PxF32 computeLateralSlip
(const PxF32 lngSpeed, const PxF32 latSpeed, const PxF32 minLatSlipDenominator)
{
const PxF32 latSlip = PxAtan(latSpeed / (PxAbs(lngSpeed) + minLatSlipDenominator));
return latSlip;
}
PX_FORCE_INLINE PxF32 computeLongitudionalSlip
(const bool useLegacyLongSlipCalculation,
const PxF32 longSpeed,
const PxF32 wheelOmega, const PxF32 wheelRadius,
const PxF32 minPassiveLongSlipDenominator, const PxF32 minActiveLongSlipDenominator,
const bool isAccelApplied, const bool isBrakeApplied)
{
const PxF32 longSpeedAbs = PxAbs(longSpeed);
const PxF32 wheelSpeed = wheelOmega * wheelRadius;
const PxF32 wheelSpeedAbs = PxAbs(wheelSpeed);
PxF32 lngSlip = 0.0f;
//If nothing is moving just avoid a divide by zero and set the long slip to zero.
if (longSpeed == 0 && wheelOmega == 0)
{
lngSlip = 0.0f;
}
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.
if (useLegacyLongSlipCalculation)
{
lngSlip = (wheelSpeed - longSpeed) / (PxMax(longSpeedAbs, wheelSpeedAbs) + minActiveLongSlipDenominator);
}
else
{
lngSlip = (wheelSpeed - longSpeed) / (longSpeedAbs + minActiveLongSlipDenominator);
}
}
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.
if (useLegacyLongSlipCalculation)
{
lngSlip = (wheelSpeed - longSpeed) / (PxMax(minPassiveLongSlipDenominator, PxMax(longSpeedAbs, wheelSpeedAbs)));
}
else
{
lngSlip = (wheelSpeed - longSpeed) / (longSpeedAbs + minPassiveLongSlipDenominator);
}
}
}
return lngSlip;
}
void PxVehicleTireSlipSpeedsUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxF32 steerAngle, const PxVehicleSuspensionState& suspStates, const PxVehicleTireDirectionState& trSlipDirs,
const PxVehicleRigidBodyState& rigidBodyState, const PxVehicleRoadGeometryState& roadGeometryState,
const PxVehicleFrame& frame,
PxVehicleTireSpeedState& trSpeedState)
{
trSpeedState.setToDefault();
//Compute the position of the bottom of the wheel (placed on the ground plane).
PxVec3 wheelBottomPos;
{
PxVec3 v,w;
PxF32 dist;
PxVehicleComputeSuspensionRaycast(frame, whlParams, suspParams, steerAngle, rigidBodyState.pose, v, w, dist);
wheelBottomPos = v + w*(dist - suspStates.jounce);
}
//Compute the rigid body velocity at the bottom of the wheel (placed on the ground plane).
PxVec3 wheelBottomVel;
{
const PxVec3 r = wheelBottomPos - rigidBodyState.pose.p;
wheelBottomVel = rigidBodyState.linearVelocity + rigidBodyState.angularVelocity.cross(r) - roadGeometryState.velocity;
}
//Comput the velocities along lateral and longitudinal tire directions.
trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL] = wheelBottomVel.dot(trSlipDirs.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]);
trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL] = wheelBottomVel.dot(trSlipDirs.directions[PxVehicleTireDirectionModes::eLATERAL]);
}
void vehicleTireSlipsUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams, const bool useLegacyLongSlipCalculation,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
trSlipState.setToDefault();
PxF32 latSlip = 0.0f;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 latSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 minLatSlipDenominator = trSlipParams.minLatSlipDenominator;
latSlip = computeLateralSlip(lngSpeed, latSpeed, minLatSlipDenominator);
}
PxF32 lngSlip = 0.0f;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 wheelRotSpeed = whlRigidBody1dState.rotationSpeed;
const PxF32 wheelRadius = whlParams.radius;
const PxF32 minPassiveLngSlipDenominator = trSlipParams.minPassiveLongSlipDenominator;
const PxF32 minActiveLngSlipDenominator = trSlipParams.minActiveLongSlipDenominator;
const bool isBrakeApplied = actState.isBrakeApplied;
const bool isAccelApplied = actState.isDriveApplied;
lngSlip = computeLongitudionalSlip(
useLegacyLongSlipCalculation,
lngSpeed, wheelRotSpeed, wheelRadius,
minPassiveLngSlipDenominator, minActiveLngSlipDenominator,
isAccelApplied, isBrakeApplied);
}
trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = latSlip;
trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = lngSlip;
}
void PxVehicleTireSlipsUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
vehicleTireSlipsUpdate(
whlParams, trSlipParams, false,
actState, trSpeedState, whlRigidBody1dState,
trSlipState);
}
void PxVehicleTireSlipsLegacyUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleTireSlipParams& trSlipParams,
const PxVehicleWheelActuationState& actState, PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlRigidBody1dState,
PxVehicleTireSlipState& trSlipState)
{
vehicleTireSlipsUpdate(
whlParams, trSlipParams, true,
actState, trSpeedState, whlRigidBody1dState,
trSlipState);
}
void PxVehicleTireCamberAnglesUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxReal steerAngle, const PxVec3& groundNormal, bool isWheelOnGround,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleFrame& frame,
PxVehicleTireCamberAngleState& trCamberAngleState)
{
trCamberAngleState.setToDefault();
//Use zero camber if the suspension could not push the wheel to the ground.
if (!isWheelOnGround)
return;
//Compute the wheel quaternion in the world frame.
//Ignore rotation due to radial symmetry.
const PxQuat wheelOrientation = PxVehicleComputeWheelOrientation(frame, suspParams, compState.camber, compState.toe, steerAngle,
rigidBodyState.pose.q, 0.0f);
//Compute the axes of the wheel.
const PxVec3 latDir = wheelOrientation.rotate(frame.getLatAxis());
const PxVec3 lngDir = wheelOrientation.rotate(frame.getLngAxis());
//Project normal into lateral/vertical plane.
//Start with:
//n = lat*alpha + lng*beta + vrt*delta
//Want to work out
//T = n - lng*beta
// = n - lng*(n.dot(lng))
//Don't forget to normalise T.
//For the angle theta to look for we have:
//T.vrtDir = cos(theta)
//However, the cosine destroys the sign of the angle, thus we
//use:
//T.latDir = cos(pi/2 - theta) = sin(theta) (latDir and vrtDir are perpendicular)
const PxF32 beta = groundNormal.dot(lngDir);
PxVec3 T = groundNormal - lngDir * beta;
T.normalize();
const PxF32 sinTheta = T.dot(latDir);
const PxF32 theta = PxAsin(sinTheta);
trCamberAngleState.camberAngle = theta;
}
PX_FORCE_INLINE PxF32 updateLowLngSpeedTimer
(const PxF32 lngSpeed, const PxF32 wheelOmega, const PxF32 wheelRadius, const PxF32 lngThresholdSpeed,
const bool isIntentionToAccelerate, const PxF32 dt, const PxF32 lowLngSpeedTime)
{
//If the tire is rotating slowly and the longitudinal speed is slow then increment the slow longitudinal 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 newLowSpeedTime = 0.0f;
if ((PxAbs(lngSpeed) < lngThresholdSpeed) && (PxAbs(wheelOmega*wheelRadius) < lngThresholdSpeed) && !isIntentionToAccelerate)
{
newLowSpeedTime = lowLngSpeedTime + dt;
}
else
{
newLowSpeedTime = 0;
}
return newLowSpeedTime;
}
PX_FORCE_INLINE void activateStickyFrictionLngConstraint
(const PxF32 longSpeed, const PxF32 wheelOmega, const PxF32 lowLngSpeedTime, const bool isIntentionToBrake,
const PxF32 thresholdSpeed, const PxF32 thresholdTime,
bool& stickyTireActiveFlag)
{
//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).
//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 longitudinal speed at the tire contact point is vanishingly small.
//(2) the accumulated time of low longitudinal speed is greater than a threshold.
stickyTireActiveFlag = false;
if (((PxAbs(longSpeed) < thresholdSpeed) && (0.0f == wheelOmega) && isIntentionToBrake) || (lowLngSpeedTime > thresholdTime))
{
stickyTireActiveFlag = true;
}
}
PX_FORCE_INLINE PxF32 updateLowLatSpeedTimer
(const PxF32 latSpeed, const bool isIntentionToAccelerate, const PxF32 timestep, const PxF32 thresholdSpeed, const PxF32 lowSpeedTime)
{
//If the lateral speed is slow then increment the slow lateral 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 newLowSpeedTime = lowSpeedTime;
if ((PxAbs(latSpeed) < thresholdSpeed) && !isIntentionToAccelerate)
{
newLowSpeedTime += timestep;
}
else
{
newLowSpeedTime = 0;
}
return newLowSpeedTime;
}
PX_FORCE_INLINE void activateStickyFrictionLatConstraint
(const bool lowSpeedLngTimerActive,
const PxF32 lowLatSpeedTimer, const PxF32 thresholdTime,
bool& stickyTireActiveFlag)
{
//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).
//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 longitudinal speed timer is > 0.
//(2) the accumulated time of low longitudinal speed is greater than a threshold.
stickyTireActiveFlag = false;
if (lowSpeedLngTimerActive && (lowLatSpeedTimer > thresholdTime))
{
stickyTireActiveFlag = true;
}
}
void PxVehicleTireStickyStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleWheelParams& whlParams,
const PxVehicleTireStickyParams& trStickyParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates,
const PxVehicleTireGripState& trGripState, const PxVehicleTireSpeedState& trSpeedState, const PxVehicleWheelRigidBody1dState& whlState,
const PxReal dt,
PxVehicleTireStickyState& trStickyState)
{
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = false;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] = false;
//Only process sticky state if tire can generate force.
const PxF32 load = trGripState.load;
const PxF32 friction = trGripState.friction;
if(0 == load*friction)
{
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL] = 0.0f;
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL] = 0.0f;
return;
}
//Work out if any wheel is to have a drive applied to it.
bool isIntentionToAccelerate = false;
bool isIntentionToBrake = false;
for(PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if(actuationStates[wheelId].isDriveApplied)
isIntentionToAccelerate = true;
if (actuationStates[wheelId].isBrakeApplied)
isIntentionToBrake = true;
}
//Long sticky state.
bool lngTimerActive = false;
{
const PxF32 lngSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 wheelOmega = whlState.rotationSpeed;
const PxF32 wheelRadius = whlParams.radius;
const PxF32 lngThresholdSpeed = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdSpeed;
const PxF32 lngLowSpeedTime = trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 newLowLngSpeedTime = updateLowLngSpeedTimer(
lngSpeed, wheelOmega, wheelRadius, lngThresholdSpeed,
isIntentionToAccelerate,
dt, lngLowSpeedTime);
lngTimerActive = (newLowLngSpeedTime > 0);
bool lngActiveState = false;
const PxF32 lngThresholdTime = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLONGITUDINAL].thresholdTime;
activateStickyFrictionLngConstraint(
lngSpeed, wheelOmega, newLowLngSpeedTime, isIntentionToBrake,
lngThresholdSpeed, lngThresholdTime,
lngActiveState);
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL] = newLowLngSpeedTime;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = lngActiveState;
}
//Lateral sticky state
{
const PxF32 latSpeed = trSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 latThresholdSpeed = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdSpeed;
const PxF32 latLowSpeedTime = trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 latNewLowSpeedTime = updateLowLatSpeedTimer(latSpeed, isIntentionToAccelerate, dt, latThresholdSpeed, latLowSpeedTime);
bool latActiveState = false;
const PxF32 latThresholdTime = trStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].thresholdTime;
activateStickyFrictionLatConstraint(lngTimerActive, latNewLowSpeedTime, latThresholdTime,
latActiveState);
trStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL] = latNewLowSpeedTime;
trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] = latActiveState;
}
}
PX_FORCE_INLINE PxF32 computeTireLoad
(const PxVehicleTireForceParams& trForceParams, const PxVehicleSuspensionForce& suspForce)
{
//Compute the normalised load.
const PxF32 rawLoad = suspForce.normalForce;
const PxF32 restLoad = trForceParams.restLoad;
const PxF32 normalisedLoad = rawLoad / restLoad;
//Get the load filter params.
const PxF32 minNormalisedLoad = trForceParams.loadFilter[0][0];
const PxF32 minFilteredNormalisedLoad = trForceParams.loadFilter[0][1];
const PxF32 maxNormalisedLoad = trForceParams.loadFilter[1][0];
const PxF32 maxFilteredNormalisedLoad = trForceParams.loadFilter[1][1];
//Compute the filtered load.
const PxF32 filteredNormalisedLoad = computeFilteredNormalisedTireLoad(minNormalisedLoad, minFilteredNormalisedLoad, maxNormalisedLoad, maxFilteredNormalisedLoad, normalisedLoad);
const PxF32 filteredLoad = restLoad * filteredNormalisedLoad;
//Set the load after applying the filter.
return filteredLoad;
}
PX_FORCE_INLINE PxF32 computeTireFriction
(const PxVehicleTireForceParams& trForceParams,
const PxReal frictionCoefficient, const PxVehicleTireSlipState& tireSlipState)
{
//Interpolate the friction using the long slip value.
const PxF32 x0 = trForceParams.frictionVsSlip[0][0];
const PxF32 y0 = trForceParams.frictionVsSlip[0][1];
const PxF32 x1 = trForceParams.frictionVsSlip[1][0];
const PxF32 y1 = trForceParams.frictionVsSlip[1][1];
const PxF32 x2 = trForceParams.frictionVsSlip[2][0];
const PxF32 y2 = trForceParams.frictionVsSlip[2][1];
const PxF32 longSlipAbs = PxAbs(tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL]);
PxF32 mu;
if (longSlipAbs < x1)
{
mu = y0 + (y1 - y0)*(longSlipAbs - x0) / (x1 - x0);
}
else if (longSlipAbs < x2)
{
mu = y1 + (y2 - y1)*(longSlipAbs - x1) / (x2 - x1);
}
else
{
mu = y2;
}
PX_ASSERT(mu >= 0);
const PxF32 tireFriction = frictionCoefficient * mu;
return tireFriction;
}
void PxVehicleTireGripUpdate
(const PxVehicleTireForceParams& trForceParams,
const PxReal frictionCoefficient, bool isWheelOnGround, const PxVehicleSuspensionForce& suspForce,
const PxVehicleTireSlipState& trSlipState,
PxVehicleTireGripState& trGripState)
{
trGripState.setToDefault();
//If the wheel is not touching the ground then carry on with zero grip state.
if (!isWheelOnGround)
return;
//Compute load and friction.
trGripState.load = computeTireLoad(trForceParams, suspForce);
trGripState.friction = computeTireFriction(trForceParams, frictionCoefficient, trSlipState);
}
void PxVehicleTireSlipsAccountingForStickyStatesUpdate
(const PxVehicleTireStickyState& trStickyState,
PxVehicleTireSlipState& trSlipState)
{
if(trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL])
trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = 0.f;
if (trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL])
trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = 0.f;
}
////////////////////////////////////////////////////////////////////////////
//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 computeTireForceMichiganModel
(const PxVehicleTireForceParams& tireData,
const PxF32 tireFriction,
const PxF32 longSlipUnClamped, const PxF32 latSlipUnClamped, const PxF32 camberUnclamped,
const PxF32 wheelRadius,
const PxF32 tireLoad,
PxF32& wheelTorque, PxF32& tireLongForceMag, PxF32& tireLatForceMag, PxF32& tireAlignMoment)
{
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 minimumSlipThreshold = 1e-5f;
const PxF32 latSlip = PxAbs(latSlipUnClamped) >= minimumSlipThreshold ? latSlipUnClamped : 0.0f;
const PxF32 longSlip = PxAbs(longSlipUnClamped) >= minimumSlipThreshold ? longSlipUnClamped : 0.0f;
const PxF32 camber = PxAbs(camberUnclamped) >= minimumSlipThreshold ? camberUnclamped : 0.0f;
//Normalise the tire load.
const PxF32 restTireLoad = tireData.restLoad;
const PxF32 normalisedTireLoad = tireLoad/ restTireLoad;
//Compute the lateral stiffness
const PxF32 latStiff = (0.0f == tireData.latStiffX) ? tireData.latStiffY : tireData.latStiffY*smoothingFunction1(normalisedTireLoad*3.0f / tireData.latStiffX);
//Get the longitudinal stiffness
const PxF32 longStiff = tireData.longStiff;
//Get the camber stiffness.
const PxF32 camberStiff = tireData.camberStiff;
//If long slip/lat slip/camber are all zero than there will be zero tire force.
if ((0 == latSlip*latStiff) && (0 == longSlip*longStiff) && (0 == camber*camberStiff))
{
return;
}
//Carry on and compute the forces.
const PxF32 TEff = PxTan(latSlip + (camber * camberStiff / latStiff)); // "+" because we define camber stiffness as a positive value
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/longStiff;
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;
}
void PxVehicleTireForcesUpdate
(const PxVehicleWheelParams& whlParams, const PxVehicleSuspensionParams& suspParams,
const PxVehicleTireForceParams& trForceParams,
const PxVehicleSuspensionComplianceState& compState,
const PxVehicleTireGripState& trGripState, const PxVehicleTireDirectionState& trDirectionState,
const PxVehicleTireSlipState& trSlipState, const PxVehicleTireCamberAngleState& cmbAngleState,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehicleTireForce& trForce)
{
trForce.setToDefault();
//If the tire can generate no force then carry on with zero force.
if(0 == trGripState.friction*trGripState.load)
return;
PxF32 wheelTorque = 0;
PxF32 tireLongForceMag = 0;
PxF32 tireLatForceMag = 0;
PxF32 tireAlignMoment = 0;
const PxF32 friction = trGripState.friction;
const PxF32 tireLoad = trGripState.load;
const PxF32 lngSlip = trSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL];
const PxF32 latSlip = trSlipState.slips[PxVehicleTireDirectionModes::eLATERAL];
const PxF32 camber = cmbAngleState.camberAngle;
const PxF32 wheelRadius = whlParams.radius;
computeTireForceMichiganModel(trForceParams, friction, lngSlip, latSlip, camber, wheelRadius, tireLoad,
wheelTorque, tireLongForceMag, tireLatForceMag, tireAlignMoment);
//Compute the forces.
const PxVec3 tireLongForce = trDirectionState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]*tireLongForceMag;
const PxVec3 tireLatForce = trDirectionState.directions[PxVehicleTireDirectionModes::eLATERAL]*tireLatForceMag;
//Compute the torques.
const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(compState.tireForceAppPoint));
const PxVec3 tireLongTorque = r.cross(tireLongForce);
const PxVec3 tireLatTorque = r.cross(tireLatForce);
//Set the torques.
trForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongForce;
trForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongTorque;
trForce.forces[PxVehicleTireDirectionModes::eLATERAL] = tireLatForce;
trForce.torques[PxVehicleTireDirectionModes::eLATERAL] = tireLatTorque;
trForce.aligningMoment = tireAlignMoment;
trForce.wheelTorque = wheelTorque;
}
} //namespace vehicle2
} //namespace physx
| 29,600 | C++ | 40.055478 | 180 | 0.782196 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/drivetrain/VhDrivetrainHelpers.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleFunctions.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleMatrixNNLUSolver::decomposeLU(const PxVehicleMatrixNN& A)
{
const PxU32 D = A.mSize;
mLU = A;
mDetM = 1.0f;
for (PxU32 k = 0; k < D - 1; ++k)
{
PxU32 pivot_row = k;
PxU32 pivot_col = k;
float abs_pivot_elem = 0.0f;
for (PxU32 c = k; c < D; ++c)
{
for (PxU32 r = k; r < D; ++r)
{
const PxF32 abs_elem = PxAbs(mLU.get(r, c));
if (abs_elem > abs_pivot_elem)
{
abs_pivot_elem = abs_elem;
pivot_row = r;
pivot_col = c;
}
}
}
mP[k] = pivot_row;
if (pivot_row != k)
{
mDetM = -mDetM;
for (PxU32 c = 0; c < D; ++c)
{
//swap(m_LU(k,c), m_LU(pivot_row,c));
const PxF32 pivotrowc = mLU.get(pivot_row, c);
mLU.set(pivot_row, c, mLU.get(k, c));
mLU.set(k, c, pivotrowc);
}
}
mQ[k] = pivot_col;
if (pivot_col != k)
{
mDetM = -mDetM;
for (PxU32 r = 0; r < D; ++r)
{
//swap(m_LU(r,k), m_LU(r,pivot_col));
const PxF32 rpivotcol = mLU.get(r, pivot_col);
mLU.set(r, pivot_col, mLU.get(r, k));
mLU.set(r, k, rpivotcol);
}
}
mDetM *= mLU.get(k, k);
if (mLU.get(k, k) != 0.0f)
{
for (PxU32 r = k + 1; r < D; ++r)
{
mLU.set(r, k, mLU.get(r, k) / mLU.get(k, k));
for (PxU32 c = k + 1; c < D; ++c)
{
//m_LU(r,c) -= m_LU(r,k)*m_LU(k,c);
const PxF32 rc = mLU.get(r, c);
const PxF32 rk = mLU.get(r, k);
const PxF32 kc = mLU.get(k, c);
mLU.set(r, c, rc - rk * kc);
}
}
}
}
mDetM *= mLU.get(D - 1, D - 1);
}
bool PxVehicleMatrixNNLUSolver::solve(const PxVehicleVectorN& b, PxVehicleVectorN& x) const
{
const PxU32 D = x.getSize();
if ((b.getSize() != x.getSize()) || (b.getSize() != mLU.getSize()) || (0.0f == mDetM))
{
for (PxU32 i = 0; i < D; i++)
{
x[i] = 0.0f;
}
return false;
}
x = b;
// Perform row permutation to get Pb
for (PxU32 i = 0; i < D - 1; ++i)
{
//swap(x(i), x(m_P[i]));
const PxF32 xp = x[mP[i]];
x[mP[i]] = x[i];
x[i] = xp;
}
// Forward substitute to get (L^-1)Pb
for (PxU32 r = 1; r < D; ++r)
{
for (PxU32 i = 0; i < r; ++i)
{
x[r] -= mLU.get(r, i)*x[i];
}
}
// Back substitute to get (U^-1)(L^-1)Pb
for (PxU32 r = D; r-- > 0;)
{
for (PxU32 i = r + 1; i < D; ++i)
{
x[r] -= mLU.get(r, i)*x[i];
}
x[r] /= mLU.get(r, r);
}
// Perform column permutation to get the solution (Q^T)(U^-1)(L^-1)Pb
for (PxU32 i = D - 1; i-- > 0;)
{
//swap(x(i), x(m_Q[i]));
const PxF32 xq = x[mQ[i]];
x[mQ[i]] = x[i];
x[i] = xq;
}
return true;
}
void PxVehicleMatrixNGaussSeidelSolver::solve(const PxU32 maxIterations, const PxF32 tolerance, const PxVehicleMatrixNN& A, const PxVehicleVectorN& b, PxVehicleVectorN& result) const
{
const PxU32 N = A.getSize();
PxVehicleVectorN DInv(N);
PxF32 bLength2 = 0.0f;
for (PxU32 i = 0; i < N; i++)
{
DInv[i] = 1.0f / A.get(i, i);
bLength2 += (b[i] * b[i]);
}
PxU32 iteration = 0;
PxF32 error = PX_MAX_F32;
while (iteration < maxIterations && tolerance < error)
{
for (PxU32 i = 0; i < N; i++)
{
PxF32 l = 0.0f;
for (PxU32 j = 0; j < i; j++)
{
l += A.get(i, j) * result[j];
}
PxF32 u = 0.0f;
for (PxU32 j = i + 1; j < N; j++)
{
u += A.get(i, j) * result[j];
}
result[i] = DInv[i] * (b[i] - l - u);
}
//Compute the error.
PxF32 rLength2 = 0;
for (PxU32 i = 0; i < N; i++)
{
PxF32 e = -b[i];
for (PxU32 j = 0; j < N; j++)
{
e += A.get(i, j) * result[j];
}
rLength2 += e * e;
}
error = (rLength2 / (bLength2 + 1e-10f));
iteration++;
}
}
bool PxVehicleMatrix33Solver::solve(const PxVehicleMatrixNN& A_, const PxVehicleVectorN& b_, PxVehicleVectorN& result) const
{
const PxF32 a = A_.get(0, 0);
const PxF32 b = A_.get(0, 1);
const PxF32 c = A_.get(0, 2);
const PxF32 d = A_.get(1, 0);
const PxF32 e = A_.get(1, 1);
const PxF32 f = A_.get(1, 2);
const PxF32 g = A_.get(2, 0);
const PxF32 h = A_.get(2, 1);
const PxF32 k = A_.get(2, 2);
const PxF32 detA = a * (e*k - f * h) - b * (k*d - f * g) + c * (d*h - e * g);
if (0.0f == detA)
{
return false;
}
const PxF32 detAInv = 1.0f / detA;
const PxF32 A = (e*k - f * h);
const PxF32 D = -(b*k - c * h);
const PxF32 G = (b*f - c * e);
const PxF32 B = -(d*k - f * g);
const PxF32 E = (a*k - c * g);
const PxF32 H = -(a*f - c * d);
const PxF32 C = (d*h - e * g);
const PxF32 F = -(a*h - b * g);
const PxF32 K = (a*e - b * d);
result[0] = detAInv * (A*b_[0] + D * b_[1] + G * b_[2]);
result[1] = detAInv * (B*b_[0] + E * b_[1] + H * b_[2]);
result[2] = detAInv * (C*b_[0] + F * b_[1] + K * b_[2]);
return true;
}
void PxVehicleLegacyDifferentialWheelSpeedContributionsCompute
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxU32 nbWheels, PxReal* diffAveWheelSpeedContributions)
{
PxMemZero(diffAveWheelSpeedContributions, sizeof(PxReal) * nbWheels);
const PxU32 wheelIds[4] =
{
diffParams.frontWheelIds[0],
diffParams.frontWheelIds[1],
diffParams.rearWheelIds[0],
diffParams.rearWheelIds[1],
};
const PxF32 frontRearSplit = diffParams.frontRearSplit;
const PxF32 frontNegPosSplit = diffParams.frontNegPosSplit;
const PxF32 rearNegPosSplit = diffParams.rearNegPosSplit;
const PxF32 oneMinusFrontRearSplit = 1.0f - diffParams.frontRearSplit;
const PxF32 oneMinusFrontNegPosSplit = 1.0f - diffParams.frontNegPosSplit;
const PxF32 oneMinusRearNegPosSplit = 1.0f - diffParams.rearNegPosSplit;
switch (diffParams.type)
{
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_4WD:
diffAveWheelSpeedContributions[wheelIds[0]] = frontRearSplit * frontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[1]] = frontRearSplit * oneMinusFrontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[2]] = oneMinusFrontRearSplit * rearNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[3]] = oneMinusFrontRearSplit * oneMinusRearNegPosSplit;
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_FRONTWD:
diffAveWheelSpeedContributions[wheelIds[0]] = frontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[1]] = oneMinusFrontNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[2]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[3]] = 0.0f;
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_REARWD:
diffAveWheelSpeedContributions[wheelIds[0]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[1]] = 0.0f;
diffAveWheelSpeedContributions[wheelIds[2]] = rearNegPosSplit;
diffAveWheelSpeedContributions[wheelIds[3]] = oneMinusRearNegPosSplit;
break;
default:
PX_ASSERT(false);
break;
}
PX_ASSERT(
((diffAveWheelSpeedContributions[wheelIds[0]] + diffAveWheelSpeedContributions[wheelIds[1]] + diffAveWheelSpeedContributions[wheelIds[2]] + diffAveWheelSpeedContributions[wheelIds[3]]) >= 0.999f) &&
((diffAveWheelSpeedContributions[wheelIds[0]] + diffAveWheelSpeedContributions[wheelIds[1]] + diffAveWheelSpeedContributions[wheelIds[2]] + diffAveWheelSpeedContributions[wheelIds[3]]) <= 1.001f));
}
PX_FORCE_INLINE void splitTorque
(const PxF32 w1, const PxF32 w2, const PxF32 diffBias, const PxF32 defaultSplitRatio,
PxF32* t1, PxF32* t2)
{
PX_ASSERT(PxVehicleComputeSign(w1) == PxVehicleComputeSign(w2) && 0.0f != PxVehicleComputeSign(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);
}
void PxVehicleLegacyDifferentialTorqueRatiosCompute
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelOmegas,
const PxU32 nbWheels, PxReal* diffTorqueRatios)
{
PxMemZero(diffTorqueRatios, sizeof(PxReal) * nbWheels);
const PxU32 wheelIds[4] =
{
diffParams.frontWheelIds[0],
diffParams.frontWheelIds[1],
diffParams.rearWheelIds[0],
diffParams.rearWheelIds[1],
};
const PxF32 wfl = wheelOmegas[wheelIds[0]].rotationSpeed;
const PxF32 wfr = wheelOmegas[wheelIds[1]].rotationSpeed;
const PxF32 wrl = wheelOmegas[wheelIds[2]].rotationSpeed;
const PxF32 wrr = wheelOmegas[wheelIds[3]].rotationSpeed;
const PxF32 centreBias = diffParams.centerBias;
const PxF32 frontBias = diffParams.frontBias;
const PxF32 rearBias = diffParams.rearBias;
const PxF32 frontRearSplit = diffParams.frontRearSplit;
const PxF32 frontLeftRightSplit = diffParams.frontNegPosSplit;
const PxF32 rearLeftRightSplit = diffParams.rearNegPosSplit;
const PxF32 oneMinusFrontRearSplit = 1.0f - diffParams.frontRearSplit;
const PxF32 oneMinusFrontLeftRightSplit = 1.0f - diffParams.frontNegPosSplit;
const PxF32 oneMinusRearLeftRightSplit = 1.0f - diffParams.rearNegPosSplit;
const PxF32 swfl = PxVehicleComputeSign(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 (diffParams.type)
{
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_4WD:
if (0.0f != swfl && swfl == PxVehicleComputeSign(wfr) && swfl == PxVehicleComputeSign(wrl) && swfl == PxVehicleComputeSign(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
{
torqueFrontLeft = frontRearSplit * frontLeftRightSplit;
torqueFrontRight = frontRearSplit * oneMinusFrontLeftRightSplit;
torqueRearLeft = oneMinusFrontRearSplit * rearLeftRightSplit;
torqueRearRight = oneMinusFrontRearSplit * oneMinusRearLeftRightSplit;
}
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_FRONTWD:
if (0.0f != swfl && swfl == PxVehicleComputeSign(wfr))
{
splitTorque(wfl, wfr, frontBias, frontLeftRightSplit, &torqueFrontLeft, &torqueFrontRight);
}
else
{
torqueFrontLeft = frontLeftRightSplit;
torqueFrontRight = oneMinusFrontLeftRightSplit;
}
break;
case PxVehicleFourWheelDriveDifferentialLegacyParams::eDIFF_TYPE_LS_REARWD:
if (0.0f != PxVehicleComputeSign(wrl) && PxVehicleComputeSign(wrl) == PxVehicleComputeSign(wrr))
{
splitTorque(wrl, wrr, rearBias, rearLeftRightSplit, &torqueRearLeft, &torqueRearRight);
}
else
{
torqueRearLeft = rearLeftRightSplit;
torqueRearRight = oneMinusRearLeftRightSplit;
}
break;
default:
PX_ASSERT(false);
break;
}
diffTorqueRatios[wheelIds[0]] = torqueFrontLeft;
diffTorqueRatios[wheelIds[1]] = torqueFrontRight;
diffTorqueRatios[wheelIds[2]] = torqueRearLeft;
diffTorqueRatios[wheelIds[3]] = torqueRearRight;
PX_ASSERT(((torqueFrontLeft + torqueFrontRight + torqueRearLeft + torqueRearRight) >= 0.999f) && ((torqueFrontLeft + torqueFrontRight + torqueRearLeft + torqueRearRight) <= 1.001f));
}
} //namespace vehicle2
} //namespace physx
| 13,838 | C++ | 30.452273 | 200 | 0.686226 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/drivetrain/VhDrivetrainFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleFunctions.h"
#include "vehicle2/PxVehicleMaths.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainFunctions.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainHelpers.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleDirectDriveThrottleCommandResponseUpdate
(const PxReal throttle, const PxVehicleDirectDriveTransmissionCommandState& transmissionCommands, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleDirectDriveThrottleCommandResponseParams& responseParams,
PxReal& throttleResponse)
{
//The gearing decides how we will multiply the response.
PxF32 gearMultiplier = 0.0f;
switch (transmissionCommands.gear)
{
case PxVehicleDirectDriveTransmissionCommandState::eREVERSE:
gearMultiplier = -1.0f;
break;
case PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL:
gearMultiplier = 0.0f;
break;
case PxVehicleDirectDriveTransmissionCommandState::eFORWARD:
gearMultiplier = 1.0f;
break;
}
throttleResponse = gearMultiplier * PxVehicleNonLinearResponseCompute(throttle, longitudinalSpeed, wheelId, responseParams);
}
void PxVehicleDirectDriveActuationStateUpdate
(const PxReal brakeTorque, const PxReal driveTorque,
PxVehicleWheelActuationState& actState)
{
PxMemZero(&actState, sizeof(PxVehicleWheelActuationState));
actState.isBrakeApplied = (brakeTorque != 0.0f);
actState.isDriveApplied = (driveTorque != 0.0f);
}
void PxVehicleDirectDriveUpdate
(const PxVehicleWheelParams& whlParams,
const PxVehicleWheelActuationState& actState,
const PxReal brkTorque, const PxReal drvTorque, const PxVehicleTireForce& trForce,
const PxF32 dt,
PxVehicleWheelRigidBody1dState& whlState)
{
//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)
const PxF32 wheelRotSpeed = whlState.rotationSpeed;
const PxF32 dtOverMOI = dt/whlParams.moi;
const PxF32 tireTorque = trForce.wheelTorque;
const PxF32 brakeTorque = -brkTorque*PxVehicleComputeSign(wheelRotSpeed);
const PxF32 driveTorque = drvTorque;
const PxF32 wheelDampingRate = whlParams.dampingRate;
//Integrate the wheel rotation speed.
const PxF32 newRotSpeedNoBrakelock = (wheelRotSpeed + dtOverMOI*(tireTorque + driveTorque + brakeTorque)) / (1.0f + wheelDampingRate*dtOverMOI);
//If the brake is applied and the sign flipped then lock the brake.
const bool isBrakeApplied = actState.isBrakeApplied;
const PxF32 newRotSpeedWithBrakelock = (isBrakeApplied && ((wheelRotSpeed*newRotSpeedNoBrakelock) <= 0)) ? 0.0f : newRotSpeedNoBrakelock;
whlState.rotationSpeed = newRotSpeedWithBrakelock;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleFourWheelDriveDifferentialLegacyParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
PxVehicleDifferentialState& diffState)
{
diffState.setToDefault();
//4 wheels are connected.
diffState.connectedWheels[0] = diffParams.frontWheelIds[0];
diffState.connectedWheels[1] = diffParams.frontWheelIds[1];
diffState.connectedWheels[2] = diffParams.rearWheelIds[0];
diffState.connectedWheels[3] = diffParams.rearWheelIds[1];
diffState.nbConnectedWheels = 4;
//Compute the contributions to average speed and ratios of available torque.
PxVehicleLegacyDifferentialWheelSpeedContributionsCompute(diffParams, PxVehicleLimits::eMAX_NB_WHEELS,
diffState.aveWheelSpeedContributionAllWheels);
PxVehicleLegacyDifferentialTorqueRatiosCompute(diffParams, wheelStates, PxVehicleLimits::eMAX_NB_WHEELS,
diffState.torqueRatiosAllWheels);
}
PX_FORCE_INLINE PxF32 computeTargetRatio
(const PxF32 target, const PxF32 dt, const PxF32 strength, const PxF32 ratio)
{
const PxF32 targ = (PX_VEHICLE_FOUR_WHEEL_DIFFERENTIAL_MAXIMUM_STRENGTH == strength) ? target : PxMax(target, ratio - strength * dt);
return targ;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelStates,
const PxReal dt,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState)
{
diffState.setToDefault();
wheelConstraintGroupState.setToDefault();
PxU32 nbConnectedWheels = 0;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (diffParams.torqueRatios[wheelId] != 0.0f)
{
diffState.connectedWheels[nbConnectedWheels] = wheelId;
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
if (0.0f == diffParams.frontBias && 0.0f == diffParams.rearBias && 0.0f == diffParams.centerBias)
return;
if (0.0f == diffParams.rate)
return;
bool frontBiasBreached = false;
PxF32 Rf = 0.0f;
PxF32 Tf = 0.0f;
{
const PxF32 bias = diffParams.frontBias;
if (bias >= 1.0f)
{
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxReal w0 = wheelStates[wheel0].rotationSpeed;
const PxReal w1 = wheelStates[wheel1].rotationSpeed;
const PxReal aw0 = PxAbs(w0);
const PxReal aw1 = PxAbs(w1);
const PxReal sw0 = PxVehicleComputeSign(w0);
const PxReal sw1 = PxVehicleComputeSign(w1);
if ((w0 != 0.0f) && (sw0 == sw1))
{
const PxF32 ratio = PxMax(aw0, aw1) / PxMin(aw0, aw1);
frontBiasBreached = (ratio > bias);
//const PxF32 target = diffParams.frontTarget + (1.0f - diffParams.strength) * (ratio - diffParams.frontTarget);
const PxF32 target = computeTargetRatio(diffParams.frontTarget, dt, diffParams.rate, ratio);
Tf = (aw0 > aw1) ? 1.0f / target : target;
Rf = aw1 / aw0;
}
}
}
bool rearBiasBreached = false;
PxF32 Rr = 0.0f;
PxF32 Tr = 0.0f;
{
const PxF32 bias = diffParams.rearBias;
if (bias >= 1.0f)
{
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxReal w2 = wheelStates[wheel2].rotationSpeed;
const PxReal w3 = wheelStates[wheel3].rotationSpeed;
const PxReal aw2 = PxAbs(w2);
const PxReal aw3 = PxAbs(w3);
const PxReal sw2 = PxVehicleComputeSign(w2);
const PxReal sw3 = PxVehicleComputeSign(w3);
if ((w2 != 0.0f) && (sw2 == sw3))
{
const PxF32 ratio = PxMax(aw2, aw3) / PxMin(aw2, aw3);
rearBiasBreached = (ratio > bias);
//const PxF32 target = diffParams.rearTarget + (1.0f - diffParams.strength) * (ratio - diffParams.rearTarget);
const PxF32 target = computeTargetRatio(diffParams.rearTarget, dt, diffParams.rate, ratio);
Tr = (aw2 > aw3) ? 1.0f / target : target;
Rr = aw3 / aw2;
}
}
}
bool centreBiasBrached = false;
//PxF32 Rc = 0.0f;
PxF32 Tc = 0.0f;
{
const PxF32 bias = diffParams.centerBias;
if(bias >= 1.0f)
{
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxReal w0 = wheelStates[wheel0].rotationSpeed;
const PxReal w1 = wheelStates[wheel1].rotationSpeed;
const PxReal w2 = wheelStates[wheel2].rotationSpeed;
const PxReal w3 = wheelStates[wheel3].rotationSpeed;
const PxReal aw0 = PxAbs(w0);
const PxReal aw1 = PxAbs(w1);
const PxReal aw2 = PxAbs(w2);
const PxReal aw3 = PxAbs(w3);
const PxReal sw0 = PxVehicleComputeSign(w0);
const PxReal sw1 = PxVehicleComputeSign(w1);
const PxReal sw2 = PxVehicleComputeSign(w2);
const PxReal sw3 = PxVehicleComputeSign(w3);
if ((w0 != 0.0f) && (sw0 == sw1) && (sw0 == sw2) && (sw0 == sw3))
{
const PxF32 ratio = PxMax(aw0 + aw1, aw2 + aw3) / PxMin(aw0 + aw1, aw2 + aw3);
centreBiasBrached = (ratio > bias);
//const PxF32 target = diffParams.centerTarget + (1.0f - diffParams.strength) * (ratio - diffParams.centerTarget);
const PxF32 target = computeTargetRatio(diffParams.centerTarget, dt, diffParams.rate, ratio);
Tc = ((aw0 + aw1) > (aw2 + aw3)) ? 1.0f / target : target;
//Rc = (aw2 + aw3) / (aw0 + aw1);
}
}
}
if (centreBiasBrached)
{
PxF32 f = 0.0f;
PxF32 r = 0.0f;
if (frontBiasBreached && rearBiasBreached)
{
f = Tf;
r = Tr;
}
else if (frontBiasBreached)
{
f = Tf;
r = Rr;
}
else if (rearBiasBreached)
{
f = Rf;
r = Tr;
}
else
{
f = Rf;
r = Rr;
}
const PxU32 wheel0 = diffParams.frontWheelIds[0];
const PxU32 wheel1 = diffParams.frontWheelIds[1];
const PxU32 wheel2 = diffParams.rearWheelIds[0];
const PxU32 wheel3 = diffParams.rearWheelIds[1];
const PxU32 wheelIds[4] = { wheel0, wheel1, wheel2, wheel3 };
const PxF32 constraintMultipliers[4] = { 1.0f, f, Tc*(1 + f) / (1 + r), r*Tc*(1 + f) / (1 + r) };
wheelConstraintGroupState.addConstraintGroup(4, wheelIds, constraintMultipliers);
}
else
{
if (frontBiasBreached)
{
const PxU32* wheelIds = diffParams.frontWheelIds;
const PxF32 constraintMultipliers[2] = { 1.0f, Tf };
wheelConstraintGroupState.addConstraintGroup(2, wheelIds, constraintMultipliers);
}
if (rearBiasBreached)
{
const PxU32* wheelIds = diffParams.rearWheelIds;
const PxF32 constraintMultipliers[2] = { 1.0f, Tr };
wheelConstraintGroupState.addConstraintGroup(2, wheelIds, constraintMultipliers);
}
}
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription, const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
PxVehicleDifferentialState& diffState)
{
diffState.setToDefault();
PxU32 nbConnectedWheels = 0;
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (diffParams.torqueRatios[wheelId] != 0.0f)
{
diffState.connectedWheels[nbConnectedWheels] = wheelId;
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
}
void PxVehicleDifferentialStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, const PxVehicleTankDriveDifferentialParams& diffParams,
const PxReal thrust0, PxReal thrust1,
PxVehicleDifferentialState& diffState, PxVehicleWheelConstraintGroupState& wheelConstraintGroupState)
{
diffState.setToDefault();
wheelConstraintGroupState.setToDefault();
//Store the tank track id for each wheel.
//Store the thrust controller id for each wheel.
//Store 0xffffffff for wheels not in a tank track.
PxU32 tankTrackIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(tankTrackIds, 0xff, sizeof(tankTrackIds));
PxU32 thrustControllerIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(thrustControllerIds, 0xff, sizeof(thrustControllerIds));
for (PxU32 i = 0; i < diffParams.getNbTracks(); i++)
{
const PxU32 thrustControllerIndex = diffParams.getThrustControllerIndex(i);
for (PxU32 j = 0; j < diffParams.getNbWheelsInTrack(i); j++)
{
const PxU32 wheelId = diffParams.getWheelInTrack(j, i);
tankTrackIds[wheelId] = i;
thrustControllerIds[wheelId] = thrustControllerIndex;
}
}
//Treat every wheel connected to a tank track as connected to the differential but with zero torque split.
//If a wheel is not connected to the differential but is connected to a tank track then we treat that as a connected wheel with
//zero drive torque applied.
//We do this because we need to treat these wheels as being coupled to other wheels in the linear equations that solve engine+wheels
PxU32 nbConnectedWheels = 0;
const PxReal thrusts[2] = { thrust0, thrust1 };
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
const PxU32 tankTrackId = tankTrackIds[wheelId];
if (diffParams.torqueRatios[wheelId] != 0.0f && 0xffffffff != tankTrackId)
{
//Wheel connected to diff and in a tank track.
//Modify the default torque split using the relevant thrust.
const PxU32 thrustId = thrustControllerIds[wheelId];
const PxF32 torqueSplitMultiplier = thrusts[thrustId];
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.torqueRatios[wheelId] * torqueSplitMultiplier;
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
else if (diffParams.torqueRatios[wheelId] != 0.0f)
{
//Wheel connected to diff but not in a tank track.
//Use the default torque split.
diffState.aveWheelSpeedContributionAllWheels[wheelId] = diffParams.aveWheelSpeedRatios[wheelId];
diffState.torqueRatiosAllWheels[wheelId] = diffParams.torqueRatios[wheelId];
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
else if (0xffffffff != tankTrackId)
{
//Wheel not connected to diff but is in a tank track.
//Zero torque split.
diffState.aveWheelSpeedContributionAllWheels[wheelId] = 0.0f;
diffState.torqueRatiosAllWheels[wheelId] = 0.0f;
diffState.connectedWheels[nbConnectedWheels] = wheelId;
nbConnectedWheels++;
}
}
diffState.nbConnectedWheels = nbConnectedWheels;
//Add each tank track as a constraint group.
for (PxU32 i = 0; i < diffParams.getNbTracks(); i++)
{
const PxU32 nbWheelsInTrack = diffParams.getNbWheelsInTrack(i);
if (nbWheelsInTrack >= 2)
{
const PxU32* wheelsInTrack = diffParams.wheelIdsInTrackOrder + diffParams.trackToWheelIds[i];
PxF32 multipliers[PxVehicleLimits::eMAX_NB_WHEELS];
const PxU32 wheelId0 = wheelsInTrack[0];
const PxF32 wheelRadius0 = wheelParams[wheelId0].radius;
//for (PxU32 j = 0; j < 1; j++)
{
//j = 0 is a special case with multiplier = 1.0
multipliers[0] = 1.0f;
}
for (PxU32 j = 1; j < nbWheelsInTrack; j++)
{
const PxU32 wheelIdJ = wheelsInTrack[j];
const PxF32 wheelRadiusJ = wheelParams[wheelIdJ].radius;
multipliers[j] = wheelRadius0 / wheelRadiusJ;
}
wheelConstraintGroupState.addConstraintGroup(nbWheelsInTrack, wheelsInTrack, multipliers);
}
}
}
void PxVehicleEngineDriveActuationStateUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleGearboxParams& gearboxParams,
const PxVehicleArrayData<const PxReal>& brakeResponseStates,
const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const PxVehicleGearboxState& gearboxState, const PxVehicleDifferentialState& diffState, const PxVehicleClutchCommandResponseState& clutchResponseState,
PxVehicleArrayData<PxVehicleWheelActuationState>& actuationStates)
{
//Which wheels receive drive torque from the engine?
const PxF32* diffTorqueRatios = diffState.torqueRatiosAllWheels;
//Work out the clutch strength.
//If the cutch strength is zero then none of the wheels receive drive torque from the engine.
const PxF32 K = PxVehicleClutchStrengthCompute(clutchResponseState, gearboxParams, gearboxState);
//Work out the applied throttle
const PxF32 appliedThrottle = throttleResponseState.commandResponse;
//Ready to set the boolean actuation state that is used to compute the tire slips.
//(Note: for a tire under drive or brake torque we compute the slip with a smaller denominator to accentuate the applied torque).
//(Note: for a tire that is not under drive or brake torque we compute the sip with a larger denominator to smooth the vehicle slowing down).
for(PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
//Reset the actuation states.
PxVehicleWheelActuationState& actState = actuationStates[wheelId];
PxMemZero(&actState, sizeof(PxVehicleWheelActuationState));
const PxF32 brakeTorque = brakeResponseStates[wheelId];
const PxF32 diffTorqueRatio = diffTorqueRatios[wheelId];
const bool isIntentionToAccelerate = (0.0f == brakeTorque) && (K != 0.0f) && (diffTorqueRatio != 0.0f) && (appliedThrottle != 0.0f);
actState.isDriveApplied = isIntentionToAccelerate;
actState.isBrakeApplied = (brakeTorque!= 0.0f);
}
}
void PxVehicleGearCommandResponseUpdate
(const PxU32 targetGearCommand,
const PxVehicleGearboxParams& gearboxParams,
PxVehicleGearboxState& gearboxState)
{
//Check that we're not halfway through a gear change and we need to execute a change of gear.
//If we are halfway through a gear change then we cannot execute another until the first is complete.
//Check that the command stays in a legal gear range.
if ((gearboxState.currentGear == gearboxState.targetGear) && (targetGearCommand != gearboxState.currentGear) && (targetGearCommand < gearboxParams.nbRatios))
{
//We're not executing a gear change and we need to start one.
//Start the gear change by
//a)setting the target gear.
//b)putting vehicle in neutral
//c)set the switch time to PX_VEHICLE_GEAR_SWITCH_INITIATED to flag that we just started a gear change.
gearboxState.currentGear = gearboxParams.neutralGear;
gearboxState.targetGear = targetGearCommand;
gearboxState.gearSwitchTime = PX_VEHICLE_GEAR_SWITCH_INITIATED;
}
}
void PxVehicleAutoBoxUpdate
(const PxVehicleEngineParams& engineParams, const PxVehicleGearboxParams& gearboxParams, const PxVehicleAutoboxParams& autoboxParams,
const PxVehicleEngineState& engineState, const PxVehicleGearboxState& gearboxState,
const PxReal dt,
PxU32& targetGearCommand, PxVehicleAutoboxState& autoboxState,
PxReal& throttle)
{
if(targetGearCommand != PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR)
{
autoboxState.activeAutoboxGearShift = false;
autoboxState.timeSinceLastShift = PX_VEHICLE_UNSPECIFIED_TIME_SINCE_LAST_SHIFT;
return;
}
//Current and target gear allow us to determine if a gear change is underway.
const PxU32 currentGear = gearboxState.currentGear;
const PxU32 targetGear = gearboxState.targetGear;
//Set to current target gear in case no gear change will be initiated.
targetGearCommand = targetGear;
//If the autobox triggered a gear change and the gear change is complete then
//reset the corresponding flag.
if(autoboxState.activeAutoboxGearShift && (currentGear == targetGear))
{
autoboxState.activeAutoboxGearShift = false;
}
//If the autobox triggered a gear change and the gear change is incomplete then
//turn off the throttle pedal. This happens in autoboxes
//to stop the driver revving the engine then damaging the
//clutch when the clutch re-engages at the end of the gear change.
if(autoboxState.activeAutoboxGearShift && (currentGear != targetGear))
{
throttle = 0.0f;
}
//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.
if (targetGear == currentGear)
{
const PxF32 autoBoxSwitchTime = autoboxState.timeSinceLastShift;
const PxF32 autoBoxLatencyTime = autoboxParams.latency;
if ((currentGear <= gearboxParams.neutralGear) && ((gearboxParams.neutralGear + 1) < gearboxParams.nbRatios))
{
// eAUTOMATIC_GEAR has been set while in neutral or one of the reverse gears
// => switch to first
targetGearCommand = gearboxParams.neutralGear + 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
else if (autoBoxSwitchTime > autoBoxLatencyTime)
{
const PxF32 normalisedEngineOmega = engineState.rotationSpeed/engineParams.maxOmega;
const PxU32 neutralGear = gearboxParams.neutralGear;
const PxU32 nbGears = gearboxParams.nbRatios;
const PxF32 upRatio = autoboxParams.upRatios[currentGear];
const PxF32 downRatio = autoboxParams.downRatios[currentGear];
//If revs too high and not in reverse/neutral and there is a higher gear then switch up.
//Note: never switch up from neutral to first
//Note: never switch up from reverse to neutral
//Note: never switch up from one reverse gear to another reverse gear.
PX_ASSERT(currentGear > neutralGear);
if ((normalisedEngineOmega > upRatio) && ((currentGear + 1) < nbGears))
{
targetGearCommand = currentGear + 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
//If revs too low and in gear higher than first then switch down.
//Note: never switch from forward to neutral
//Note: never switch from neutral to reverse
//Note: never switch from reverse gear to reverse gear.
if ((normalisedEngineOmega < downRatio) && (currentGear > (neutralGear + 1)))
{
targetGearCommand = currentGear - 1;
throttle = 0.0f;
autoboxState.timeSinceLastShift = 0.0f;
autoboxState.activeAutoboxGearShift = true;
}
}
else
{
autoboxState.timeSinceLastShift += dt;
}
}
else
{
autoboxState.timeSinceLastShift += dt;
}
}
void PxVehicleGearboxUpdate(const PxVehicleGearboxParams& gearboxParams, const PxF32 dt, PxVehicleGearboxState& gearboxState)
{
if(gearboxState.targetGear != gearboxState.currentGear)
{
//If we just started a gear change then set the timer to zero.
//This replicates legacy behaviour.
if(gearboxState.gearSwitchTime == PX_VEHICLE_GEAR_SWITCH_INITIATED)
gearboxState.gearSwitchTime = 0.0f;
else
gearboxState.gearSwitchTime += dt;
//If we've exceed the switch time then switch to the target gear
//and reset the timer.
if (gearboxState.gearSwitchTime > gearboxParams.switchTime)
{
gearboxState.currentGear = gearboxState.targetGear;
gearboxState.gearSwitchTime = PX_VEHICLE_NO_GEAR_SWITCH_PENDING;
}
}
}
void countConnectedWheelsNotInConstraintGroup
(const PxU32* connectedWheelIds, const PxU32 nbConnectedWheelIds, const PxVehicleWheelConstraintGroupState& constraintGroups,
PxU32 connectedWheelsNotInConstraintGroup[PxVehicleLimits::eMAX_NB_WHEELS], PxU32& nbConnectedWheelsNotInConstraintGroup)
{
//Record the constraint group for each wheel.
//0xffffffff is reserved for a wheel not in a constraint group.
PxU32 wheelConstraintGroupIds[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemSet(wheelConstraintGroupIds, 0xffffffff, sizeof(wheelConstraintGroupIds));
for (PxU32 i = 0; i < constraintGroups.getNbConstraintGroups(); i++)
{
for (PxU32 j = 0; j < constraintGroups.getNbWheelsInConstraintGroup(i); j++)
{
const PxU32 wheelId = constraintGroups.getWheelInConstraintGroup(j, i);
wheelConstraintGroupIds[wheelId] = i;
}
}
//Iterate over all connected wheels and count the number not in a group.
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
const PxU32 constraintGroupId = wheelConstraintGroupIds[wheelId];
if (0xffffffff == constraintGroupId)
{
connectedWheelsNotInConstraintGroup[nbConnectedWheelsNotInConstraintGroup] = wheelId;
nbConnectedWheelsNotInConstraintGroup++;
}
}
}
void PxVehicleEngineDrivetrainUpdate
(const PxVehicleAxleDescription& axleDescription,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleEngineParams& engineParams, const PxVehicleClutchParams& clutchParams, const PxVehicleGearboxParams& gearboxParams,
const PxVehicleArrayData<const PxReal>& brakeResponseStates,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehicleGearboxState& gearboxState,
const PxVehicleEngineDriveThrottleCommandResponseState& throttleCommandResponseState, const PxVehicleClutchCommandResponseState& clutchCommandResponseState,
const PxVehicleDifferentialState& diffState, const PxVehicleWheelConstraintGroupState* constraintGroupState,
const PxReal DT,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidbody1dStates,
PxVehicleEngineState& engineState,
PxVehicleClutchSlipState& clutchState)
{
const PxF32 K = PxVehicleClutchStrengthCompute(clutchCommandResponseState, gearboxParams, gearboxState);
const PxF32 G = PxVehicleGearRatioCompute(gearboxParams, gearboxState);
const PxF32 engineDriveTorque = PxVehicleEngineDriveTorqueCompute(engineParams, engineState, throttleCommandResponseState);
const PxF32 engineDampingRate = PxVehicleEngineDampingRateCompute(engineParams, gearboxParams, gearboxState, clutchCommandResponseState, throttleCommandResponseState);
//Arrange wheel parameters in they order they appear in the connected wheel list.
const PxU32* connectedWheelIds = diffState.connectedWheels;
const PxU32 nbConnectedWheelIds = diffState.nbConnectedWheels;
PxU32 wheelIdToConnectedWheelId[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelDiffTorqueRatios[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelGearings[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelAveWheelSpeedContributions[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelMois[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelRotSpeeds[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelBrakeTorques[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelTireTorques[PxVehicleLimits::eMAX_NB_WHEELS];
PxF32 connectedWheelDampingRates[PxVehicleLimits::eMAX_NB_WHEELS];
bool connectedWheelIsBrakeApplied[PxVehicleLimits::eMAX_NB_WHEELS];
//PxF32 connectedWheelRadii[PxVehicleLimits::eMAX_NB_WHEELS];
for(PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
wheelIdToConnectedWheelId[wheelId] = i;
connectedWheelDiffTorqueRatios[i] = PxAbs(diffState.torqueRatiosAllWheels[wheelId]);
connectedWheelGearings[i] = PxVehicleComputeSign(diffState.torqueRatiosAllWheels[wheelId]);
connectedWheelAveWheelSpeedContributions[i] = diffState.aveWheelSpeedContributionAllWheels[wheelId];
connectedWheelMois[i] = wheelParams[wheelId].moi;
connectedWheelRotSpeeds[i] = wheelRigidbody1dStates[wheelId].rotationSpeed;
connectedWheelBrakeTorques[i] = -PxVehicleComputeSign(wheelRigidbody1dStates[wheelId].rotationSpeed)*brakeResponseStates[wheelId];
connectedWheelTireTorques[i] = tireForces[wheelId].wheelTorque;
connectedWheelDampingRates[i] = wheelParams[wheelId].dampingRate;
connectedWheelIsBrakeApplied[i] = actuationStates[wheelId].isBrakeApplied;
//connectedWheelRadii[i] = wheelParams[wheelId].radius;
};
//Compute the clutch slip
clutchState.setToDefault();
PxF32 clutchSlip = 0;
{
PxF32 averageWheelSpeed = 0;
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
averageWheelSpeed += connectedWheelRotSpeeds[i] * connectedWheelAveWheelSpeedContributions[i];
}
clutchSlip = G*averageWheelSpeed - engineState.rotationSpeed;
}
clutchState.clutchSlip = clutchSlip;
//
//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);
PxVehicleMatrixNN M(nbConnectedWheelIds + 1);
PxVehicleVectorN b(nbConnectedWheelIds + 1);
PxVehicleVectorN result(nbConnectedWheelIds + 1);
const PxF32 KG = K * G;
const PxF32 KGG = K * G*G;
//Wheels
{
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxF32 dt = DT / connectedWheelMois[i];
const PxF32 R = connectedWheelDiffTorqueRatios[i];
const PxF32 g = connectedWheelGearings[i];
const PxF32 dtKGGRg = dt * KGG*R*g;
for(PxU32 j = 0; j < nbConnectedWheelIds; j++)
{
M.set(i, j, dtKGGRg*connectedWheelAveWheelSpeedContributions[j]*connectedWheelGearings[j]);
}
M.set(i, i, 1.0f + dtKGGRg*connectedWheelAveWheelSpeedContributions[i]*connectedWheelGearings[i] + dt * connectedWheelDampingRates[i]);
M.set(i, nbConnectedWheelIds, -dt*KG*R*g);
b[i] = connectedWheelRotSpeeds[i] + dt * (connectedWheelBrakeTorques[i] + connectedWheelTireTorques[i]);
result[i] = connectedWheelRotSpeeds[i];
}
}
//Engine.
{
const PxF32 dt = DT / engineParams.moi;
const PxF32 dtKG = dt*K*G;
for(PxU32 j = 0; j < nbConnectedWheelIds; j++)
{
M.set(nbConnectedWheelIds, j, -dtKG * connectedWheelAveWheelSpeedContributions[j]* connectedWheelGearings[j]);
}
M.set(nbConnectedWheelIds, nbConnectedWheelIds, 1.0f + dt * (K + engineDampingRate));
b[nbConnectedWheelIds] = engineState.rotationSpeed + dt * engineDriveTorque;
result[nbConnectedWheelIds] = engineState.rotationSpeed;
}
if (constraintGroupState && constraintGroupState->getNbConstraintGroups() > 0)
{
const PxU32 nbConstraintGroups = constraintGroupState->getNbConstraintGroups();
//Count the wheels not in a constraint group.
PxU32 connectedWheelsNotInConstraintGroup[PxVehicleLimits::eMAX_NB_WHEELS];
PxU32 nbConnectedWheelsNotInConstraintGroup = 0;
countConnectedWheelsNotInConstraintGroup(
connectedWheelIds, nbConnectedWheelIds, *constraintGroupState,
connectedWheelsNotInConstraintGroup, nbConnectedWheelsNotInConstraintGroup);
//After applying constraint groups:
// number of columns remains nbConnectedWheelIds + 1
// each row will be of length nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups + 1
PxVehicleMatrixNN A(nbConnectedWheelIds + 1);
for (PxU32 i = 0; i < nbConnectedWheelIds + 1; i++)
{
//1 entry for each wheel not in a constraint group.
for (PxU32 j = 0; j < nbConnectedWheelsNotInConstraintGroup; j++)
{
const PxU32 wheelId = connectedWheelsNotInConstraintGroup[j];
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIJ = M.get(i, connectedWheelId);
A.set(i, j, MIJ);
}
//1 entry for each constraint group.
for (PxU32 j = nbConnectedWheelsNotInConstraintGroup; j < nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups; j++)
{
const PxU32 constraintGroupId = (j - nbConnectedWheelsNotInConstraintGroup);
PxF32 sum = 0.0f;
//for (PxU32 k = 0; k < 1; k++)
{
//k = 0 is a special case with multiplier = 1.0.
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(0, constraintGroupId);
const PxF32 multiplier = 1.0f;
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIK = M.get(i, connectedWheelId);
sum += MIK * multiplier;
}
for (PxU32 k = 1; k < constraintGroupState->getNbWheelsInConstraintGroup(constraintGroupId); k++)
{
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(k, constraintGroupId);
const PxF32 multiplier = constraintGroupState->getMultiplierInConstraintGroup(k, constraintGroupId);
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
const PxF32 MIK = M.get(i, connectedWheelId);
sum += MIK*multiplier;
}
A.set(i, j, sum);
}
//1 entry for the engine.
{
const PxF32 MIJ = M.get(i, nbConnectedWheelIds);
A.set(i, nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups, MIJ);
}
}
const PxU32 N = (nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups + 1);
//Compute A^T * A
PxVehicleMatrixNN ATA(N);
for (PxU32 i = 0; i < N; i++)
{
for (PxU32 j = 0; j < N; j++)
{
PxF32 sum = 0.0f;
for (PxU32 k = 0; k < nbConnectedWheelIds + 1; k++)
{
sum += A.get(k, i)*A.get(k, j);
}
ATA.set(i, j, sum);
}
}
//Compute A^T*b;
PxVehicleVectorN ATb(N);
for (PxU32 i = 0; i < N; i++)
{
PxF32 sum = 0;
for (PxU32 j = 0; j < nbConnectedWheelIds + 1; j++)
{
sum += A.get(j, i)*b[j];
}
ATb[i] = sum;
}
//Solve it.
PxVehicleMatrixNNLUSolver solver;
PxVehicleVectorN result2(N);
solver.decomposeLU(ATA);
solver.solve(ATb, result2);
//Map from result2 back to result.
for (PxU32 j = 0; j < nbConnectedWheelsNotInConstraintGroup; j++)
{
const PxU32 wheelId = connectedWheelsNotInConstraintGroup[j];
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = result2[j];
}
for (PxU32 j = nbConnectedWheelsNotInConstraintGroup; j < nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups; j++)
{
const PxU32 constraintGroupId = (j - nbConnectedWheelsNotInConstraintGroup);
//for (PxU32 k = 0; k < 1; k++)
{
//k = 0 is a special case with multiplier = 1.0
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(0, constraintGroupId);
const PxF32 multiplier = 1.0f;
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = multiplier * result2[j];
}
for (PxU32 k = 1; k < constraintGroupState->getNbWheelsInConstraintGroup(constraintGroupId); k++)
{
const PxU32 wheelId = constraintGroupState->getWheelInConstraintGroup(k, constraintGroupId);
const PxF32 multiplier = constraintGroupState->getMultiplierInConstraintGroup(k, constraintGroupId);
const PxU32 connectedWheelId = wheelIdToConnectedWheelId[wheelId];
result[connectedWheelId] = multiplier * result2[j];
}
}
{
result[nbConnectedWheelIds] = result2[nbConnectedWheelsNotInConstraintGroup + nbConstraintGroups];
}
}
else if (PxVehicleClutchAccuracyMode::eBEST_POSSIBLE == clutchParams.accuracyMode)
{
//Solve Aw=b
PxVehicleMatrixNNLUSolver solver;
solver.decomposeLU(M);
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
{
PxVehicleMatrixNGaussSeidelSolver solver;
solver.solve(clutchParams.estimateIterations, 1e-10f, M, 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 < nbConnectedWheelIds; i++)
{
result[i] = (connectedWheelIsBrakeApplied[i] && (connectedWheelRotSpeeds[i] * 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.
//The alternative would be to add constraints to the solver, which would be much more expensive.
result[nbConnectedWheelIds] = PxClamp(result[nbConnectedWheelIds], engineParams.idleOmega, engineParams.maxOmega);
//Copy back to the car's internal rotation speeds.
for (PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
wheelRigidbody1dStates[wheelId].rotationSpeed = result[i];
}
engineState.rotationSpeed = result[nbConnectedWheelIds];
//Update the undriven wheels.
bool isDrivenWheel[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(isDrivenWheel, sizeof(isDrivenWheel));
for(PxU32 i = 0; i < nbConnectedWheelIds; i++)
{
const PxU32 wheelId = connectedWheelIds[i];
isDrivenWheel[wheelId] = true;
}
for (PxU32 i = 0; i < axleDescription.nbWheels; i++)
{
const PxU32 wheelId = axleDescription.wheelIdsInAxleOrder[i];
if (!isDrivenWheel[wheelId])
{
PxVehicleDirectDriveUpdate(
wheelParams[wheelId],
actuationStates[wheelId],
brakeResponseStates[wheelId], 0.0f,
tireForces[wheelId], DT, wheelRigidbody1dStates[wheelId]);
}
}
}
void PxVehicleClutchCommandResponseLinearUpdate
(const PxReal clutchCommand,
const PxVehicleClutchCommandResponseParams& clutchResponseParams,
PxVehicleClutchCommandResponseState& clutchResponse)
{
clutchResponse.normalisedCommandResponse = (1.0f - clutchCommand);
clutchResponse.commandResponse = (1.0f - clutchCommand)*clutchResponseParams.maxResponse;
}
void PxVehicleEngineDriveThrottleCommandResponseLinearUpdate
(const PxVehicleCommandState& commands,
PxVehicleEngineDriveThrottleCommandResponseState& throttleResponse)
{
throttleResponse.commandResponse = commands.throttle;
}
} //namespace vehicle2
} //namespace physx
| 40,132 | C++ | 40.077789 | 218 | 0.75598 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdFunctions.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 "VhPvdAttributeHandles.h"
#include "VhPvdObjectHandles.h"
#include "VhPvdWriter.h"
#include "vehicle2/pvd/PxVehiclePvdFunctions.h"
#include "foundation/PxAllocatorCallback.h"
#include <stdio.h>
#include <stdlib.h>
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
PX_FORCE_INLINE void createPvdObject
(OmniPvdWriter& omniWriter, OmniPvdContextHandle contextHandle,
OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName)
{
omniWriter.createObject(contextHandle, classHandle, objectHandle, objectName);
}
PX_FORCE_INLINE void writeObjectHandleAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah,
OmniPvdObjectHandle val)
{
PX_ASSERT(oh);
PX_ASSERT(ah);
if(val)
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(OmniPvdObjectHandle));
}
PX_FORCE_INLINE void addObjectHandleToUniqueList
(OmniPvdWriter& ow, OmniPvdContextHandle ch, OmniPvdObjectHandle setOwnerOH, OmniPvdAttributeHandle setAH, OmniPvdObjectHandle ohToAdd)
{
PX_ASSERT(setOwnerOH);
PX_ASSERT(setAH);
if(ohToAdd)
ow.addToUniqueListAttribute(ch, setOwnerOH, setAH, reinterpret_cast<const uint8_t*>(&ohToAdd), sizeof(OmniPvdObjectHandle));
}
PX_FORCE_INLINE void appendWithInt(char* buffer, PxU32 number)
{
char num[8];
sprintf(num, "%d", number);
strcat(buffer, num);
}
PX_FORCE_INLINE void createVehicleObject
(const PxVehiclePvdAttributeHandles& attributeHandles,
PxVehiclePvdObjectHandles& objectHandles, OmniPvdWriter& omniWriter)
{
// Register the top-level vehicle object if this hasn't already been done.
if(0 == objectHandles.vehicleOH)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle vehicleOH = reinterpret_cast<OmniPvdObjectHandle>(&objectHandles.vehicleOH);
createPvdObject(omniWriter, objectHandles.contextHandle, attributeHandles.vehicle.CH, vehicleOH, "Vehicle");
objectHandles.vehicleOH = vehicleOH;
}
}
/////////////////////////////////
//RIGID BODY
/////////////////////////////////
void PxVehiclePvdRigidBodyRegister
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(rbodyParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.rigidBodyParamsOH);
createPvdObject(ow, ch, ah.rigidBodyParams.CH, oh, "RigidBodyParams");
objHands.rigidBodyParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.rigidBodyParamsAH, oh);
}
if(rbodyState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.rigidBodyStateOH);
createPvdObject(ow, ch, ah.rigidBodyState.CH, oh, "RigidBodyState");
objHands.rigidBodyStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.rigidBodyStateAH, oh);
}
}
void PxVehiclePvdRigidBodyWrite
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.rigidBodyParamsOH && rbodyParams)
{
writeRigidBodyParams(*rbodyParams, oh.rigidBodyParamsOH, ah.rigidBodyParams, ow, ch);
}
if(oh.rigidBodyStateOH && rbodyState)
{
writeRigidBodyState(*rbodyState, oh.rigidBodyStateOH, ah.rigidBodyState, ow, ch);
}
}
//////////////////////////////
//SUSP STATE CALC PARAMS
//////////////////////////////
void PxVehiclePvdSuspensionStateCalculationParamsRegister
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(suspStateCalcParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspStateCalcParamsOH);
createPvdObject(ow, ch, ah.suspStateCalcParams.CH, oh, "SuspStateCalcParams");
objHands.suspStateCalcParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.suspStateCalcParamsAH, oh);
}
}
void PxVehiclePvdSuspensionStateCalculationParamsWrite
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
if(oh.suspStateCalcParamsOH && suspStateCalcParams)
{
writeSuspStateCalcParams(*suspStateCalcParams, oh.suspStateCalcParamsOH, ah.suspStateCalcParams, omniWriter, oh.contextHandle);
}
}
/////////////////////////////
//COMMAND RESPONSE PARAMS
/////////////////////////////
void PxVehiclePvdCommandResponseRegister
(const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
brakeResponseParams.size <= 2,
"PxVehiclePvdCommandResponseRegister : brakeResponseParams.size must have less than or equal to 2");
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
for(PxU32 i = 0; i < brakeResponseParams.size; i++)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.brakeResponseParamOHs[i]);
char objectName[32] = "BrakeComandResponseParams";
appendWithInt(objectName, i);
createPvdObject(ow, ch, ah.brakeCommandResponseParams.CH, oh, objectName);
objHands.brakeResponseParamOHs[i] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.brakeResponseParamsSetAH, oh);
}
if(steerResponseParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.steerResponseParamsOH);
const char objectName[32] = "SteerCommandResponseParams";
createPvdObject(ow, ch, ah.steerCommandResponseParams.CH, oh, objectName);
objHands.steerResponseParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.steerResponseParamsAH, oh);
}
if (ackermannParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.ackermannParamsOH);
createPvdObject(ow, ch, ah.ackermannParams.CH, oh, "AckermannParams");
objHands.ackermannParamsOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.ackermannParamsAH, oh);
}
if(!brakeResponseStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.brakeResponseStateOH);
const char objectName[32] = "BrakeCommandResponseStates";
createPvdObject(ow, ch, ah.brakeCommandResponseStates.CH, oh, objectName);
objHands.brakeResponseStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.brakeResponseStatesAH, oh);
}
if(!steerResponseStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.steerResponseStateOH);
const char objectName[32] = "SteerCommandResponseStates";
createPvdObject(ow, ch, ah.steerCommandResponseStates.CH, oh, objectName);
objHands.steerResponseStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.steerResponseStatesAH, oh);
}
}
void PxVehiclePvdCommandResponseWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
brakeResponseParams.size <= 2,
"PxVehiclePvdCommandResponseWrite : brakeResponseParams.size must have less than or equal to 2");
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < brakeResponseParams.size; i++)
{
if(oh.brakeResponseParamOHs[i])
{
writeBrakeResponseParams(
axleDesc, brakeResponseParams[i],
oh.brakeResponseParamOHs[i], ah.brakeCommandResponseParams, ow, ch);
}
}
if(oh.steerResponseParamsOH && steerResponseParams)
{
writeSteerResponseParams(
axleDesc, *steerResponseParams,
oh.steerResponseParamsOH, ah.steerCommandResponseParams, ow, ch);
}
if (oh.ackermannParamsOH && ackermannParams)
{
writeAckermannParams(*ackermannParams, oh.ackermannParamsOH, ah.ackermannParams, ow, ch);
}
if(oh.brakeResponseStateOH && !brakeResponseStates.isEmpty())
{
writeBrakeResponseStates(axleDesc, brakeResponseStates, oh.brakeResponseStateOH, ah.brakeCommandResponseStates, ow, ch);
}
if(oh.steerResponseStateOH && !steerResponseStates.isEmpty())
{
writeSteerResponseStates(axleDesc, steerResponseStates, oh.steerResponseStateOH, ah.steerCommandResponseStates, ow, ch);
}
}
void PxVehiclePvdWheelAttachmentsRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspCompParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the wheel attachments
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < objHands.nbWheels,
"PxVehiclePvdWheelAttachmentsRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(!wheelParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelParamsOHs[wheelId]);
char objectName[32] = "WheelParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelParams.CH, oh, objectName);
objHands.wheelParamsOHs[wheelId] = oh;
}
if(!wheelActuationStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelActuationStateOHs[wheelId]);
char objectName[32] = "WheelActuationState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelActuationState.CH, oh, objectName);
objHands.wheelActuationStateOHs[wheelId] = oh;
}
if(!wheelRigidBody1dStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelRigidBody1dStateOHs[wheelId]);
char objectName[32] = "WheelRigidBody1dState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelRigidBody1dState.CH, oh, objectName);
objHands.wheelRigidBody1dStateOHs[wheelId] = oh;
}
if(!wheelLocalPoses.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelLocalPoseStateOHs[wheelId]);
char objectName[32] = "WheelLocalPoseState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelLocalPoseState.CH, oh, objectName);
objHands.wheelLocalPoseStateOHs[wheelId] = oh;
}
if(!roadGeometryStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.roadGeomStateOHs[wheelId]);
char objectName[32] = "RoadGeometryState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.roadGeomState.CH, oh, objectName);
objHands.roadGeomStateOHs[wheelId] = oh;
}
if(!suspParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspParamsOHs[wheelId]);
char objectName[32] = "SuspParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspParams.CH, oh, objectName);
objHands.suspParamsOHs[wheelId] = oh;
}
if(!suspCompParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspCompParamsOHs[wheelId]);
char objectName[32] = "SuspCompParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspCompParams.CH, oh, objectName);
objHands.suspCompParamsOHs[wheelId] = oh;
}
if(!suspForceParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspForceParamsOHs[wheelId]);
char objectName[32] = "SuspForceParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspForceParams.CH, oh, objectName);
objHands.suspForceParamsOHs[wheelId] = oh;
}
if(!suspStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspStateOHs[wheelId]);
char objectName[32] = "SuspState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspState.CH, oh, objectName);
objHands.suspStateOHs[wheelId] = oh;
}
if(!suspCompStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspCompStateOHs[wheelId]);
char objectName[32] = "SuspComplianceState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspCompState.CH, oh, objectName);
objHands.suspCompStateOHs[wheelId] = oh;
}
if(!suspForces.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.suspForceOHs[wheelId]);
char objectName[32] = "SuspForce";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.suspForce.CH, oh, objectName);
objHands.suspForceOHs[wheelId] = oh;
}
if(!tireForceParams.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireParamsOHs[wheelId]);
char objectName[32] = "TireParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireParams.CH, oh, objectName);
objHands.tireParamsOHs[wheelId] = oh;
}
if(!tireDirectionStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireDirectionStateOHs[wheelId]);
char objectName[32] = "TireDirectionState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireDirectionState.CH, oh, objectName);
objHands.tireDirectionStateOHs[wheelId] = oh;
}
if(!tireSpeedStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireSpeedStateOHs[wheelId]);
char objectName[32] = "TireSpeedState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireSpeedState.CH, oh, objectName);
objHands.tireSpeedStateOHs[wheelId] = oh;
}
if(!tireSlipStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireSlipStateOHs[wheelId]);
char objectName[32] = "TireSlipState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireSlipState.CH, oh, objectName);
objHands.tireSlipStateOHs[wheelId] = oh;
}
if(!tireStickyStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireStickyStateOHs[wheelId]);
char objectName[32] = "TireStickyState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireStickyState.CH, oh, objectName);
objHands.tireStickyStateOHs[wheelId] = oh;
}
if(!tireGripStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireGripStateOHs[wheelId]);
char objectName[32] = "TireGripState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireGripState.CH, oh, objectName);
objHands.tireGripStateOHs[wheelId] = oh;
}
if(!tireCamberStates.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireCamberStateOHs[wheelId]);
char objectName[32] = "TireCamberState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireCamberState.CH, oh, objectName);
objHands.tireCamberStateOHs[wheelId] = oh;
}
if(!tireForces.isEmpty())
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.tireForceOHs[wheelId]);
char objectName[32] = "TireForce";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.tireForce.CH, oh, objectName);
objHands.tireForceOHs[wheelId] = oh;
}
{
//Get a unique id from a memory adress in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.wheelAttachmentOHs[wheelId]);
char objectName[32] = "WheelAttachment";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.wheelAttachment.CH, oh, objectName);
objHands.wheelAttachmentOHs[wheelId] = oh;
// Point the wheel attachment object at the wheel params, susp state, tire force etc objects.
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelParamsAH, objHands.wheelParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelActuationStateAH, objHands.wheelActuationStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelRigidBody1dStateAH, objHands.wheelRigidBody1dStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.wheelLocalPoseStateAH, objHands.wheelLocalPoseStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.roadGeomStateAH, objHands.roadGeomStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspParamsAH, objHands.suspParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspCompParamsAH, objHands.suspCompParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspForceParamsAH, objHands.suspForceParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspStateAH, objHands.suspStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspCompStateAH, objHands.suspCompStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.suspForceAH, objHands.suspForceOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireParamsAH, objHands.tireParamsOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireDirectionStateAH, objHands.tireDirectionStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireSpeedStateAH, objHands.tireSpeedStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireSlipStateAH, objHands.tireSlipStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireStickyStateAH, objHands.tireStickyStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireGripStateAH, objHands.tireGripStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireCamberStateAH, objHands.tireCamberStateOHs[wheelId]);
writeObjectHandleAttribute(
ow, ch, oh, ah.wheelAttachment.tireForceAH, objHands.tireForceOHs[wheelId]);
//Point the vehicle object at the wheel attachment object.
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.wheelAttachmentSetAH, oh);
}
}
}
void PxVehiclePvdWheelAttachmentsWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspComplianceParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < oh.nbWheels,
"PxVehiclePvdWheelAttachmentsRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(oh.wheelParamsOHs[wheelId] && !wheelParams.isEmpty())
{
writeWheelParams(wheelParams[wheelId], oh.wheelParamsOHs[wheelId], ah.wheelParams, ow, ch);
}
if(oh.wheelActuationStateOHs[wheelId] && !wheelActuationStates.isEmpty())
{
writeWheelActuationState(wheelActuationStates[wheelId], oh.wheelActuationStateOHs[wheelId], ah.wheelActuationState, ow, ch);
}
if(oh.wheelRigidBody1dStateOHs[wheelId] && !wheelRigidBody1dStates.isEmpty())
{
writeWheelRigidBody1dState(wheelRigidBody1dStates[wheelId], oh.wheelRigidBody1dStateOHs[wheelId], ah.wheelRigidBody1dState, ow, ch);
}
if(oh.wheelLocalPoseStateOHs[wheelId] && !wheelLocalPoses.isEmpty())
{
writeWheelLocalPoseState(wheelLocalPoses[wheelId], oh.wheelLocalPoseStateOHs[wheelId], ah.wheelLocalPoseState, ow, ch);
}
if(oh.roadGeomStateOHs[wheelId] && !roadGeometryStates.isEmpty())
{
writeRoadGeomState(roadGeometryStates[wheelId], oh.roadGeomStateOHs[wheelId], ah.roadGeomState, ow, ch);
}
if(oh.suspParamsOHs[wheelId] && !suspParams.isEmpty())
{
writeSuspParams(suspParams[wheelId], oh.suspParamsOHs[wheelId], ah.suspParams, ow, ch);
}
if(oh.suspCompParamsOHs[wheelId] && !suspComplianceParams.isEmpty())
{
writeSuspComplianceParams(suspComplianceParams[wheelId], oh.suspCompParamsOHs[wheelId], ah.suspCompParams, ow, ch);
}
if(oh.suspForceParamsOHs[wheelId] && !suspForceParams.isEmpty())
{
writeSuspForceParams(suspForceParams[wheelId], oh.suspForceParamsOHs[wheelId], ah.suspForceParams, ow, ch);
}
if(oh.suspStateOHs[wheelId] && !suspStates.isEmpty())
{
writeSuspState(suspStates[wheelId], oh.suspStateOHs[wheelId], ah.suspState, ow, ch);
}
if(oh.suspCompStateOHs[wheelId] && !suspCompStates.isEmpty())
{
writeSuspComplianceState(suspCompStates[wheelId], oh.suspCompStateOHs[wheelId], ah.suspCompState, ow, ch);
}
if(oh.suspForceOHs[wheelId] && !suspForces.isEmpty())
{
writeSuspForce(suspForces[wheelId], oh.suspForceOHs[wheelId], ah.suspForce, ow, ch);
}
if(oh.tireParamsOHs[wheelId] && !tireForceParams.isEmpty())
{
writeTireParams(tireForceParams[wheelId], oh.tireParamsOHs[wheelId], ah.tireParams, ow, ch);
}
if(oh.tireDirectionStateOHs[wheelId] && !tireDirectionStates.isEmpty())
{
writeTireDirectionState(tireDirectionStates[wheelId], oh.tireDirectionStateOHs[wheelId], ah.tireDirectionState, ow, ch);
}
if(oh.tireSpeedStateOHs[wheelId] && !tireSpeedStates.isEmpty())
{
writeTireSpeedState(tireSpeedStates[wheelId], oh.tireSpeedStateOHs[wheelId], ah.tireSpeedState, ow, ch);
}
if(oh.tireSlipStateOHs[wheelId] && !tireSlipStates.isEmpty())
{
writeTireSlipState(tireSlipStates[wheelId], oh.tireSlipStateOHs[wheelId], ah.tireSlipState, ow, ch);
}
if(oh.tireStickyStateOHs[wheelId] && !tireStickyStates.isEmpty())
{
writeTireStickyState(tireStickyStates[wheelId], oh.tireStickyStateOHs[wheelId], ah.tireStickyState, ow, ch);
}
if(oh.tireGripStateOHs[wheelId] && !tireGripStates.isEmpty())
{
writeTireGripState(tireGripStates[wheelId], oh.tireGripStateOHs[wheelId], ah.tireGripState, ow, ch);
}
if(oh.tireCamberStateOHs[wheelId] && !tireCamberStates.isEmpty())
{
writeTireCamberState(tireCamberStates[wheelId], oh.tireCamberStateOHs[wheelId], ah.tireCamberState, ow, ch);
}
if(oh.tireForceOHs[wheelId] && !tireForces.isEmpty())
{
writeTireForce(tireForces[wheelId], oh.tireForceOHs[wheelId], ah.tireForce, ow, ch);
}
}
}
void PxVehiclePvdDirectDrivetrainRegister
(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(commandState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveCommandStateOH);
createPvdObject(ow, ch, ah.directDriveCommandState.CH, oh, "DirectDriveCommandState");
objHands.directDriveCommandStateOH = oh;
}
if(transmissionState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveTransmissionCommandStateOH);
createPvdObject(ow, ch, ah.directDriveTransmissionCommandState.CH, oh, "DirectDriveTransmissionCommandState");
objHands.directDriveTransmissionCommandStateOH = oh;
}
if(directDriveThrottleResponseParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveThrottleResponseParamsOH);
createPvdObject(ow, ch, ah.directDriveThrottleCommandResponseParams.CH, oh, "DirectDriveThrottleResponseParams");
objHands.directDriveThrottleResponseParamsOH = oh;
}
if(!directDriveThrottleResponseState.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDriveThrottleResponseStateOH);
createPvdObject(ow, ch, ah.directDriveThrottleCommandResponseState.CH, oh, "DirectDriveThrottleResponseState");
objHands.directDriveThrottleResponseStateOH = oh;
}
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.directDrivetrainOH);
createPvdObject(ow, ch, ah.directDrivetrain.CH, oh, "DirectDrivetrain");
objHands.directDrivetrainOH = oh;
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.commandStateAH, objHands.directDriveCommandStateOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.transmissionCommandStateAH, objHands.directDriveTransmissionCommandStateOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.throttleResponseParamsAH, objHands.directDriveThrottleResponseParamsOH);
writeObjectHandleAttribute(
ow, ch, oh, ah.directDrivetrain.throttleResponseStateAH, objHands.directDriveThrottleResponseStateOH);
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.directDrivetrainAH, oh);
}
}
void PxVehiclePvdDirectDrivetrainWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.directDriveCommandStateOH && commandState)
{
writeDirectDriveCommandState(*commandState, oh.directDriveCommandStateOH, ah.directDriveCommandState, ow, ch);
}
if(oh.directDriveTransmissionCommandStateOH && transmissionState)
{
writeDirectDriveTransmissionCommandState(*transmissionState, oh.directDriveTransmissionCommandStateOH, ah.directDriveTransmissionCommandState, ow, ch);
}
if(oh.directDriveThrottleResponseParamsOH)
{
writeDirectDriveThrottleResponseParams(axleDesc, *directDriveThrottleResponseParams, oh.directDriveThrottleResponseParamsOH, ah.directDriveThrottleCommandResponseParams, ow, ch);
}
if(oh.directDriveThrottleResponseStateOH && !directDriveThrottleResponseState.isEmpty())
{
writeDirectDriveThrottleResponseState(axleDesc, directDriveThrottleResponseState, oh.directDriveThrottleResponseStateOH, ah.directDriveThrottleCommandResponseState, ow, ch);
}
}
void PxVehiclePvdEngineDrivetrainRegister
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(commandState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveCommandStateOH);
createPvdObject(ow, ch, ah.engineDriveCommandState.CH, oh, "EngineDriveCommandState");
objHands.engineDriveCommandStateOH = oh;
}
if(engineDriveTransmissionCommandState || tankDriveTransmissionCommandState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveTransmissionCommandStateOH);
objHands.engineDriveTransmissionCommandStateOH = oh;
if (engineDriveTransmissionCommandState)
{
createPvdObject(ow, ch, ah.engineDriveTransmissionCommandState.CH, oh, "EngineDriveTransmissionCommandState");
}
else
{
PX_ASSERT(tankDriveTransmissionCommandState);
createPvdObject(ow, ch, ah.tankDriveTransmissionCommandState.CH, oh, "TankDriveTransmissionCommandState");
}
}
if(clutchResponseParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchResponseParamsOH);
createPvdObject(ow, ch, ah.clutchCommandResponseParams.CH, oh, "ClutchResponseParams");
objHands.clutchResponseParamsOH = oh;
}
if(clutchParms)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchParamsOH);
createPvdObject(ow, ch, ah.clutchParams.CH, oh, "ClutchParams");
objHands.clutchParamsOH = oh;
}
if(engineParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineParamsOH);
createPvdObject(ow, ch, ah.engineParams.CH, oh, "EngineParams");
objHands.engineParamsOH = oh;
}
if(gearboxParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.gearboxParamsOH);
createPvdObject(ow, ch, ah.gearboxParams.CH, oh, "GearboxParams");
objHands.gearboxParamsOH = oh;
}
if(autoboxParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.autoboxParamsOH);
createPvdObject(ow, objHands.contextHandle, ah.autoboxParams.CH, oh, "AutoboxParams");
objHands.autoboxParamsOH = oh;
}
if(multiWheelDiffParams || fourWheelDiffParams || tankDiffParams)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.differentialParamsOH);
objHands.differentialParamsOH = oh;
if(multiWheelDiffParams)
{
createPvdObject(ow, ch, ah.multiwheelDiffParams.CH, oh, "MultiWheelDiffParams");
}
else if(fourWheelDiffParams)
{
createPvdObject(ow, ch, ah.fourwheelDiffParams.CH, oh, "FourWheelDiffParams");
}
else
{
PX_ASSERT(tankDiffParams);
createPvdObject(ow, ch, ah.tankDiffParams.CH, oh, "TankDiffParams");
}
}
if(clutchResponseState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchResponseStateOH);
createPvdObject(ow, ch, ah.clutchResponseState.CH, oh, "ClutchResponseState");
objHands.clutchResponseStateOH = oh;
}
if(throttleResponseState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDriveThrottleResponseStateOH);
createPvdObject(ow, ch, ah.throttleResponseState.CH, oh, "ThrottleResponseState");
objHands.engineDriveThrottleResponseStateOH = oh;
}
if(engineState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineStateOH);
createPvdObject(ow, ch, ah.engineState.CH, oh, "EngineState");
objHands.engineStateOH = oh;
}
if(gearboxState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.gearboxStateOH);
createPvdObject(ow, ch, ah.gearboxState.CH, oh, "GearboxState");
objHands.gearboxStateOH = oh;
}
if(autoboxState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.autoboxStateOH);
createPvdObject(ow, ch, ah.autoboxState.CH, oh, "AutoboxState");
objHands.autoboxStateOH = oh;
}
if(diffState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.diffStateOH);
createPvdObject(ow, ch, ah.diffState.CH, oh, "DiffState");
objHands.diffStateOH = oh;
}
if(clutchSlipState)
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.clutchSlipStateOH);
createPvdObject(ow, ch, ah.clutchSlipState.CH, oh, "ClutchSlipState");
objHands.clutchSlipStateOH = oh;
}
//Engine drivetrain
{
//Get a unique id from a memory address in objectHandles.
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.engineDrivetrainOH);
createPvdObject(ow, ch, ah.engineDrivetrain.CH, oh, "EngineDrivetrain");
objHands.engineDrivetrainOH = oh;
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.commandStateAH, objHands.engineDriveCommandStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.transmissionCommandStateAH, objHands.engineDriveTransmissionCommandStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchResponseParamsAH, objHands.clutchResponseParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchParamsAH, objHands.clutchParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.engineParamsAH, objHands.engineParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.gearboxParamsAH, objHands.gearboxParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.autoboxParamsAH, objHands.autoboxParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.differentialParamsAH, objHands.differentialParamsOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchResponseStateAH, objHands.clutchResponseStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.throttleResponseStateAH, objHands.engineDriveThrottleResponseStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.engineStateAH, objHands.engineStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.gearboxStateAH, objHands.gearboxStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.autoboxStateAH, objHands.autoboxStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.diffStateAH, objHands.diffStateOH);
writeObjectHandleAttribute(ow, ch, oh, ah.engineDrivetrain.clutchSlipStateAH, objHands.clutchSlipStateOH);
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.engineDriveTrainAH, oh);
}
}
void PxVehiclePvdEngineDrivetrainWrite
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
const OmniPvdContextHandle ch = oh.contextHandle;
if(oh.engineDriveCommandStateOH && commandState)
{
writeEngineDriveCommandState(*commandState, oh.engineDriveCommandStateOH, ah.engineDriveCommandState, omniWriter, ch);
}
if(oh.engineDriveTransmissionCommandStateOH)
{
if (engineDriveTransmissionCommandState)
{
writeEngineDriveTransmissionCommandState(*engineDriveTransmissionCommandState,
oh.engineDriveTransmissionCommandStateOH, ah.engineDriveTransmissionCommandState, omniWriter, ch);
}
else if (tankDriveTransmissionCommandState)
{
writeTankDriveTransmissionCommandState(*tankDriveTransmissionCommandState, oh.engineDriveTransmissionCommandStateOH,
ah.engineDriveTransmissionCommandState, ah.tankDriveTransmissionCommandState, omniWriter, ch);
}
}
if(oh.clutchResponseParamsOH && clutchResponseParams)
{
writeClutchResponseParams(*clutchResponseParams, oh.clutchResponseParamsOH, ah.clutchCommandResponseParams, omniWriter, ch);
}
if(oh.clutchParamsOH && clutchParms)
{
writeClutchParams(*clutchParms, oh.clutchParamsOH, ah.clutchParams, omniWriter, ch);
}
if(oh.engineParamsOH && engineParams)
{
writeEngineParams(*engineParams, oh.engineParamsOH, ah.engineParams, omniWriter, ch);
}
if(oh.gearboxParamsOH && gearboxParams)
{
writeGearboxParams(*gearboxParams, oh.gearboxParamsOH, ah.gearboxParams, omniWriter, ch);
}
if(oh.autoboxParamsOH && autoboxParams)
{
writeAutoboxParams(*autoboxParams, oh.autoboxParamsOH, ah.autoboxParams, omniWriter, ch);
}
if(oh.differentialParamsOH)
{
if (multiWheelDiffParams)
{
writeMultiWheelDiffParams(*multiWheelDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, omniWriter, ch);
}
else if (fourWheelDiffParams)
{
writeFourWheelDiffParams(*fourWheelDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, ah.fourwheelDiffParams, omniWriter, ch);
}
else if (tankDiffParams)
{
writeTankDiffParams(*tankDiffParams, oh.differentialParamsOH,
ah.multiwheelDiffParams, ah.tankDiffParams, omniWriter, ch);
}
}
if(oh.clutchResponseStateOH && clutchResponseState)
{
writeClutchResponseState(*clutchResponseState, oh.clutchResponseStateOH, ah.clutchResponseState, omniWriter, ch);
}
if(oh.engineDriveThrottleResponseStateOH && throttleResponseState)
{
writeThrottleResponseState(*throttleResponseState, oh.engineDriveThrottleResponseStateOH, ah.throttleResponseState, omniWriter, ch);
}
if(oh.engineStateOH && engineState)
{
writeEngineState(*engineState, oh.engineStateOH, ah.engineState, omniWriter, ch);
}
if(oh.gearboxStateOH && gearboxState)
{
writeGearboxState(*gearboxState, oh.gearboxStateOH, ah.gearboxState, omniWriter, ch);
}
if(oh.autoboxStateOH && autoboxState)
{
writeAutoboxState(*autoboxState, oh.autoboxStateOH, ah.autoboxState, omniWriter, ch);
}
if(oh.diffStateOH && diffState)
{
writeDiffState(*diffState, oh.diffStateOH, ah.diffState, omniWriter, ch);
}
if(oh.clutchSlipStateOH && clutchSlipState)
{
writeClutchSlipState(*clutchSlipState, oh.clutchSlipStateOH, ah.clutchSlipState, omniWriter, ch);
}
}
void PxVehiclePvdAntiRollsRegister
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
antiRollForceParams.size <= objHands.nbAntirolls,
"PxVehiclePvdAntiRollsRegister - antiRollForceParams.size must be less than or equal to vallue of nbAntirolls argument in the function PxVehiclePvdObjectCreate");
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the antiroll params.
for(PxU32 i = 0; i < antiRollForceParams.size; i++)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.antiRollParamOHs[i]);
char objectName[32] = "AntiRollParams";
appendWithInt(objectName, i);
createPvdObject(ow, ch, ah.antiRollParams.CH, oh, objectName);
objHands.antiRollParamOHs[i] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.antiRollSetAH, oh);
}
// Register the antiroll force.
if(antiRollTorque)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.antiRollTorqueOH);
const char objectName[32] = "AntiRollTorque";
createPvdObject(ow, ch, ah.antiRollForce.CH, oh, objectName);
objHands.antiRollTorqueOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.antiRollForceAH, oh);
}
}
void PxVehiclePvdAntiRollsWrite
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_CHECK_AND_RETURN(
antiRollForceParams.size <= oh.nbAntirolls,
"PxVehiclePvdAntiRollsWrite - antiRollForceParams.size must be less than or equal to vallue of nbAntirolls argument in the function PxVehiclePvdObjectCreate");
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < antiRollForceParams.size; i++)
{
if(oh.antiRollParamOHs[i] && !antiRollForceParams.isEmpty())
{
writeAntiRollParams(antiRollForceParams[i], oh.antiRollParamOHs[i], ah.antiRollParams, ow, ch);
}
}
if(oh.antiRollTorqueOH && antiRollTorque)
{
writeAntiRollForce(*antiRollTorque, oh.antiRollTorqueOH, ah.antiRollForce, ow, ch);
}
}
void PxVehiclePvdPhysXWheelAttachmentRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxRoadGeomState);
PX_UNUSED(physxConstraintStates);
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
// Register the wheel attachments
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < objHands.nbWheels,
"PxVehiclePvdPhysXWheelAttachmentRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(!physxSuspLimitConstraintParams.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxConstraintParamOHs[wheelId]);
char objectName[32] = "PhysXSuspLimtConstraintParams";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxSuspLimitConstraintParams.CH, oh, objectName);
objHands.physxConstraintParamOHs[wheelId] = oh;
}
if(physxActor && physxActor->wheelShapes[wheelId])
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxWheelShapeOHs[wheelId]);
char objectName[32] = "PhysXWheelShape";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxWheelShape.CH, oh, objectName);
objHands.physxWheelShapeOHs[wheelId] = oh;
}
if(!physxConstraintStates.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxConstraintStateOHs[wheelId]);
char objectName[32] = "PhysXConstraintState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxConstraintState.CH, oh, objectName);
objHands.physxConstraintStateOHs[wheelId] = oh;
}
if(!physxRoadGeomState.isEmpty())
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomStateOHs[wheelId]);
char objectName[32] = "PhysXRoadGeomState";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxRoadGeomState.CH, oh, objectName);
objHands.physxRoadGeomStateOHs[wheelId] = oh;
}
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxWheelAttachmentOHs[wheelId]);
char objectName[32] = "PhysxWheelAttachment";
appendWithInt(objectName, wheelId);
createPvdObject(ow, ch, ah.physxWheelAttachment.CH, oh, objectName);
objHands.physxWheelAttachmentOHs[wheelId] = oh;
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxConstraintParamsAH, objHands.physxConstraintParamOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxWeelShapeAH, objHands.physxWheelShapeOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxRoadGeometryStateAH, objHands.physxRoadGeomStateOHs[wheelId]);
writeObjectHandleAttribute(ow, ch, oh, ah.physxWheelAttachment.physxConstraintStateAH, objHands.physxConstraintStateOHs[wheelId]);
addObjectHandleToUniqueList(ow, ch, objHands.vehicleOH, ah.vehicle.physxWheelAttachmentSetAH, oh);
}
if(!physxMaterialFrictionParams.isEmpty())
{
for(PxU32 j = 0; j < objHands.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = wheelId*objHands.nbPhysXMaterialFrictions + j;
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxMaterialFrictionOHs[id]);
char objectName[32] = "PhysxMaterialFriction";
appendWithInt(objectName, wheelId);
strcat(objectName, "_");
appendWithInt(objectName, j);
createPvdObject(ow, ch, ah.physxMaterialFriction.CH, oh, objectName);
objHands.physxMaterialFrictionOHs[id] = oh;
addObjectHandleToUniqueList(ow, ch, objHands.physxWheelAttachmentOHs[wheelId], ah.physxWheelAttachment.physxMaterialFrictionSetAH, oh);
}
}
}
if(physxRoadGeomQryParams)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryParamOH);
char objectName[32] = "PhysxRoadGeomQryParams";
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.CH, oh, objectName);
objHands.physxRoadGeomQueryParamOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxRoadGeometryQueryParamsAH, oh);
const OmniPvdObjectHandle defaultFilterDataOH = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryDefaultFilterDataOH);
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.filterDataParams.CH, defaultFilterDataOH, "");
objHands.physxRoadGeomQueryDefaultFilterDataOH = defaultFilterDataOH;
writeObjectHandleAttribute(ow, ch, objHands.physxRoadGeomQueryParamOH, ah.physxRoadGeometryQueryParams.defaultFilterDataAH, defaultFilterDataOH);
if (physxRoadGeomQryParams->filterDataEntries)
{
for (PxU32 j = 0; j < axleDesc.nbWheels; j++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[j];
const OmniPvdObjectHandle filterDataOH = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRoadGeomQueryFilterDataOHs[wheelId]);
char filterDataObjectName[32] = "FilterData";
appendWithInt(filterDataObjectName, wheelId);
createPvdObject(ow, ch, ah.physxRoadGeometryQueryParams.filterDataParams.CH, filterDataOH, filterDataObjectName);
objHands.physxRoadGeomQueryFilterDataOHs[wheelId] = filterDataOH;
addObjectHandleToUniqueList(ow, ch, objHands.physxRoadGeomQueryParamOH, ah.physxRoadGeometryQueryParams.filterDataSetAH, filterDataOH);
}
}
#if PX_DEBUG
else
{
for (PxU32 j = 0; j < axleDesc.nbWheels; j++)
{
// note: objHands.physxRoadGeomQueryFilterDataOHs entries are zero initialized
// which matches the invalid handle for now.
PX_ASSERT(objHands.physxRoadGeomQueryFilterDataOHs[j] == 0);
// TODO: test against invalid hanndle once it gets introduced
}
}
#endif
}
}
void PxVehiclePvdPhysXWheelAttachmentWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomStates,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxRoadGeomStates);
PX_UNUSED(physxConstraintStates);
const OmniPvdContextHandle ch = oh.contextHandle;
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
PX_CHECK_AND_RETURN(
wheelId < oh.nbWheels,
"PxVehiclePvdPhysXWheelAttachmentRegister - axleDesc.axleToWheelIds[i] must be less than the value of the nbWheels argument in the function PxVehiclePvdObjectCreate()");
if(oh.physxConstraintParamOHs[wheelId] && !physxSuspLimitConstraintParams.isEmpty())
{
writePhysXSuspLimitConstraintParams(physxSuspLimitConstraintParams[wheelId], oh.physxConstraintParamOHs[wheelId], ah.physxSuspLimitConstraintParams, ow, ch);
}
if(oh.physxWheelShapeOHs[wheelId] && physxActor)
{
writePhysXWheelShape(physxActor->wheelShapes[wheelId], oh.physxWheelShapeOHs[wheelId], ah.physxWheelShape, ow, ch);
}
if(oh.physxRoadGeomStateOHs[wheelId] && !physxRoadGeomStates.isEmpty())
{
writePhysXRoadGeomState(physxRoadGeomStates[wheelId], oh.physxRoadGeomStateOHs[wheelId], ah.physxRoadGeomState, ow, ch);
}
if(oh.physxConstraintStateOHs[wheelId] && !physxConstraintStates.isEmpty())
{
writePhysXConstraintState(physxConstraintStates[wheelId], oh.physxConstraintStateOHs[wheelId], ah.physxConstraintState, ow, ch);
}
if(!physxMaterialFrictionParams.isEmpty())
{
for(PxU32 j = 0; j < physxMaterialFrictionParams[wheelId].nbMaterialFrictions; j++)
{
const PxU32 id = wheelId*oh.nbPhysXMaterialFrictions + j;
if(oh.physxMaterialFrictionOHs[id])
{
const PxVehiclePhysXMaterialFriction& m = physxMaterialFrictionParams[wheelId].materialFrictions[j];
writePhysXMaterialFriction(m, oh.physxMaterialFrictionOHs[id], ah.physxMaterialFriction, ow, ch);
}
}
for(PxU32 j = physxMaterialFrictionParams[wheelId].nbMaterialFrictions; j < oh.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = wheelId*oh.nbPhysXMaterialFrictions + j;
if(oh.physxMaterialFrictionOHs[id])
{
PxVehiclePhysXMaterialFriction m;
m.friction = -1.0f;
m.material = NULL;
writePhysXMaterialFriction(m, oh.physxMaterialFrictionOHs[id], ah.physxMaterialFriction, ow, ch);
}
}
}
}
if(oh.physxRoadGeomQueryParamOH && physxRoadGeomQryParams)
{
writePhysXRoadGeometryQueryParams(*physxRoadGeomQryParams, axleDesc,
oh.physxRoadGeomQueryParamOH, oh.physxRoadGeomQueryDefaultFilterDataOH, oh.physxRoadGeomQueryFilterDataOHs,
ah.physxRoadGeometryQueryParams, ow, ch);
}
}
void PxVehiclePvdPhysXRigidActorRegister
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(physxActor && physxActor->rigidBody)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxRigidActorOH);
createPvdObject(ow, ch, ah.physxRigidActor.CH, oh, "PhysXRigidActor");
objHands.physxRigidActorOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxRigidActorAH, oh);
}
}
void PxVehiclePvdPhysXRigidActorWrite
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
if(oh.physxRigidActorOH && physxActor)
{
writePhysXRigidActor(physxActor->rigidBody, oh.physxRigidActorOH, ah.physxRigidActor, ow, oh.contextHandle);
}
}
void PxVehiclePvdPhysXSteerStateRegister
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
// Register the top-level vehicle object if this hasn't already been done.
createVehicleObject(ah, objHands, ow);
const OmniPvdContextHandle ch = objHands.contextHandle;
if(physxSteerState)
{
const OmniPvdObjectHandle oh = reinterpret_cast<OmniPvdObjectHandle>(&objHands.physxSteerStateOH);
createPvdObject(ow, ch, ah.physxSteerState.CH, oh, "PhysXSteerState");
objHands.physxSteerStateOH = oh;
writeObjectHandleAttribute(ow, ch, objHands.vehicleOH, ah.vehicle.physxSteerStateAH, oh);
}
}
void PxVehiclePvdPhysXSteerStateWrite
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
if (objHands.physxSteerStateOH && physxSteerState) // TODO: test against invalid handle once that gets introduced
{
writePhysXSteerState(*physxSteerState, objHands.physxSteerStateOH, ah.physxSteerState, ow, objHands.contextHandle);
}
}
#else //PX_SUPPORT_OMNI_PVD
void PxVehiclePvdRigidBodyRegister
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(rbodyParams);
PX_UNUSED(rbodyState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdRigidBodyWrite
(const PxVehicleRigidBodyParams* rbodyParams, const PxVehicleRigidBodyState* rbodyState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(rbodyParams);
PX_UNUSED(rbodyState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdSuspensionStateCalculationParamsRegister
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(suspStateCalcParams);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdSuspensionStateCalculationParamsWrite
(const PxVehicleSuspensionStateCalculationParams* suspStateCalcParams,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(suspStateCalcParams);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdCommandResponseRegister
(const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(steerResponseParams);
PX_UNUSED(brakeResponseParams);
PX_UNUSED(ackermannParams);
PX_UNUSED(steerResponseStates);
PX_UNUSED(brakeResponseStates);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdCommandResponseWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSizedArrayData<const PxVehicleBrakeCommandResponseParams>& brakeResponseParams,
const PxVehicleSteerCommandResponseParams* steerResponseParams,
const PxVehicleAckermannParams* ackermannParams,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(steerResponseParams);
PX_UNUSED(brakeResponseParams);
PX_UNUSED(ackermannParams);
PX_UNUSED(steerResponseStates);
PX_UNUSED(brakeResponseStates);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdWheelAttachmentsRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspCompParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(wheelParams);
PX_UNUSED(wheelActuationStates);
PX_UNUSED(wheelRigidBody1dStates);
PX_UNUSED(wheelLocalPoses);
PX_UNUSED(roadGeometryStates);
PX_UNUSED(suspParams);
PX_UNUSED(suspCompParams);
PX_UNUSED(suspForceParams);
PX_UNUSED(suspStates);
PX_UNUSED(suspCompStates);
PX_UNUSED(suspForces);
PX_UNUSED(tireForceParams);
PX_UNUSED(tireDirectionStates);
PX_UNUSED(tireSpeedStates);
PX_UNUSED(tireSlipStates);
PX_UNUSED(tireStickyStates);
PX_UNUSED(tireGripStates);
PX_UNUSED(tireCamberStates);
PX_UNUSED(tireForces);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdWheelAttachmentsWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
const PxVehicleArrayData<const PxVehicleWheelActuationState>& wheelActuationStates,
const PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
const PxVehicleArrayData<const PxVehicleWheelLocalPose>& wheelLocalPoses,
const PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeometryStates,
const PxVehicleArrayData<const PxVehicleSuspensionParams>& suspParams,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceParams>& suspComplianceParams,
const PxVehicleArrayData<const PxVehicleSuspensionForceParams>& suspForceParams,
const PxVehicleArrayData<const PxVehicleSuspensionState>& suspStates,
const PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspCompStates,
const PxVehicleArrayData<const PxVehicleSuspensionForce>& suspForces,
const PxVehicleArrayData<const PxVehicleTireForceParams>& tireForceParams,
const PxVehicleArrayData<const PxVehicleTireDirectionState>& tireDirectionStates,
const PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
const PxVehicleArrayData<const PxVehicleTireSlipState>& tireSlipStates,
const PxVehicleArrayData<const PxVehicleTireStickyState>& tireStickyStates,
const PxVehicleArrayData<const PxVehicleTireGripState>& tireGripStates,
const PxVehicleArrayData<const PxVehicleTireCamberAngleState>& tireCamberStates,
const PxVehicleArrayData<const PxVehicleTireForce>& tireForces,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(wheelParams);
PX_UNUSED(wheelActuationStates);
PX_UNUSED(wheelRigidBody1dStates);
PX_UNUSED(wheelLocalPoses);
PX_UNUSED(roadGeometryStates);
PX_UNUSED(suspParams);
PX_UNUSED(suspComplianceParams);
PX_UNUSED(suspForceParams);
PX_UNUSED(suspStates);
PX_UNUSED(suspCompStates);
PX_UNUSED(suspForces);
PX_UNUSED(tireForceParams);
PX_UNUSED(tireDirectionStates);
PX_UNUSED(tireSpeedStates);
PX_UNUSED(tireSlipStates);
PX_UNUSED(tireStickyStates);
PX_UNUSED(tireGripStates);
PX_UNUSED(tireCamberStates);
PX_UNUSED(tireForces);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdDirectDrivetrainRegister
(const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(commandState);
PX_UNUSED(transmissionState);
PX_UNUSED(directDriveThrottleResponseParams);
PX_UNUSED(directDriveThrottleResponseState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdDirectDrivetrainWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleCommandState* commandState, const PxVehicleDirectDriveTransmissionCommandState* transmissionState,
const PxVehicleDirectDriveThrottleCommandResponseParams* directDriveThrottleResponseParams,
const PxVehicleArrayData<PxReal>& directDriveThrottleResponseState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(commandState);
PX_UNUSED(transmissionState);
PX_UNUSED(directDriveThrottleResponseParams);
PX_UNUSED(directDriveThrottleResponseState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdEngineDrivetrainRegister
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffPrams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(commandState);
PX_UNUSED(engineDriveTransmissionCommandState);
PX_UNUSED(tankDriveTransmissionCommandState);
PX_UNUSED(clutchResponseParams);
PX_UNUSED(clutchParms);
PX_UNUSED(engineParams);
PX_UNUSED(gearboxParams);
PX_UNUSED(autoboxParams);
PX_UNUSED(multiWheelDiffParams);
PX_UNUSED(fourWheelDiffPrams);
PX_UNUSED(tankDiffParams);
PX_UNUSED(clutchResponseState);
PX_UNUSED(throttleResponseState);
PX_UNUSED(engineState);
PX_UNUSED(gearboxState);
PX_UNUSED(autoboxState);
PX_UNUSED(diffState);
PX_UNUSED(clutchSlipState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdEngineDrivetrainWrite
(const PxVehicleCommandState* commandState,
const PxVehicleEngineDriveTransmissionCommandState* engineDriveTransmissionCommandState,
const PxVehicleTankDriveTransmissionCommandState* tankDriveTransmissionCommandState,
const PxVehicleClutchCommandResponseParams* clutchResponseParams,
const PxVehicleClutchParams* clutchParms,
const PxVehicleEngineParams* engineParams,
const PxVehicleGearboxParams* gearboxParams,
const PxVehicleAutoboxParams* autoboxParams,
const PxVehicleMultiWheelDriveDifferentialParams* multiWheelDiffParams,
const PxVehicleFourWheelDriveDifferentialParams* fourWheelDiffParams,
const PxVehicleTankDriveDifferentialParams* tankDiffParams,
const PxVehicleClutchCommandResponseState* clutchResponseState,
const PxVehicleEngineDriveThrottleCommandResponseState* throttleResponseState,
const PxVehicleEngineState* engineState,
const PxVehicleGearboxState* gearboxState,
const PxVehicleAutoboxState* autoboxState,
const PxVehicleDifferentialState* diffState,
const PxVehicleClutchSlipState* clutchSlipState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& omniWriter)
{
PX_UNUSED(commandState);
PX_UNUSED(engineDriveTransmissionCommandState);
PX_UNUSED(tankDriveTransmissionCommandState);
PX_UNUSED(clutchResponseParams);
PX_UNUSED(clutchParms);
PX_UNUSED(engineParams);
PX_UNUSED(gearboxParams);
PX_UNUSED(autoboxParams);
PX_UNUSED(multiWheelDiffParams);
PX_UNUSED(fourWheelDiffParams);
PX_UNUSED(tankDiffParams);
PX_UNUSED(clutchResponseState);
PX_UNUSED(throttleResponseState);
PX_UNUSED(engineState);
PX_UNUSED(gearboxState);
PX_UNUSED(autoboxState);
PX_UNUSED(diffState);
PX_UNUSED(clutchSlipState);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(omniWriter);
}
void PxVehiclePvdAntiRollsRegister
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(antiRollForceParams);
PX_UNUSED(antiRollTorque);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdAntiRollsWrite
(const PxVehicleSizedArrayData<const PxVehicleAntiRollForceParams>& antiRollForceParams,
const PxVehicleAntiRollTorque* antiRollTorque,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(antiRollForceParams);
PX_UNUSED(antiRollTorque);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXWheelAttachmentRegister
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomState,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(physxSuspLimitConstraintParams);
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxActor);
PX_UNUSED(physxRoadGeomQryParams);
PX_UNUSED(physxRoadGeomState);
PX_UNUSED(physxConstraintStates);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXWheelAttachmentWrite
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<const PxVehiclePhysXSuspensionLimitConstraintParams>& physxSuspLimitConstraintParams,
const PxVehicleArrayData<const PxVehiclePhysXMaterialFrictionParams>& physxMaterialFrictionParams,
const PxVehiclePhysXActor* physxActor, const PxVehiclePhysXRoadGeometryQueryParams* physxRoadGeomQryParams,
const PxVehicleArrayData<const PxVehiclePhysXRoadGeometryQueryState>& physxRoadGeomStates,
const PxVehicleArrayData<const PxVehiclePhysXConstraintState>& physxConstraintStates,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(axleDesc);
PX_UNUSED(physxSuspLimitConstraintParams);
PX_UNUSED(physxMaterialFrictionParams);
PX_UNUSED(physxActor);
PX_UNUSED(physxRoadGeomQryParams);
PX_UNUSED(physxRoadGeomStates);
PX_UNUSED(physxConstraintStates);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXRigidActorRegister
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxActor);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXRigidActorWrite
(const PxVehiclePhysXActor* physxActor,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& oh, OmniPvdWriter& ow)
{
PX_UNUSED(physxActor);
PX_UNUSED(ah);
PX_UNUSED(oh);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXSteerStateRegister
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxSteerState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
void PxVehiclePvdPhysXSteerStateWrite
(const PxVehiclePhysXSteerState* physxSteerState,
const PxVehiclePvdAttributeHandles& ah,
const PxVehiclePvdObjectHandles& objHands, OmniPvdWriter& ow)
{
PX_UNUSED(physxSteerState);
PX_UNUSED(ah);
PX_UNUSED(objHands);
PX_UNUSED(ow);
}
#endif
} // namespace vehicle2
} // namespace physx
/** @} */
| 77,426 | C++ | 39.923362 | 181 | 0.803761 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdObjectHandles.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.
#pragma once
#include "vehicle2/PxVehicleLimits.h"
#if PX_SUPPORT_OMNI_PVD
#include "OmniPvdWriter.h"
#endif
#include "foundation/PxMemory.h"
/** \addtogroup vehicle2
@{
*/
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehiclePvdObjectHandles
{
#if PX_SUPPORT_OMNI_PVD
OmniPvdObjectHandle vehicleOH;
OmniPvdObjectHandle rigidBodyParamsOH;
OmniPvdObjectHandle rigidBodyStateOH;
OmniPvdObjectHandle suspStateCalcParamsOH;
OmniPvdObjectHandle brakeResponseParamOHs[2];
OmniPvdObjectHandle steerResponseParamsOH;
OmniPvdObjectHandle brakeResponseStateOH;
OmniPvdObjectHandle steerResponseStateOH;
OmniPvdObjectHandle ackermannParamsOH;
OmniPvdObjectHandle directDriveCommandStateOH;
OmniPvdObjectHandle directDriveTransmissionCommandStateOH;
OmniPvdObjectHandle directDriveThrottleResponseParamsOH;
OmniPvdObjectHandle directDriveThrottleResponseStateOH;
OmniPvdObjectHandle directDrivetrainOH;
OmniPvdObjectHandle engineDriveCommandStateOH;
OmniPvdObjectHandle engineDriveTransmissionCommandStateOH;
OmniPvdObjectHandle clutchResponseParamsOH;
OmniPvdObjectHandle clutchParamsOH;
OmniPvdObjectHandle engineParamsOH;
OmniPvdObjectHandle gearboxParamsOH;
OmniPvdObjectHandle autoboxParamsOH;
OmniPvdObjectHandle differentialParamsOH;
OmniPvdObjectHandle clutchResponseStateOH;
OmniPvdObjectHandle engineDriveThrottleResponseStateOH;
OmniPvdObjectHandle engineStateOH;
OmniPvdObjectHandle gearboxStateOH;
OmniPvdObjectHandle autoboxStateOH;
OmniPvdObjectHandle diffStateOH;
OmniPvdObjectHandle clutchSlipStateOH;
OmniPvdObjectHandle engineDrivetrainOH;
OmniPvdObjectHandle* wheelAttachmentOHs;
OmniPvdObjectHandle* wheelParamsOHs;
OmniPvdObjectHandle* wheelActuationStateOHs;
OmniPvdObjectHandle* wheelRigidBody1dStateOHs;
OmniPvdObjectHandle* wheelLocalPoseStateOHs;
OmniPvdObjectHandle* roadGeomStateOHs;
OmniPvdObjectHandle* suspParamsOHs;
OmniPvdObjectHandle* suspCompParamsOHs;
OmniPvdObjectHandle* suspForceParamsOHs;
OmniPvdObjectHandle* suspStateOHs;
OmniPvdObjectHandle* suspCompStateOHs;
OmniPvdObjectHandle* suspForceOHs;
OmniPvdObjectHandle* tireParamsOHs;
OmniPvdObjectHandle* tireDirectionStateOHs;
OmniPvdObjectHandle* tireSpeedStateOHs;
OmniPvdObjectHandle* tireSlipStateOHs;
OmniPvdObjectHandle* tireStickyStateOHs;
OmniPvdObjectHandle* tireGripStateOHs;
OmniPvdObjectHandle* tireCamberStateOHs;
OmniPvdObjectHandle* tireForceOHs;
OmniPvdObjectHandle* physxWheelAttachmentOHs;
OmniPvdObjectHandle* physxWheelShapeOHs;
OmniPvdObjectHandle* physxConstraintParamOHs;
OmniPvdObjectHandle* physxConstraintStateOHs;
OmniPvdObjectHandle* physxRoadGeomStateOHs;
OmniPvdObjectHandle physxSteerStateOH;
OmniPvdObjectHandle* physxMaterialFrictionSetOHs;
OmniPvdObjectHandle* physxMaterialFrictionOHs;
OmniPvdObjectHandle physxRoadGeomQueryParamOH;
OmniPvdObjectHandle physxRoadGeomQueryDefaultFilterDataOH;
OmniPvdObjectHandle* physxRoadGeomQueryFilterDataOHs;
OmniPvdObjectHandle physxRigidActorOH;
OmniPvdObjectHandle* antiRollParamOHs;
OmniPvdObjectHandle antiRollTorqueOH;
PxU32 nbWheels;
PxU32 nbPhysXMaterialFrictions;
PxU32 nbAntirolls;
OmniPvdContextHandle contextHandle;
#endif //PX_SUPPORT_OMNI_PVD
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,002 | C | 34.482269 | 74 | 0.833667 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdWriter.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 "VhPvdWriter.h"
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
PX_FORCE_INLINE void writeFloatAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, float val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<uint8_t*>(&val), sizeof(float));
}
PX_FORCE_INLINE void writeFloatArrayAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const float* val, const PxU32 nbVals)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(val), sizeof(float) * nbVals);
}
PX_FORCE_INLINE void writeUInt32ArrayAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const uint32_t* val, const PxU32 nbVals)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(val), sizeof(uint32_t) * nbVals);
}
PX_FORCE_INLINE void writeVec3Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxVec3& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxVec3));
}
PX_FORCE_INLINE void writePlaneAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxPlane& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxPlane));
}
PX_FORCE_INLINE void writeQuatAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const PxQuat& val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(PxQuat));
}
PX_FORCE_INLINE void writeUInt8Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint8_t val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(uint8_t));
}
PX_FORCE_INLINE void writeUInt32Attribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint32_t val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(uint32_t));
}
PX_FORCE_INLINE void writeFlagAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch, OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, uint32_t val)
{
writeUInt32Attribute(omniWriter, ch, oh, ah, val);
}
PX_FORCE_INLINE void writeLookupTableAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, PxVehicleFixedSizeLookupTable<float, 3> val)
{
float buffer[6] = { -1.0f, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f };
for(PxU32 i = 0; i < val.nbDataPairs; i++)
{
buffer[2 * i + 0] = val.xVals[i];
buffer[2 * i + 1] = val.yVals[i];
}
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(buffer), sizeof(buffer));
}
PX_FORCE_INLINE void writeLookupTableAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, PxVehicleFixedSizeLookupTable<PxVec3, 3> val)
{
float buffer[12] = { -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f };
for(PxU32 i = 0; i < val.nbDataPairs; i++)
{
buffer[4 * i + 0] = val.xVals[i];
buffer[4 * i + 1] = val.yVals[i].x;
buffer[4 * i + 2] = val.yVals[i].y;
buffer[4 * i + 3] = val.yVals[i].z;
}
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(buffer), sizeof(buffer));
}
void writePtrAttribute
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh, OmniPvdAttributeHandle ah, const void* val)
{
omniWriter.setAttribute(ch, oh, ah, reinterpret_cast<const uint8_t*>(&val), sizeof(val));
}
////////////////////////////////
//RIGID BODY
////////////////////////////////
RigidBodyParams registerRigidBodyParams(OmniPvdWriter& omniWriter)
{
RigidBodyParams r;
r.CH = omniWriter.registerClass("RigidBodyParams");
r.massAH = omniWriter.registerAttribute(r.CH, "mass", OmniPvdDataType::eFLOAT32, 1);
r.moiAH = omniWriter.registerAttribute(r.CH, "moi", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRigidBodyParams
(const PxVehicleRigidBodyParams& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.massAH, rbodyParams.mass);
writeVec3Attribute(omniWriter, ch, oh, ah.moiAH, rbodyParams.moi);
}
RigidBodyState registerRigidBodyState(OmniPvdWriter& omniWriter)
{
RigidBodyState r;
r.CH = omniWriter.registerClass("RigidBodyState");
r.posAH = omniWriter.registerAttribute(r.CH, "pos", OmniPvdDataType::eFLOAT32, 3);
r.quatAH = omniWriter.registerAttribute(r.CH, "quat", OmniPvdDataType::eFLOAT32, 4);
r.linearVelocityAH = omniWriter.registerAttribute(r.CH, "linvel", OmniPvdDataType::eFLOAT32, 3);
r.angularVelocityAH = omniWriter.registerAttribute(r.CH, "angvel", OmniPvdDataType::eFLOAT32, 3);
r.previousLinearVelocityAH = omniWriter.registerAttribute(r.CH, "prevLinvel", OmniPvdDataType::eFLOAT32, 3);
r.previousAngularVelocityAH = omniWriter.registerAttribute(r.CH, "prevAngvel", OmniPvdDataType::eFLOAT32, 3);
r.externalForceAH = omniWriter.registerAttribute(r.CH, "extForce", OmniPvdDataType::eFLOAT32, 3);
r.externalTorqueAH = omniWriter.registerAttribute(r.CH, "extTorque", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRigidBodyState
(const PxVehicleRigidBodyState& rbodyState,
const OmniPvdObjectHandle oh, const RigidBodyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.posAH, rbodyState.pose.p);
writeQuatAttribute(omniWriter, ch, oh, ah.quatAH, rbodyState.pose.q);
writeVec3Attribute(omniWriter, ch, oh, ah.linearVelocityAH, rbodyState.linearVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.angularVelocityAH, rbodyState.angularVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.previousLinearVelocityAH, rbodyState.previousLinearVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.previousAngularVelocityAH, rbodyState.previousAngularVelocity);
writeVec3Attribute(omniWriter, ch, oh, ah.externalForceAH, rbodyState.externalForce);
writeVec3Attribute(omniWriter, ch, oh, ah.externalTorqueAH, rbodyState.externalTorque);
}
/////////////////////////////////
//CONTROLS
/////////////////////////////////
WheelResponseParams registerWheelResponseParams(const char* name, OmniPvdWriter& omniWriter)
{
WheelResponseParams w;
w.CH = omniWriter.registerClass(name);
w.maxResponseAH = omniWriter.registerAttribute(w.CH, "maxResponse", OmniPvdDataType::eFLOAT32, 1);
w.responseMultipliers0To3AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers0To3", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers4To7AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers4To7", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers8To11AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers8To11", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers12To15AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers12To15", OmniPvdDataType::eFLOAT32, 4);
w.responseMultipliers16To19AH = omniWriter.registerAttribute(w.CH, "wheelMultipliers16To19", OmniPvdDataType::eFLOAT32, 4);
return w;
}
WheelResponseParams registerSteerResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("SteerResponseParams", omniWriter);
}
WheelResponseParams registerBrakeResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("BrakeResponseParams", omniWriter);
}
WheelResponseStates registerWheelResponseStates(const char* name, OmniPvdWriter& omniWriter)
{
WheelResponseStates w;
w.CH = omniWriter.registerClass(name);
w.responseStates0To3AH = omniWriter.registerAttribute(w.CH, "wheelStates0To3", OmniPvdDataType::eFLOAT32, 4);
w.responseStates4To7AH = omniWriter.registerAttribute(w.CH, "wheelStatess4To7", OmniPvdDataType::eFLOAT32, 4);
w.responseStates8To11AH = omniWriter.registerAttribute(w.CH, "wheelStates8To11", OmniPvdDataType::eFLOAT32, 4);
w.responseStates12To15AH = omniWriter.registerAttribute(w.CH, "wheelStates12To15", OmniPvdDataType::eFLOAT32, 4);
w.responseStates16To19AH = omniWriter.registerAttribute(w.CH, "wheelStates16To19", OmniPvdDataType::eFLOAT32, 4);
return w;
}
WheelResponseStates registerSteerResponseStates(OmniPvdWriter& omniWriter)
{
return registerWheelResponseStates("SteerResponseState", omniWriter);
}
WheelResponseStates registerBrakeResponseStates(OmniPvdWriter& omniWriter)
{
return registerWheelResponseStates("BrakeResponseState", omniWriter);
}
AckermannParams registerAckermannParams(OmniPvdWriter& omniWriter)
{
AckermannParams a;
a.CH = omniWriter.registerClass("AckermannParams");
a.wheelIdsAH = omniWriter.registerAttribute(a.CH, "wheelIds", OmniPvdDataType::eUINT32, 2);
a.wheelBaseAH = omniWriter.registerAttribute(a.CH, "wheelBase", OmniPvdDataType::eFLOAT32, 1);
a.trackWidthAH = omniWriter.registerAttribute(a.CH, "trackWidth", OmniPvdDataType::eFLOAT32, 1);
a.strengthAH = omniWriter.registerAttribute(a.CH, "strength", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeWheelResponseParams
(const PxVehicleAxleDescription& axleDesc, const PxVehicleCommandResponseParams& responseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.maxResponseAH, responseParams.maxResponse);
float responseMultipliers[PxVehicleLimits::eMAX_NB_WHEELS];
for(PxU32 i = 0; i < PxVehicleLimits::eMAX_NB_WHEELS; i++)
{
responseMultipliers[i] = PX_MAX_F32;
}
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
responseMultipliers[wheelId] = responseParams.wheelResponseMultipliers[wheelId];
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers0To3AH, responseMultipliers + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers4To7AH, responseMultipliers + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers8To11AH, responseMultipliers + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers12To15AH, responseMultipliers + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseMultipliers16To19AH, responseMultipliers + 16, 4);
}
void writeSteerResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSteerCommandResponseParams& steerResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, steerResponseParams, oh, ah, omniWriter, ch);
}
void writeBrakeResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleBrakeCommandResponseParams& brakeResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, brakeResponseParams, oh, ah, omniWriter, ch);
}
void writeWheelResponseStates
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& responseState,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float responseStates[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(responseStates, sizeof(responseStates));
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
responseStates[wheelId] = responseState[wheelId];
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates0To3AH, responseStates + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates4To7AH, responseStates + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates8To11AH, responseStates + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates12To15AH, responseStates + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.responseStates16To19AH, responseStates + 16, 4);
}
void writeSteerResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseStates(axleDesc, steerResponseStates, oh, ah, omniWriter, ch);
}
void writeBrakeResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseStates(axleDesc, brakeResponseStates, oh, ah, omniWriter, ch);
}
void writeAckermannParams
(const PxVehicleAckermannParams& ackermannParams,
const OmniPvdObjectHandle oh, const AckermannParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.wheelIdsAH, ackermannParams.wheelIds,
sizeof(PxVehicleAckermannParams::wheelIds) / sizeof(PxVehicleAckermannParams::wheelIds[0]));
writeFloatAttribute(omniWriter, ch, oh, ah.wheelBaseAH, ackermannParams.wheelBase);
writeFloatAttribute(omniWriter, ch, oh, ah.trackWidthAH, ackermannParams.trackWidth);
writeFloatAttribute(omniWriter, ch, oh, ah.strengthAH, ackermannParams.strength);
}
void writeClutchResponseParams
(const PxVehicleClutchCommandResponseParams& clutchResponseParams,
const OmniPvdObjectHandle oh, const ClutchResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.maxResponseAH, clutchResponseParams.maxResponse);
}
//////////////////////////////
//WHEEL ATTACHMENTS
//////////////////////////////
WheelParams registerWheelParams(OmniPvdWriter& omniWriter)
{
WheelParams w;
w.CH = omniWriter.registerClass("WheelParams");
w.wheelRadiusAH = omniWriter.registerAttribute(w.CH, "radius", OmniPvdDataType::eFLOAT32, 1);
w.halfWidthAH = omniWriter.registerAttribute(w.CH, "halfWidth", OmniPvdDataType::eFLOAT32, 1);
w.massAH = omniWriter.registerAttribute(w.CH, "mass", OmniPvdDataType::eFLOAT32, 1);
w.moiAH = omniWriter.registerAttribute(w.CH, "moi", OmniPvdDataType::eFLOAT32, 1);
w.dampingRateAH = omniWriter.registerAttribute(w.CH, "dampingRate", OmniPvdDataType::eFLOAT32, 1);
return w;
}
void writeWheelParams
(const PxVehicleWheelParams& params,
const OmniPvdObjectHandle oh, const WheelParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateAH, params.dampingRate);
writeFloatAttribute(omniWriter, ch, oh, ah.halfWidthAH, params.halfWidth);
writeFloatAttribute(omniWriter, ch, oh, ah.massAH, params.mass);
writeFloatAttribute(omniWriter, ch, oh, ah.moiAH, params.moi);
writeFloatAttribute(omniWriter, ch, oh, ah.wheelRadiusAH, params.radius);
}
WheelActuationState registerWheelActuationState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("WheelStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
WheelActuationState w;
w.CH = omniWriter.registerClass("WheelActuationState");
w.isBrakeAppliedAH = omniWriter.registerFlagsAttribute(w.CH, "isBrakeApplied", boolAsEnum.CH);
w.isDriveAppliedAH = omniWriter.registerFlagsAttribute(w.CH, "isDriveApplied", boolAsEnum.CH);
return w;
}
void writeWheelActuationState
(const PxVehicleWheelActuationState& actState,
const OmniPvdObjectHandle oh, const WheelActuationState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.isBrakeAppliedAH, actState.isBrakeApplied ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.isDriveAppliedAH, actState.isDriveApplied ? 1 : 0);
}
WheelRigidBody1dState registerWheelRigidBody1dState(OmniPvdWriter& omniWriter)
{
WheelRigidBody1dState w;
w.CH = omniWriter.registerClass("WheelRigidBodyState");
w.rotationSpeedAH = omniWriter.registerAttribute(w.CH, "rotationSpeed", OmniPvdDataType::eFLOAT32, 1);
w.correctedRotationSpeedAH = omniWriter.registerAttribute(w.CH, "correctedRotationSpeed", OmniPvdDataType::eFLOAT32, 1);
w.rotationAngleAH = omniWriter.registerAttribute(w.CH, "rotationAngle", OmniPvdDataType::eFLOAT32, 1);
return w;
}
void writeWheelRigidBody1dState
(const PxVehicleWheelRigidBody1dState& rigidBodyState,
const OmniPvdObjectHandle oh, const WheelRigidBody1dState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.rotationSpeedAH, rigidBodyState.rotationSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.correctedRotationSpeedAH, rigidBodyState.correctedRotationSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.rotationAngleAH, rigidBodyState.rotationAngle);
}
WheelLocalPoseState registerWheelLocalPoseState(OmniPvdWriter& omniWriter)
{
WheelLocalPoseState w;
w.CH = omniWriter.registerClass("WheelLocalPoseState");
w.posAH = omniWriter.registerAttribute(w.CH, "posInRbodyFrame", OmniPvdDataType::eFLOAT32, 3);
w.quatAH = omniWriter.registerAttribute(w.CH, "quatInRbodyFrame", OmniPvdDataType::eFLOAT32, 4);
return w;
}
void writeWheelLocalPoseState
(const PxVehicleWheelLocalPose& pose,
const OmniPvdObjectHandle oh, const WheelLocalPoseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.posAH, pose.localPose.p);
writeQuatAttribute(omniWriter, ch, oh, ah.quatAH, pose.localPose.q);
}
RoadGeometryState registerRoadGeomState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("RoadGeomStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
RoadGeometryState r;
r.CH = omniWriter.registerClass("RoadGeometryState");
r.planeAH = omniWriter.registerAttribute(r.CH, "plane", OmniPvdDataType::eFLOAT32, 4);
r.frictionAH = omniWriter.registerAttribute(r.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
r.hitStateAH = omniWriter.registerFlagsAttribute(r.CH, "hitState", boolAsEnum.CH);
r.velocityAH = omniWriter.registerAttribute(r.CH, "hitVelocity", OmniPvdDataType::eFLOAT32, 3);
return r;
}
void writeRoadGeomState
(const PxVehicleRoadGeometryState& roadGeometryState,
const OmniPvdObjectHandle oh, const RoadGeometryState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePlaneAttribute(omniWriter, ch, oh, ah.planeAH, roadGeometryState.plane);
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, roadGeometryState.friction);
writeFlagAttribute(omniWriter, ch, oh, ah.hitStateAH, roadGeometryState.hitState);
writeVec3Attribute(omniWriter, ch, oh, ah.velocityAH, roadGeometryState.velocity);
}
SuspParams registerSuspParams(OmniPvdWriter& omniWriter)
{
SuspParams s;
s.CH = omniWriter.registerClass("SuspensionParams");
s.suspAttachmentPosAH = omniWriter.registerAttribute(s.CH, "suspAttachmentPos", OmniPvdDataType::eFLOAT32, 3);
s.suspAttachmentQuatAH = omniWriter.registerAttribute(s.CH, "suspAttachmentQuat", OmniPvdDataType::eFLOAT32, 4);
s.suspDirAH = omniWriter.registerAttribute(s.CH, "suspDir", OmniPvdDataType::eFLOAT32, 3);
s.suspTravleDistAH = omniWriter.registerAttribute(s.CH, "suspTravelDist", OmniPvdDataType::eFLOAT32, 1);
s.wheelAttachmentPosAH = omniWriter.registerAttribute(s.CH, "wheelAttachmentPos", OmniPvdDataType::eFLOAT32, 3);
s.wheelAttachmentQuatAH = omniWriter.registerAttribute(s.CH, "wheelAttachmentQuat", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspParams
(const PxVehicleSuspensionParams& suspParams,
const OmniPvdObjectHandle oh, const SuspParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.suspAttachmentPosAH, suspParams.suspensionAttachment.p);
writeQuatAttribute(omniWriter, ch, oh, ah.suspAttachmentQuatAH, suspParams.suspensionAttachment.q);
writeVec3Attribute(omniWriter, ch, oh, ah.suspDirAH, suspParams.suspensionTravelDir);
writeFloatAttribute(omniWriter, ch, oh, ah.suspTravleDistAH, suspParams.suspensionTravelDist);
writeVec3Attribute(omniWriter, ch, oh, ah.wheelAttachmentPosAH, suspParams.wheelAttachment.p);
writeQuatAttribute(omniWriter, ch, oh, ah.wheelAttachmentQuatAH, suspParams.wheelAttachment.q);
}
SuspCompParams registerSuspComplianceParams(OmniPvdWriter& omniWriter)
{
SuspCompParams s;
s.CH = omniWriter.registerClass("SuspensionComplianceParams");
s.toeAngleAH = omniWriter.registerAttribute(s.CH, "toeAngle", OmniPvdDataType::eFLOAT32, 6);
s.camberAngleAH = omniWriter.registerAttribute(s.CH, "camberAngle", OmniPvdDataType::eFLOAT32, 6);
s.suspForceAppPointAH = omniWriter.registerAttribute(s.CH, "suspForceAppPoint", OmniPvdDataType::eFLOAT32, 12);
s.tireForceAppPointAH = omniWriter.registerAttribute(s.CH, "tireForceAppPoint", OmniPvdDataType::eFLOAT32, 12);
return s;
}
void writeSuspComplianceParams
(const PxVehicleSuspensionComplianceParams& compParams,
const OmniPvdObjectHandle oh, const SuspCompParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeLookupTableAttribute(omniWriter, ch, oh, ah.camberAngleAH, compParams.wheelCamberAngle);
writeLookupTableAttribute(omniWriter, ch, oh, ah.toeAngleAH, compParams.wheelToeAngle);
writeLookupTableAttribute(omniWriter, ch, oh, ah.suspForceAppPointAH, compParams.suspForceAppPoint);
writeLookupTableAttribute(omniWriter, ch, oh, ah.tireForceAppPointAH, compParams.tireForceAppPoint);
}
SuspForceParams registerSuspForceParams(OmniPvdWriter& omniWriter)
{
SuspForceParams s;
s.CH = omniWriter.registerClass("SuspensionForceParams");
s.stiffnessAH = omniWriter.registerAttribute(s.CH, "stiffness", OmniPvdDataType::eFLOAT32, 1);
s.dampingAH = omniWriter.registerAttribute(s.CH, "damping", OmniPvdDataType::eFLOAT32, 1);
s.sprungMassAH = omniWriter.registerAttribute(s.CH, "sprungMass", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writeSuspForceParams
(const PxVehicleSuspensionForceParams& forceParams,
const OmniPvdObjectHandle oh, const SuspForceParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.dampingAH, forceParams.damping);
writeFloatAttribute(omniWriter, ch, oh, ah.sprungMassAH, forceParams.sprungMass);
writeFloatAttribute(omniWriter, ch, oh, ah.stiffnessAH, forceParams.stiffness);
}
SuspState registerSuspState(OmniPvdWriter& omniWriter)
{
SuspState s;
s.CH = omniWriter.registerClass("SuspensionState");
s.jounceAH = omniWriter.registerAttribute(s.CH, "jounce", OmniPvdDataType::eFLOAT32, 1);
s.jounceSpeedAH = omniWriter.registerAttribute(s.CH, "jounceSpeed", OmniPvdDataType::eFLOAT32, 1);
s.separationAH = omniWriter.registerAttribute(s.CH, "separation", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writeSuspState
(const PxVehicleSuspensionState& suspState,
const OmniPvdObjectHandle oh, const SuspState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.jounceAH, suspState.jounce);
writeFloatAttribute(omniWriter, ch, oh, ah.jounceSpeedAH, suspState.jounceSpeed);
writeFloatAttribute(omniWriter, ch, oh, ah.separationAH, suspState.separation);
}
SuspCompState registerSuspComplianceState(OmniPvdWriter& omniWriter)
{
SuspCompState s;
s.CH = omniWriter.registerClass("SuspensionComplianceState");
s.toeAH = omniWriter.registerAttribute(s.CH, "toe", OmniPvdDataType::eFLOAT32, 1);
s.camberAH = omniWriter.registerAttribute(s.CH, "camber", OmniPvdDataType::eFLOAT32, 1);
s.tireForceAppPointAH = omniWriter.registerAttribute(s.CH, "tireForceAppPoint", OmniPvdDataType::eFLOAT32, 3);
s.suspForceAppPointAH = omniWriter.registerAttribute(s.CH, "suspForceAppPoint", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspComplianceState
(const PxVehicleSuspensionComplianceState& suspCompState,
const OmniPvdObjectHandle oh, const SuspCompState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.camberAH, suspCompState.camber);
writeFloatAttribute(omniWriter, ch, oh, ah.toeAH, suspCompState.toe);
writeVec3Attribute(omniWriter, ch, oh, ah.suspForceAppPointAH, suspCompState.suspForceAppPoint);
writeVec3Attribute(omniWriter, ch, oh, ah.tireForceAppPointAH, suspCompState.tireForceAppPoint);
}
SuspForce registerSuspForce(OmniPvdWriter& omniWriter)
{
SuspForce s;
s.CH = omniWriter.registerClass("SuspensionForce");
s.forceAH = omniWriter.registerAttribute(s.CH, "force", OmniPvdDataType::eFLOAT32, 3);
s.torqueAH = omniWriter.registerAttribute(s.CH, "torque", OmniPvdDataType::eFLOAT32, 3);
s.normalForceAH = omniWriter.registerAttribute(s.CH, "normalForce", OmniPvdDataType::eFLOAT32, 3);
return s;
}
void writeSuspForce
(const PxVehicleSuspensionForce& suspForce,
const OmniPvdObjectHandle oh, const SuspForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.forceAH, suspForce.force);
writeVec3Attribute(omniWriter, ch, oh, ah.torqueAH, suspForce.torque);
writeFloatAttribute(omniWriter, ch, oh, ah.normalForceAH, suspForce.normalForce);
}
TireParams registerTireParams(OmniPvdWriter& omniWriter)
{
TireParams t;
t.CH = omniWriter.registerClass("TireParams");
t.latStiffXAH = omniWriter.registerAttribute(t.CH, "latStiffX", OmniPvdDataType::eFLOAT32, 1);
t.latStiffYAH = omniWriter.registerAttribute(t.CH, "latStiffY", OmniPvdDataType::eFLOAT32, 1);
t.longStiffAH = omniWriter.registerAttribute(t.CH, "longStiff", OmniPvdDataType::eFLOAT32, 1);
t.camberStiffAH = omniWriter.registerAttribute(t.CH, "camberStiff", OmniPvdDataType::eFLOAT32, 1);
t.frictionVsSlipAH = omniWriter.registerAttribute(t.CH, "frictionVsSlip", OmniPvdDataType::eFLOAT32, 6);
t.restLoadAH = omniWriter.registerAttribute(t.CH, "restLoad", OmniPvdDataType::eFLOAT32, 1);
t.loadFilterAH = omniWriter.registerAttribute(t.CH, "loadFilter", OmniPvdDataType::eFLOAT32, 4);
return t;
}
void writeTireParams
(const PxVehicleTireForceParams& tireParams,
const OmniPvdObjectHandle oh, const TireParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.latStiffXAH, tireParams.latStiffX);
writeFloatAttribute(omniWriter, ch, oh, ah.latStiffYAH, tireParams.latStiffY);
writeFloatAttribute(omniWriter, ch, oh, ah.longStiffAH, tireParams.longStiff);
writeFloatAttribute(omniWriter, ch, oh, ah.camberStiffAH, tireParams.camberStiff);
writeFloatAttribute(omniWriter, ch, oh, ah.restLoadAH, tireParams.restLoad);
const float fricVsSlip[6] =
{
tireParams.frictionVsSlip[0][0], tireParams.frictionVsSlip[0][1], tireParams.frictionVsSlip[1][0],
tireParams.frictionVsSlip[1][1], tireParams.frictionVsSlip[2][0], tireParams.frictionVsSlip[2][1],
};
writeFloatArrayAttribute(omniWriter, ch, oh, ah.frictionVsSlipAH, fricVsSlip, 6);
const float loadFilter[4] =
{
tireParams.loadFilter[0][0], tireParams.loadFilter[0][1],
tireParams.loadFilter[1][0], tireParams.loadFilter[1][1]
};
writeFloatArrayAttribute(omniWriter, ch, oh, ah.loadFilterAH, loadFilter, 4);
}
TireDirectionState registerTireDirectionState(OmniPvdWriter& omniWriter)
{
TireDirectionState t;
t.CH = omniWriter.registerClass("TireDirectionState");
t.lngDirectionAH = omniWriter.registerAttribute(t.CH, "lngDir", OmniPvdDataType::eFLOAT32, 3);
t.latDirectionAH = omniWriter.registerAttribute(t.CH, "latDir", OmniPvdDataType::eFLOAT32, 3);
return t;
}
void writeTireDirectionState
(const PxVehicleTireDirectionState& tireDirState,
const OmniPvdObjectHandle oh, const TireDirectionState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.lngDirectionAH, tireDirState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latDirectionAH, tireDirState.directions[PxVehicleTireDirectionModes::eLATERAL]);
}
TireSpeedState registerTireSpeedState(OmniPvdWriter& omniWriter)
{
TireSpeedState t;
t.CH = omniWriter.registerClass("TireSpeedState");
t.lngSpeedAH = omniWriter.registerAttribute(t.CH, "lngSpeed", OmniPvdDataType::eFLOAT32, 1);
t.latSpeedAH = omniWriter.registerAttribute(t.CH, "latSpeed", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireSpeedState
(const PxVehicleTireSpeedState& tireSpeedState,
const OmniPvdObjectHandle oh, const TireSpeedState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.lngSpeedAH, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.latSpeedAH, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL]);
}
TireSlipState registerTireSlipState(OmniPvdWriter& omniWriter)
{
TireSlipState t;
t.CH = omniWriter.registerClass("TireSlipState");
t.lngSlipAH = omniWriter.registerAttribute(t.CH, "lngSlip", OmniPvdDataType::eFLOAT32, 1);
t.latSlipAH = omniWriter.registerAttribute(t.CH, "latSlip", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireSlipState
(const PxVehicleTireSlipState& tireSlipState,
const OmniPvdObjectHandle oh, const TireSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.lngSlipAH, tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.latSlipAH, tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL]);
}
TireStickyState registerTireStickyState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("StickyTireBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
TireStickyState t;
t.CH = omniWriter.registerClass("TireStickyState");
t.lngStickyStateTimer = omniWriter.registerAttribute(t.CH, "lngStickyTimer", OmniPvdDataType::eFLOAT32, 1);
t.lngStickyStateStatus = omniWriter.registerFlagsAttribute(t.CH, "lngStickyStatus", boolAsEnum.CH);
t.latStickyStateTimer = omniWriter.registerAttribute(t.CH, "latStickyTimer", OmniPvdDataType::eFLOAT32, 1);
t.latStickyStateStatus = omniWriter.registerFlagsAttribute(t.CH, "latStickyStatus", boolAsEnum.CH);
return t;
}
void writeTireStickyState
(const PxVehicleTireStickyState& tireStickyState,
const OmniPvdObjectHandle oh, const TireStickyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.latStickyStateStatus, tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL] ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.lngStickyStateStatus, tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ? 1 : 0);
writeFloatAttribute(omniWriter, ch, oh, ah.latStickyStateTimer, tireStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.lngStickyStateTimer, tireStickyState.lowSpeedTime[PxVehicleTireDirectionModes::eLONGITUDINAL]);
}
TireGripState registerTireGripState(OmniPvdWriter& omniWriter)
{
TireGripState t;
t.CH = omniWriter.registerClass("TireGripState");
t.loadAH = omniWriter.registerAttribute(t.CH, "load", OmniPvdDataType::eFLOAT32, 1);
t.frictionAH = omniWriter.registerAttribute(t.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireGripState
(const PxVehicleTireGripState& tireGripState,
const OmniPvdObjectHandle oh, const TireGripState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, tireGripState.friction);
writeFloatAttribute(omniWriter, ch, oh, ah.loadAH, tireGripState.load);
}
TireCamberState registerTireCamberState(OmniPvdWriter& omniWriter)
{
TireCamberState t;
t.CH = omniWriter.registerClass("TireCamberState");
t.camberAngleAH = omniWriter.registerAttribute(t.CH, "camberAngle", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeTireCamberState
(const PxVehicleTireCamberAngleState& tireCamberState,
const OmniPvdObjectHandle oh, const TireCamberState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.camberAngleAH, tireCamberState.camberAngle);
}
TireForce registerTireForce(OmniPvdWriter& omniWriter)
{
TireForce t;
t.CH = omniWriter.registerClass("TireForce");
t.lngForceAH = omniWriter.registerAttribute(t.CH, "lngForce", OmniPvdDataType::eFLOAT32, 3);
t.lngTorqueAH = omniWriter.registerAttribute(t.CH, "lngTorque", OmniPvdDataType::eFLOAT32, 3);
t.latForceAH = omniWriter.registerAttribute(t.CH, "latForce", OmniPvdDataType::eFLOAT32, 3);
t.latTorqueAH = omniWriter.registerAttribute(t.CH, "latTorque", OmniPvdDataType::eFLOAT32, 3);
t.aligningMomentAH = omniWriter.registerAttribute(t.CH, "aligningMoment", OmniPvdDataType::eFLOAT32, 3);
t.wheelTorqueAH = omniWriter.registerAttribute(t.CH, "wheelTorque", OmniPvdDataType::eFLOAT32, 3);
return t;
}
void writeTireForce
(const PxVehicleTireForce& tireForce,
const OmniPvdObjectHandle oh, const TireForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.lngForceAH, tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.lngTorqueAH, tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latForceAH, tireForce.forces[PxVehicleTireDirectionModes::eLATERAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.latTorqueAH, tireForce.torques[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.aligningMomentAH, tireForce.aligningMoment);
writeFloatAttribute(omniWriter, ch, oh, ah.wheelTorqueAH, tireForce.wheelTorque);
}
WheelAttachment registerWheelAttachment(OmniPvdWriter& omniWriter)
{
WheelAttachment w;
w.CH = omniWriter.registerClass("WheelAttachment");
w.wheelParamsAH = omniWriter.registerAttribute(w.CH, "wheelParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelActuationStateAH = omniWriter.registerAttribute(w.CH, "wheelActuationState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelRigidBody1dStateAH = omniWriter.registerAttribute(w.CH, "wheelRigidBody1dState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.wheelLocalPoseStateAH = omniWriter.registerAttribute(w.CH, "wheelLocalPosetate", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.roadGeomStateAH = omniWriter.registerAttribute(w.CH, "roadGeomState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspParamsAH = omniWriter.registerAttribute(w.CH, "suspParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspCompParamsAH = omniWriter.registerAttribute(w.CH, "suspComplianceParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspForceParamsAH = omniWriter.registerAttribute(w.CH, "suspForceParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspStateAH = omniWriter.registerAttribute(w.CH, "suspState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspCompStateAH = omniWriter.registerAttribute(w.CH, "suspComplianceState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.suspForceAH = omniWriter.registerAttribute(w.CH, "suspForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireParamsAH = omniWriter.registerAttribute(w.CH, "tireParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireDirectionStateAH = omniWriter.registerAttribute(w.CH, "tireDirectionState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireSpeedStateAH = omniWriter.registerAttribute(w.CH, "tireSpeedState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireSlipStateAH = omniWriter.registerAttribute(w.CH, "tireSlipState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireStickyStateAH = omniWriter.registerAttribute(w.CH, "tireStickyState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireGripStateAH = omniWriter.registerAttribute(w.CH, "tireGripState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireCamberStateAH = omniWriter.registerAttribute(w.CH, "tireCamberState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.tireForceAH = omniWriter.registerAttribute(w.CH, "tireForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
return w;
}
//////////////////////////
//ANTIROLL
//////////////////////////
AntiRollParams registerAntiRollParams(OmniPvdWriter& omniWriter)
{
AntiRollParams a;
a.CH = omniWriter.registerClass("AntiRollParams");
a.wheel0AH = omniWriter.registerAttribute(a.CH, "wheel0", OmniPvdDataType::eUINT32, 1);
a.wheel1AH = omniWriter.registerAttribute(a.CH, "wheel1", OmniPvdDataType::eUINT32, 1);
a.stiffnessAH = omniWriter.registerAttribute(a.CH, "stiffness", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeAntiRollParams
(const PxVehicleAntiRollForceParams& antiRollParams,
const OmniPvdObjectHandle oh, const AntiRollParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.wheel0AH, antiRollParams.wheel0);
writeUInt32Attribute(omniWriter, ch, oh, ah.wheel1AH, antiRollParams.wheel1);
writeFloatAttribute(omniWriter, ch, oh, ah.stiffnessAH, antiRollParams.stiffness);
}
AntiRollForce registerAntiRollForce(OmniPvdWriter& omniWriter)
{
AntiRollForce a;
a.CH = omniWriter.registerClass("AntiRollForce");
a.torqueAH = omniWriter.registerAttribute(a.CH, "torque", OmniPvdDataType::eFLOAT32, 3);
return a;
}
void writeAntiRollForce
(const PxVehicleAntiRollTorque& antiRollForce,
const OmniPvdObjectHandle oh, const AntiRollForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.torqueAH, antiRollForce.antiRollTorque);
}
//////////////////////////////////
//SUSPENSION STATE CALCULATION
//////////////////////////////////
SuspStateCalcParams registerSuspStateCalcParams(OmniPvdWriter& omniWriter)
{
struct SuspJounceCalcType
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle raycastAH;
OmniPvdAttributeHandle sweepAH;
OmniPvdAttributeHandle noneAH;
};
SuspJounceCalcType jounceCalcType;
jounceCalcType.CH = omniWriter.registerClass("SuspJounceCalculationType");
jounceCalcType.raycastAH = omniWriter.registerEnumValue(jounceCalcType.CH, "raycast", PxVehicleSuspensionJounceCalculationType::eRAYCAST);
jounceCalcType.sweepAH = omniWriter.registerEnumValue(jounceCalcType.CH, "sweep", PxVehicleSuspensionJounceCalculationType::eSWEEP);
jounceCalcType.noneAH = omniWriter.registerEnumValue(jounceCalcType.CH, "none", PxVehicleSuspensionJounceCalculationType::eMAX_NB);
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("SuspStateCalcParamsBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
SuspStateCalcParams s;
s.CH = omniWriter.registerClass("SuspStateCalculationParams");
s.calcTypeAH = omniWriter.registerFlagsAttribute(s.CH, "suspJounceCalculationType", jounceCalcType.CH);
s.limitExpansionValAH = omniWriter.registerFlagsAttribute(s.CH, "limitSuspensionExpansionVelocity", boolAsEnum.CH);
return s;
}
void writeSuspStateCalcParams
(const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const OmniPvdObjectHandle oh, const SuspStateCalcParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.limitExpansionValAH, suspStateCalcParams.limitSuspensionExpansionVelocity ? 1 : 0);
writeFlagAttribute(omniWriter, ch, oh, ah.calcTypeAH, suspStateCalcParams.suspensionJounceCalculationType);
}
//////////////////////////////////////
//DIRECT DRIVETRAIN
//////////////////////////////////////
DirectDriveCommandState registerDirectDriveCommandState(OmniPvdWriter& omniWriter)
{
DirectDriveCommandState c;
c.CH = omniWriter.registerClass("DirectDriveCommandState");
c.brakesAH= omniWriter.registerAttribute(c.CH, "brakes", OmniPvdDataType::eFLOAT32, 2);
c.throttleAH= omniWriter.registerAttribute(c.CH, "throttle", OmniPvdDataType::eFLOAT32, 1);
c.steerAH= omniWriter.registerAttribute(c.CH, "steer", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeDirectDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const DirectDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float brakes[2];
for(PxU32 i = 0; i < commands.nbBrakes; i++)
{
brakes[i] = commands.brakes[i];
}
for(PxU32 i = commands.nbBrakes; i < 2; i++)
{
brakes[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.brakesAH, brakes, 2);
writeFloatAttribute(omniWriter, ch, oh, ah.throttleAH, commands.throttle);
writeFloatAttribute(omniWriter, ch, oh, ah.steerAH, commands.steer);
}
DirectDriveTransmissionCommandState registerDirectDriveTransmissionCommandState(OmniPvdWriter& omniWriter)
{
struct DirectDriveGear
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle reverse;
OmniPvdAttributeHandle neutral;
OmniPvdAttributeHandle forward;
};
DirectDriveGear g;
g.CH = omniWriter.registerClass("DirectDriveGear");
g.reverse = omniWriter.registerEnumValue(g.CH, "reverse", PxVehicleDirectDriveTransmissionCommandState::eREVERSE);
g.neutral = omniWriter.registerEnumValue(g.CH, "neutral", PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL);
g.forward = omniWriter.registerEnumValue(g.CH, "forward", PxVehicleDirectDriveTransmissionCommandState::eFORWARD);
DirectDriveTransmissionCommandState c;
c.CH = omniWriter.registerClass("DirectDriveTransmissionCommandState");
c.gearAH = omniWriter.registerFlagsAttribute(c.CH, "gear", g.CH);
return c;
}
void writeDirectDriveTransmissionCommandState
(const PxVehicleDirectDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const DirectDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.gearAH, transmission.gear);
}
WheelResponseParams registerDirectDriveThrottleResponseParams(OmniPvdWriter& omniWriter)
{
return registerWheelResponseParams("DirectDriveThrottleResponseParams", omniWriter);
}
void writeDirectDriveThrottleResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleDirectDriveThrottleCommandResponseParams& directDriveThrottleResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeWheelResponseParams(axleDesc, directDriveThrottleResponseParams, oh, ah, omniWriter, ch);
}
DirectDriveThrottleResponseState registerDirectDriveThrottleResponseState(OmniPvdWriter& omniWriter)
{
DirectDriveThrottleResponseState d;
d.CH = omniWriter.registerClass("DirectDriveThrottleResponseState");
d.states0To3AH = omniWriter.registerAttribute(d.CH, "responseState0To3", OmniPvdDataType::eFLOAT32, 4);
d.states4To7AH = omniWriter.registerAttribute(d.CH, "responseState4To7", OmniPvdDataType::eFLOAT32, 4);
d.states8To11AH = omniWriter.registerAttribute(d.CH, "responseState8To11", OmniPvdDataType::eFLOAT32, 4);
d.states12To15AH = omniWriter.registerAttribute(d.CH, "responseState12To15", OmniPvdDataType::eFLOAT32, 4);
d.states16To19AH = omniWriter.registerAttribute(d.CH, "responseState16To19", OmniPvdDataType::eFLOAT32, 4);
return d;
}
void writeDirectDriveThrottleResponseState
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& throttleResponseState,
const OmniPvdObjectHandle oh, const DirectDriveThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
//States are always in setToDefault() state as default.
PxF32 states[PxVehicleLimits::eMAX_NB_WHEELS];
PxMemZero(states, sizeof(states));
if(!throttleResponseState.isEmpty())
{
for(PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
states[wheelId] = throttleResponseState[wheelId];
}
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states0To3AH, states + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states4To7AH, states + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states8To11AH, states + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states12To15AH, states + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.states16To19AH, states + 16, 4);
}
DirectDrivetrain registerDirectDrivetrain(OmniPvdWriter& omniWriter)
{
DirectDrivetrain d;
d.CH = omniWriter.registerClass("DirectDrivetrain");
d.throttleResponseParamsAH = omniWriter.registerAttribute(d.CH, "throttleResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.commandStateAH = omniWriter.registerAttribute(d.CH, "commandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.transmissionCommandStateAH = omniWriter.registerAttribute(d.CH, "transmissionCommandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
d.throttleResponseStateAH = omniWriter.registerAttribute(d.CH, "throttleResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return d;
}
//////////////////////////////
//ENGINE DRIVETRAIN
//////////////////////////////
EngineDriveCommandState registerEngineDriveCommandState(OmniPvdWriter& omniWriter)
{
EngineDriveCommandState c;
c.CH = omniWriter.registerClass("EngineDriveCommandState");
c.brakesAH = omniWriter.registerAttribute(c.CH, "brakes", OmniPvdDataType::eFLOAT32, 2);
c.throttleAH = omniWriter.registerAttribute(c.CH, "throttle", OmniPvdDataType::eFLOAT32, 1);
c.steerAH = omniWriter.registerAttribute(c.CH, "steer", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeEngineDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const EngineDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float brakes[2];
for(PxU32 i = 0; i < commands.nbBrakes; i++)
{
brakes[i] = commands.brakes[i];
}
for(PxU32 i = commands.nbBrakes; i < 2; i++)
{
brakes[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.brakesAH, brakes, 2);
writeFloatAttribute(omniWriter, ch, oh, ah.throttleAH, commands.throttle);
writeFloatAttribute(omniWriter, ch, oh, ah.steerAH, commands.steer);
}
EngineDriveTransmissionCommandState registerEngineDriveTransmissionCommandState(OmniPvdWriter& omniWriter)
{
EngineDriveTransmissionCommandState c;
c.CH = omniWriter.registerClass("EngineDriveTransmissionCommandState");
c.gearAH = omniWriter.registerAttribute(c.CH, "targetGear", OmniPvdDataType::eUINT32, 1);
c.clutchAH = omniWriter.registerAttribute(c.CH, "clutch", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeEngineDriveTransmissionCommandState
(const PxVehicleEngineDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.gearAH, transmission.targetGear);
writeFloatAttribute(omniWriter, ch, oh, ah.clutchAH, transmission.clutch);
}
static const PxU32 tankThrustsCommandEntryCount = sizeof(PxVehicleTankDriveTransmissionCommandState::thrusts) / sizeof(PxVehicleTankDriveTransmissionCommandState::thrusts[0]);
TankDriveTransmissionCommandState registerTankDriveTransmissionCommandState(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
TankDriveTransmissionCommandState t;
t.CH = omniWriter.registerClass("TankDriveTransmissionCommandState", baseClass);
t.thrustsAH = omniWriter.registerAttribute(t.CH, "thrusts", OmniPvdDataType::eFLOAT32, tankThrustsCommandEntryCount);
return t;
}
void writeTankDriveTransmissionCommandState
(const PxVehicleTankDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& engineDriveAH,
const TankDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeEngineDriveTransmissionCommandState(transmission, oh, engineDriveAH, omniWriter, ch);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.thrustsAH, transmission.thrusts, tankThrustsCommandEntryCount);
}
ClutchResponseParams registerClutchResponseParams(OmniPvdWriter& omniWriter)
{
ClutchResponseParams c;
c.CH = omniWriter.registerClass("ClutchResponseParams");
c.maxResponseAH = omniWriter.registerAttribute(c.CH, "MaxResponse", OmniPvdDataType::eFLOAT32, 1);
return c;
}
ClutchParams registerClutchParams(OmniPvdWriter& omniWriter)
{
struct VehicleClutchAccuracyMode
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle estimateAH;
OmniPvdAttributeHandle bestPossibleAH;
};
VehicleClutchAccuracyMode mode;
mode.CH = omniWriter.registerClass("ClutchAccuracyMode");
mode.estimateAH = omniWriter.registerEnumValue(mode.CH, "estimate", PxVehicleClutchAccuracyMode::eESTIMATE);
mode.bestPossibleAH = omniWriter.registerEnumValue(mode.CH, "bestPossible", PxVehicleClutchAccuracyMode::eBEST_POSSIBLE);
ClutchParams v;
v.CH = omniWriter.registerClass("ClutchParams");
v.accuracyAH = omniWriter.registerFlagsAttribute(v.CH, "accuracyMode", mode.CH);
v.iterationsAH = omniWriter.registerAttribute(v.CH, "iterations", OmniPvdDataType::eUINT32, 1);
return v;
}
void writeClutchParams
(const PxVehicleClutchParams& clutchParams,
const OmniPvdObjectHandle oh, const ClutchParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.accuracyAH, clutchParams.accuracyMode);
writeUInt32Attribute(omniWriter, ch, oh, ah.iterationsAH, clutchParams.estimateIterations);
}
EngineParams registerEngineParams(OmniPvdWriter& omniWriter)
{
EngineParams e;
e.CH = omniWriter.registerClass("EngineParams");
e.torqueCurveAH = omniWriter.registerAttribute(e.CH, "torqueCurve", OmniPvdDataType::eFLOAT32, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2);
e.peakTorqueAH = omniWriter.registerAttribute(e.CH, "peakTorque", OmniPvdDataType::eFLOAT32, 1);
e.moiAH = omniWriter.registerAttribute(e.CH, "moi", OmniPvdDataType::eFLOAT32, 1);
e.idleOmegaAH = omniWriter.registerAttribute(e.CH, "idleOmega", OmniPvdDataType::eFLOAT32, 1);
e.maxOmegaAH = omniWriter.registerAttribute(e.CH, "maxOmega", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateFullThrottleAH = omniWriter.registerAttribute(e.CH, "dampingRateFullThrottleAH", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateZeroThrottleClutchDisengagedAH = omniWriter.registerAttribute(e.CH, "dampingRateZeroThrottleClutchDisengaged", OmniPvdDataType::eFLOAT32, 1);
e.dampingRateZeroThrottleClutchEngagedAH = omniWriter.registerAttribute(e.CH, "dampingRateZeroThrottleClutchEngaged", OmniPvdDataType::eFLOAT32, 1);
return e;
}
void writeEngineParams
(const PxVehicleEngineParams& engineParams,
const OmniPvdObjectHandle oh, const EngineParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float torqueCurve[PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2];
for(PxU32 i = 0; i < engineParams.torqueCurve.nbDataPairs; i++)
{
torqueCurve[2*i + 0] = engineParams.torqueCurve.xVals[i];
torqueCurve[2*i + 1] = engineParams.torqueCurve.yVals[i];
}
for(PxU32 i = engineParams.torqueCurve.nbDataPairs; i < PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES; i++)
{
torqueCurve[2*i + 0] = PX_MAX_F32;
torqueCurve[2*i + 1] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueCurveAH, torqueCurve, PxVehicleEngineParams::eMAX_NB_ENGINE_TORQUE_CURVE_ENTRIES*2);
writeFloatAttribute(omniWriter, ch, oh, ah.peakTorqueAH, engineParams.peakTorque);
writeFloatAttribute(omniWriter, ch, oh, ah.moiAH, engineParams.moi);
writeFloatAttribute(omniWriter, ch, oh, ah.idleOmegaAH, engineParams.idleOmega);
writeFloatAttribute(omniWriter, ch, oh, ah.maxOmegaAH, engineParams.maxOmega);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateFullThrottleAH, engineParams.dampingRateFullThrottle);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateZeroThrottleClutchDisengagedAH, engineParams.dampingRateZeroThrottleClutchDisengaged);
writeFloatAttribute(omniWriter, ch, oh, ah.dampingRateZeroThrottleClutchEngagedAH, engineParams.dampingRateZeroThrottleClutchEngaged);
}
GearboxParams registerGearboxParams(OmniPvdWriter& omniWriter)
{
GearboxParams g;
g.CH = omniWriter.registerClass("GearboxParams");
g.ratiosAH = omniWriter.registerAttribute(g.CH, "ratios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
g.nbRatiosAH = omniWriter.registerAttribute(g.CH, "nbRatios", OmniPvdDataType::eUINT32, 1);
g.neutralGearAH = omniWriter.registerAttribute(g.CH, "neutralGear", OmniPvdDataType::eUINT32, 1);
g.finalRatioAH = omniWriter.registerAttribute(g.CH, "finalRatio", OmniPvdDataType::eFLOAT32, 1);
g.switchTimeAH = omniWriter.registerAttribute(g.CH, "switchTime", OmniPvdDataType::eFLOAT32, 1);
return g;
}
void writeGearboxParams
(const PxVehicleGearboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const GearboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
float ratios[PxVehicleGearboxParams::eMAX_NB_GEARS];
PxMemCopy(ratios, gearboxParams.ratios, sizeof(float)*gearboxParams.nbRatios);
for(PxU32 i = gearboxParams.nbRatios; i < PxVehicleGearboxParams::eMAX_NB_GEARS; i++)
{
ratios[i] = PX_MAX_F32;
}
writeFloatArrayAttribute(omniWriter, ch, oh, ah.ratiosAH, ratios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeUInt32Attribute(omniWriter, ch, oh, ah.nbRatiosAH, gearboxParams.nbRatios);
writeUInt32Attribute(omniWriter, ch, oh, ah.neutralGearAH, gearboxParams.neutralGear);
writeFloatAttribute(omniWriter, ch, oh, ah.finalRatioAH, gearboxParams.finalRatio);
writeFloatAttribute(omniWriter, ch, oh, ah.switchTimeAH, gearboxParams.switchTime);
}
AutoboxParams registerAutoboxParams(OmniPvdWriter& omniWriter)
{
AutoboxParams a;
a.CH = omniWriter.registerClass("AutoboxParams");
a.upRatiosAH = omniWriter.registerAttribute(a.CH, "upRatios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
a.downRatiosAH = omniWriter.registerAttribute(a.CH, "downRatios", OmniPvdDataType::eFLOAT32, PxVehicleGearboxParams::eMAX_NB_GEARS);
a.latencyAH = omniWriter.registerAttribute(a.CH, "latency", OmniPvdDataType::eFLOAT32, 1);
return a;
}
void writeAutoboxParams
(const PxVehicleAutoboxParams& autoboxParams,
const OmniPvdObjectHandle oh, const AutoboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.upRatiosAH, autoboxParams.upRatios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.downRatiosAH, autoboxParams.downRatios, PxVehicleGearboxParams::eMAX_NB_GEARS);
writeFloatAttribute(omniWriter, ch, oh, ah.latencyAH, autoboxParams.latency);
}
MultiWheelDiffParams registerMultiWheelDiffParams(OmniPvdWriter& omniWriter)
{
MultiWheelDiffParams m;
m.CH = omniWriter.registerClass("MultiWheelDiffParams");
m.torqueRatios0To3AH = omniWriter.registerAttribute(m.CH, "torqueRatios0To3", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios4To7AH = omniWriter.registerAttribute(m.CH, "torqueRatios4To7", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios8To11AH = omniWriter.registerAttribute(m.CH, "torqueRatios8To11", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios12To15AH = omniWriter.registerAttribute(m.CH, "torqueRatios12To15", OmniPvdDataType::eFLOAT32, 4);
m.torqueRatios16To19AH = omniWriter.registerAttribute(m.CH, "torqueRatios16To19", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios0To3AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios0To3", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios4To7AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios4To7", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios8To11AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios8To11", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios12To15AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios12To15", OmniPvdDataType::eFLOAT32, 4);
m.aveWheelSpeedRatios16To19AH = omniWriter.registerAttribute(m.CH, "aveWheelSpeedRatios16To19", OmniPvdDataType::eFLOAT32, 4);
return m;
}
FourWheelDiffParams registerFourWheelDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
FourWheelDiffParams m;
m.CH = omniWriter.registerClass("FourWheelDiffParams", baseClass);
m.frontBiasAH = omniWriter.registerAttribute(m.CH, "frontBias", OmniPvdDataType::eFLOAT32, 1);
m.frontTargetAH = omniWriter.registerAttribute(m.CH, "frontTarget", OmniPvdDataType::eFLOAT32, 1);
m.rearBiasAH = omniWriter.registerAttribute(m.CH, "rearBias", OmniPvdDataType::eFLOAT32, 1);
m.rearTargetAH = omniWriter.registerAttribute(m.CH, "rearTarget", OmniPvdDataType::eFLOAT32, 1);
m.centreBiasAH = omniWriter.registerAttribute(m.CH, "centerBias", OmniPvdDataType::eFLOAT32, 1);
m.centreTargetAH = omniWriter.registerAttribute(m.CH, "centerTarget", OmniPvdDataType::eFLOAT32, 1);
m.frontWheelsAH = omniWriter.registerAttribute(m.CH, "frontWheels", OmniPvdDataType::eUINT32, 2);
m.rearWheelsAH = omniWriter.registerAttribute(m.CH, "rearWheels", OmniPvdDataType::eUINT32, 2);
return m;
}
TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass)
{
TankDiffParams t;
t.CH = omniWriter.registerClass("TankDiffParams", baseClass);
t.nbTracksAH = omniWriter.registerAttribute(t.CH, "nbTracks", OmniPvdDataType::eUINT32, 1);
t.thrustIdPerTrackAH = omniWriter.registerAttribute(t.CH, "thrustIdPerTrack", OmniPvdDataType::eUINT32, 0);
t.nbWheelsPerTrackAH = omniWriter.registerAttribute(t.CH, "nbWheelsPerTrack", OmniPvdDataType::eUINT32, 0);
t.trackToWheelIdsAH = omniWriter.registerAttribute(t.CH, "trackToWheelIds", OmniPvdDataType::eUINT32, 0);
t.wheelIdsInTrackOrderAH = omniWriter.registerAttribute(t.CH, "wheelIdsInTrackOrder", OmniPvdDataType::eUINT32, 0);
return t;
}
void writeMultiWheelDiffParams
(const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios0To3AH, diffParams.aveWheelSpeedRatios + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios4To7AH, diffParams.aveWheelSpeedRatios + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios8To11AH, diffParams.aveWheelSpeedRatios + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios12To15AH, diffParams.aveWheelSpeedRatios + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios16To19AH, diffParams.aveWheelSpeedRatios + 16, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios0To3AH, diffParams.torqueRatios + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios4To7AH, diffParams.torqueRatios + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios8To11AH, diffParams.torqueRatios + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios12To15AH, diffParams.torqueRatios + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios16To19AH, diffParams.torqueRatios + 16, 4);
}
void writeFourWheelDiffParams
(const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& multiWheelDiffAH, const FourWheelDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeMultiWheelDiffParams(diffParams, oh, multiWheelDiffAH, omniWriter, ch);
writeFloatAttribute(omniWriter, ch, oh, ah.frontBiasAH, diffParams.frontBias);
writeFloatAttribute(omniWriter, ch, oh, ah.frontTargetAH, diffParams.frontTarget);
writeFloatAttribute(omniWriter, ch, oh, ah.rearBiasAH, diffParams.rearBias);
writeFloatAttribute(omniWriter, ch, oh, ah.rearTargetAH, diffParams.rearTarget);
writeFloatAttribute(omniWriter, ch, oh, ah.centreBiasAH, diffParams.centerBias);
writeFloatAttribute(omniWriter, ch, oh, ah.centreTargetAH, diffParams.centerTarget);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.frontWheelsAH, diffParams.frontWheelIds, 2);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.rearWheelsAH, diffParams.rearWheelIds, 2);
}
void writeTankDiffParams
(const PxVehicleTankDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& multiWheelDiffAH, const TankDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
PxU32 entryCount = 0;
for (PxU32 i = 0; i < diffParams.nbTracks; i++)
{
entryCount = PxMax(entryCount, diffParams.trackToWheelIds[i] + diffParams.nbWheelsPerTrack[i]);
// users can remove tracks such that there are holes in the wheelIdsInTrackOrder buffer
}
writeMultiWheelDiffParams(diffParams, oh, multiWheelDiffAH, omniWriter, ch);
writeUInt32Attribute(omniWriter, ch, oh, ah.nbTracksAH, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.thrustIdPerTrackAH, diffParams.thrustIdPerTrack, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.nbWheelsPerTrackAH, diffParams.nbWheelsPerTrack, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.trackToWheelIdsAH, diffParams.trackToWheelIds, diffParams.nbTracks);
writeUInt32ArrayAttribute(omniWriter, ch, oh, ah.wheelIdsInTrackOrderAH, diffParams.wheelIdsInTrackOrder, entryCount);
}
ClutchResponseState registerClutchResponseState(OmniPvdWriter& omniWriter)
{
ClutchResponseState c;
c.CH = omniWriter.registerClass("ClutchResponseState");
c.normalisedResponseAH = omniWriter.registerAttribute(c.CH, "normalisedResponse", OmniPvdDataType::eFLOAT32, 1);
c.responseAH = omniWriter.registerAttribute(c.CH, "response", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeClutchResponseState
(const PxVehicleClutchCommandResponseState& clutchResponseState,
const OmniPvdObjectHandle oh, const ClutchResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.normalisedResponseAH, clutchResponseState.normalisedCommandResponse);
writeFloatAttribute(omniWriter, ch, oh, ah.responseAH, clutchResponseState.commandResponse);
}
ThrottleResponseState registerThrottleResponseState(OmniPvdWriter& omniWriter)
{
ThrottleResponseState t;
t.CH = omniWriter.registerClass("ThrottleResponseState");
t.responseAH = omniWriter.registerAttribute(t.CH, "response", OmniPvdDataType::eFLOAT32, 1);
return t;
}
void writeThrottleResponseState
(const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const OmniPvdObjectHandle oh, const ThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.responseAH, throttleResponseState.commandResponse);
}
EngineState registerEngineState(OmniPvdWriter& omniWriter)
{
EngineState e;
e.CH = omniWriter.registerClass("EngineState");
e.rotationSpeedAH = omniWriter.registerAttribute(e.CH, "rotationSpeed", OmniPvdDataType::eFLOAT32, 1);
return e;
}
void writeEngineState
(const PxVehicleEngineState& engineState,
const OmniPvdObjectHandle oh, const EngineState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.rotationSpeedAH, engineState.rotationSpeed);
}
GearboxState registerGearboxState(OmniPvdWriter& omniWriter)
{
GearboxState g;
g.CH = omniWriter.registerClass("GearboxState");
g.currentGearAH = omniWriter.registerAttribute(g.CH, "currentGear", OmniPvdDataType::eUINT32, 1);
g.targetGearAH = omniWriter.registerAttribute(g.CH, "targetGear", OmniPvdDataType::eUINT32, 1);
g.switchTimeAH = omniWriter.registerAttribute(g.CH, "switchTime", OmniPvdDataType::eFLOAT32, 1);
return g;
}
void writeGearboxState
(const PxVehicleGearboxState& gearboxState,
const OmniPvdObjectHandle oh, const GearboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.currentGearAH, gearboxState.currentGear);
writeUInt32Attribute(omniWriter, ch, oh, ah.targetGearAH, gearboxState.targetGear);
writeFloatAttribute(omniWriter, ch, oh, ah.switchTimeAH, gearboxState.gearSwitchTime);
}
AutoboxState registerAutoboxState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("AutoboxStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
AutoboxState a;
a.CH = omniWriter.registerClass("AutoboxState");
a.timeSinceLastShiftAH = omniWriter.registerAttribute(a.CH, "timeSinceLastShift", OmniPvdDataType::eFLOAT32, 1);
a.activeAutoboxGearShiftAH = omniWriter.registerFlagsAttribute(a.CH, "activeAutoboxShift", boolAsEnum.CH);
return a;
}
void writeAutoboxState
(const PxVehicleAutoboxState& autoboxState,
const OmniPvdObjectHandle oh, const AutoboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.timeSinceLastShiftAH, autoboxState.timeSinceLastShift);
writeFlagAttribute(omniWriter, ch, oh, ah.activeAutoboxGearShiftAH, autoboxState.activeAutoboxGearShift ? 1: 0);
}
DiffState registerDiffState(OmniPvdWriter& omniWriter)
{
DiffState d;
d.CH = omniWriter.registerClass("DifferentialState");
d.torqueRatios0To3AH = omniWriter.registerAttribute(d.CH, "torqueRatios0To3", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios4To7AH = omniWriter.registerAttribute(d.CH, "torqueRatios4To7", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios8To11AH = omniWriter.registerAttribute(d.CH, "torqueRatios8To11", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios12To15AH = omniWriter.registerAttribute(d.CH, "torqueRatios12To15", OmniPvdDataType::eFLOAT32, 4);
d.torqueRatios16To19AH = omniWriter.registerAttribute(d.CH, "torqueRatios16To19", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios0To3AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios0To3", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios4To7AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios4To7", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios8To11AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios8To11", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios12To15AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios12To15", OmniPvdDataType::eFLOAT32, 4);
d.aveWheelSpeedRatios16To19AH = omniWriter.registerAttribute(d.CH, "aveWheelSpeedRatios16To19", OmniPvdDataType::eFLOAT32, 4);
return d;
}
void writeDiffState
(const PxVehicleDifferentialState& diffState,
const OmniPvdObjectHandle oh, const DiffState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios0To3AH, diffState.aveWheelSpeedContributionAllWheels + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios4To7AH, diffState.aveWheelSpeedContributionAllWheels + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios8To11AH, diffState.aveWheelSpeedContributionAllWheels + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios12To15AH, diffState.aveWheelSpeedContributionAllWheels + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.aveWheelSpeedRatios16To19AH, diffState.aveWheelSpeedContributionAllWheels + 16, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios0To3AH, diffState.torqueRatiosAllWheels + 0, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios4To7AH, diffState.torqueRatiosAllWheels + 4, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios8To11AH, diffState.torqueRatiosAllWheels + 8, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios12To15AH, diffState.torqueRatiosAllWheels + 12, 4);
writeFloatArrayAttribute(omniWriter, ch, oh, ah.torqueRatios16To19AH, diffState.torqueRatiosAllWheels + 16, 4);
}
ClutchSlipState registerClutchSlipState(OmniPvdWriter& omniWriter)
{
ClutchSlipState c;
c.CH = omniWriter.registerClass("ClutchSlipState");
c.slipAH = omniWriter.registerAttribute(c.CH, "clutchSlip", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writeClutchSlipState
(const PxVehicleClutchSlipState& clutchSlipState,
const OmniPvdObjectHandle oh, const ClutchSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.slipAH, clutchSlipState.clutchSlip);
}
EngineDrivetrain registerEngineDrivetrain(OmniPvdWriter& omniWriter)
{
EngineDrivetrain e;
e.CH = omniWriter.registerClass("EngineDrivetrain");
e.commandStateAH = omniWriter.registerAttribute(e.CH, "commandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.transmissionCommandStateAH = omniWriter.registerAttribute(e.CH, "transmissionCommandState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchResponseParamsAH = omniWriter.registerAttribute(e.CH, "clutchResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchParamsAH = omniWriter.registerAttribute(e.CH, "clutchParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.engineParamsAH = omniWriter.registerAttribute(e.CH, "engineParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.gearboxParamsAH = omniWriter.registerAttribute(e.CH, "gearboxParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.autoboxParamsAH = omniWriter.registerAttribute(e.CH, "autoboxParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.differentialParamsAH = omniWriter.registerAttribute(e.CH, "differentialParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchResponseStateAH= omniWriter.registerAttribute(e.CH, "clutchResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.throttleResponseStateAH= omniWriter.registerAttribute(e.CH, "throttleResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.engineStateAH = omniWriter.registerAttribute(e.CH, "engineState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.gearboxStateAH = omniWriter.registerAttribute(e.CH, "gearboxState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.autoboxStateAH = omniWriter.registerAttribute(e.CH, "autoboxState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.diffStateAH = omniWriter.registerAttribute(e.CH, "diffState", OmniPvdDataType::eOBJECT_HANDLE, 1);
e.clutchSlipStateAH = omniWriter.registerAttribute(e.CH, "clutchSlipState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return e;
}
////////////////////////////
//PHYSX WHEEL ATTACHMENT
////////////////////////////
PhysXSuspensionLimitConstraintParams registerSuspLimitConstraintParams(OmniPvdWriter& omniWriter)
{
struct DirSpecifier
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle suspensionAH;
OmniPvdAttributeHandle geomNormalAH;
OmniPvdAttributeHandle noneAH;
};
DirSpecifier s;
s.CH = omniWriter.registerClass("DirectionSpecifier");
s.suspensionAH = omniWriter.registerEnumValue(s.CH, "suspensionDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eSUSPENSION);
s.geomNormalAH = omniWriter.registerEnumValue(s.CH, "geomNormalDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eROAD_GEOMETRY_NORMAL);
s.noneAH = omniWriter.registerEnumValue(s.CH, "geomNormalDir",
PxVehiclePhysXSuspensionLimitConstraintParams::DirectionSpecifier::eNONE);
PhysXSuspensionLimitConstraintParams c;
c.CH = omniWriter.registerClass("PhysXSuspLimitConstraintParams");
c.restitutionAH = omniWriter.registerAttribute(c.CH, "restitution", OmniPvdDataType::eFLOAT32, 1);
c.directionForSuspensionLimitConstraintAH = omniWriter.registerFlagsAttribute(c.CH, "directionMode", s.CH);
return c;
}
void writePhysXSuspLimitConstraintParams
(const PxVehiclePhysXSuspensionLimitConstraintParams& params,
const OmniPvdObjectHandle oh, const PhysXSuspensionLimitConstraintParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.directionForSuspensionLimitConstraintAH, params.directionForSuspensionLimitConstraint);
writeFloatAttribute(omniWriter, ch, oh, ah.restitutionAH, params.restitution);
}
PhysXWheelShape registerPhysXWheelShape(OmniPvdWriter& omniWriter)
{
PhysXWheelShape w;
w.CH = omniWriter.registerClass("PhysXWheelShape");
w.shapePtrAH = omniWriter.registerAttribute(w.CH, "pxShapePtr", OmniPvdDataType::eOBJECT_HANDLE, 1);
return w;
}
void writePhysXWheelShape
(const PxShape* wheelShape,
const OmniPvdObjectHandle oh, const PhysXWheelShape& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePtrAttribute(omniWriter, ch, oh, ah.shapePtrAH, wheelShape);
}
PhysXRoadGeomState registerPhysXRoadGeomState(OmniPvdWriter& omniWriter)
{
PhysXRoadGeomState g;
g.CH = omniWriter.registerClass("PhysXRoadGeomState");
g.hitPositionAH = omniWriter.registerAttribute(g.CH, "hitPosition", OmniPvdDataType::eFLOAT32, 3);
g.hitActorPtrAH = omniWriter.registerAttribute(g.CH, "PxActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
g.hitShapePtrAH = omniWriter.registerAttribute(g.CH, "PxShape", OmniPvdDataType::eOBJECT_HANDLE, 1);
g.hitMaterialPtrAH = omniWriter.registerAttribute(g.CH, "PxMaterial", OmniPvdDataType::eOBJECT_HANDLE, 1);
return g;
}
void writePhysXRoadGeomState
(const PxVehiclePhysXRoadGeometryQueryState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXRoadGeomState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeVec3Attribute(omniWriter, ch, oh, ah.hitPositionAH, roadGeomState.hitPosition);
writePtrAttribute(omniWriter, ch, oh, ah.hitActorPtrAH, roadGeomState.actor);
writePtrAttribute(omniWriter, ch, oh, ah.hitMaterialPtrAH, roadGeomState.material);
writePtrAttribute(omniWriter, ch, oh, ah.hitShapePtrAH, roadGeomState.shape);
}
PhysXConstraintState registerPhysXConstraintState(OmniPvdWriter& omniWriter)
{
struct BoolAsEnum
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle falseAH;
OmniPvdAttributeHandle trueAH;
};
BoolAsEnum boolAsEnum;
boolAsEnum.CH = omniWriter.registerClass("PhysXConstraintStateBool");
boolAsEnum.falseAH = omniWriter.registerEnumValue(boolAsEnum.CH, "False", 0);
boolAsEnum.trueAH = omniWriter.registerEnumValue(boolAsEnum.CH, "True", 1);
PhysXConstraintState c;
c.CH = omniWriter.registerClass("PhysXConstraintState");
c.tireLongActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "tireLongitudinalActiveStatus", boolAsEnum.CH);
c.tireLongLinearAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalLinear", OmniPvdDataType::eFLOAT32, 3);
c.tireLongAngularAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalAngular", OmniPvdDataType::eFLOAT32, 3);
c.tireLongDampingAH = omniWriter.registerAttribute(c.CH, "tireLongitudinalDamping", OmniPvdDataType::eFLOAT32, 1);
c.tireLatActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "tireLateralActiveStatus", boolAsEnum.CH);
c.tireLatLinearAH = omniWriter.registerAttribute(c.CH, "tireLateralLinear", OmniPvdDataType::eFLOAT32, 3);
c.tireLatAngularAH = omniWriter.registerAttribute(c.CH, "tireLateralAngular", OmniPvdDataType::eFLOAT32, 3);
c.tireLatDampingAH = omniWriter.registerAttribute(c.CH, "tireLateralDamping", OmniPvdDataType::eFLOAT32, 1);
c.suspActiveStatusAH = omniWriter.registerFlagsAttribute(c.CH, "suspActiveStatus", boolAsEnum.CH);
c.suspLinearAH = omniWriter.registerAttribute(c.CH, "suspLinear", OmniPvdDataType::eFLOAT32, 3);
c.suspAngularAH = omniWriter.registerAttribute(c.CH, "suspAngular", OmniPvdDataType::eFLOAT32, 3);
c.suspRestitutionAH = omniWriter.registerAttribute(c.CH, "suspRestitution", OmniPvdDataType::eFLOAT32, 1);
c.suspGeometricErrorAH = omniWriter.registerAttribute(c.CH, "suspGeometricError", OmniPvdDataType::eFLOAT32, 1);
return c;
}
void writePhysXConstraintState
(const PxVehiclePhysXConstraintState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXConstraintState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, oh, ah.suspActiveStatusAH, roadGeomState.suspActiveStatus ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.suspLinearAH, roadGeomState.suspLinear);
writeVec3Attribute(omniWriter, ch, oh, ah.suspAngularAH, roadGeomState.suspAngular);
writeFloatAttribute(omniWriter, ch, oh, ah.suspGeometricErrorAH, roadGeomState.suspGeometricError);
writeFloatAttribute(omniWriter, ch, oh, ah.suspRestitutionAH, roadGeomState.restitution);
writeFlagAttribute(omniWriter, ch, oh, ah.tireLongActiveStatusAH, roadGeomState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLongLinearAH, roadGeomState.tireLinears[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLongAngularAH, roadGeomState.tireAngulars[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.tireLongDampingAH, roadGeomState.tireDamping[PxVehicleTireDirectionModes::eLONGITUDINAL]);
writeFlagAttribute(omniWriter, ch, oh, ah.tireLatActiveStatusAH, roadGeomState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] ? 1 : 0);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLatLinearAH, roadGeomState.tireLinears[PxVehicleTireDirectionModes::eLATERAL]);
writeVec3Attribute(omniWriter, ch, oh, ah.tireLatAngularAH, roadGeomState.tireAngulars[PxVehicleTireDirectionModes::eLATERAL]);
writeFloatAttribute(omniWriter, ch, oh, ah.tireLatDampingAH, roadGeomState.tireDamping[PxVehicleTireDirectionModes::eLATERAL]);
}
PhysXMaterialFriction registerPhysXMaterialFriction(OmniPvdWriter& omniWriter)
{
PhysXMaterialFriction f;
f.CH = omniWriter.registerClass("PhysXMaterialFriction");
f.frictionAH = omniWriter.registerAttribute(f.CH, "friction", OmniPvdDataType::eFLOAT32, 1);
f.materialPtrAH = omniWriter.registerAttribute(f.CH, "material", OmniPvdDataType::eOBJECT_HANDLE, 1);
return f;
}
void writePhysXMaterialFriction
(const PxVehiclePhysXMaterialFriction& materialFriction,
const OmniPvdObjectHandle oh, const PhysXMaterialFriction& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.frictionAH, materialFriction.friction);
writePtrAttribute(omniWriter, ch, oh, ah.materialPtrAH, materialFriction.material);
}
PhysXWheelAttachment registerPhysXWheelAttachment(OmniPvdWriter& omniWriter)
{
PhysXWheelAttachment w;
w.CH = omniWriter.registerClass("PhysXWheelAttachment");
w.physxConstraintParamsAH = omniWriter.registerAttribute(w.CH, "physxConstraintParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxConstraintStateAH = omniWriter.registerAttribute(w.CH, "physxConstraintState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxWeelShapeAH = omniWriter.registerAttribute(w.CH, "physxWheelShape", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxRoadGeometryStateAH = omniWriter.registerAttribute(w.CH, "physxRoadGeomState", OmniPvdDataType::eOBJECT_HANDLE, 1);
w.physxMaterialFrictionSetAH = omniWriter.registerUniqueListAttribute(w.CH, "physXMaterialFrictions", OmniPvdDataType::eOBJECT_HANDLE);
return w;
}
//////////////////////////
//PHYSX RIGID ACTOR
//////////////////////////
PhysXRigidActor registerPhysXRigidActor(OmniPvdWriter& omniWriter)
{
PhysXRigidActor a;
a.CH = omniWriter.registerClass("PhysXRigidActor");
a.rigidActorAH = omniWriter.registerAttribute(a.CH, "rigidActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
return a;
}
void writePhysXRigidActor
(const PxRigidActor* actor,
const OmniPvdObjectHandle oh, const PhysXRigidActor& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writePtrAttribute(omniWriter, ch, oh, ah.rigidActorAH, actor);
}
PhysXRoadGeometryQueryParams registerPhysXRoadGeometryQueryParams(OmniPvdWriter& omniWriter)
{
struct QueryType
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle raycastAH;
OmniPvdAttributeHandle sweepAH;
OmniPvdAttributeHandle noneAH;
};
QueryType queryType;
queryType.CH = omniWriter.registerClass("PhysXRoadGeometryQueryTpe");
queryType.raycastAH = omniWriter.registerEnumValue(queryType.CH, "raycast", PxVehiclePhysXRoadGeometryQueryType::eRAYCAST);
queryType.sweepAH = omniWriter.registerEnumValue(queryType.CH, "sweep", PxVehiclePhysXRoadGeometryQueryType::eSWEEP);
queryType.noneAH = omniWriter.registerEnumValue(queryType.CH, "none", PxVehiclePhysXRoadGeometryQueryType::eNONE);
PhysXRoadGeometryQueryParams a;
a.CH = omniWriter.registerClass("PhysXRoadGeomQueryParams");
a.queryTypeAH = omniWriter.registerFlagsAttribute(a.CH, "physxQueryType", queryType.CH);
struct QueryFlag
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle staticAH;
OmniPvdAttributeHandle dynamicAH;
OmniPvdAttributeHandle preFilterAH;
OmniPvdAttributeHandle postFilterAH;
OmniPvdAttributeHandle anyHitAH;
OmniPvdAttributeHandle noBlockAH;
OmniPvdAttributeHandle batchQueryLegacyBehaviourAH;
OmniPvdAttributeHandle disableHardcodedFilterAH;
};
QueryFlag queryFlag;
queryFlag.CH = omniWriter.registerClass("PhysXRoadGeometryQueryFlag");
queryFlag.staticAH = omniWriter.registerEnumValue(queryFlag.CH, "eSTATIC", PxQueryFlag::eSTATIC);
queryFlag.dynamicAH = omniWriter.registerEnumValue(queryFlag.CH, "eDYNAMIC", PxQueryFlag::eDYNAMIC);
queryFlag.preFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "ePREFILTER", PxQueryFlag::ePREFILTER);
queryFlag.postFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "ePOSTFILTER", PxQueryFlag::ePOSTFILTER);
queryFlag.anyHitAH = omniWriter.registerEnumValue(queryFlag.CH, "eANY_HIT", PxQueryFlag::eANY_HIT);
queryFlag.noBlockAH = omniWriter.registerEnumValue(queryFlag.CH, "eNO_BLOCK", PxQueryFlag::eNO_BLOCK);
queryFlag.batchQueryLegacyBehaviourAH = omniWriter.registerEnumValue(queryFlag.CH, "eBATCH_QUERY_LEGACY_BEHAVIOUR", PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR);
queryFlag.disableHardcodedFilterAH = omniWriter.registerEnumValue(queryFlag.CH, "eDISABLE_HARDCODED_FILTER", PxQueryFlag::eDISABLE_HARDCODED_FILTER);
a.filterDataParams.CH = omniWriter.registerClass("PhysXRoadGeometryQueryFilterData");
a.filterDataParams.word0AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word0", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word1AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word1", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word2AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word2", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.word3AH = omniWriter.registerAttribute(a.filterDataParams.CH, "word3", OmniPvdDataType::eUINT32, 1);
a.filterDataParams.flagsAH = omniWriter.registerFlagsAttribute(a.filterDataParams.CH, "flags", queryFlag.CH);
a.defaultFilterDataAH = omniWriter.registerAttribute(a.CH, "defaultFilterData", OmniPvdDataType::eOBJECT_HANDLE, 1);
a.filterDataSetAH = omniWriter.registerUniqueListAttribute(a.CH, "filterDataSet", OmniPvdDataType::eOBJECT_HANDLE);
return a;
}
void writePhysXRoadGeometryQueryFilterData
(const PxQueryFilterData& queryFilterData,
const OmniPvdObjectHandle oh, const PhysXRoadGeometryQueryFilterData& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeUInt32Attribute(omniWriter, ch, oh, ah.word0AH, queryFilterData.data.word0);
writeUInt32Attribute(omniWriter, ch, oh, ah.word1AH, queryFilterData.data.word1);
writeUInt32Attribute(omniWriter, ch, oh, ah.word2AH, queryFilterData.data.word2);
writeUInt32Attribute(omniWriter, ch, oh, ah.word3AH, queryFilterData.data.word3);
writeFlagAttribute(omniWriter, ch, oh, ah.flagsAH, queryFilterData.flags);
}
void writePhysXRoadGeometryQueryParams
(const PxVehiclePhysXRoadGeometryQueryParams& queryParams, const PxVehicleAxleDescription& axleDesc,
const OmniPvdObjectHandle queryParamsOH, const OmniPvdObjectHandle defaultFilterDataOH, const OmniPvdObjectHandle* filterDataOHs,
const PhysXRoadGeometryQueryParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFlagAttribute(omniWriter, ch, queryParamsOH, ah.queryTypeAH, queryParams.roadGeometryQueryType);
if (defaultFilterDataOH) // TODO: test against invalid hanndle once it gets introduced
{
writePhysXRoadGeometryQueryFilterData(queryParams.defaultFilterData, defaultFilterDataOH, ah.filterDataParams,
omniWriter, ch);
}
if (queryParams.filterDataEntries)
{
for (PxU32 i = 0; i < axleDesc.nbWheels; i++)
{
const PxU32 wheelId = axleDesc.wheelIdsInAxleOrder[i];
const OmniPvdObjectHandle fdOH = filterDataOHs[wheelId];
if (fdOH) // TODO: test against invalid hanndle once it gets introduced
{
writePhysXRoadGeometryQueryFilterData(queryParams.filterDataEntries[wheelId], fdOH, ah.filterDataParams,
omniWriter, ch);
}
}
}
}
PhysXSteerState registerPhysXSteerState(OmniPvdWriter& omniWriter)
{
PhysXSteerState s;
s.CH = omniWriter.registerClass("PhysXSteerState");
s.previousSteerCommandAH = omniWriter.registerAttribute(s.CH, "previousSteerCommand", OmniPvdDataType::eFLOAT32, 1);
return s;
}
void writePhysXSteerState
(const PxVehiclePhysXSteerState& steerState,
const OmniPvdObjectHandle oh, const PhysXSteerState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch)
{
writeFloatAttribute(omniWriter, ch, oh, ah.previousSteerCommandAH, steerState.previousSteerCommand);
}
//////////////////////
//VEHICLE
//////////////////////
Vehicle registerVehicle(OmniPvdWriter& omniWriter)
{
Vehicle v;
v.CH = omniWriter.registerClass("Vehicle");
v.rigidBodyParamsAH = omniWriter.registerAttribute(v.CH, "rigidBodyParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.rigidBodyStateAH = omniWriter.registerAttribute(v.CH, "rigidBodyState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.suspStateCalcParamsAH = omniWriter.registerAttribute(v.CH, "suspStateCalcParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.wheelAttachmentSetAH = omniWriter.registerUniqueListAttribute(v.CH, "wheelAttachmentSet", OmniPvdDataType::eOBJECT_HANDLE);
v.antiRollSetAH = omniWriter.registerUniqueListAttribute(v.CH, "antiRollSet", OmniPvdDataType::eOBJECT_HANDLE);
v.antiRollForceAH = omniWriter.registerAttribute(v.CH, "antiRollForce", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.brakeResponseParamsSetAH = omniWriter.registerUniqueListAttribute(v.CH, "brakeResponseParamsSet", OmniPvdDataType::eOBJECT_HANDLE);
v.steerResponseParamsAH = omniWriter.registerAttribute(v.CH, "steerResponseParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.brakeResponseStatesAH = omniWriter.registerAttribute(v.CH, "brakeResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.steerResponseStatesAH = omniWriter.registerAttribute(v.CH, "steerResponseState", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.ackermannParamsAH = omniWriter.registerAttribute(v.CH, "ackermannParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.directDrivetrainAH = omniWriter.registerAttribute(v.CH, "directDrivetrain", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.engineDriveTrainAH = omniWriter.registerAttribute(v.CH, "engineDrivetrain", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxWheelAttachmentSetAH = omniWriter.registerUniqueListAttribute(v.CH, "physxWheelAttachmentSet", OmniPvdDataType::eOBJECT_HANDLE);
v.physxRoadGeometryQueryParamsAH = omniWriter.registerAttribute(v.CH, "physxRoadGeomQryParams", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxRigidActorAH = omniWriter.registerAttribute(v.CH, "physxRigidActor", OmniPvdDataType::eOBJECT_HANDLE, 1);
v.physxSteerStateAH = omniWriter.registerAttribute(v.CH, "physxSteerState", OmniPvdDataType::eOBJECT_HANDLE, 1);
return v;
}
#endif //PX_SUPPORT_OMNI_PVD
} // namespace vehicle2
} // namespace physx
/** @} */
| 89,353 | C++ | 49.114414 | 175 | 0.80455 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdAttributeHandles.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.
#pragma once
#include "vehicle2/pvd/PxVehiclePvdHelpers.h"
#include "VhPvdWriter.h"
/** \addtogroup vehicle2
@{
*/
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
struct PxVehiclePvdAttributeHandles
{
#if PX_SUPPORT_OMNI_PVD
/////////////////////
//RIGID BODY
/////////////////////////
RigidBodyParams rigidBodyParams;
RigidBodyState rigidBodyState;
/////////////////////////
//SUSP STATE CALC PARAMS
/////////////////////////
SuspStateCalcParams suspStateCalcParams;
/////////////////////////
//CONTROL ATTRIBUTES
/////////////////////////
WheelResponseParams brakeCommandResponseParams;
WheelResponseParams steerCommandResponseParams;
AckermannParams ackermannParams;
WheelResponseStates brakeCommandResponseStates;
WheelResponseStates steerCommandResponseStates;
/////////////////////////////////
//WHEEL ATTACHMENT ATTRIBUTES
/////////////////////////////////
WheelParams wheelParams;
WheelActuationState wheelActuationState;
WheelRigidBody1dState wheelRigidBody1dState;
WheelLocalPoseState wheelLocalPoseState;
RoadGeometryState roadGeomState;
SuspParams suspParams;
SuspCompParams suspCompParams;
SuspForceParams suspForceParams;
SuspState suspState;
SuspCompState suspCompState;
SuspForce suspForce;
TireParams tireParams;
TireDirectionState tireDirectionState;
TireSpeedState tireSpeedState;
TireSlipState tireSlipState;
TireStickyState tireStickyState;
TireGripState tireGripState;
TireCamberState tireCamberState;
TireForce tireForce;
WheelAttachment wheelAttachment;
///////////////////////
//ANTIROLL BARS
///////////////////////
AntiRollParams antiRollParams;
AntiRollForce antiRollForce;
///////////////////////////////////
//DIRECT DRIVETRAIN
///////////////////////////////////
DirectDriveCommandState directDriveCommandState;
DirectDriveTransmissionCommandState directDriveTransmissionCommandState;
WheelResponseParams directDriveThrottleCommandResponseParams;
DirectDriveThrottleResponseState directDriveThrottleCommandResponseState;
DirectDrivetrain directDrivetrain;
//////////////////////////////////
//ENGINE DRIVETRAIN ATTRIBUTES
//////////////////////////////////
EngineDriveCommandState engineDriveCommandState;
EngineDriveTransmissionCommandState engineDriveTransmissionCommandState;
TankDriveTransmissionCommandState tankDriveTransmissionCommandState;
ClutchResponseParams clutchCommandResponseParams;
ClutchParams clutchParams;
EngineParams engineParams;
GearboxParams gearboxParams;
AutoboxParams autoboxParams;
MultiWheelDiffParams multiwheelDiffParams;
FourWheelDiffParams fourwheelDiffParams;
TankDiffParams tankDiffParams;
ClutchResponseState clutchResponseState;
ThrottleResponseState throttleResponseState;
EngineState engineState;
GearboxState gearboxState;
AutoboxState autoboxState;
DiffState diffState;
ClutchSlipState clutchSlipState;
EngineDrivetrain engineDrivetrain;
//////////////////////////////////////
//PHYSX WHEEL ATTACHMENT INTEGRATION
//////////////////////////////////////
PhysXSuspensionLimitConstraintParams physxSuspLimitConstraintParams;
PhysXWheelShape physxWheelShape;
PhysXRoadGeomState physxRoadGeomState;
PhysXConstraintState physxConstraintState;
PhysXMaterialFriction physxMaterialFriction;
PhysXWheelAttachment physxWheelAttachment;
////////////////////
//PHYSX RIGID ACTOR
////////////////////
PhysXRoadGeometryQueryParams physxRoadGeometryQueryParams;
PhysXRigidActor physxRigidActor;
PhysXSteerState physxSteerState;
//////////////////////////////////
//VEHICLE ATTRIBUTES
//////////////////////////////////
Vehicle vehicle;
#endif
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
/** @} */
| 5,419 | C | 30.32948 | 74 | 0.731685 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdWriter.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.
#pragma once
#include "vehicle2/braking/PxVehicleBrakingParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainParams.h"
#include "vehicle2/drivetrain/PxVehicleDrivetrainStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyParams.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/steering/PxVehicleSteeringParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireParams.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/wheel/PxVehicleWheelParams.h"
#include "vehicle2/wheel/PxVehicleWheelStates.h"
#if PX_SUPPORT_OMNI_PVD
#include "OmniPvdWriter.h"
#endif
/** \addtogroup vehicle2
@{
*/
#if PX_SUPPORT_OMNI_PVD
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
///////////////////////////////
//RIGID BODY
///////////////////////////////
struct RigidBodyParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle massAH;
};
struct RigidBodyState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle posAH;
OmniPvdAttributeHandle quatAH;
OmniPvdAttributeHandle linearVelocityAH;
OmniPvdAttributeHandle angularVelocityAH;
OmniPvdAttributeHandle previousLinearVelocityAH;
OmniPvdAttributeHandle previousAngularVelocityAH;
OmniPvdAttributeHandle externalForceAH;
OmniPvdAttributeHandle externalTorqueAH;
};
RigidBodyParams registerRigidBodyParams(OmniPvdWriter& omniWriter);
RigidBodyState registerRigidBodyState(OmniPvdWriter& omniWriter);
void writeRigidBodyParams
(const PxVehicleRigidBodyParams& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeRigidBodyState
(const PxVehicleRigidBodyState& rbodyParams,
const OmniPvdObjectHandle oh, const RigidBodyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////
//CONTROL
/////////////////////////////////
struct WheelResponseParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseMultipliers0To3AH;
OmniPvdAttributeHandle responseMultipliers4To7AH;
OmniPvdAttributeHandle responseMultipliers8To11AH;
OmniPvdAttributeHandle responseMultipliers12To15AH;
OmniPvdAttributeHandle responseMultipliers16To19AH;
OmniPvdAttributeHandle maxResponseAH;
};
struct WheelResponseStates
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseStates0To3AH;
OmniPvdAttributeHandle responseStates4To7AH;
OmniPvdAttributeHandle responseStates8To11AH;
OmniPvdAttributeHandle responseStates12To15AH;
OmniPvdAttributeHandle responseStates16To19AH;
};
struct AckermannParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelIdsAH;
OmniPvdAttributeHandle wheelBaseAH;
OmniPvdAttributeHandle trackWidthAH;
OmniPvdAttributeHandle strengthAH;
};
WheelResponseParams registerSteerResponseParams(OmniPvdWriter& omniWriter);
WheelResponseParams registerBrakeResponseParams(OmniPvdWriter& omniWriter);
WheelResponseStates registerSteerResponseStates(OmniPvdWriter& omniWriter);
WheelResponseStates registerBrakeResponseStates(OmniPvdWriter& omniWriter);
AckermannParams registerAckermannParams(OmniPvdWriter&);
void writeSteerResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleSteerCommandResponseParams& steerResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeBrakeResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleBrakeCommandResponseParams& brakeResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSteerResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& steerResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeBrakeResponseStates
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleArrayData<PxReal>& brakeResponseStates,
const OmniPvdObjectHandle oh, const WheelResponseStates& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAckermannParams
(const PxVehicleAckermannParams&,
const OmniPvdObjectHandle, const AckermannParams&, OmniPvdWriter&, OmniPvdContextHandle);
/////////////////////////////////////////////
//WHEEL ATTACHMENTS
/////////////////////////////////////////////
struct WheelParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelRadiusAH;
OmniPvdAttributeHandle halfWidthAH;
OmniPvdAttributeHandle massAH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle dampingRateAH;
};
struct WheelActuationState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle isBrakeAppliedAH;
OmniPvdAttributeHandle isDriveAppliedAH;
};
struct WheelRigidBody1dState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rotationSpeedAH;
OmniPvdAttributeHandle correctedRotationSpeedAH;
OmniPvdAttributeHandle rotationAngleAH;
};
struct WheelLocalPoseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle posAH;
OmniPvdAttributeHandle quatAH;
};
struct RoadGeometryState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle planeAH;
OmniPvdAttributeHandle frictionAH;
OmniPvdAttributeHandle velocityAH;
OmniPvdAttributeHandle hitStateAH;
};
struct SuspParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle suspAttachmentPosAH;
OmniPvdAttributeHandle suspAttachmentQuatAH;
OmniPvdAttributeHandle suspDirAH;
OmniPvdAttributeHandle suspTravleDistAH;
OmniPvdAttributeHandle wheelAttachmentPosAH;
OmniPvdAttributeHandle wheelAttachmentQuatAH;
};
struct SuspCompParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle toeAngleAH;
OmniPvdAttributeHandle camberAngleAH;
OmniPvdAttributeHandle suspForceAppPointAH;
OmniPvdAttributeHandle tireForceAppPointAH;
};
struct SuspForceParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle stiffnessAH;
OmniPvdAttributeHandle dampingAH;
OmniPvdAttributeHandle sprungMassAH;
};
struct SuspState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle jounceAH;
OmniPvdAttributeHandle jounceSpeedAH;
OmniPvdAttributeHandle separationAH;
};
struct SuspCompState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle toeAH;
OmniPvdAttributeHandle camberAH;
OmniPvdAttributeHandle tireForceAppPointAH;
OmniPvdAttributeHandle suspForceAppPointAH;
};
struct SuspForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle forceAH;
OmniPvdAttributeHandle torqueAH;
OmniPvdAttributeHandle normalForceAH;
};
struct TireParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle latStiffXAH;
OmniPvdAttributeHandle latStiffYAH;
OmniPvdAttributeHandle longStiffAH;
OmniPvdAttributeHandle camberStiffAH;
OmniPvdAttributeHandle frictionVsSlipAH;
OmniPvdAttributeHandle restLoadAH;
OmniPvdAttributeHandle loadFilterAH;
};
struct TireDirectionState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngDirectionAH;
OmniPvdAttributeHandle latDirectionAH;
};
struct TireSpeedState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngSpeedAH;
OmniPvdAttributeHandle latSpeedAH;
};
struct TireSlipState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngSlipAH;
OmniPvdAttributeHandle latSlipAH;
};
struct TireGripState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle loadAH;
OmniPvdAttributeHandle frictionAH;
};
struct TireCamberState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle camberAngleAH;
};
struct TireStickyState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngStickyStateTimer;
OmniPvdAttributeHandle lngStickyStateStatus;
OmniPvdAttributeHandle latStickyStateTimer;
OmniPvdAttributeHandle latStickyStateStatus;
};
struct TireForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle lngForceAH;
OmniPvdAttributeHandle lngTorqueAH;
OmniPvdAttributeHandle latForceAH;
OmniPvdAttributeHandle latTorqueAH;
OmniPvdAttributeHandle aligningMomentAH;
OmniPvdAttributeHandle wheelTorqueAH;
};
struct WheelAttachment
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheelParamsAH;
OmniPvdAttributeHandle wheelActuationStateAH;
OmniPvdAttributeHandle wheelRigidBody1dStateAH;
OmniPvdAttributeHandle wheelLocalPoseStateAH;
OmniPvdAttributeHandle roadGeomStateAH;
OmniPvdAttributeHandle suspParamsAH;
OmniPvdAttributeHandle suspCompParamsAH;
OmniPvdAttributeHandle suspForceParamsAH;
OmniPvdAttributeHandle suspStateAH;
OmniPvdAttributeHandle suspCompStateAH;
OmniPvdAttributeHandle suspForceAH;
OmniPvdAttributeHandle tireParamsAH;
OmniPvdAttributeHandle tireDirectionStateAH;
OmniPvdAttributeHandle tireSpeedStateAH;
OmniPvdAttributeHandle tireSlipStateAH;
OmniPvdAttributeHandle tireStickyStateAH;
OmniPvdAttributeHandle tireGripStateAH;
OmniPvdAttributeHandle tireCamberStateAH;
OmniPvdAttributeHandle tireForceAH;
};
WheelParams registerWheelParams(OmniPvdWriter& omniWriter);
WheelActuationState registerWheelActuationState(OmniPvdWriter& omniWriter);
WheelRigidBody1dState registerWheelRigidBody1dState(OmniPvdWriter& omniWriter);
WheelLocalPoseState registerWheelLocalPoseState(OmniPvdWriter& omniWriter);
RoadGeometryState registerRoadGeomState(OmniPvdWriter& omniWriter);
SuspParams registerSuspParams(OmniPvdWriter& omniWriter);
SuspCompParams registerSuspComplianceParams(OmniPvdWriter& omniWriter);
SuspForceParams registerSuspForceParams(OmniPvdWriter& omniWriter);
SuspState registerSuspState(OmniPvdWriter& omniWriter);
SuspCompState registerSuspComplianceState(OmniPvdWriter& omniWriter);
SuspForce registerSuspForce(OmniPvdWriter& omniWriter);
TireParams registerTireParams(OmniPvdWriter& omniWriter);
TireDirectionState registerTireDirectionState(OmniPvdWriter& omniWriter);
TireSpeedState registerTireSpeedState(OmniPvdWriter& omniWriter);
TireSlipState registerTireSlipState(OmniPvdWriter& omniWriter);
TireStickyState registerTireStickyState(OmniPvdWriter& omniWriter);
TireGripState registerTireGripState(OmniPvdWriter& omniWriter);
TireCamberState registerTireCamberState(OmniPvdWriter& omniWriter);
TireForce registerTireForce(OmniPvdWriter& omniWriter);
WheelAttachment registerWheelAttachment(OmniPvdWriter& omniWriter);
void writeWheelParams
(const PxVehicleWheelParams& params,
const OmniPvdObjectHandle oh, const WheelParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelActuationState
(const PxVehicleWheelActuationState& actState,
const OmniPvdObjectHandle oh, const WheelActuationState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelRigidBody1dState
(const PxVehicleWheelRigidBody1dState& rigidBodyState,
const OmniPvdObjectHandle oh, const WheelRigidBody1dState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeWheelLocalPoseState
(const PxVehicleWheelLocalPose& pose,
const OmniPvdObjectHandle oh, const WheelLocalPoseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeRoadGeomState
(const PxVehicleRoadGeometryState& roadGeometryState,
const OmniPvdObjectHandle oh, const RoadGeometryState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspParams
(const PxVehicleSuspensionParams& suspParams,
const OmniPvdObjectHandle oh, const SuspParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspComplianceParams
(const PxVehicleSuspensionComplianceParams& compParams,
const OmniPvdObjectHandle oh, const SuspCompParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspForceParams
(const PxVehicleSuspensionForceParams& forceParams,
const OmniPvdObjectHandle oh, const SuspForceParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspState
(const PxVehicleSuspensionState& suspState,
const OmniPvdObjectHandle oh, const SuspState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspComplianceState
(const PxVehicleSuspensionComplianceState& suspCompState,
const OmniPvdObjectHandle oh, const SuspCompState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeSuspForce
(const PxVehicleSuspensionForce& suspForce,
const OmniPvdObjectHandle oh, const SuspForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireParams
(const PxVehicleTireForceParams& tireParams,
const OmniPvdObjectHandle oh, const TireParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireDirectionState
(const PxVehicleTireDirectionState& tireDirState,
const OmniPvdObjectHandle oh, const TireDirectionState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireSpeedState
(const PxVehicleTireSpeedState& tireSpeedState,
const OmniPvdObjectHandle oh, const TireSpeedState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireSlipState
(const PxVehicleTireSlipState& tireSlipState,
const OmniPvdObjectHandle oh, const TireSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireStickyState
(const PxVehicleTireStickyState& tireStickyState,
const OmniPvdObjectHandle oh, const TireStickyState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireGripState
(const PxVehicleTireGripState& tireGripState,
const OmniPvdObjectHandle oh, const TireGripState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireCamberState
(const PxVehicleTireCamberAngleState& tireCamberState,
const OmniPvdObjectHandle oh, const TireCamberState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTireForce
(const PxVehicleTireForce& tireForce,
const OmniPvdObjectHandle oh, const TireForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//ANTIROLL
/////////////////////////////////////////
struct AntiRollParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle wheel0AH;
OmniPvdAttributeHandle wheel1AH;
OmniPvdAttributeHandle stiffnessAH;
};
struct AntiRollForce
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueAH;
};
AntiRollParams registerAntiRollParams(OmniPvdWriter& omniWriter);
AntiRollForce registerAntiRollForce(OmniPvdWriter& omniWriter);
void writeAntiRollParams
(const PxVehicleAntiRollForceParams& antiRollParams,
const OmniPvdObjectHandle oh, const AntiRollParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAntiRollForce
(const PxVehicleAntiRollTorque& antiRollForce,
const OmniPvdObjectHandle oh, const AntiRollForce& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
////////////////////////////////////////
//SUSPENSION STATE CALCULATION
////////////////////////////////////////
struct SuspStateCalcParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle calcTypeAH;
OmniPvdAttributeHandle limitExpansionValAH;
};
SuspStateCalcParams registerSuspStateCalcParams(OmniPvdWriter& omniWriter);
void writeSuspStateCalcParams
(const PxVehicleSuspensionStateCalculationParams& suspStateCalcParams,
const OmniPvdObjectHandle oh, const SuspStateCalcParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//DIRECT DRIVETRAIN
////////////////////////////////////////
struct DirectDriveCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle brakesAH;
OmniPvdAttributeHandle throttleAH;
OmniPvdAttributeHandle steerAH;
};
struct DirectDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle gearAH;
};
struct DirectDriveThrottleResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle states0To3AH;
OmniPvdAttributeHandle states4To7AH;
OmniPvdAttributeHandle states8To11AH;
OmniPvdAttributeHandle states12To15AH;
OmniPvdAttributeHandle states16To19AH;
};
struct DirectDrivetrain
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle throttleResponseParamsAH;
OmniPvdAttributeHandle commandStateAH;
OmniPvdAttributeHandle transmissionCommandStateAH;
OmniPvdAttributeHandle throttleResponseStateAH;
};
WheelResponseParams registerDirectDriveThrottleResponseParams(OmniPvdWriter& omniWriter);
DirectDriveCommandState registerDirectDriveCommandState(OmniPvdWriter& omniWriter);
DirectDriveTransmissionCommandState registerDirectDriveTransmissionCommandState(OmniPvdWriter& omniWriter);
DirectDriveThrottleResponseState registerDirectDriveThrottleResponseState(OmniPvdWriter& omniWriter);
DirectDrivetrain registerDirectDrivetrain(OmniPvdWriter& omniWriter);
void writeDirectDriveThrottleResponseParams
(const PxVehicleAxleDescription& axleDesc,
const PxVehicleDirectDriveThrottleCommandResponseParams& directDriveThrottleResponseParams,
const OmniPvdObjectHandle oh, const WheelResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveCommandState
(const PxVehicleCommandState& commands,
const OmniPvdObjectHandle oh, const DirectDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveTransmissionCommandState
(const PxVehicleDirectDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const DirectDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDirectDriveThrottleResponseState
(const PxVehicleAxleDescription& axleDesc, const PxVehicleArrayData<PxReal>& throttleResponseState,
const OmniPvdObjectHandle oh, const DirectDriveThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
/////////////////////////////////////////
//ENGINE DRIVETRAIN
////////////////////////////////////////
struct EngineDriveCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle brakesAH;
OmniPvdAttributeHandle throttleAH;
OmniPvdAttributeHandle steerAH;
};
struct EngineDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle gearAH;
OmniPvdAttributeHandle clutchAH;
};
struct TankDriveTransmissionCommandState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle thrustsAH;
};
struct ClutchResponseParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle maxResponseAH;
};
struct ClutchParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle accuracyAH;
OmniPvdAttributeHandle iterationsAH;
};
struct EngineParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueCurveAH;
OmniPvdAttributeHandle moiAH;
OmniPvdAttributeHandle peakTorqueAH;
OmniPvdAttributeHandle idleOmegaAH;
OmniPvdAttributeHandle maxOmegaAH;
OmniPvdAttributeHandle dampingRateFullThrottleAH;
OmniPvdAttributeHandle dampingRateZeroThrottleClutchEngagedAH;
OmniPvdAttributeHandle dampingRateZeroThrottleClutchDisengagedAH;
};
struct GearboxParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle ratiosAH;
OmniPvdAttributeHandle nbRatiosAH;
OmniPvdAttributeHandle neutralGearAH;
OmniPvdAttributeHandle finalRatioAH;
OmniPvdAttributeHandle switchTimeAH;
};
struct AutoboxParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle upRatiosAH;
OmniPvdAttributeHandle downRatiosAH;
OmniPvdAttributeHandle latencyAH;
};
struct MultiWheelDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueRatios0To3AH;
OmniPvdAttributeHandle torqueRatios4To7AH;
OmniPvdAttributeHandle torqueRatios8To11AH;
OmniPvdAttributeHandle torqueRatios12To15AH;
OmniPvdAttributeHandle torqueRatios16To19AH;
OmniPvdAttributeHandle aveWheelSpeedRatios0To3AH;
OmniPvdAttributeHandle aveWheelSpeedRatios4To7AH;
OmniPvdAttributeHandle aveWheelSpeedRatios8To11AH;
OmniPvdAttributeHandle aveWheelSpeedRatios12To15AH;
OmniPvdAttributeHandle aveWheelSpeedRatios16To19AH;
};
struct FourWheelDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle frontWheelsAH;
OmniPvdAttributeHandle rearWheelsAH;
OmniPvdAttributeHandle frontBiasAH;
OmniPvdAttributeHandle frontTargetAH;
OmniPvdAttributeHandle rearBiasAH;
OmniPvdAttributeHandle rearTargetAH;
OmniPvdAttributeHandle centreBiasAH;
OmniPvdAttributeHandle centreTargetAH;
};
struct TankDiffParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle nbTracksAH;
OmniPvdAttributeHandle thrustIdPerTrackAH;
OmniPvdAttributeHandle nbWheelsPerTrackAH;
OmniPvdAttributeHandle trackToWheelIdsAH;
OmniPvdAttributeHandle wheelIdsInTrackOrderAH;
};
struct ClutchResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle normalisedResponseAH;
OmniPvdAttributeHandle responseAH;
};
struct ThrottleResponseState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle responseAH;
};
struct EngineState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rotationSpeedAH;
};
struct GearboxState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle currentGearAH;
OmniPvdAttributeHandle targetGearAH;
OmniPvdAttributeHandle switchTimeAH;
};
struct AutoboxState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle timeSinceLastShiftAH;
OmniPvdAttributeHandle activeAutoboxGearShiftAH;
};
struct DiffState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle torqueRatios0To3AH;
OmniPvdAttributeHandle torqueRatios4To7AH;
OmniPvdAttributeHandle torqueRatios8To11AH;
OmniPvdAttributeHandle torqueRatios12To15AH;
OmniPvdAttributeHandle torqueRatios16To19AH;
OmniPvdAttributeHandle aveWheelSpeedRatios0To3AH;
OmniPvdAttributeHandle aveWheelSpeedRatios4To7AH;
OmniPvdAttributeHandle aveWheelSpeedRatios8To11AH;
OmniPvdAttributeHandle aveWheelSpeedRatios12To15AH;
OmniPvdAttributeHandle aveWheelSpeedRatios16To19AH;
};
struct ClutchSlipState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle slipAH;
};
struct EngineDrivetrain
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle commandStateAH;
OmniPvdAttributeHandle transmissionCommandStateAH;
OmniPvdAttributeHandle clutchResponseParamsAH;
OmniPvdAttributeHandle clutchParamsAH;
OmniPvdAttributeHandle engineParamsAH;
OmniPvdAttributeHandle gearboxParamsAH;
OmniPvdAttributeHandle autoboxParamsAH;
OmniPvdAttributeHandle differentialParamsAH;
OmniPvdAttributeHandle clutchResponseStateAH;
OmniPvdAttributeHandle throttleResponseStateAH;
OmniPvdAttributeHandle engineStateAH;
OmniPvdAttributeHandle gearboxStateAH;
OmniPvdAttributeHandle autoboxStateAH;
OmniPvdAttributeHandle diffStateAH;
OmniPvdAttributeHandle clutchSlipStateAH;
};
EngineDriveCommandState registerEngineDriveCommandState(OmniPvdWriter& omniWriter);
EngineDriveTransmissionCommandState registerEngineDriveTransmissionCommandState(OmniPvdWriter& omniWriter);
TankDriveTransmissionCommandState registerTankDriveTransmissionCommandState(OmniPvdWriter&, OmniPvdClassHandle baseClass);
ClutchResponseParams registerClutchResponseParams(OmniPvdWriter& omniWriter);
ClutchParams registerClutchParams(OmniPvdWriter& omniWriter);
EngineParams registerEngineParams(OmniPvdWriter& omniWriter);
GearboxParams registerGearboxParams(OmniPvdWriter& omniWriter);
AutoboxParams registerAutoboxParams(OmniPvdWriter& omniWriter);
MultiWheelDiffParams registerMultiWheelDiffParams(OmniPvdWriter& omniWriter);
FourWheelDiffParams registerFourWheelDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass);
TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter, OmniPvdClassHandle baseClass);
//TankDiffParams registerTankDiffParams(OmniPvdWriter& omniWriter);
ClutchResponseState registerClutchResponseState(OmniPvdWriter& omniWriter);
ThrottleResponseState registerThrottleResponseState(OmniPvdWriter& omniWriter);
EngineState registerEngineState(OmniPvdWriter& omniWriter);
GearboxState registerGearboxState(OmniPvdWriter& omniWriter);
AutoboxState registerAutoboxState(OmniPvdWriter& omniWriter);
DiffState registerDiffState(OmniPvdWriter& omniWriter);
ClutchSlipState registerClutchSlipState(OmniPvdWriter& omniWriter);
EngineDrivetrain registerEngineDrivetrain(OmniPvdWriter& omniWriter);
void writeEngineDriveCommandState
(const PxVehicleCommandState& commandState,
const OmniPvdObjectHandle oh, const EngineDriveCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineDriveTransmissionCommandState
(const PxVehicleEngineDriveTransmissionCommandState& transmission,
const OmniPvdObjectHandle oh, const EngineDriveTransmissionCommandState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTankDriveTransmissionCommandState
(const PxVehicleTankDriveTransmissionCommandState&, const OmniPvdObjectHandle,
const EngineDriveTransmissionCommandState&, const TankDriveTransmissionCommandState&,
OmniPvdWriter&, OmniPvdContextHandle);
void writeClutchResponseParams
(const PxVehicleClutchCommandResponseParams& clutchResponseParams,
const OmniPvdObjectHandle oh, const ClutchResponseParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeClutchParams
(const PxVehicleClutchParams& clutchParams,
const OmniPvdObjectHandle oh, const ClutchParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineParams
(const PxVehicleEngineParams& engineParams,
const OmniPvdObjectHandle oh, const EngineParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeGearboxParams
(const PxVehicleGearboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const GearboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAutoboxParams
(const PxVehicleAutoboxParams& gearboxParams,
const OmniPvdObjectHandle oh, const AutoboxParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeMultiWheelDiffParams
(const PxVehicleMultiWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeFourWheelDiffParams
(const PxVehicleFourWheelDriveDifferentialParams& diffParams,
const OmniPvdObjectHandle oh, const MultiWheelDiffParams&, const FourWheelDiffParams& ah,
OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeTankDiffParams
(const PxVehicleTankDriveDifferentialParams&,
const OmniPvdObjectHandle, const MultiWheelDiffParams&, const TankDiffParams&,
OmniPvdWriter&, OmniPvdContextHandle);
void writeClutchResponseState
(const PxVehicleClutchCommandResponseState& clutchResponseState,
const OmniPvdObjectHandle oh, const ClutchResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeThrottleResponseState
(const PxVehicleEngineDriveThrottleCommandResponseState& throttleResponseState,
const OmniPvdObjectHandle oh, const ThrottleResponseState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeEngineState
(const PxVehicleEngineState& engineState,
const OmniPvdObjectHandle oh, const EngineState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeGearboxState
(const PxVehicleGearboxState& gearboxState,
const OmniPvdObjectHandle oh, const GearboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeAutoboxState
(const PxVehicleAutoboxState& gearboxState,
const OmniPvdObjectHandle oh, const AutoboxState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeDiffState
(const PxVehicleDifferentialState& diffState,
const OmniPvdObjectHandle oh, const DiffState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writeClutchSlipState
(const PxVehicleClutchSlipState& clutchSlipState,
const OmniPvdObjectHandle oh, const ClutchSlipState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
///////////////////////////////
//WHEEL ATTACHMENT PHYSX INTEGRATION
///////////////////////////////
struct PhysXSuspensionLimitConstraintParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle restitutionAH;
OmniPvdAttributeHandle directionForSuspensionLimitConstraintAH;
};
struct PhysXWheelShape
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle shapePtrAH;
};
struct PhysXRoadGeomState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle hitActorPtrAH;
OmniPvdAttributeHandle hitShapePtrAH;
OmniPvdAttributeHandle hitMaterialPtrAH;
OmniPvdAttributeHandle hitPositionAH;
};
struct PhysXConstraintState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle tireLongActiveStatusAH;
OmniPvdAttributeHandle tireLongLinearAH;
OmniPvdAttributeHandle tireLongAngularAH;
OmniPvdAttributeHandle tireLongDampingAH;
OmniPvdAttributeHandle tireLatActiveStatusAH;
OmniPvdAttributeHandle tireLatLinearAH;
OmniPvdAttributeHandle tireLatAngularAH;
OmniPvdAttributeHandle tireLatDampingAH;
OmniPvdAttributeHandle suspActiveStatusAH;
OmniPvdAttributeHandle suspLinearAH;
OmniPvdAttributeHandle suspAngularAH;
OmniPvdAttributeHandle suspGeometricErrorAH;
OmniPvdAttributeHandle suspRestitutionAH;
};
struct PhysXWheelAttachment
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle physxWeelShapeAH;
OmniPvdAttributeHandle physxConstraintParamsAH;
OmniPvdAttributeHandle physxRoadGeometryStateAH;
OmniPvdAttributeHandle physxConstraintStateAH;
OmniPvdAttributeHandle physxMaterialFrictionSetAH;
};
struct PhysXMaterialFriction
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle frictionAH;
OmniPvdAttributeHandle materialPtrAH;
};
PhysXSuspensionLimitConstraintParams registerSuspLimitConstraintParams(OmniPvdWriter& omniWriter);
PhysXWheelShape registerPhysXWheelShape(OmniPvdWriter& omniWriter);
PhysXRoadGeomState registerPhysXRoadGeomState(OmniPvdWriter& omniWriter);
PhysXConstraintState registerPhysXConstraintState(OmniPvdWriter& omniWriter);
PhysXWheelAttachment registerPhysXWheelAttachment(OmniPvdWriter& omniWriter);
PhysXMaterialFriction registerPhysXMaterialFriction(OmniPvdWriter& omniWriter);
void writePhysXSuspLimitConstraintParams
(const PxVehiclePhysXSuspensionLimitConstraintParams& params,
const OmniPvdObjectHandle oh, const PhysXSuspensionLimitConstraintParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXWheelShape
(const PxShape* wheelShape,
const OmniPvdObjectHandle oh, const PhysXWheelShape& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXRoadGeomState
(const PxVehiclePhysXRoadGeometryQueryState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXRoadGeomState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXConstraintState
(const PxVehiclePhysXConstraintState& roadGeomState,
const OmniPvdObjectHandle oh, const PhysXConstraintState& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXMaterialFriction
(const PxVehiclePhysXMaterialFriction& materialFriction,
const OmniPvdObjectHandle oh, const PhysXMaterialFriction& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
//////////////////////////////
//PHYSX RIGID ACTOR
//////////////////////////////
struct PhysXRoadGeometryQueryFilterData
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle word0AH;
OmniPvdAttributeHandle word1AH;
OmniPvdAttributeHandle word2AH;
OmniPvdAttributeHandle word3AH;
OmniPvdAttributeHandle flagsAH;
};
struct PhysXRoadGeometryQueryParams
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle queryTypeAH;
PhysXRoadGeometryQueryFilterData filterDataParams;
OmniPvdAttributeHandle defaultFilterDataAH;
OmniPvdAttributeHandle filterDataSetAH;
};
struct PhysXRigidActor
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rigidActorAH;
};
struct PhysXSteerState
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle previousSteerCommandAH;
};
PhysXRoadGeometryQueryParams registerPhysXRoadGeometryQueryParams(OmniPvdWriter& omniWriter);
PhysXRigidActor registerPhysXRigidActor(OmniPvdWriter& omniWriter);
PhysXSteerState registerPhysXSteerState(OmniPvdWriter& omniWriter);
void writePhysXRigidActor
(const PxRigidActor* actor,
const OmniPvdObjectHandle oh, const PhysXRigidActor& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXRoadGeometryQueryFilterData
(const PxQueryFilterData&,
const OmniPvdObjectHandle, const PhysXRoadGeometryQueryFilterData&, OmniPvdWriter&, OmniPvdContextHandle);
void writePhysXRoadGeometryQueryParams
(const PxVehiclePhysXRoadGeometryQueryParams&, const PxVehicleAxleDescription& axleDesc,
const OmniPvdObjectHandle queryParamsOH, const OmniPvdObjectHandle defaultFilterDataOH, const OmniPvdObjectHandle* filterDataOHs,
const PhysXRoadGeometryQueryParams& ah, OmniPvdWriter& omniWriter, OmniPvdContextHandle ch);
void writePhysXSteerState
(const PxVehiclePhysXSteerState&,
const OmniPvdObjectHandle, const PhysXSteerState&, OmniPvdWriter&, OmniPvdContextHandle);
//////////////////////////////
//VEHICLE
//////////////////////////////
struct Vehicle
{
OmniPvdClassHandle CH;
OmniPvdAttributeHandle rigidBodyParamsAH;
OmniPvdAttributeHandle rigidBodyStateAH;
OmniPvdAttributeHandle suspStateCalcParamsAH;
OmniPvdAttributeHandle brakeResponseParamsSetAH;
OmniPvdAttributeHandle steerResponseParamsAH;
OmniPvdAttributeHandle brakeResponseStatesAH;
OmniPvdAttributeHandle steerResponseStatesAH;
OmniPvdAttributeHandle ackermannParamsAH;
OmniPvdAttributeHandle wheelAttachmentSetAH;
OmniPvdAttributeHandle antiRollSetAH;
OmniPvdAttributeHandle antiRollForceAH;
OmniPvdAttributeHandle directDrivetrainAH;
OmniPvdAttributeHandle engineDriveTrainAH;
OmniPvdAttributeHandle physxWheelAttachmentSetAH;
OmniPvdAttributeHandle physxRoadGeometryQueryParamsAH;
OmniPvdAttributeHandle physxRigidActorAH;
OmniPvdAttributeHandle physxSteerStateAH;
};
Vehicle registerVehicle(OmniPvdWriter& omniWriter);
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
#endif //PX_SUPPORT_OMNI_PVD
/** @} */
| 35,223 | C | 32.901829 | 131 | 0.845385 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/pvd/VhPvdHelpers.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 "vehicle2/pvd/PxVehiclePvdHelpers.h"
#include "foundation/PxAllocatorCallback.h"
#include "VhPvdAttributeHandles.h"
#include "VhPvdObjectHandles.h"
namespace physx
{
namespace vehicle2
{
#if PX_SUPPORT_OMNI_PVD
///////////////////////////////
//ATTRIBUTE REGISTRATION
///////////////////////////////
PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter)
{
PxVehiclePvdAttributeHandles* attributeHandles =
reinterpret_cast<PxVehiclePvdAttributeHandles*>(
allocator.allocate(sizeof(PxVehiclePvdAttributeHandles), "PxVehiclePvdAttributeHandles", PX_FL));
PxMemZero(attributeHandles, sizeof(PxVehiclePvdAttributeHandles));
//Rigid body
attributeHandles->rigidBodyParams = registerRigidBodyParams(omniWriter);
attributeHandles->rigidBodyState = registerRigidBodyState(omniWriter);
//Susp state calc params.
attributeHandles->suspStateCalcParams = registerSuspStateCalcParams(omniWriter);
//Controls
attributeHandles->steerCommandResponseParams = registerSteerResponseParams(omniWriter);
attributeHandles->brakeCommandResponseParams = registerBrakeResponseParams(omniWriter);
attributeHandles->steerCommandResponseStates = registerSteerResponseStates(omniWriter);
attributeHandles->brakeCommandResponseStates = registerBrakeResponseStates(omniWriter);
attributeHandles->ackermannParams = registerAckermannParams(omniWriter);
//Wheel attachment
attributeHandles->wheelParams = registerWheelParams(omniWriter);
attributeHandles->wheelActuationState = registerWheelActuationState(omniWriter);
attributeHandles->wheelRigidBody1dState = registerWheelRigidBody1dState(omniWriter);
attributeHandles->wheelLocalPoseState = registerWheelLocalPoseState(omniWriter);
attributeHandles->roadGeomState = registerRoadGeomState(omniWriter);
attributeHandles->suspParams = registerSuspParams(omniWriter);
attributeHandles->suspCompParams = registerSuspComplianceParams(omniWriter);
attributeHandles->suspForceParams = registerSuspForceParams(omniWriter);
attributeHandles->suspState = registerSuspState(omniWriter);
attributeHandles->suspCompState = registerSuspComplianceState(omniWriter);
attributeHandles->suspForce = registerSuspForce(omniWriter);
attributeHandles->tireParams = registerTireParams(omniWriter);
attributeHandles->tireDirectionState = registerTireDirectionState(omniWriter);
attributeHandles->tireSpeedState = registerTireSpeedState(omniWriter);
attributeHandles->tireSlipState = registerTireSlipState(omniWriter);
attributeHandles->tireStickyState = registerTireStickyState(omniWriter);
attributeHandles->tireGripState = registerTireGripState(omniWriter);
attributeHandles->tireCamberState = registerTireCamberState(omniWriter);
attributeHandles->tireForce = registerTireForce(omniWriter);
attributeHandles->wheelAttachment = registerWheelAttachment(omniWriter);
//Antiroll
attributeHandles->antiRollParams = registerAntiRollParams(omniWriter);
attributeHandles->antiRollForce = registerAntiRollForce(omniWriter);
//Direct drivetrain
attributeHandles->directDriveThrottleCommandResponseParams = registerDirectDriveThrottleResponseParams(omniWriter);
attributeHandles->directDriveCommandState = registerDirectDriveCommandState(omniWriter);
attributeHandles->directDriveTransmissionCommandState = registerDirectDriveTransmissionCommandState(omniWriter);
attributeHandles->directDriveThrottleCommandResponseState = registerDirectDriveThrottleResponseState(omniWriter);
attributeHandles->directDrivetrain = registerDirectDrivetrain(omniWriter);
//Engine drivetrain
attributeHandles->engineDriveCommandState = registerEngineDriveCommandState(omniWriter);
attributeHandles->engineDriveTransmissionCommandState = registerEngineDriveTransmissionCommandState(omniWriter);
attributeHandles->tankDriveTransmissionCommandState = registerTankDriveTransmissionCommandState(omniWriter,
attributeHandles->engineDriveTransmissionCommandState.CH);
attributeHandles->clutchCommandResponseParams = registerClutchResponseParams(omniWriter);
attributeHandles->clutchParams = registerClutchParams(omniWriter);
attributeHandles->engineParams = registerEngineParams(omniWriter);
attributeHandles->gearboxParams = registerGearboxParams(omniWriter);
attributeHandles->autoboxParams = registerAutoboxParams(omniWriter);
attributeHandles->multiwheelDiffParams = registerMultiWheelDiffParams(omniWriter);
attributeHandles->fourwheelDiffParams = registerFourWheelDiffParams(omniWriter, attributeHandles->multiwheelDiffParams.CH);
attributeHandles->tankDiffParams = registerTankDiffParams(omniWriter, attributeHandles->multiwheelDiffParams.CH);
attributeHandles->clutchResponseState = registerClutchResponseState(omniWriter);
attributeHandles->throttleResponseState = registerThrottleResponseState(omniWriter);
attributeHandles->engineState = registerEngineState(omniWriter);
attributeHandles->gearboxState = registerGearboxState(omniWriter);
attributeHandles->autoboxState = registerAutoboxState(omniWriter);
attributeHandles->diffState = registerDiffState(omniWriter);
attributeHandles->clutchSlipState = registerClutchSlipState(omniWriter);
attributeHandles->engineDrivetrain = registerEngineDrivetrain(omniWriter);
//Physx wheel attachment
attributeHandles->physxSuspLimitConstraintParams = registerSuspLimitConstraintParams(omniWriter);
attributeHandles->physxWheelShape = registerPhysXWheelShape(omniWriter);
attributeHandles->physxRoadGeomState = registerPhysXRoadGeomState(omniWriter);
attributeHandles->physxConstraintState = registerPhysXConstraintState(omniWriter);
attributeHandles->physxWheelAttachment = registerPhysXWheelAttachment(omniWriter);
attributeHandles->physxMaterialFriction = registerPhysXMaterialFriction(omniWriter);
//Physx rigid actor
attributeHandles->physxRoadGeometryQueryParams = registerPhysXRoadGeometryQueryParams(omniWriter);
attributeHandles->physxRigidActor = registerPhysXRigidActor(omniWriter);
attributeHandles->physxSteerState = registerPhysXSteerState(omniWriter);
//Vehicle
attributeHandles->vehicle = registerVehicle(omniWriter);
return attributeHandles;
}
///////////////////////////////
//ATTRIBUTE DESTRUCTION
///////////////////////////////
void PxVehiclePvdAttributesRelease(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles)
{
allocator.deallocate(&attributeHandles);
}
////////////////////////////////////////
//OBJECT REGISTRATION
////////////////////////////////////////
PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate
(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysXMaterialFrictions,
const OmniPvdContextHandle contextHandle,
PxAllocatorCallback& allocator)
{
const PxU32 byteSize =
sizeof(PxVehiclePvdObjectHandles) +
sizeof(OmniPvdObjectHandle)*nbWheels*(
1 + //OmniPvdObjectHandle* wheelAttachmentOHs;
1 + //OmniPvdObjectHandle* wheelParamsOHs;
1 + //OmniPvdObjectHandle* wheelActuationStateOHs;
1 + //OmniPvdObjectHandle* wheelRigidBody1dStateOHs;
1 + //OmniPvdObjectHandle* wheelLocalPoseStateOHs;
1 + //OmniPvdObjectHandle* roadGeomStateOHs;
1 + //OmniPvdObjectHandle* suspParamsOHs;
1 + //OmniPvdObjectHandle* suspCompParamsOHs;
1 + //OmniPvdObjectHandle* suspForceParamsOHs;
1 + //OmniPvdObjectHandle* suspStateOHs;
1 + //OmniPvdObjectHandle* suspCompStateOHs;
1 + //OmniPvdObjectHandle* suspForceOHs;
1 + //OmniPvdObjectHandle* tireParamsOHs;
1 + //OmniPvdObjectHandle* tireDirectionStateOHs;
1 + //OmniPvdObjectHandle* tireSpeedStateOHs;
1 + //OmniPvdObjectHandle* tireSlipStateOHs;
1 + //OmniPvdObjectHandle* tireStickyStateOHs;
1 + //OmniPvdObjectHandle* tireGripStateOHs;
1 + //OmniPvdObjectHandle* tireCamberStateOHs;
1 + //OmniPvdObjectHandle* tireForceOHs;
1 + //OmniPvdObjectHandle* physxWheelAttachmentOHs;
1 + //OmniPvdObjectHandle* physxWheelShapeOHs;
1 + //OmniPvdObjectHandle* physxConstraintParamOHs;
1 + //OmniPvdObjectHandle* physxConstraintStateOHs;
1 + //OmniPvdObjectHandle* physxRoadGeomStateOHs;
1 + //OmniPvdObjectHandle* physxMaterialFrictionSetOHs;
maxNbPhysXMaterialFrictions + //OmniPvdObjectHandle* physxMaterialFrictionOHs;
1) + //OmniPvdObjectHandle* physxRoadGeomQueryFilterDataOHs;
sizeof(OmniPvdObjectHandle)*nbAntirolls*(
1); //OmniPvdObjectHandle* antiRollParamOHs
PxU8* buffer = reinterpret_cast<PxU8*>(allocator.allocate(byteSize, "PxVehiclePvdObjectHandles", PX_FL));
#if PX_ENABLE_ASSERTS
PxU8* start = buffer;
#endif
PxMemZero(buffer, byteSize);
PxVehiclePvdObjectHandles* objectHandles = reinterpret_cast<PxVehiclePvdObjectHandles*>(buffer);
buffer += sizeof(PxVehiclePvdObjectHandles);
if(nbWheels != 0)
{
objectHandles->wheelAttachmentOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelActuationStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelRigidBody1dStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->wheelLocalPoseStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->roadGeomStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspCompParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspForceParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspCompStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->suspForceOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireParamsOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireDirectionStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireSpeedStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireSlipStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireStickyStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireGripStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireCamberStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->tireForceOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxWheelAttachmentOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxConstraintParamOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxWheelShapeOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxConstraintStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxRoadGeomStateOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
if(maxNbPhysXMaterialFrictions != 0)
{
objectHandles->physxMaterialFrictionSetOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
objectHandles->physxMaterialFrictionOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels*maxNbPhysXMaterialFrictions;
}
objectHandles->physxRoadGeomQueryFilterDataOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbWheels;
}
if(nbAntirolls != 0)
{
objectHandles->antiRollParamOHs = reinterpret_cast<OmniPvdObjectHandle*>(buffer);
buffer += sizeof(OmniPvdObjectHandle)*nbAntirolls;
}
objectHandles->nbWheels = nbWheels;
objectHandles->nbPhysXMaterialFrictions = maxNbPhysXMaterialFrictions;
objectHandles->nbAntirolls = nbAntirolls;
objectHandles->contextHandle = contextHandle;
PX_ASSERT((start + byteSize) == buffer);
return objectHandles;
}
////////////////////////////////////
//OBJECT DESTRUCTION
////////////////////////////////////
PX_FORCE_INLINE void destroyObject
(OmniPvdWriter& omniWriter, OmniPvdContextHandle ch,
OmniPvdObjectHandle oh)
{
// note: "0" needs to be replaced with a marker for invalid object handle as soon as PVD
// provides it (and PxVehiclePvdObjectCreate needs to initialize accordingly or
// compile time assert that the value is 0 for now)
if(oh != 0)
omniWriter.destroyObject(ch, oh);
}
void PxVehiclePvdObjectRelease
(OmniPvdWriter& ow, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& oh)
{
const OmniPvdContextHandle ch = oh.contextHandle;
//rigid body
destroyObject(ow, ch, oh.rigidBodyParamsOH);
destroyObject(ow, ch, oh.rigidBodyStateOH);
//susp state calc params
destroyObject(ow, ch, oh.suspStateCalcParamsOH);
//controls
for(PxU32 i = 0; i < 2; i++)
{
destroyObject(ow, ch, oh.brakeResponseParamOHs[i]);
}
destroyObject(ow, ch, oh.steerResponseParamsOH);
destroyObject(ow, ch, oh.brakeResponseStateOH);
destroyObject(ow, ch, oh.steerResponseStateOH);
destroyObject(ow, ch, oh.ackermannParamsOH);
//Wheel attachments
for(PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.wheelParamsOHs[i]);
destroyObject(ow, ch, oh.wheelActuationStateOHs[i]);
destroyObject(ow, ch, oh.wheelRigidBody1dStateOHs[i]);
destroyObject(ow, ch, oh.wheelLocalPoseStateOHs[i]);
destroyObject(ow, ch, oh.suspParamsOHs[i]);
destroyObject(ow, ch, oh.suspCompParamsOHs[i]);
destroyObject(ow, ch, oh.suspForceParamsOHs[i]);
destroyObject(ow, ch, oh.suspStateOHs[i]);
destroyObject(ow, ch, oh.suspCompStateOHs[i]);
destroyObject(ow, ch, oh.suspForceOHs[i]);
destroyObject(ow, ch, oh.tireParamsOHs[i]);
destroyObject(ow, ch, oh.tireDirectionStateOHs[i]);
destroyObject(ow, ch, oh.tireSpeedStateOHs[i]);
destroyObject(ow, ch, oh.tireSlipStateOHs[i]);
destroyObject(ow, ch, oh.tireStickyStateOHs[i]);
destroyObject(ow, ch, oh.tireGripStateOHs[i]);
destroyObject(ow, ch, oh.tireCamberStateOHs[i]);
destroyObject(ow, ch, oh.tireForceOHs[i]);
destroyObject(ow, ch, oh.wheelAttachmentOHs[i]);
}
//Antiroll
for(PxU32 i = 0; i < oh.nbAntirolls; i++)
{
destroyObject(ow, ch, oh.antiRollParamOHs[i]);
}
destroyObject(ow, ch, oh.antiRollTorqueOH);
//direct drive
destroyObject(ow, ch, oh.directDriveCommandStateOH);
destroyObject(ow, ch, oh.directDriveTransmissionCommandStateOH);
destroyObject(ow, ch, oh.directDriveThrottleResponseParamsOH);
destroyObject(ow, ch, oh.directDriveThrottleResponseStateOH);
destroyObject(ow, ch, oh.directDrivetrainOH);
//engine drive
destroyObject(ow, ch, oh.engineDriveCommandStateOH);
destroyObject(ow, ch, oh.engineDriveTransmissionCommandStateOH);
destroyObject(ow, ch, oh.clutchResponseParamsOH);
destroyObject(ow, ch, oh.clutchParamsOH);
destroyObject(ow, ch, oh.engineParamsOH);
destroyObject(ow, ch, oh.gearboxParamsOH);
destroyObject(ow, ch, oh.autoboxParamsOH);
destroyObject(ow, ch, oh.differentialParamsOH);
destroyObject(ow, ch, oh.clutchResponseStateOH);
destroyObject(ow, ch, oh.engineDriveThrottleResponseStateOH);
destroyObject(ow, ch, oh.engineStateOH);
destroyObject(ow, ch, oh.gearboxStateOH);
destroyObject(ow, ch, oh.autoboxStateOH);
destroyObject(ow, ch, oh.diffStateOH);
destroyObject(ow, ch, oh.clutchSlipStateOH);
destroyObject(ow, ch, oh.engineDrivetrainOH);
//PhysX Wheel attachments
for(PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.physxConstraintParamOHs[i]);
destroyObject(ow, ch, oh.physxWheelShapeOHs[i]);
destroyObject(ow, ch, oh.physxRoadGeomStateOHs[i]);
destroyObject(ow, ch, oh.physxConstraintStateOHs[i]);
for(PxU32 j = 0; j < oh.nbPhysXMaterialFrictions; j++)
{
const PxU32 id = i*oh.nbPhysXMaterialFrictions + j;
destroyObject(ow, ch, oh.physxMaterialFrictionOHs[id]);
}
destroyObject(ow, ch, oh.physxWheelAttachmentOHs[i]);
}
//Physx rigid actor
destroyObject(ow, ch, oh.physxRoadGeomQueryParamOH);
destroyObject(ow, ch, oh.physxRoadGeomQueryDefaultFilterDataOH);
for (PxU32 i = 0; i < oh.nbWheels; i++)
{
destroyObject(ow, ch, oh.physxRoadGeomQueryFilterDataOHs[i]);
// safe even if not using per wheel filter data since it should hold the
// invalid handle value and thus destroyObject will do nothing
}
destroyObject(ow, ch, oh.physxRigidActorOH);
destroyObject(ow, ch, oh.physxSteerStateOH);
//Free the memory.
allocator.deallocate(&oh);
}
#else //#if PX_SUPPORT_OMNI_PVD
PxVehiclePvdAttributeHandles* PxVehiclePvdAttributesCreate(PxAllocatorCallback& allocator, OmniPvdWriter& omniWriter)
{
PX_UNUSED(allocator);
PX_UNUSED(omniWriter);
return NULL;
}
void PxVehiclePvdAttributesRelease(PxAllocatorCallback& allocator, PxVehiclePvdAttributeHandles& attributeHandles)
{
PX_UNUSED(allocator);
PX_UNUSED(attributeHandles);
}
PxVehiclePvdObjectHandles* PxVehiclePvdObjectCreate
(const PxU32 nbWheels, const PxU32 nbAntirolls, const PxU32 maxNbPhysXMaterialFrictions,
const PxU64 contextHandle,
PxAllocatorCallback& allocator)
{
PX_UNUSED(nbWheels);
PX_UNUSED(nbAntirolls);
PX_UNUSED(maxNbPhysXMaterialFrictions);
PX_UNUSED(contextHandle);
PX_UNUSED(allocator);
return NULL;
}
void PxVehiclePvdObjectRelease
(OmniPvdWriter& ow, PxAllocatorCallback& allocator, PxVehiclePvdObjectHandles& oh)
{
PX_UNUSED(ow);
PX_UNUSED(allocator);
PX_UNUSED(oh);
}
#endif //#if PX_SUPPORT_OMNI_PVD
} // namespace vehicle2
} // namespace physx
/** @} */
| 20,482 | C++ | 44.619154 | 124 | 0.784103 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/steering/VhSteeringFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/steering/PxVehicleSteeringParams.h"
namespace physx
{
namespace vehicle2
{
void PxVehicleSteerCommandResponseUpdate
(const PxReal steer, const PxReal longitudinalSpeed,
const PxU32 wheelId, const PxVehicleSteerCommandResponseParams& responseParams,
PxReal& steerResponse)
{
PxReal sign = PxSign(steer);
steerResponse = sign * PxVehicleNonLinearResponseCompute(PxAbs(steer), longitudinalSpeed, wheelId, responseParams);
}
void PxVehicleAckermannSteerUpdate
(const PxReal steer,
const PxVehicleSteerCommandResponseParams& steerResponseParams, const PxVehicleSizedArrayData<const PxVehicleAckermannParams>& ackermannParams,
PxVehicleArrayData<PxReal>& steerResponseStates)
{
for (PxU32 i = 0; i < ackermannParams.size; i++)
{
const PxVehicleAckermannParams& ackParams = ackermannParams[i];
if (ackParams.strength > 0.0f)
{
//Axle yaw is the average of the two wheels.
const PxF32 axleYaw =
(PxVehicleLinearResponseCompute(steer, ackParams.wheelIds[0], steerResponseParams) +
PxVehicleLinearResponseCompute(steer, ackParams.wheelIds[1], steerResponseParams))*0.5f;
if (axleYaw != 0.0f)
{
//Work out the ackermann steer for +ve steer then swap and negate the steer angles if the steer is -ve.
//Uncorrected yaw angle.
//One of the wheels will adopt this angle.
//The other will be corrected.
const PxF32 posWheelYaw = PxAbs(axleYaw);
//Work out the yaw of the other wheel.
PxF32 negWheelCorrectedYaw;
{
const PxF32 dz = ackParams.wheelBase;
const PxF32 dx = ackParams.trackWidth + ackParams.wheelBase / PxTan(posWheelYaw);
const PxF32 negWheelPerfectYaw = PxAtan(dz / dx);
negWheelCorrectedYaw = posWheelYaw + ackParams.strength*(negWheelPerfectYaw - posWheelYaw);
}
//Now assign axleYaw and negWheelCorrectedYaw to the correct wheels with the correct signs.
const PxF32 negWheelFinalYaw = intrinsics::fsel(axleYaw, negWheelCorrectedYaw, -posWheelYaw);
const PxF32 posWheelFinalYaw = intrinsics::fsel(axleYaw, posWheelYaw, -negWheelCorrectedYaw);
//Apply the per axle distributions to each wheel on the axle that is affected by this Ackermann correction.
steerResponseStates[ackParams.wheelIds[0]] = negWheelFinalYaw;
steerResponseStates[ackParams.wheelIds[1]] = posWheelFinalYaw;
}
}
}
}
} //namespace vehicle2
} //namespace physx
| 4,232 | C++ | 42.639175 | 144 | 0.766068 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/commands/VhCommandHelpers.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 "vehicle2/commands/PxVehicleCommandParams.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
namespace physx
{
namespace vehicle2
{
static float interpolate(const PxReal* speedVals, const PxReal* responseVals, const PxU16 nb, const PxReal speed)
{
if (1 == nb)
{
return responseVals[0];
}
else
{
const PxReal smallestSpeed = speedVals[0];
const PxReal largestSpeed = speedVals[nb - 1];
if (smallestSpeed >= speed)
{
return responseVals[0];
}
else if (largestSpeed <= speed)
{
return responseVals[nb - 1];
}
else
{
PxU16 speedId = 0;
while ((speedVals[speedId] < speed) && (speedId < nb))
speedId++;
// Make sure that we stay in range.
PxU16 speedLowerId = speedId - 1;
PxU16 speeddUpperId = speedId;
if (nb == speedId)
speeddUpperId = nb - 1;
if (0 == speedId)
speedLowerId = 0;
return responseVals[speedLowerId] + (speed - speedVals[speedLowerId]) * (responseVals[speeddUpperId] - responseVals[speedLowerId]) / (speedVals[speeddUpperId] - speedVals[speedLowerId]);
}
}
}
PxReal PxVehicleNonLinearResponseCompute
(const PxReal commandValue, const PxReal speed, const PxU32 wheelId, const PxVehicleCommandResponseParams& responseParams)
{
const PxU16 nbResponsesAtSpeeds = responseParams.nonlinearResponse.nbSpeedResponses;
if (0 == nbResponsesAtSpeeds)
{
//Empty response table.
//Use linear interpolation.
return PxVehicleLinearResponseCompute(commandValue, wheelId, responseParams);
}
const PxReal* commandValues = responseParams.nonlinearResponse.commandValues;
const PxU16* speedResponsesPerCommandValue = responseParams.nonlinearResponse.speedResponsesPerCommandValue;
const PxU16* nbSpeedResponsesPerCommandValue = responseParams.nonlinearResponse.nbSpeedResponsesPerCommandValue;
const PxU16 nbCommandValues = responseParams.nonlinearResponse.nbCommandValues;
const PxReal* speedResponses = responseParams.nonlinearResponse.speedResponses;
PxReal normalisedResponse = 0.0f;
if ((1 == nbCommandValues) || (commandValues[0] >= commandValue))
{
//Input command value less than the smallest value in the response table or
//there is just a single command value in the response table.
//No need to interpolate response of two command values.
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[0];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[0];
const PxU16 nb = nbSpeedResponsesPerCommandValue[0];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
else if (commandValues[nbCommandValues - 1] <= commandValue)
{
//Input command value greater than the largest value in the response table.
//No need to interpolate response of two command values.
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[nbCommandValues - 1];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[nbCommandValues - 1];
const PxU16 nb = nbSpeedResponsesPerCommandValue[nbCommandValues - 1];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
else
{
// Find the id of the command value that is immediately above the input command
PxU16 commandId = 0;
while ((commandValues[commandId] < commandValue) && (commandId < nbCommandValues))
{
commandId++;
}
// Make sure that we stay in range.
PxU16 commandLowerId = commandId - 1;
PxU16 commandUpperId = commandId;
if (nbCommandValues == commandId)
commandUpperId = nbCommandValues - 1;
if (0 == commandId)
commandLowerId = 0;
if (commandUpperId != commandLowerId)
{
float zLower;
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandLowerId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandLowerId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandLowerId];
zLower = interpolate(speeds, responseValues, nb, speed);
}
float zUpper;
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandUpperId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandUpperId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandUpperId];
zUpper = interpolate(speeds, responseValues, nb, speed);
}
const PxReal commandUpper = commandValues[commandUpperId];
const PxReal commandLower = commandValues[commandLowerId];
normalisedResponse = zLower + (commandValue - commandLower) * (zUpper - zLower) / (commandUpper - commandLower);
}
else
{
const PxReal* speeds = speedResponses + 2*speedResponsesPerCommandValue[commandUpperId];
const PxReal* responseValues = speeds + nbSpeedResponsesPerCommandValue[commandUpperId];
const PxU16 nb = nbSpeedResponsesPerCommandValue[commandUpperId];
normalisedResponse = interpolate(speeds, responseValues, nb, speed);
}
}
return PxVehicleLinearResponseCompute(normalisedResponse, wheelId, responseParams);
}
} // namespace vehicle2
} // namespace physx
| 6,702 | C++ | 40.63354 | 189 | 0.760668 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxConstraints/VhPhysXConstraintFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintFunctions.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/suspension/PxVehicleSuspensionParams.h"
#include "vehicle2/suspension/PxVehicleSuspensionStates.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintParams.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE PxVec3 computeAngular
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& direction)
{
const PxVec3 cmOffset = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(suspComplianceState.tireForceAppPoint));
const PxVec3 angular = cmOffset.cross(direction);
// note: not normalized on purpose. The angular component should hold the raw cross product as that
// is needed for the type of constraint we want to set up (see vehicleConstraintSolverPrep).
return angular;
}
PX_FORCE_INLINE PxVec3 computeTireAngular
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleTireDirectionState& trDirState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVehicleTireDirectionModes::Enum direction)
{
return computeAngular(suspParams, suspComplianceState, rigidBodyState, trDirState.directions[direction]);
}
PX_FORCE_INLINE PxVec3 computeSuspAngular
(const PxVehicleSuspensionParams& suspParams,
const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState,
const PxVec3& direction)
{
return computeAngular(suspParams, suspComplianceState, rigidBodyState, direction);
}
void PxVehiclePhysXConstraintStatesUpdate
(const PxVehicleSuspensionParams& suspParams,
const PxVehiclePhysXSuspensionLimitConstraintParams& suspensionLimitParams,
const PxVehicleSuspensionState& suspState, const PxVehicleSuspensionComplianceState& suspComplianceState,
const PxVec3& groundPlaneNormal,
const PxReal tireStickyDampingLong, const PxReal tireStickyDampingLat,
const PxVehicleTireDirectionState& trDirState, const PxVehicleTireStickyState& trStickyState,
const PxVehicleRigidBodyState& rigidBodyState,
PxVehiclePhysXConstraintState& cnstrtState)
{
cnstrtState.setToDefault();
//Sticky tire longitudinal
{
const bool isActive = trStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL];
cnstrtState.tireActiveStatus[PxVehicleTireDirectionModes::eLONGITUDINAL] = isActive;
if (isActive)
{
cnstrtState.tireLinears[PxVehicleTireDirectionModes::eLONGITUDINAL] = trDirState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL];
cnstrtState.tireAngulars[PxVehicleTireDirectionModes::eLONGITUDINAL] = computeTireAngular(suspParams, suspComplianceState, trDirState, rigidBodyState, PxVehicleTireDirectionModes::eLONGITUDINAL);
cnstrtState.tireDamping[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireStickyDampingLong;
}
}
//Sticky tire lateral
{
const bool isActive = trStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL];
cnstrtState.tireActiveStatus[PxVehicleTireDirectionModes::eLATERAL] = isActive;
if (isActive)
{
cnstrtState.tireLinears[PxVehicleTireDirectionModes::eLATERAL] = trDirState.directions[PxVehicleTireDirectionModes::eLATERAL];
cnstrtState.tireAngulars[PxVehicleTireDirectionModes::eLATERAL] = computeTireAngular(suspParams, suspComplianceState, trDirState, rigidBodyState, PxVehicleTireDirectionModes::eLATERAL);
cnstrtState.tireDamping[PxVehicleTireDirectionModes::eLATERAL] = tireStickyDampingLat;
}
}
//Suspension limit
{
if (suspState.separation >= 0.0f || PxVehiclePhysXSuspensionLimitConstraintParams::eNONE == suspensionLimitParams.directionForSuspensionLimitConstraint)
{
cnstrtState.suspActiveStatus = false;
}
else
{
// To maintain the wheel on the ground plane, the suspension is required to compress beyond the suspension compression limit
// or expand beyond maximum droop (for example, top of wheel being in collision with something).
// We manage the compression up to the limit with a suspension force.
// Everything beyond the limits is managed with an impulse applied to the rigid body via a constraint.
// The constraint attempts to resolve the geometric error declared in the separation state.
// We have two choices:
// 1) apply the impulse along the suspension dir (more like the effect of a bump stop spring)
// 2) apply the impulse along the ground normal (more like the effect of a real tire's contact wtih the ground).
if (PxVehiclePhysXSuspensionLimitConstraintParams::eROAD_GEOMETRY_NORMAL == suspensionLimitParams.directionForSuspensionLimitConstraint)
{
cnstrtState.suspActiveStatus = true;
cnstrtState.suspGeometricError = suspState.separation;
cnstrtState.suspLinear = groundPlaneNormal;
cnstrtState.suspAngular = computeSuspAngular(suspParams, suspComplianceState, rigidBodyState, groundPlaneNormal);
cnstrtState.restitution = suspensionLimitParams.restitution;
}
else
{
const PxVec3 suspDirWorldFrame = rigidBodyState.pose.rotate(suspParams.suspensionTravelDir);
const PxF32 projection = groundPlaneNormal.dot(suspDirWorldFrame);
if (projection != 0.0f)
{
cnstrtState.suspActiveStatus = true;
cnstrtState.suspGeometricError = suspState.separation;
const PxVec3 suspLinear = suspDirWorldFrame * PxSign(projection);
cnstrtState.suspLinear = suspLinear;
cnstrtState.suspAngular = computeSuspAngular(suspParams, suspComplianceState, rigidBodyState, suspLinear);
cnstrtState.restitution = suspensionLimitParams.restitution;
}
else
{
cnstrtState.suspActiveStatus = false;
}
}
}
}
}
} //namespace vehicle2
} //namespace physx
| 7,753 | C++ | 46.864197 | 199 | 0.804979 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxConstraints/VhPhysXConstraintHelpers.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/PxAllocator.h"
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintStates.h"
#include "vehicle2/physxConstraints/PxVehiclePhysXConstraintHelpers.h"
#include "vehicle2/physxActor/PxVehiclePhysXActorStates.h"
#include "PxConstraintDesc.h"
#include "PxConstraint.h"
#include "PxPhysics.h"
#include "PxRigidDynamic.h"
#include "PxArticulationLink.h"
namespace physx
{
namespace vehicle2
{
PxConstraintShaderTable gVehicleConstraintTable =
{
vehicleConstraintSolverPrep,
visualiseVehicleConstraint,
PxConstraintFlag::Enum(0)
};
void PxVehicleConstraintsCreate(
const PxVehicleAxleDescription& axleDescription,
PxPhysics& physics, PxRigidBody& physxActor,
PxVehiclePhysXConstraints& vehicleConstraints)
{
vehicleConstraints.setToDefault();
//Each PxConstraint has a limit of 12 1d constraints.
//Each wheel has longitudinal, lateral and suspension limit degrees of freedom.
//This sums up to 3 dofs per wheel and 12 dofs per 4 wheels.
//4 wheels therefore equals 1 PxConstraint
//Iterate over each block of 4 wheels and create a PxConstraints for each block of 4.
PxU32 constraintIndex = 0;
for(PxU32 i = 0; i < axleDescription.getNbWheels(); i+= PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT)
{
void* memory = PX_ALLOC(sizeof(PxVehicleConstraintConnector), PxVehicleConstraintConnector);
PxVehicleConstraintConnector* pxConnector = PX_PLACEMENT_NEW(memory, PxVehicleConstraintConnector)(vehicleConstraints.constraintStates + i);
PxConstraint* pxConstraint = physics.createConstraint(&physxActor, NULL, *pxConnector, gVehicleConstraintTable, sizeof(PxVehiclePhysXConstraintState)*PxVehiclePhysXConstraintLimits::eNB_WHEELS_PER_PXCONSTRAINT);
vehicleConstraints.constraints[constraintIndex] = pxConstraint;
vehicleConstraints.constraintConnectors[constraintIndex] = pxConnector;
constraintIndex++;
}
}
void PxVehicleConstraintsDirtyStateUpdate
(PxVehiclePhysXConstraints& vehicleConstraints)
{
for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE; i++)
{
if (vehicleConstraints.constraints[i])
{
vehicleConstraints.constraints[i]->markDirty();
}
}
}
void PxVehicleConstraintsDestroy(
PxVehiclePhysXConstraints& vehicleConstraints)
{
for (PxU32 i = 0; i < PxVehiclePhysXConstraintLimits::eNB_CONSTRAINTS_PER_VEHICLE; i++)
{
if (vehicleConstraints.constraints[i])
{
vehicleConstraints.constraints[i]->release();
vehicleConstraints.constraints[i] = NULL;
}
if (vehicleConstraints.constraintConnectors[i])
{
vehicleConstraints.constraintConnectors[i]->~PxVehicleConstraintConnector();
PX_FREE(vehicleConstraints.constraintConnectors[i]);
vehicleConstraints.constraintConnectors[i] = NULL;
}
}
}
} //namespace vehicle2
} //namespace physx
| 4,520 | C++ | 39.008849 | 213 | 0.786947 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxRoadGeometry/VhPhysXRoadGeometryHelpers.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryHelpers.h"
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxCooking.h"
#include "extensions/PxDefaultStreams.h"
#include "PxPhysics.h"
namespace physx
{
namespace vehicle2
{
PxConvexMesh* PxVehicleUnitCylinderSweepMeshCreate
(const PxVehicleFrame& runtimeFrame, PxPhysics& physics, const PxCookingParams& params)
{
const PxMat33 mat33 = runtimeFrame.getFrame();
const PxQuat frame(mat33);
const PxReal radius = 1.0f;
const PxReal halfWidth = 1.0f;
#define NB_CIRCUMFERENCE_POINTS 64
PxVec3 points[2 * NB_CIRCUMFERENCE_POINTS];
for (PxU32 i = 0; i < NB_CIRCUMFERENCE_POINTS; i++)
{
const PxF32 cosTheta = PxCos(i * PxPi * 2.0f / float(NB_CIRCUMFERENCE_POINTS));
const PxF32 sinTheta = PxSin(i * PxPi * 2.0f / float(NB_CIRCUMFERENCE_POINTS));
const PxF32 x = radius * cosTheta;
const PxF32 z = radius * sinTheta;
points[2 * i + 0] = frame.rotate(PxVec3(x, -halfWidth, z));
points[2 * i + 1] = frame.rotate(PxVec3(x, +halfWidth, z));
}
// Create descriptor for convex mesh
PxConvexMeshDesc convexDesc;
convexDesc.points.count = sizeof(points)/sizeof(PxVec3);
convexDesc.points.stride = sizeof(PxVec3);
convexDesc.points.data = points;
convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX;
PxConvexMesh* convexMesh = NULL;
PxDefaultMemoryOutputStream buf;
if (PxCookConvexMesh(params, convexDesc, buf))
{
PxDefaultMemoryInputData id(buf.getData(), buf.getSize());
convexMesh = physics.createConvexMesh(id);
}
return convexMesh;
}
void PxVehicleUnitCylinderSweepMeshDestroy(PxConvexMesh* mesh)
{
mesh->release();
}
} //namespace vehicle2
} //namespace physx
| 3,405 | C++ | 37.704545 | 87 | 0.758003 |
NVIDIA-Omniverse/PhysX/physx/source/physxvehicle2/src/physxRoadGeometry/VhPhysXRoadGeometryFunctions.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 "vehicle2/PxVehicleParams.h"
#include "vehicle2/roadGeometry/PxVehicleRoadGeometryState.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryFunctions.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryParams.h"
#include "vehicle2/physxRoadGeometry/PxVehiclePhysXRoadGeometryState.h"
#include "vehicle2/rigidBody/PxVehicleRigidBodyStates.h"
#include "vehicle2/suspension/PxVehicleSuspensionHelpers.h"
#include "extensions/PxRigidBodyExt.h"
#include "PxScene.h"
#include "PxShape.h"
#include "PxRigidActor.h"
#include "PxMaterial.h"
#include "geometry/PxMeshScale.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxGeometryQuery.h"
namespace physx
{
namespace vehicle2
{
PX_FORCE_INLINE PxF32 computeMaterialFriction(const PxShape* hitShape, const PxU32 hitFaceIndex,
const PxVehiclePhysXMaterialFrictionParams& materialFrictionParams, PxMaterial*& hitMaterial)
{
PxBaseMaterial* baseMaterial = hitShape->getMaterialFromInternalFaceIndex(hitFaceIndex);
PX_ASSERT(!baseMaterial || baseMaterial->getConcreteType()==PxConcreteType::eMATERIAL);
hitMaterial = static_cast<PxMaterial*>(baseMaterial);
PxReal hitFriction = materialFrictionParams.defaultFriction;
for(PxU32 i = 0; i < materialFrictionParams.nbMaterialFrictions; i++)
{
if(materialFrictionParams.materialFrictions[i].material == hitMaterial)
{
hitFriction = materialFrictionParams.materialFrictions[i].friction;
break;
}
}
return hitFriction;
}
PX_FORCE_INLINE PxVec3 computeVelocity(const PxRigidActor& actor, const PxVec3& hitPoint)
{
return actor.is<PxRigidBody>() ? PxRigidBodyExt::getVelocityAtPos(*actor.is<PxRigidBody>(), hitPoint) : PxVec3(PxZero);
}
template<typename THitBuffer>
PX_FORCE_INLINE void copyHitInfo(const THitBuffer& hitBuffer, PxMaterial* hitMaterial,
PxVehiclePhysXRoadGeometryQueryState& physxRoadGeometryState)
{
physxRoadGeometryState.actor = hitBuffer.actor;
physxRoadGeometryState.shape = hitBuffer.shape;
physxRoadGeometryState.material = hitMaterial;
physxRoadGeometryState.hitPosition = hitBuffer.position;
}
void PxVehiclePhysXRoadGeometryQueryUpdate
(const PxVehicleWheelParams& wheelParams, const PxVehicleSuspensionParams& suspParams,
const PxVehiclePhysXRoadGeometryQueryType::Enum queryType,
PxQueryFilterCallback* filterCallback, const PxQueryFilterData& filterData,
const PxVehiclePhysXMaterialFrictionParams& materialFrictionParams,
const PxF32 steerAngle, const PxVehicleRigidBodyState& rigidBodyState,
const PxScene& scene, const PxConvexMesh* unitCylinderSweepMesh,
const PxVehicleFrame& frame,
PxVehicleRoadGeometryState& roadGeomState,
PxVehiclePhysXRoadGeometryQueryState* physxRoadGeometryState)
{
if(PxVehiclePhysXRoadGeometryQueryType::eRAYCAST == queryType)
{
//Assume no hits until we know otherwise.
roadGeomState.setToDefault();
//Compute the start pos, dir and length of raycast.
PxVec3 v, w;
PxF32 dist;
PxVehicleComputeSuspensionRaycast(frame, wheelParams, suspParams, steerAngle, rigidBodyState.pose, v, w, dist);
//Perform the raycast.
PxRaycastBuffer buff;
scene.raycast(v, w, dist, buff, PxHitFlag::eDEFAULT, filterData, filterCallback);
//Process the raycast result.
if(buff.hasBlock && buff.block.distance != 0.0f)
{
const PxPlane hitPlane(v + w * buff.block.distance, buff.block.normal);
roadGeomState.plane = hitPlane;
roadGeomState.hitState = true;
PxMaterial* hitMaterial;
roadGeomState.friction = computeMaterialFriction(buff.block.shape, buff.block.faceIndex, materialFrictionParams,
hitMaterial);
roadGeomState.velocity = computeVelocity(*buff.block.actor, buff.block.position);
if (physxRoadGeometryState)
{
copyHitInfo(buff.block, hitMaterial, *physxRoadGeometryState);
}
}
else
{
if (physxRoadGeometryState)
physxRoadGeometryState->setToDefault();
}
}
else if(PxVehiclePhysXRoadGeometryQueryType::eSWEEP == queryType)
{
PX_ASSERT(unitCylinderSweepMesh);
//Assume no hits until we know otherwise.
roadGeomState.setToDefault();
//Compute the start pose, dir and length of sweep.
PxTransform T;
PxVec3 w;
PxF32 dist;
PxVehicleComputeSuspensionSweep(frame, suspParams, steerAngle, rigidBodyState.pose, T, w, dist);
//Scale the unit cylinder.
const PxVec3 scale = PxVehicleComputeTranslation(frame, wheelParams.radius, wheelParams.halfWidth, wheelParams.radius).abs();
const PxMeshScale meshScale(scale, PxQuat(PxIdentity));
const PxConvexMeshGeometry convMeshGeom(const_cast<PxConvexMesh*>(unitCylinderSweepMesh), meshScale);
//Perform the sweep.
PxSweepBuffer buff;
scene.sweep(convMeshGeom, T, w, dist, buff, PxHitFlag::eDEFAULT | PxHitFlag::eMTD, filterData, filterCallback);
//Process the sweep result.
if (buff.hasBlock && buff.block.distance >= 0.0f)
{
//Sweep started outside scene geometry.
const PxPlane hitPlane(buff.block.position, buff.block.normal);
roadGeomState.plane = hitPlane;
roadGeomState.hitState = true;
PxMaterial* hitMaterial;
roadGeomState.friction = computeMaterialFriction(buff.block.shape, buff.block.faceIndex, materialFrictionParams,
hitMaterial);
roadGeomState.velocity = computeVelocity(*buff.block.actor, buff.block.position);
if (physxRoadGeometryState)
{
copyHitInfo(buff.block, hitMaterial, *physxRoadGeometryState);
}
}
else if (buff.hasBlock && buff.block.distance < 0.0f)
{
//The sweep started inside scene geometry.
//We want to have another go but this time starting outside the hit geometry because this is the most reliable
//way to get a hit plane.
//-buff.block.distance is the distance we need to move along buff.block.normal to be outside the hit geometry.
//Note that buff.block.distance can be a vanishingly small number. Moving along the normal by a vanishingly
//small number might not push us out of overlap due to numeric precision of the overlap test.
//We want to move a numerically significant distance to guarantee that we change the overlap status
//at the start pose of the sweep.
//We achieve this by choosing a minimum translation that is numerically significant.
//Any number will do but we choose the wheel radius because this ought to be a numerically significant value.
//We're only sweeping against the hit shape and not against the scene
//so we don't risk hitting other stuff by moving a numerically significant distance.
const PxVec3 unitDir = -buff.block.normal;
const PxF32 maxDist = PxMax(wheelParams.radius, -buff.block.distance);
const PxGeometry& geom0 = convMeshGeom;
const PxTransform pose0(T.p + buff.block.normal*(maxDist*1.01f), T.q);
const PxGeometry& geom1 = buff.block.shape->getGeometry();
const PxTransform pose1 = buff.block.actor->getGlobalPose()*buff.block.shape->getLocalPose();
PxGeomSweepHit buff2;
const bool b2 = PxGeometryQuery::sweep(
unitDir, maxDist*1.02f,
geom0, pose0, geom1, pose1, buff2, PxHitFlag::eDEFAULT | PxHitFlag::eMTD);
if (b2 && buff2.distance > 0.0f)
{
//Sweep started outside scene geometry.
const PxPlane hitPlane(buff2.position, buff2.normal);
roadGeomState.plane = hitPlane;
roadGeomState.hitState = true;
PxMaterial* hitMaterial;
roadGeomState.friction = computeMaterialFriction(buff.block.shape, buff.block.faceIndex, materialFrictionParams,
hitMaterial);
roadGeomState.velocity = computeVelocity(*buff.block.actor, buff.block.position);
if (physxRoadGeometryState)
{
copyHitInfo(buff.block, hitMaterial, *physxRoadGeometryState);
}
}
else
{
if (physxRoadGeometryState)
physxRoadGeometryState->setToDefault();
}
}
else
{
if (physxRoadGeometryState)
physxRoadGeometryState->setToDefault();
}
}
}
} //namespace vehicle2
} //namespace physx
| 9,523 | C++ | 40.051724 | 127 | 0.770766 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCapsuleController.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 CCT_CAPSULE_CONTROLLER
#define CCT_CAPSULE_CONTROLLER
/* Exclude from documentation */
/** \cond */
#include "characterkinematic/PxCapsuleController.h"
#include "CctController.h"
namespace physx
{
class PxPhysics;
namespace Cct
{
class CapsuleController : public PxCapsuleController, public Controller
{
public:
CapsuleController(const PxControllerDesc& desc, PxPhysics& sdk, PxScene* scene);
virtual ~CapsuleController();
// Controller
virtual PxF32 getHalfHeightInternal() const PX_OVERRIDE { return mRadius+mHeight*0.5f; }
virtual bool getWorldBox(PxExtendedBounds3& box) const PX_OVERRIDE;
virtual PxController* getPxController() PX_OVERRIDE { return this; }
//~Controller
// PxController
virtual PxControllerShapeType::Enum getType() const PX_OVERRIDE { return mType; }
virtual void release() PX_OVERRIDE { releaseInternal(); }
virtual PxControllerCollisionFlags move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles) PX_OVERRIDE;
virtual bool setPosition(const PxExtendedVec3& position) PX_OVERRIDE { return setPos(position); }
virtual const PxExtendedVec3& getPosition() const PX_OVERRIDE { return mPosition; }
virtual bool setFootPosition(const PxExtendedVec3& position) PX_OVERRIDE;
virtual PxExtendedVec3 getFootPosition() const PX_OVERRIDE;
virtual PxRigidDynamic* getActor() const PX_OVERRIDE { return mKineActor; }
virtual void setStepOffset(const float offset) PX_OVERRIDE { if(offset>=0.0f)
mUserParams.mStepOffset = offset; }
virtual PxF32 getStepOffset() const PX_OVERRIDE { return mUserParams.mStepOffset; }
virtual void setNonWalkableMode(PxControllerNonWalkableMode::Enum flag) PX_OVERRIDE { mUserParams.mNonWalkableMode = flag; }
virtual PxControllerNonWalkableMode::Enum getNonWalkableMode() const PX_OVERRIDE { return mUserParams.mNonWalkableMode; }
virtual PxF32 getContactOffset() const PX_OVERRIDE { return mUserParams.mContactOffset; }
virtual void setContactOffset(PxF32 offset) PX_OVERRIDE { if(offset>0.0f)
mUserParams.mContactOffset = offset;}
virtual PxVec3 getUpDirection() const PX_OVERRIDE { return mUserParams.mUpDirection; }
virtual void setUpDirection(const PxVec3& up) PX_OVERRIDE { setUpDirectionInternal(up); }
virtual PxF32 getSlopeLimit() const PX_OVERRIDE { return mUserParams.mSlopeLimit; }
virtual void setSlopeLimit(PxF32 slopeLimit) PX_OVERRIDE { if(slopeLimit>0.0f)
mUserParams.mSlopeLimit = slopeLimit;}
virtual void invalidateCache() PX_OVERRIDE;
virtual PxScene* getScene() PX_OVERRIDE { return mScene; }
virtual void* getUserData() const PX_OVERRIDE { return mUserData; }
virtual void setUserData(void* userData) PX_OVERRIDE { mUserData = userData; }
virtual void getState(PxControllerState& state) const PX_OVERRIDE { return getInternalState(state); }
virtual void getStats(PxControllerStats& stats) const PX_OVERRIDE { return getInternalStats(stats); }
virtual void resize(PxReal height) PX_OVERRIDE;
//~PxController
// PxCapsuleController
virtual PxF32 getRadius() const PX_OVERRIDE { return mRadius; }
virtual PxF32 getHeight() const PX_OVERRIDE { return mHeight; }
virtual PxCapsuleClimbingMode::Enum getClimbingMode() const PX_OVERRIDE;
virtual bool setRadius(PxF32 radius) PX_OVERRIDE;
virtual bool setHeight(PxF32 height) PX_OVERRIDE;
virtual bool setClimbingMode(PxCapsuleClimbingMode::Enum) PX_OVERRIDE;
//~ PxCapsuleController
void getCapsule(PxExtendedCapsule& capsule) const;
PxF32 mRadius;
PxF32 mHeight;
PxCapsuleClimbingMode::Enum mClimbingMode;
};
} // namespace Cct
}
/** \endcond */
#endif
| 5,903 | C | 52.672727 | 182 | 0.704218 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctInternalStructs.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 CCT_INTERNAL_STRUCTS_H
#define CCT_INTERNAL_STRUCTS_H
#include "CctController.h"
namespace physx
{
class PxObstacle; // (*)
namespace Cct
{
class ObstacleContext;
enum UserObjectType
{
USER_OBJECT_CCT = 0,
USER_OBJECT_BOX_OBSTACLE = 1,
USER_OBJECT_CAPSULE_OBSTACLE = 2
};
PX_FORCE_INLINE PxU32 encodeUserObject(PxU32 index, UserObjectType type)
{
PX_ASSERT(index<=0xffff);
PX_ASSERT(PxU32(type)<=0xffff);
return (PxU16(index)<<16)|PxU32(type);
}
PX_FORCE_INLINE UserObjectType decodeType(PxU32 code)
{
return UserObjectType(code & 0xffff);
}
PX_FORCE_INLINE PxU32 decodeIndex(PxU32 code)
{
return code>>16;
}
struct PxInternalCBData_OnHit : InternalCBData_OnHit
{
Controller* controller;
const ObstacleContext* obstacles;
const PxObstacle* touchedObstacle;
PxObstacleHandle touchedObstacleHandle;
};
struct PxInternalCBData_FindTouchedGeom : InternalCBData_FindTouchedGeom
{
PxScene* scene;
PxRenderBuffer* renderBuffer; // Render buffer from controller manager, not the one from the scene
PxHashSet<PxShape*>* cctShapeHashSet;
};
}
}
#endif
| 2,824 | C | 32.235294 | 102 | 0.752833 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctController.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 CCT_CONTROLLER
#define CCT_CONTROLLER
/* Exclude from documentation */
/** \cond */
#include "CctCharacterController.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxMutex.h"
namespace physx
{
class PxPhysics;
class PxScene;
class PxRigidDynamic;
class PxGeometry;
class PxMaterial;
namespace Cct
{
class CharacterControllerManager;
class Controller : public PxUserAllocated
{
PX_NOCOPY(Controller)
public:
Controller(const PxControllerDesc& desc, PxScene* scene);
virtual ~Controller();
void releaseInternal();
void getInternalState(PxControllerState& state) const;
void getInternalStats(PxControllerStats& stats) const;
virtual PxF32 getHalfHeightInternal() const = 0;
virtual bool getWorldBox(PxExtendedBounds3& box) const = 0;
virtual PxController* getPxController() = 0;
void onOriginShift(const PxVec3& shift);
void onRelease(const PxBase& observed);
void setCctManager(CharacterControllerManager* cm)
{
mManager = cm;
mCctModule.setCctManager(cm);
}
PX_FORCE_INLINE CharacterControllerManager* getCctManager() { return mManager; }
PX_FORCE_INLINE PxU64 getContextId() const { return PxU64(mScene); }
PxControllerShapeType::Enum mType;
// User params
CCTParams mUserParams;
PxUserControllerHitReport* mReportCallback;
PxControllerBehaviorCallback* mBehaviorCallback;
void* mUserData;
// Internal data
SweepTest mCctModule; // Internal CCT object. Optim test for Ubi.
PxRigidDynamic* mKineActor; // Associated kinematic actor
PxExtendedVec3 mPosition; // Current position
PxVec3 mDeltaXP;
PxVec3 mOverlapRecover;
PxScene* mScene; // Handy scene owner
PxU32 mPreviousSceneTimestamp;
PxF64 mGlobalTime;
PxF64 mPreviousGlobalTime;
PxF32 mProxyDensity; // Density for proxy actor
PxF32 mProxyScaleCoeff; // Scale coeff for proxy actor
PxControllerCollisionFlags mCollisionFlags; // Last known collision flags (PxControllerCollisionFlag)
bool mCachedStandingOnMoving;
bool mRegisterDeletionListener;
mutable PxMutex mWriteLock; // Lock used for guarding touched pointers and cache data from overwriting
// during onRelease call.
protected:
// Internal methods
void setUpDirectionInternal(const PxVec3& up);
PxShape* getKineShape() const;
bool createProxyActor(PxPhysics& sdk, const PxGeometry& geometry, const PxMaterial& material, PxClientID clientID);
bool setPos(const PxExtendedVec3& pos);
void findTouchedObject(const PxControllerFilters& filters, const PxObstacleContext* obstacleContext, const PxVec3& upDirection);
bool rideOnTouchedObject(SweptVolume& volume, const PxVec3& upDirection, PxVec3& disp, const PxObstacleContext* obstacleContext);
PxControllerCollisionFlags move(SweptVolume& volume, const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles, bool constrainedClimbingMode);
bool filterTouchedShape(const PxControllerFilters& filters);
PX_FORCE_INLINE float computeTimeCoeff()
{
const float elapsedTime = float(mGlobalTime - mPreviousGlobalTime);
mPreviousGlobalTime = mGlobalTime;
return 1.0f / elapsedTime;
}
CharacterControllerManager* mManager; // Owner manager
};
} // namespace Cct
}
/** \endcond */
#endif
| 5,443 | C | 40.876923 | 215 | 0.708249 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCharacterController.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 "foundation/PxMathUtils.h"
#include "PxRigidDynamic.h"
#include "CctCharacterController.h"
#include "CctCharacterControllerManager.h"
#include "CctSweptBox.h"
#include "CctSweptCapsule.h"
#include "CctObstacleContext.h"
#include "GuIntersectionBoxBox.h"
#include "GuDistanceSegmentBox.h"
#include "foundation/PxFPU.h"
#include "CmVisualization.h"
#include "CmUtils.h"
// PT: TODO: remove those includes.... shouldn't be allowed from here
#include "characterkinematic/PxControllerObstacles.h" // (*)
#include "characterkinematic/PxControllerManager.h" // (*)
#include "characterkinematic/PxControllerBehavior.h" // (*)
#include "CctInternalStructs.h" // (*)
//#define DEBUG_MTD
#ifdef DEBUG_MTD
#include <stdio.h>
#endif
#define MAX_ITER 10
using namespace physx;
using namespace Cct;
using namespace Gu;
using namespace Cm;
static const PxU32 gObstacleDebugColor = PxU32(PxDebugColor::eARGB_CYAN);
//static const PxU32 gCCTBoxDebugColor = PxU32(PxDebugColor::eARGB_YELLOW);
static const PxU32 gTBVDebugColor = PxU32(PxDebugColor::eARGB_MAGENTA);
static const bool gUsePartialUpdates = true;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE PxHitFlags getSweepHitFlags(const CCTParams& params)
{
PxHitFlags sweepHitFlags = PxHitFlag::eDEFAULT/*|PxHitFlag::eMESH_BOTH_SIDES*/;
// sweepHitFlags |= PxHitFlag::eASSUME_NO_INITIAL_OVERLAP;
if(params.mPreciseSweeps)
sweepHitFlags |= PxHitFlag::ePRECISE_SWEEP;
return sweepHitFlags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool shouldApplyRecoveryModule(const PxRigidActor& rigidActor)
{
// PT: we must let the dynamic objects go through the CCT for proper 2-way interactions.
// But we should still apply the recovery module for kinematics.
const PxType type = rigidActor.getConcreteType();
if(type==PxConcreteType::eRIGID_STATIC)
return true;
if(type!=PxConcreteType::eRIGID_DYNAMIC)
return false;
return static_cast<const PxRigidBody&>(rigidActor).getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const bool gUseLocalSpace = true;
static PxVec3 worldToLocal(const PxObstacle& obstacle, const PxExtendedVec3& worldPos)
{
const PxTransform tr(toVec3(obstacle.mPos), obstacle.mRot);
return tr.transformInv(toVec3(worldPos));
}
static PxVec3 localToWorld(const PxObstacle& obstacle, const PxVec3& localPos)
{
const PxTransform tr(toVec3(obstacle.mPos), obstacle.mRot);
return tr.transform(localPos);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef PX_BIG_WORLDS
typedef PxExtendedBounds3 PxCCTBounds3;
typedef PxExtendedVec3 PxCCTVec3;
#else
typedef PxBounds3 PxCCTBounds3;
typedef PxVec3 PxCCTVec3;
#endif
static PX_INLINE void scale(PxCCTBounds3& b, const PxVec3& scale)
{
PxCCTVec3 center; getCenter(b, center);
PxVec3 extents; getExtents(b, extents);
extents.x *= scale.x;
extents.y *= scale.y;
extents.z *= scale.z;
setCenterExtents(b, center, extents);
}
static PX_INLINE void computeReflexionVector(PxVec3& reflected, const PxVec3& incomingDir, const PxVec3& outwardNormal)
{
reflected = incomingDir - outwardNormal * 2.0f * (incomingDir.dot(outwardNormal));
}
static PX_INLINE void collisionResponse(PxExtendedVec3& targetPosition, const PxExtendedVec3& currentPosition, const PxVec3& currentDir, const PxVec3& hitNormal, PxF32 bump, PxF32 friction, bool normalize=false)
{
// Compute reflect direction
PxVec3 reflectDir;
computeReflexionVector(reflectDir, currentDir, hitNormal);
reflectDir.normalize();
// Decompose it
PxVec3 normalCompo, tangentCompo;
decomposeVector(normalCompo, tangentCompo, reflectDir, hitNormal);
// Compute new destination position
const PxF32 amplitude = diff(targetPosition, currentPosition).magnitude();
targetPosition = currentPosition;
if(bump!=0.0f)
{
if(normalize)
normalCompo.normalize();
add(targetPosition, normalCompo*bump*amplitude);
}
if(friction!=0.0f)
{
if(normalize)
tangentCompo.normalize();
add(targetPosition, tangentCompo*friction*amplitude);
}
}
static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const PxExtendedVec3& center, const PxVec3& extents, const PxExtendedVec3& origin, const PxQuat& quatFromUp)
{
boxGeom.halfExtents = extents;
pose.p.x = float(center.x - origin.x);
pose.p.y = float(center.y - origin.y);
pose.p.z = float(center.z - origin.z);
pose.q = quatFromUp;
}
static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const TouchedUserBox& userBox)
{
relocateBox(boxGeom, pose, userBox.mBox.center, userBox.mBox.extents, userBox.mOffset, userBox.mBox.rot);
}
static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const TouchedBox& box)
{
boxGeom.halfExtents = box.mExtents;
pose.p = box.mCenter;
pose.q = box.mRot;
}
static PX_INLINE void relocateCapsule(
PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const SweptCapsule* sc,
const PxQuat& quatFromUp,
const PxExtendedVec3& center, const PxExtendedVec3& origin)
{
capsuleGeom.radius = sc->mRadius;
capsuleGeom.halfHeight = 0.5f * sc->mHeight;
pose.p.x = float(center.x - origin.x);
pose.p.y = float(center.y - origin.y);
pose.p.z = float(center.z - origin.z);
pose.q = quatFromUp;
}
static PX_INLINE void relocateCapsule(PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const PxVec3& p0, const PxVec3& p1, PxReal radius)
{
capsuleGeom.radius = radius;
pose = PxTransformFromSegment(p0, p1, &capsuleGeom.halfHeight);
if(capsuleGeom.halfHeight==0.0f)
capsuleGeom.halfHeight = FLT_EPSILON;
}
static PX_INLINE void relocateCapsule(PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const TouchedUserCapsule& userCapsule)
{
PxVec3 p0, p1;
p0.x = float(userCapsule.mCapsule.p0.x - userCapsule.mOffset.x);
p0.y = float(userCapsule.mCapsule.p0.y - userCapsule.mOffset.y);
p0.z = float(userCapsule.mCapsule.p0.z - userCapsule.mOffset.z);
p1.x = float(userCapsule.mCapsule.p1.x - userCapsule.mOffset.x);
p1.y = float(userCapsule.mCapsule.p1.y - userCapsule.mOffset.y);
p1.z = float(userCapsule.mCapsule.p1.z - userCapsule.mOffset.z);
relocateCapsule(capsuleGeom, pose, p0, p1, userCapsule.mCapsule.radius);
}
static bool SweepBoxUserBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eUSER_BOX);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedUserBox* TC = static_cast<const TouchedUserBox*>(geom);
PxBoxGeometry boxGeom0;
PxTransform boxPose0;
// To precompute
relocateBox(boxGeom0, boxPose0, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp);
PxBoxGeometry boxGeom1;
PxTransform boxPose1;
relocateBox(boxGeom1, boxPose1, *TC);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom0, boxPose0, boxGeom1, boxPose1, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mWorldNormal = sweepHit.normal;
impact.mDistance = sweepHit.distance;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TC->mOffset);
return true;
}
static bool SweepBoxUserCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eUSER_CAPSULE);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedUserCapsule* TC = static_cast<const TouchedUserCapsule*>(geom);
PxBoxGeometry boxGeom;
PxTransform boxPose;
// To precompute
relocateBox(boxGeom, boxPose, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, *TC);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, capsuleGeom, capsulePose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
//TO CHECK: Investigate whether any significant performance improvement can be achieved through
// making the impact point computation optional in the sweep calls and compute it later
/*{
// ### check this
float t;
PxVec3 p;
float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, Box0.center, Box0.extents, Box0.rot, &t, &p);
Box0.rot.multiply(p,p);
impact.mWorldPos.x = p.x + Box0.center.x + TC->mOffset.x;
impact.mWorldPos.y = p.y + Box0.center.y + TC->mOffset.y;
impact.mWorldPos.z = p.z + Box0.center.z + TC->mOffset.z;
}*/
{
impact.setWorldPos(sweepHit.position, TC->mOffset);
}
return true;
}
static bool sweepVolumeVsMesh( const SweepTest* sweepTest, const TouchedMesh* touchedMesh, SweptContact& impact,
const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose,
PxU32 nbTris, const PxTriangle* triangles,
PxU32 cachedIndex)
{
PxGeomSweepHit sweepHit;
if(PxMeshQuery::sweep(unitDir, impact.mDistance, geom, pose, nbTris, triangles, sweepHit, getSweepHitFlags(sweepTest->mUserParams), &cachedIndex))
{
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.setWorldPos(sweepHit.position, touchedMesh->mOffset);
// Returned index is only between 0 and nbTris, i.e. it indexes the array of cached triangles, not the original mesh.
PX_ASSERT(sweepHit.faceIndex < nbTris);
sweepTest->mCachedTriIndex[sweepTest->mCachedTriIndexIndex] = sweepHit.faceIndex;
// The CCT loop will use the index from the start of the cache...
impact.mInternalIndex = sweepHit.faceIndex + touchedMesh->mIndexWorldTriangles;
const PxU32* triangleIndices = &sweepTest->mTriangleIndices[touchedMesh->mIndexWorldTriangles];
impact.mTriangleIndex = triangleIndices[sweepHit.faceIndex];
return true;
}
return false;
}
static bool SweepBoxMesh(const SweepTest* sweep_test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eMESH);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedMesh* TM = static_cast<const TouchedMesh*>(geom);
PxU32 nbTris = TM->mNbTris;
if(!nbTris)
return false;
// Fetch triangle data for current mesh (the stream may contain triangles from multiple meshes)
const PxTriangle* T = &sweep_test->mWorldTriangles.getTriangle(TM->mIndexWorldTriangles);
// PT: this only really works when the CCT collides with a single mesh, but that's the most common case. When it doesn't, there's just no speedup but it still works.
PxU32 CachedIndex = sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex];
if(CachedIndex>=nbTris)
CachedIndex=0;
PxBoxGeometry boxGeom;
boxGeom.halfExtents = SB->mExtents;
PxTransform boxPose(PxVec3(float(center.x - TM->mOffset.x), float(center.y - TM->mOffset.y), float(center.z - TM->mOffset.z)), sweep_test->mUserParams.mQuatFromUp); // Precompute
return sweepVolumeVsMesh(sweep_test, TM, impact, dir, boxGeom, boxPose, nbTris, T, CachedIndex);
}
static bool SweepCapsuleMesh(
const SweepTest* sweep_test, const SweptVolume* volume, const TouchedGeom* geom,
const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eMESH);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedMesh* TM = static_cast<const TouchedMesh*>(geom);
PxU32 nbTris = TM->mNbTris;
if(!nbTris)
return false;
// Fetch triangle data for current mesh (the stream may contain triangles from multiple meshes)
const PxTriangle* T = &sweep_test->mWorldTriangles.getTriangle(TM->mIndexWorldTriangles);
// PT: this only really works when the CCT collides with a single mesh, but that's the most common case.
// When it doesn't, there's just no speedup but it still works.
PxU32 CachedIndex = sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex];
if(CachedIndex>=nbTris)
CachedIndex=0;
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, SC, sweep_test->mUserParams.mQuatFromUp, center, TM->mOffset);
return sweepVolumeVsMesh(sweep_test, TM, impact, dir, capsuleGeom, capsulePose, nbTris, T, CachedIndex);
}
static bool SweepBoxBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eBOX);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedBox* TB = static_cast<const TouchedBox*>(geom);
PxBoxGeometry boxGeom0;
PxTransform boxPose0;
// To precompute
relocateBox(boxGeom0, boxPose0, center, SB->mExtents, TB->mOffset, test->mUserParams.mQuatFromUp);
PxBoxGeometry boxGeom1;
PxTransform boxPose1;
relocateBox(boxGeom1, boxPose1, *TB);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom0, boxPose0, boxGeom1, boxPose1, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mWorldNormal = sweepHit.normal;
impact.mDistance = sweepHit.distance;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TB->mOffset);
return true;
}
static bool SweepBoxSphere(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eSPHERE);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedSphere* TS = static_cast<const TouchedSphere*>(geom);
PxBoxGeometry boxGeom;
PxTransform boxPose;
// To precompute
relocateBox(boxGeom, boxPose, center, SB->mExtents, TS->mOffset, test->mUserParams.mQuatFromUp);
PxSphereGeometry sphereGeom;
sphereGeom.radius = TS->mRadius;
PxTransform spherePose;
spherePose.p = TS->mCenter;
spherePose.q = PxQuat(PxIdentity);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, sphereGeom, spherePose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
//TO CHECK: Investigate whether any significant performance improvement can be achieved through
// making the impact point computation optional in the sweep calls and compute it later
/*
{
// The sweep test doesn't compute the impact point automatically, so we have to do it here.
PxVec3 NewSphereCenter = TS->mSphere.center - d * dir;
PxVec3 Closest;
gUtilLib->PxPointOBBSqrDist(NewSphereCenter, Box0.center, Box0.extents, Box0.rot, &Closest);
// Compute point on the box, after sweep
Box0.rot.multiply(Closest, Closest);
impact.mWorldPos.x = TS->mOffset.x + Closest.x + Box0.center.x + d * dir.x;
impact.mWorldPos.y = TS->mOffset.y + Closest.y + Box0.center.y + d * dir.y;
impact.mWorldPos.z = TS->mOffset.z + Closest.z + Box0.center.z + d * dir.z;
impact.mWorldNormal = -impact.mWorldNormal;
}*/
{
impact.setWorldPos(sweepHit.position, TS->mOffset);
}
return true;
}
static bool SweepBoxCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eBOX);
PX_ASSERT(geom->mType==TouchedGeomType::eCAPSULE);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedCapsule* TC = static_cast<const TouchedCapsule*>(geom);
PxBoxGeometry boxGeom;
PxTransform boxPose;
// To precompute
relocateBox(boxGeom, boxPose, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, TC->mP0, TC->mP1, TC->mRadius);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, capsuleGeom, capsulePose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
//TO CHECK: Investigate whether any significant performance improvement can be achieved through
// making the impact point computation optional in the sweep calls and compute it later
/*{
float t;
PxVec3 p;
float d = gUtilLib->PxSegmentOBBSqrDist(TC->mCapsule, Box0.center, Box0.extents, Box0.rot, &t, &p);
Box0.rot.multiply(p,p);
impact.mWorldPos.x = p.x + Box0.center.x + TC->mOffset.x;
impact.mWorldPos.y = p.y + Box0.center.y + TC->mOffset.y;
impact.mWorldPos.z = p.z + Box0.center.z + TC->mOffset.z;
}*/
{
impact.setWorldPos(sweepHit.position, TC->mOffset);
}
return true;
}
static bool SweepCapsuleBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eBOX);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedBox* TB = static_cast<const TouchedBox*>(geom);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TB->mOffset);
PxBoxGeometry boxGeom;
PxTransform boxPose;
// To precompute
relocateBox(boxGeom, boxPose, *TB);
// The box and capsule coordinates are relative to the center of the cached bounding box
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, boxGeom, boxPose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
//TO CHECK: Investigate whether any significant performance improvement can be achieved through
// making the impact point computation optional in the sweep calls and compute it later
/*{
float t;
PxVec3 p;
float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, TB->mBox.center, TB->mBox.extents, TB->mBox.rot, &t, &p);
TB->mBox.rot.multiply(p,p);
p += TB->mBox.center;
impact.mWorldPos.x = p.x + TB->mOffset.x;
impact.mWorldPos.y = p.y + TB->mOffset.y;
impact.mWorldPos.z = p.z + TB->mOffset.z;
}*/
{
impact.setWorldPos(sweepHit.position, TB->mOffset);
}
return true;
}
static bool SweepCapsuleSphere(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eSPHERE);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedSphere* TS = static_cast<const TouchedSphere*>(geom);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TS->mOffset);
PxSphereGeometry sphereGeom;
sphereGeom.radius = TS->mRadius;
PxTransform spherePose;
spherePose.p = TS->mCenter;
spherePose.q = PxQuat(PxIdentity);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, sphereGeom, spherePose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TS->mOffset);
return true;
}
static bool SweepCapsuleCustom(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType() == SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType == TouchedGeomType::eCUSTOM);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedCustom* TC = static_cast<const TouchedCustom*>(geom);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TC->mOffset);
PxCustomGeometry customGeom(*TC->mCustomCallbacks);
PxTransform customPose;
customPose.p = TC->mCenter;
customPose.q = PxQuat(PxIdentity);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, customGeom, customPose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TC->mOffset);
return true;
}
static bool SweepBoxCustom(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType() == SweptVolumeType::eBOX);
PX_ASSERT(geom->mType == TouchedGeomType::eCUSTOM);
const SweptBox* SB = static_cast<const SweptBox*>(volume);
const TouchedCustom* TC = static_cast<const TouchedCustom*>(geom);
PxBoxGeometry boxGeom;
PxTransform boxPose;
// To precompute
relocateBox(boxGeom, boxPose, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp);
PxCustomGeometry customGeom(*TC->mCustomCallbacks);
PxTransform customPose;
customPose.p = TC->mCenter;
customPose.q = PxQuat(PxIdentity);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, customGeom, customPose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TC->mOffset);
return true;
}
static bool SweepCapsuleCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eCAPSULE);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedCapsule* TC = static_cast<const TouchedCapsule*>(geom);
PxCapsuleGeometry capsuleGeom0;
PxTransform capsulePose0;
relocateCapsule(capsuleGeom0, capsulePose0, SC, test->mUserParams.mQuatFromUp, center, TC->mOffset);
PxCapsuleGeometry capsuleGeom1;
PxTransform capsulePose1;
relocateCapsule(capsuleGeom1, capsulePose1, TC->mP0, TC->mP1, TC->mRadius);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom0, capsulePose0, capsuleGeom1, capsulePose1, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TC->mOffset);
return true;
}
static bool SweepCapsuleUserCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eUSER_CAPSULE);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedUserCapsule* TC = static_cast<const TouchedUserCapsule*>(geom);
PxCapsuleGeometry capsuleGeom0;
PxTransform capsulePose0;
relocateCapsule(capsuleGeom0, capsulePose0, SC, test->mUserParams.mQuatFromUp, center, TC->mOffset);
PxCapsuleGeometry capsuleGeom1;
PxTransform capsulePose1;
relocateCapsule(capsuleGeom1, capsulePose1, *TC);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom0, capsulePose0, capsuleGeom1, capsulePose1, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.setWorldPos(sweepHit.position, TC->mOffset);
return true;
}
static bool SweepCapsuleUserBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact)
{
PX_ASSERT(volume->getType()==SweptVolumeType::eCAPSULE);
PX_ASSERT(geom->mType==TouchedGeomType::eUSER_BOX);
const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume);
const TouchedUserBox* TB = static_cast<const TouchedUserBox*>(geom);
PxCapsuleGeometry capsuleGeom;
PxTransform capsulePose;
relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TB->mOffset);
PxBoxGeometry boxGeom;
PxTransform boxPose;
relocateBox(boxGeom, boxPose, *TB);
PxGeomSweepHit sweepHit;
if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, boxGeom, boxPose, sweepHit, getSweepHitFlags(test->mUserParams)))
return false;
if(sweepHit.distance >= impact.mDistance)
return false;
impact.mDistance = sweepHit.distance;
impact.mWorldNormal = sweepHit.normal;
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
//TO CHECK: Investigate whether any significant performance improvement can be achieved through
// making the impact point computation optional in the sweep calls and compute it later
/*{
// ### check this
float t;
PxVec3 p;
float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, Box.center, Box.extents, Box.rot, &t, &p);
p += Box.center;
impact.mWorldPos.x = p.x + TB->mOffset.x;
impact.mWorldPos.y = p.y + TB->mOffset.y;
impact.mWorldPos.z = p.z + TB->mOffset.z;
}*/
{
impact.setWorldPos(sweepHit.position, TB->mOffset);
}
return true;
}
typedef bool (*SweepFunc) (const SweepTest*, const SweptVolume*, const TouchedGeom*, const PxExtendedVec3&, const PxVec3&, SweptContact&);
static SweepFunc gSweepMap[SweptVolumeType::eLAST][TouchedGeomType::eLAST] = {
// Box funcs
{
SweepBoxUserBox,
SweepBoxUserCapsule,
SweepBoxMesh,
SweepBoxBox,
SweepBoxSphere,
SweepBoxCapsule,
SweepBoxCustom
},
// Capsule funcs
{
SweepCapsuleUserBox,
SweepCapsuleUserCapsule,
SweepCapsuleMesh,
SweepCapsuleBox,
SweepCapsuleSphere,
SweepCapsuleCapsule,
SweepCapsuleCustom
}
};
PX_COMPILE_TIME_ASSERT(sizeof(gSweepMap)==SweptVolumeType::eLAST*TouchedGeomType::eLAST*sizeof(SweepFunc));
static const PxU32 GeomSizes[] =
{
sizeof(TouchedUserBox),
sizeof(TouchedUserCapsule),
sizeof(TouchedMesh),
sizeof(TouchedBox),
sizeof(TouchedSphere),
sizeof(TouchedCapsule),
sizeof(TouchedCustom)
};
static const TouchedGeom* CollideGeoms(
const SweepTest* sweep_test, const SweptVolume& volume, const IntArray& geom_stream,
const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact, bool discardInitialOverlap)
{
impact.mInternalIndex = PX_INVALID_U32;
impact.mTriangleIndex = PX_INVALID_U32;
impact.mGeom = NULL;
const PxU32* Data = geom_stream.begin();
const PxU32* Last = geom_stream.end();
while(Data!=Last)
{
const TouchedGeom* CurrentGeom = reinterpret_cast<const TouchedGeom*>(Data);
SweepFunc ST = gSweepMap[volume.getType()][CurrentGeom->mType];
if(ST)
{
SweptContact C;
C.mDistance = impact.mDistance; // Initialize with current best distance
C.mInternalIndex = PX_INVALID_U32;
C.mTriangleIndex = PX_INVALID_U32;
if((ST)(sweep_test, &volume, CurrentGeom, center, dir, C))
{
if(C.mDistance==0.0f)
{
if(!discardInitialOverlap)
{
if(CurrentGeom->mType==TouchedGeomType::eUSER_BOX || CurrentGeom->mType==TouchedGeomType::eUSER_CAPSULE)
{
}
else
{
const PxRigidActor* touchedActor = CurrentGeom->mActor;
PX_ASSERT(touchedActor);
if(shouldApplyRecoveryModule(*touchedActor))
{
impact = C;
impact.mGeom = const_cast<TouchedGeom*>(CurrentGeom);
return CurrentGeom;
}
}
}
}
/* else
if(discardInitialOverlap && C.mDistance==0.0f)
{
// PT: we previously used eINITIAL_OVERLAP without eINITIAL_OVERLAP_KEEP, i.e. initially overlapping shapes got ignored.
// So we replicate this behavior here.
}*/
else if(C.mDistance<impact.mDistance)
{
impact = C;
impact.mGeom = const_cast<TouchedGeom*>(CurrentGeom);
if(C.mDistance <= 0.0f) // there is no point testing for closer hits
return CurrentGeom; // since we are touching a shape already
}
}
}
const PxU8* ptr = reinterpret_cast<const PxU8*>(Data);
ptr += GeomSizes[CurrentGeom->mType];
Data = reinterpret_cast<const PxU32*>(ptr);
}
return impact.mGeom;
}
static PxVec3 computeMTD(const SweepTest* sweep_test, const SweptVolume& volume, const IntArray& geom_stream, const PxExtendedVec3& center, float contactOffset)
{
PxVec3 p = toVec3(center);
// contactOffset += 0.01f;
const PxU32 maxIter = 4;
PxU32 nbIter = 0;
bool isValid = true;
while(isValid && nbIter<maxIter)
{
const PxU32* Data = geom_stream.begin();
const PxU32* Last = geom_stream.end();
while(Data!=Last)
{
const TouchedGeom* CurrentGeom = reinterpret_cast<const TouchedGeom*>(Data);
if(CurrentGeom->mType==TouchedGeomType::eUSER_BOX || CurrentGeom->mType==TouchedGeomType::eUSER_CAPSULE)
{
}
else
{
const PxRigidActor* touchedActor = CurrentGeom->mActor;
PX_ASSERT(touchedActor);
if(shouldApplyRecoveryModule(*touchedActor))
{
const PxShape* touchedShape = reinterpret_cast<const PxShape*>(CurrentGeom->mTGUserData);
PX_ASSERT(touchedShape);
const PxGeometry& touchedGeom = touchedShape->getGeometry();
const PxTransform globalPose = getShapeGlobalPose(*touchedShape, *touchedActor);
PxVec3 mtd;
PxF32 depth;
const PxTransform volumePose(p, sweep_test->mUserParams.mQuatFromUp);
if(volume.getType()==SweptVolumeType::eCAPSULE)
{
const SweptCapsule& sc = static_cast<const SweptCapsule&>(volume);
const PxCapsuleGeometry capsuleGeom(sc.mRadius+contactOffset, sc.mHeight*0.5f);
isValid = PxGeometryQuery::computePenetration(mtd, depth, capsuleGeom, volumePose, touchedGeom, globalPose);
}
else
{
PX_ASSERT(volume.getType()==SweptVolumeType::eBOX);
const SweptBox& sb = static_cast<const SweptBox&>(volume);
const PxBoxGeometry boxGeom(sb.mExtents+PxVec3(contactOffset));
isValid = PxGeometryQuery::computePenetration(mtd, depth, boxGeom, volumePose, touchedGeom, globalPose);
}
if(isValid)
{
nbIter++;
PX_ASSERT(depth>=0.0f);
PX_ASSERT(mtd.isFinite());
PX_ASSERT(PxIsFinite(depth));
#ifdef DEBUG_MTD
PX_ASSERT(depth<=1.0f);
if(depth>1.0f || !mtd.isFinite() || !PxIsFinite(depth))
{
int stop=1;
(void)stop;
}
printf("Depth: %f\n", depth);
printf("mtd: %f %f %f\n", mtd.x, mtd.y, mtd.z);
#endif
p += mtd * depth;
}
}
}
const PxU8* ptr = reinterpret_cast<const PxU8*>(Data);
ptr += GeomSizes[CurrentGeom->mType];
Data = reinterpret_cast<const PxU32*>(ptr);
}
}
return p;
}
static bool ParseGeomStream(const void* object, const IntArray& geom_stream)
{
const PxU32* Data = geom_stream.begin();
const PxU32* Last = geom_stream.end();
while(Data!=Last)
{
const TouchedGeom* CurrentGeom = reinterpret_cast<const TouchedGeom*>(Data);
if(CurrentGeom->mTGUserData==object)
return true;
const PxU8* ptr = reinterpret_cast<const PxU8*>(Data);
ptr += GeomSizes[CurrentGeom->mType];
Data = reinterpret_cast<const PxU32*>(ptr);
}
return false;
}
CCTParams::CCTParams() :
mNonWalkableMode (PxControllerNonWalkableMode::ePREVENT_CLIMBING),
mQuatFromUp (PxQuat(PxIdentity)),
mUpDirection (PxVec3(0.0f)),
mSlopeLimit (0.0f),
mContactOffset (0.0f),
mStepOffset (0.0f),
mInvisibleWallHeight (0.0f),
mMaxJumpHeight (0.0f),
mMaxEdgeLength2 (0.0f),
mTessellation (false),
mHandleSlope (false),
mOverlapRecovery (false),
mPreciseSweeps (true),
mPreventVerticalSlidingAgainstCeiling (false)
{
}
SweepTest::SweepTest(bool registerDeletionListener) :
mRenderBuffer (NULL),
mRenderFlags (0),
mTriangleIndices ("sweepTestTriangleIndices"),
mGeomStream ("sweepTestStream"),
mTouchedShape (registerDeletionListener),
mTouchedActor (registerDeletionListener),
mSQTimeStamp (0xffffffff),
mNbFullUpdates (0),
mNbPartialUpdates (0),
mNbTessellation (0),
mNbIterations (0),
mFlags (0),
mRegisterDeletionListener(registerDeletionListener),
mCctManager (NULL)
{
mCacheBounds.setEmpty();
mCachedTriIndexIndex = 0;
mCachedTriIndex[0] = mCachedTriIndex[1] = mCachedTriIndex[2] = 0;
mNbCachedStatic = 0;
mNbCachedT = 0;
mTouchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
mTouchedPos = PxVec3(0);
mTouchedPosShape_Local = PxVec3(0);
mTouchedPosShape_World = PxVec3(0);
mTouchedPosObstacle_Local = PxVec3(0);
mTouchedPosObstacle_World = PxVec3(0);
// mVolumeGrowth = 1.2f; // Must be >1.0f and not too big
mVolumeGrowth = 1.5f; // Must be >1.0f and not too big
// mVolumeGrowth = 2.0f; // Must be >1.0f and not too big
mContactNormalDownPass = PxVec3(0.0f);
mContactNormalSidePass = PxVec3(0.0f);
mTouchedTriMin = 0.0f;
mTouchedTriMax = 0.0f;
}
SweepTest::~SweepTest()
{
// set the TouchedObject to NULL so we unregister the actor/shape
mTouchedShape = NULL;
mTouchedActor = NULL;
}
void SweepTest::voidTestCache()
{
mTouchedShape = NULL;
mTouchedActor = NULL;
mCacheBounds.setEmpty();
mTouchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
}
void SweepTest::onRelease(const PxBase& observed)
{
if (mTouchedActor == &observed)
{
mTouchedShape = NULL;
mTouchedActor = NULL;
return;
}
if(ParseGeomStream(&observed, mGeomStream))
mCacheBounds.setEmpty();
if (mTouchedShape == &observed)
mTouchedShape = NULL;
}
void SweepTest::updateCachedShapesRegistration(PxU32 startIndex, bool unregister)
{
if(!mRegisterDeletionListener)
return;
if(!mGeomStream.size() || startIndex == mGeomStream.size())
return;
PX_ASSERT(startIndex <= mGeomStream.size());
const PxU32* data = &mGeomStream[startIndex];
const PxU32* last = mGeomStream.end();
while (data != last)
{
const TouchedGeom* CurrentGeom = reinterpret_cast<const TouchedGeom*>(data);
if (CurrentGeom->mActor)
{
if(unregister)
mCctManager->unregisterObservedObject(reinterpret_cast<const PxBase*>(CurrentGeom->mTGUserData));
else
mCctManager->registerObservedObject(reinterpret_cast<const PxBase*>(CurrentGeom->mTGUserData));
}
else
{
// we can early exit, the rest of the data are user obstacles
return;
}
const PxU8* ptr = reinterpret_cast<const PxU8*>(data);
ptr += GeomSizes[CurrentGeom->mType];
data = reinterpret_cast<const PxU32*>(ptr);
}
}
void SweepTest::onObstacleAdded(PxObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance )
{
if(mTouchedObstacleHandle != PX_INVALID_OBSTACLE_HANDLE)
{
// check if new obstacle is closer
const ObstacleContext* obstContext = static_cast<const ObstacleContext*> (context);
PxGeomRaycastHit obstacleHit;
const PxObstacle* obst = obstContext->raycastSingle(obstacleHit,index,origin,unitDir,distance);
if(obst && (obstacleHit.position.dot(unitDir))<(mTouchedPosObstacle_World.dot(unitDir)))
{
PX_ASSERT(obstacleHit.distance<=distance);
mTouchedObstacleHandle = index;
if(!gUseLocalSpace)
{
mTouchedPos = toVec3(obst->mPos);
}
else
{
mTouchedPosObstacle_World = obstacleHit.position;
mTouchedPosObstacle_Local = worldToLocal(*obst, PxExtendedVec3(PxExtended(obstacleHit.position.x),PxExtended(obstacleHit.position.y),PxExtended(obstacleHit.position.z)));
}
}
}
}
void SweepTest::onObstacleRemoved(PxObstacleHandle index)
{
if(index == mTouchedObstacleHandle)
{
mTouchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
}
}
void SweepTest::onObstacleUpdated(PxObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance)
{
if(index == mTouchedObstacleHandle)
{
// check if updated obstacle is still closest
const ObstacleContext* obstContext = static_cast<const ObstacleContext*> (context);
PxGeomRaycastHit obstacleHit;
PxObstacleHandle closestHandle = PX_INVALID_OBSTACLE_HANDLE;
const PxObstacle* obst = obstContext->raycastSingle(obstacleHit,origin,unitDir,distance,closestHandle);
if(mTouchedObstacleHandle == closestHandle)
return;
if(obst)
{
PX_ASSERT(obstacleHit.distance<=distance);
mTouchedObstacleHandle = closestHandle;
if(!gUseLocalSpace)
{
mTouchedPos = toVec3(obst->mPos);
}
else
{
mTouchedPosObstacle_World = obstacleHit.position;
mTouchedPosObstacle_Local = worldToLocal(*obst, PxExtendedVec3(PxExtended(obstacleHit.position.x),PxExtended(obstacleHit.position.y),PxExtended(obstacleHit.position.z)));
}
}
}
}
void SweepTest::onOriginShift(const PxVec3& shift)
{
sub(mCacheBounds.minimum, shift);
sub(mCacheBounds.maximum, shift);
if(mTouchedShape)
{
const PxRigidActor* rigidActor = mTouchedActor.get();
if(rigidActor->getConcreteType() != PxConcreteType::eRIGID_STATIC)
{
mTouchedPosShape_World -= shift;
}
}
else if (mTouchedObstacleHandle != PX_INVALID_OBSTACLE_HANDLE)
{
if(!gUseLocalSpace)
{
mTouchedPos -= shift;
}
else
{
mTouchedPosObstacle_World -= shift;
}
}
// adjust cache
PxU32* data = mGeomStream.begin();
PxU32* last = mGeomStream.end();
while(data != last)
{
TouchedGeom* currentGeom = reinterpret_cast<TouchedGeom*>(data);
sub(currentGeom->mOffset, shift);
PxU8* ptr = reinterpret_cast<PxU8*>(data);
ptr += GeomSizes[currentGeom->mType];
data = reinterpret_cast<PxU32*>(ptr);
}
}
static PxBounds3 getBounds3(const PxExtendedBounds3& extended)
{
return PxBounds3(toVec3(extended.minimum), toVec3(extended.maximum)); // LOSS OF ACCURACY
}
// PT: finds both touched CCTs and touched user-defined obstacles
void SweepTest::findTouchedObstacles(const UserObstacles& userObstacles, const PxExtendedBounds3& worldBox)
{
PxExtendedVec3 Origin; // Will be TouchedGeom::mOffset
getCenter(worldBox, Origin);
{
const PxU32 nbBoxes = userObstacles.mNbBoxes;
const PxExtendedBox* boxes = userObstacles.mBoxes;
const void** boxUserData = userObstacles.mBoxUserData;
const PxBounds3 singlePrecisionWorldBox = getBounds3(worldBox);
// Find touched boxes, i.e. other box controllers
for(PxU32 i=0;i<nbBoxes;i++)
{
const Gu::Box obb(
toVec3(boxes[i].center), // LOSS OF ACCURACY
boxes[i].extents,
PxMat33(boxes[i].rot)); // #### PT: TODO: useless conversion here
if(!Gu::intersectOBBAABB(obb, singlePrecisionWorldBox))
continue;
TouchedUserBox* UserBox = reinterpret_cast<TouchedUserBox*>(reserveContainerMemory(mGeomStream, sizeof(TouchedUserBox)/sizeof(PxU32)));
UserBox->mType = TouchedGeomType::eUSER_BOX;
UserBox->mTGUserData = boxUserData[i];
UserBox->mActor = NULL;
UserBox->mOffset = Origin;
UserBox->mBox = boxes[i];
}
}
{
// Find touched capsules, i.e. other capsule controllers
const PxU32 nbCapsules = userObstacles.mNbCapsules;
const PxExtendedCapsule* capsules = userObstacles.mCapsules;
const void** capsuleUserData = userObstacles.mCapsuleUserData;
PxExtendedVec3 Center;
PxVec3 Extents;
getCenter(worldBox, Center);
getExtents(worldBox, Extents);
for(PxU32 i=0;i<nbCapsules;i++)
{
// PT: do a quick AABB check first, to avoid calling the SDK too much
const PxF32 r = capsules[i].radius;
const PxExtended capMinx = PxMin(capsules[i].p0.x, capsules[i].p1.x);
const PxExtended capMaxx = PxMax(capsules[i].p0.x, capsules[i].p1.x);
if((capMinx - PxExtended(r) > worldBox.maximum.x) || (worldBox.minimum.x > capMaxx + PxExtended(r))) continue;
const PxExtended capMiny = PxMin(capsules[i].p0.y, capsules[i].p1.y);
const PxExtended capMaxy = PxMax(capsules[i].p0.y, capsules[i].p1.y);
if((capMiny - PxExtended(r) > worldBox.maximum.y) || (worldBox.minimum.y > capMaxy + PxExtended(r))) continue;
const PxExtended capMinz = PxMin(capsules[i].p0.z, capsules[i].p1.z);
const PxExtended capMaxz = PxMax(capsules[i].p0.z, capsules[i].p1.z);
if((capMinz - PxExtended(r) > worldBox.maximum.z) || (worldBox.minimum.z > capMaxz + PxExtended(r))) continue;
// PT: more accurate capsule-box test. Not strictly necessary but worth doing if available
const PxReal d2 = Gu::distanceSegmentBoxSquared(toVec3(capsules[i].p0), toVec3(capsules[i].p1), toVec3(Center), Extents, PxMat33(PxIdentity));
if(d2>r*r)
continue;
TouchedUserCapsule* UserCapsule = reinterpret_cast<TouchedUserCapsule*>(reserveContainerMemory(mGeomStream, sizeof(TouchedUserCapsule)/sizeof(PxU32)));
UserCapsule->mType = TouchedGeomType::eUSER_CAPSULE;
UserCapsule->mTGUserData = capsuleUserData[i];
UserCapsule->mActor = NULL;
UserCapsule->mOffset = Origin;
UserCapsule->mCapsule = capsules[i];
}
}
}
void SweepTest::updateTouchedGeoms( const InternalCBData_FindTouchedGeom* userData, const UserObstacles& userObstacles,
const PxExtendedBounds3& worldTemporalBox, const PxControllerFilters& filters, const PxVec3& sideVector)
{
/*
- if this is the first iteration (new frame) we have to redo the dynamic objects & the CCTs. The static objects can
be cached.
- if this is not, we can cache everything
*/
// PT: using "worldTemporalBox" instead of "mCacheBounds" seems to produce TTP 6207
//#define DYNAMIC_BOX worldTemporalBox
#define DYNAMIC_BOX mCacheBounds
bool newCachedBox = false;
CCTFilter filter;
filter.mFilterData = filters.mFilterData;
filter.mFilterCallback = filters.mFilterCallback;
filter.mPreFilter = filters.mFilterFlags & PxQueryFlag::ePREFILTER;
filter.mPostFilter = filters.mFilterFlags & PxQueryFlag::ePOSTFILTER;
// PT: detect changes to the static pruning structure
bool sceneHasChanged = false;
{
const PxU32 currentTimestamp = getSceneTimestamp(userData);
if(currentTimestamp!=mSQTimeStamp)
{
mSQTimeStamp = currentTimestamp;
sceneHasChanged = true;
}
}
// If the input box is inside the cached box, nothing to do
if(gUsePartialUpdates && !sceneHasChanged && worldTemporalBox.isInside(mCacheBounds))
{
//printf("CACHEIN%d\n", mFirstUpdate);
if(mFlags & STF_FIRST_UPDATE)
{
mFlags &= ~STF_FIRST_UPDATE;
// Only redo the dynamic
updateCachedShapesRegistration(mNbCachedStatic, true);
mGeomStream.forceSize_Unsafe(mNbCachedStatic);
mWorldTriangles.forceSize_Unsafe(mNbCachedT);
mTriangleIndices.forceSize_Unsafe(mNbCachedT);
filter.mStaticShapes = false;
if(filters.mFilterFlags & PxQueryFlag::eDYNAMIC)
filter.mDynamicShapes = true;
findTouchedGeometry(userData, DYNAMIC_BOX, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams, mNbTessellation);
updateCachedShapesRegistration(mNbCachedStatic, false);
findTouchedObstacles(userObstacles, DYNAMIC_BOX);
mNbPartialUpdates++;
}
}
else
{
//printf("CACHEOUTNS=%d\n", mNbCachedStatic);
newCachedBox = true;
// Cache BV used for the query
mCacheBounds = worldTemporalBox;
// Grow the volume a bit. The temporal box here doesn't take sliding & collision response into account.
// In bad cases it is possible to eventually touch a portion of space not covered by this volume. Just
// in case, we grow the initial volume slightly. Then, additional tests are performed within the loop
// to make sure the TBV is always correct. There's a tradeoff between the original (artificial) growth
// of the volume, and the number of TBV recomputations performed at runtime...
scale(mCacheBounds, PxVec3(mVolumeGrowth));
// scale(mCacheBounds, PxVec3(mVolumeGrowth, 1.0f, mVolumeGrowth));
if(1 && !sideVector.isZero())
{
const PxVec3 sn = sideVector.getNormalized();
float dp0 = PxAbs(diff(worldTemporalBox.maximum, worldTemporalBox.minimum).dot(sn));
float dp1 = PxAbs(diff(mCacheBounds.maximum, mCacheBounds.minimum).dot(sn));
dp1 -= dp0;
dp1 *= 0.5f * 0.9f;
const PxVec3 offset = sn * dp1;
// printf("%f %f %f\n", offset.x, offset.y, offset.z);
add(mCacheBounds.minimum, offset);
add(mCacheBounds.maximum, offset);
add(mCacheBounds, worldTemporalBox);
PX_ASSERT(worldTemporalBox.isInside(mCacheBounds));
}
updateCachedShapesRegistration(0, true);
// Gather triangles touched by this box. This covers multiple meshes.
mWorldTriangles.clear();
mTriangleIndices.clear();
mGeomStream.clear();
// mWorldTriangles.reset();
// mTriangleIndices.reset();
// mGeomStream.reset();
mCachedTriIndexIndex = 0;
mCachedTriIndex[0] = mCachedTriIndex[1] = mCachedTriIndex[2] = 0;
mNbFullUpdates++;
if(filters.mFilterFlags & PxQueryFlag::eSTATIC)
filter.mStaticShapes = true;
filter.mDynamicShapes = false;
findTouchedGeometry(userData, mCacheBounds, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams, mNbTessellation);
mNbCachedStatic = mGeomStream.size();
mNbCachedT = mWorldTriangles.size();
PX_ASSERT(mTriangleIndices.size()==mNbCachedT);
filter.mStaticShapes = false;
if(filters.mFilterFlags & PxQueryFlag::eDYNAMIC)
filter.mDynamicShapes = true;
findTouchedGeometry(userData, DYNAMIC_BOX, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams, mNbTessellation);
// We can't early exit when no tris are touched since we also have to handle the boxes
updateCachedShapesRegistration(0, false);
findTouchedObstacles(userObstacles, DYNAMIC_BOX);
mFlags &= ~STF_FIRST_UPDATE;
//printf("CACHEOUTNSDONE=%d\n", mNbCachedStatic);
}
if(mRenderBuffer)
{
// PT: worldTemporalBox = temporal BV for this frame
PxRenderOutput out(*mRenderBuffer);
if(mRenderFlags & PxControllerDebugRenderFlag::eTEMPORAL_BV)
{
out << gTBVDebugColor;
renderOutputDebugBox(out, getBounds3(worldTemporalBox));
}
if(mRenderFlags & PxControllerDebugRenderFlag::eCACHED_BV)
{
if(newCachedBox)
out << PxU32(PxDebugColor::eARGB_RED);
else
out << PxU32(PxDebugColor::eARGB_GREEN);
renderOutputDebugBox(out, getBounds3(mCacheBounds));
}
}
}
// This is the generic sweep test for all swept volumes, but not character-controller specific
bool SweepTest::doSweepTest(const InternalCBData_FindTouchedGeom* userData,
InternalCBData_OnHit* userHitData,
const UserObstacles& userObstacles,
SweptVolume& swept_volume,
const PxVec3& direction, const PxVec3& sideVector, PxU32 max_iter, PxU32* nb_collisions,
float min_dist, const PxControllerFilters& filters, SweepPass sweepPass,
const PxRigidActor*& touchedActorOut, const PxShape*& touchedShapeOut, PxU64 contextID)
{
// Early exit when motion is zero. Since the motion is decomposed into several vectors
// and this function is called for each of them, it actually happens quite often.
if(direction.isZero())
return false;
PX_PROFILE_ZONE("CharacterController.doSweepTest", contextID);
PX_UNUSED(contextID);
bool hasMoved = false;
mFlags &= ~(STF_VALIDATE_TRIANGLE_DOWN|STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE);
touchedShapeOut = NULL;
touchedActorOut = NULL;
mTouchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
PxExtendedVec3 currentPosition = swept_volume.mCenter;
PxExtendedVec3 targetOrientation = swept_volume.mCenter;
add(targetOrientation, direction);
PxU32 NbCollisions = 0;
while(max_iter--)
{
mNbIterations++;
// Compute current direction
PxVec3 currentDirection = diff(targetOrientation, currentPosition);
// Make sure the new TBV is still valid
{
// Compute temporal bounding box. We could use a capsule or an OBB instead:
// - the volume would be smaller
// - but the query would be slower
// Overall it's unclear whether it's worth it or not.
// TODO: optimize this part ?
PxExtendedBounds3 temporalBox;
swept_volume.computeTemporalBox(*this, temporalBox, currentPosition, currentDirection);
// Gather touched geoms
updateTouchedGeoms(userData, userObstacles, temporalBox, filters, sideVector);
}
const float Length = currentDirection.magnitude();
if(Length<=min_dist) //Use <= to handle the case where min_dist is zero.
break;
currentDirection /= Length;
// From Quake2: "if velocity is against the original velocity, stop dead to avoid tiny occilations in sloping corners"
if((currentDirection.dot(direction)) <= 0.0f)
break;
// From this point, we're going to update the position at least once
hasMoved = true;
// Find closest collision
SweptContact C;
C.mDistance = Length + mUserParams.mContactOffset;
if(!CollideGeoms(this, swept_volume, mGeomStream, currentPosition, currentDirection, C, !mUserParams.mOverlapRecovery))
{
// no collision found => move to desired position
currentPosition = targetOrientation;
break;
}
PX_ASSERT(C.mGeom); // If we reach this point, we must have touched a geom
if(mUserParams.mOverlapRecovery && C.mDistance==0.0f)
{
/* SweptContact C;
C.mDistance = 10.0f;
CollideGeoms(this, swept_volume, mGeomStream, currentPosition, -currentDirection, C, true);
currentPosition -= currentDirection*C.mDistance;
C.mDistance = 10.0f;
CollideGeoms(this, swept_volume, mGeomStream, currentPosition, currentDirection, C, true);
const float DynSkin = mUserParams.mContactOffset;
if(C.mDistance>DynSkin)
currentPosition += currentDirection*(C.mDistance-DynSkin);*/
const PxVec3 mtd = computeMTD(this, swept_volume, mGeomStream, currentPosition, mUserParams.mContactOffset);
NbCollisions++;
if(nb_collisions)
*nb_collisions = NbCollisions;
#ifdef DEBUG_MTD
printf("MTD FIXUP: %f %f %f\n", mtd.x - swept_volume.mCenter.x, mtd.y - swept_volume.mCenter.y, mtd.z - swept_volume.mCenter.z);
#endif
swept_volume.mCenter.x = PxExtended(mtd.x);
swept_volume.mCenter.y = PxExtended(mtd.y);
swept_volume.mCenter.z = PxExtended(mtd.z);
return hasMoved;
// currentPosition.x = mtd.x;
// currentPosition.y = mtd.y;
// currentPosition.z = mtd.z;
// continue;
}
bool preventVerticalMotion = false;
bool stopSliding = true;
if(C.mGeom->mType==TouchedGeomType::eUSER_BOX || C.mGeom->mType==TouchedGeomType::eUSER_CAPSULE)
{
if(sweepPass!=SWEEP_PASS_SENSOR)
{
// We touched a user object, typically another CCT, but can also be a user-defined obstacle
// PT: TODO: technically lines marked with (*) shouldn't be here... revisit later
const PxObstacle* touchedObstacle = NULL; // (*)
PxObstacleHandle touchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
// if(mValidateCallback)
{
PxInternalCBData_OnHit* internalData = static_cast<PxInternalCBData_OnHit*>(userHitData); // (*)
internalData->touchedObstacle = NULL; // (*)
internalData->touchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
const PxU32 behaviorFlags = userHitCallback(userHitData, C, currentDirection, Length);
stopSliding = (behaviorFlags & PxControllerBehaviorFlag::eCCT_SLIDE)==0; // (*)
touchedObstacle = internalData->touchedObstacle; // (*)
touchedObstacleHandle = internalData->touchedObstacleHandle;
}
// printf("INTERNAL: %d\n", int(touchedObstacle));
if(sweepPass==SWEEP_PASS_DOWN)
{
// (*)
if(touchedObstacle)
{
mFlags |= STF_TOUCH_OBSTACLE;
mTouchedObstacleHandle = touchedObstacleHandle;
if(!gUseLocalSpace)
{
mTouchedPos = toVec3(touchedObstacle->mPos);
}
else
{
mTouchedPosObstacle_World = toVec3(C.mWorldPos);
mTouchedPosObstacle_Local = worldToLocal(*touchedObstacle, C.mWorldPos);
}
}
else
{
mFlags |= STF_TOUCH_OTHER_CCT;
}
}
}
}
else
{
const PxShape* touchedShape = reinterpret_cast<const PxShape*>(C.mGeom->mTGUserData);
PX_ASSERT(touchedShape);
const PxRigidActor* touchedActor = C.mGeom->mActor;
PX_ASSERT(touchedActor);
// We touched a normal object
if(sweepPass==SWEEP_PASS_DOWN)
{
mFlags &= ~(STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE);
#ifdef USE_CONTACT_NORMAL_FOR_SLOPE_TEST
mFlags |= STF_VALIDATE_TRIANGLE_DOWN;
mContactNormalDownPass = C.mWorldNormal;
#else
// Work out if the shape is attached to a static or dynamic actor.
// The slope limit is currently only considered when walking on static actors.
// It is ignored for shapes attached attached to dynamics and kinematics.
// TODO: 1. should we treat stationary kinematics the same as statics.
// 2. should we treat all kinematics the same as statics.
// 3. should we treat no kinematics the same as statics.
if((touchedActor->getConcreteType() == PxConcreteType::eRIGID_STATIC) && (C.mInternalIndex!=PX_INVALID_U32))
{
mFlags |= STF_VALIDATE_TRIANGLE_DOWN;
const PxTriangle& touchedTri = mWorldTriangles.getTriangle(C.mInternalIndex);
const PxVec3& upDirection = mUserParams.mUpDirection;
const float dp0 = touchedTri.verts[0].dot(upDirection);
const float dp1 = touchedTri.verts[1].dot(upDirection);
const float dp2 = touchedTri.verts[2].dot(upDirection);
float dpmin = dp0;
dpmin = physx::intrinsics::selectMin(dpmin, dp1);
dpmin = physx::intrinsics::selectMin(dpmin, dp2);
float dpmax = dp0;
dpmax = physx::intrinsics::selectMax(dpmax, dp1);
dpmax = physx::intrinsics::selectMax(dpmax, dp2);
PxExtendedVec3 cacheCenter;
getCenter(mCacheBounds, cacheCenter);
const float offset = upDirection.dot(toVec3(cacheCenter));
mTouchedTriMin = dpmin + offset;
mTouchedTriMax = dpmax + offset;
touchedTri.normal(mContactNormalDownPass);
}
#endif
// Update touched shape in down pass
touchedShapeOut = const_cast<PxShape*>(touchedShape);
touchedActorOut = touchedActor;
// mTouchedPos = getShapeGlobalPose(*touchedShape).p;
const PxTransform shapeTransform = getShapeGlobalPose(*touchedShape, *touchedActor);
const PxVec3 worldPos = toVec3(C.mWorldPos);
mTouchedPosShape_World = worldPos;
mTouchedPosShape_Local = shapeTransform.transformInv(worldPos);
}
else if(sweepPass==SWEEP_PASS_SIDE || sweepPass==SWEEP_PASS_SENSOR)
{
if((touchedActor->getConcreteType() == PxConcreteType::eRIGID_STATIC) && (C.mInternalIndex!=PX_INVALID_U32))
{
mFlags |= STF_VALIDATE_TRIANGLE_SIDE;
const PxTriangle& touchedTri = mWorldTriangles.getTriangle(C.mInternalIndex);
touchedTri.normal(mContactNormalSidePass);
// printf("%f | %f | %f\n", mContactNormalSidePass.x, mContactNormalSidePass.y, mContactNormalSidePass.z);
if(mUserParams.mPreventVerticalSlidingAgainstCeiling && mContactNormalSidePass.dot(mUserParams.mUpDirection)<0.0f)
preventVerticalMotion = true;
}
}
if(sweepPass!=SWEEP_PASS_SENSOR)
// if(mValidateCallback)
{
const PxU32 behaviorFlags = shapeHitCallback(userHitData, C, currentDirection, Length);
stopSliding = (behaviorFlags & PxControllerBehaviorFlag::eCCT_SLIDE)==0; // (*)
}
}
if(sweepPass==SWEEP_PASS_DOWN && !stopSliding)
{
// Trying to solve the following problem:
// - by default, the CCT "friction" is infinite, i.e. a CCT will not slide on a slope (this is by design)
// - this produces bad results when a capsule CCT stands on top of another capsule CCT, without sliding. Visually it looks
// like the character is standing on the other character's head, it looks bad. So, here, we would like to let the CCT
// slide away, i.e. we don't want friction.
// So here we simply increase the number of iterations (== let the CCT slide) when the first down collision is with another CCT.
if(!NbCollisions)
max_iter += 9;
// max_iter += 1;
}
NbCollisions++;
// mContactPointHeight = (float)C.mWorldPos[mUserParams.mUpDirection]; // UBI
mContactPointHeight = toVec3(C.mWorldPos).dot(mUserParams.mUpDirection); // UBI
const float DynSkin = mUserParams.mContactOffset;
if(C.mDistance>DynSkin/*+0.01f*/)
add(currentPosition, currentDirection*(C.mDistance-DynSkin));
// DE6513
/* else if(sweepPass==SWEEP_PASS_SIDE)
{
// Might be better to do a proper sweep pass here, in the opposite direction
currentPosition += currentDirection*(C.mDistance-DynSkin);
}*/
//~DE6513
PxVec3 WorldNormal = C.mWorldNormal;
if(preventVerticalMotion || ((mFlags & STF_WALK_EXPERIMENT) && (mUserParams.mNonWalkableMode!=PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING)))
{
// Make sure the auto-step doesn't bypass this !
// PT: cancel out normal compo
// WorldNormal[mUserParams.mUpDirection]=0.0f;
// WorldNormal.normalize();
PxVec3 normalCompo, tangentCompo;
decomposeVector(normalCompo, tangentCompo, WorldNormal, mUserParams.mUpDirection);
WorldNormal = tangentCompo;
WorldNormal.normalize();
}
const float Bump = 0.0f; // ### doesn't work when !=0 because of Quake2 hack!
const float Friction = 1.0f;
collisionResponse(targetOrientation, currentPosition, currentDirection, WorldNormal, Bump, Friction, (mFlags & STF_NORMALIZE_RESPONSE)!=0);
}
if(nb_collisions)
*nb_collisions = NbCollisions;
// Final box position that should be reflected in the graphics engine
swept_volume.mCenter = currentPosition;
// If we didn't move, don't update the box position at all (keeping possible lazy-evaluated structures valid)
return hasMoved;
}
// ### have a return code to tell if we really moved or not
// Using swept code & direct position update (no physics engine)
// This function is the generic character controller logic, valid for all swept volumes
PxControllerCollisionFlags SweepTest::moveCharacter(
const InternalCBData_FindTouchedGeom* userData,
InternalCBData_OnHit* userHitData,
SweptVolume& volume,
const PxVec3& direction,
const UserObstacles& userObstacles,
float min_dist,
const PxControllerFilters& filters,
bool constrainedClimbingMode,
bool standingOnMoving,
const PxRigidActor*& touchedActor,
const PxShape*& touchedShape,
PxU64 contextID)
{
PX_PROFILE_ZONE("CharacterController.moveCharacter", contextID);
PX_UNUSED(contextID);
bool standingOnMovingUp = standingOnMoving;
mFlags &= ~STF_HIT_NON_WALKABLE;
PxControllerCollisionFlags CollisionFlags = PxControllerCollisionFlags(0);
const PxU32 maxIter = MAX_ITER; // 1 for "collide and stop"
const PxU32 maxIterSides = maxIter;
const PxU32 maxIterDown = ((mFlags & STF_WALK_EXPERIMENT) && mUserParams.mNonWalkableMode==PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING) ? maxIter : 1;
// const PxU32 maxIterDown = 1;
// ### this causes the artificial gap on top of chars
float stepOffset = mUserParams.mStepOffset; // Default step offset can be cancelled in some cases.
// Save initial height
const PxVec3& upDirection = mUserParams.mUpDirection;
const PxExtended originalHeight = dot(volume.mCenter, upDirection);
const PxExtended originalBottomPoint = originalHeight - PxExtended(volume.mHalfHeight); // UBI
// TEST! Disable auto-step when flying. Not sure this is really useful.
// if(direction[upDirection]>0.0f)
const float dir_dot_up = direction.dot(upDirection);
//printf("%f\n", dir_dot_up);
if(dir_dot_up>0.0f)
{
mFlags |= STF_IS_MOVING_UP;
// PT: this makes it fail on a platform moving up when jumping
// However if we don't do that a jump when moving up a slope doesn't work anymore!
// Not doing this also creates jittering when a capsule CCT jumps against another capsule CCT
if(!standingOnMovingUp) // PT: if we're standing on something moving up it's safer to do the up motion anyway, even though this won't work well before we add the flag in TA13542
{
// static int count=0; printf("Cancelling step offset... %d\n", count++);
stepOffset = 0.0f;
}
}
else
{
mFlags &= ~STF_IS_MOVING_UP;
}
// Decompose motion into 3 independent motions: up, side, down
// - if the motion is purely down (gravity only), the up part is needed to fight accuracy issues. For example if the
// character is already touching the geometry a bit, the down sweep test might have troubles. If we first move it above
// the geometry, the problems disappear.
// - if the motion is lateral (character moving forward under normal gravity) the decomposition provides the autostep feature
// - if the motion is purely up, the down part can be skipped
PxVec3 UpVector(0.0f, 0.0f, 0.0f);
PxVec3 DownVector(0.0f, 0.0f, 0.0f);
PxVec3 normal_compo, tangent_compo;
decomposeVector(normal_compo, tangent_compo, direction, upDirection);
// if(direction[upDirection]<0.0f)
if(dir_dot_up<=0.0f)
// DownVector[upDirection] = direction[upDirection];
DownVector = normal_compo;
else
// UpVector[upDirection] = direction[upDirection];
UpVector = normal_compo;
// PxVec3 SideVector = direction;
// SideVector[upDirection] = 0.0f;
PxVec3 SideVector = tangent_compo;
// If the side motion is zero, i.e. if the character is not really moving, disable auto-step.
// This is important to prevent the CCT from automatically climbing on small objects that move
// against it. We should climb over those only if there's a valid side motion from the player.
const bool sideVectorIsZero = !standingOnMovingUp && isAlmostZero(SideVector); // We can't use PxVec3::isZero() safely with arbitrary up vectors
// #### however if we do this the up pass is disabled, with bad consequences when the CCT is on a dynamic object!!
// ### this line makes it possible to push other CCTs by jumping on them
// const bool sideVectorIsZero = false;
// printf("sideVectorIsZero: %d\n", sideVectorIsZero);
// if(!SideVector.isZero())
if(!sideVectorIsZero)
// UpVector[upDirection] += stepOffset;
UpVector += upDirection*stepOffset;
// printf("stepOffset: %f\n", stepOffset);
// ==========[ Initial volume query ]===========================
// PT: the main difference between this initial query and subsequent ones is that we use the
// full direction vector here, not the components along each axis. So there is a good chance
// that this initial query will contain all the motion we need, and thus subsequent queries
// will be skipped.
{
PxExtendedBounds3 temporalBox;
volume.computeTemporalBox(*this, temporalBox, volume.mCenter, direction);
// Gather touched geoms
updateTouchedGeoms(userData, userObstacles, temporalBox, filters, SideVector);
}
// ==========[ UP PASS ]===========================
mCachedTriIndexIndex = 0;
const bool performUpPass = true;
PxU32 NbCollisions=0;
PxU32 maxIterUp;
if(mUserParams.mPreventVerticalSlidingAgainstCeiling)
maxIterUp = 1;
else
maxIterUp = isAlmostZero(SideVector) ? maxIter : 1;
if(performUpPass)
{
// printf("%f | %f | %f\n", UpVector.x, UpVector.y, UpVector.z);
// Prevent user callback for up motion. This up displacement is artificial, and only needed for auto-stepping.
// If we call the user for this, we might eventually apply upward forces to objects resting on top of us, even
// if we visually don't move. This produces weird-looking motions.
// mValidateCallback = false;
// PT: actually I think the previous comment is wrong. It's not only needed for auto-stepping: when the character
// jumps there's a legit up motion and the lack of callback in that case could need some object can't be pushed
// by the character's 'head' (for example). So I now think it's better to use the callback all the time, and
// let users figure out what to do using the available state (like "isMovingUp", etc).
// mValidateCallback = true;
// In the walk-experiment we explicitly want to ban any up motions, to avoid characters climbing slopes they shouldn't climb.
// So let's bypass the whole up pass.
if(!(mFlags & STF_WALK_EXPERIMENT))
{
// ### maxIter here seems to "solve" the V bug
if(doSweepTest(userData, userHitData, userObstacles, volume, UpVector, SideVector, maxIterUp, &NbCollisions, min_dist, filters, SWEEP_PASS_UP, touchedActor, touchedShape, contextID))
{
if(NbCollisions)
{
CollisionFlags |= PxControllerCollisionFlag::eCOLLISION_UP;
// Clamp step offset to make sure we don't undo more than what we did
float Delta = float(dot(volume.mCenter, upDirection) - originalHeight);
if(Delta<stepOffset)
{
stepOffset=Delta;
}
}
}
}
}
// ==========[ SIDE PASS ]===========================
mCachedTriIndexIndex = 1;
// mValidateCallback = true;
const bool PerformSidePass = true;
mFlags &= ~STF_VALIDATE_TRIANGLE_SIDE;
if(PerformSidePass)
{
NbCollisions=0;
//printf("BS:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic);
if(doSweepTest(userData, userHitData, userObstacles, volume, SideVector, SideVector, maxIterSides, &NbCollisions, min_dist, filters, SWEEP_PASS_SIDE, touchedActor, touchedShape, contextID))
{
if(NbCollisions)
CollisionFlags |= PxControllerCollisionFlag::eCOLLISION_SIDES;
}
//printf("AS:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic);
if(1 && constrainedClimbingMode && volume.getType()==SweptVolumeType::eCAPSULE && !(mFlags & STF_VALIDATE_TRIANGLE_SIDE))
{
const float capsuleRadius = static_cast<const SweptCapsule&>(volume).mRadius;
const float sideM = SideVector.magnitude();
if(sideM<capsuleRadius)
{
const PxVec3 sensor = SideVector.getNormalized() * capsuleRadius;
mFlags &= ~STF_VALIDATE_TRIANGLE_SIDE;
NbCollisions=0;
//printf("BS:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic);
const PxExtendedVec3 saved = volume.mCenter;
doSweepTest(userData, userHitData, userObstacles, volume, sensor, SideVector, 1, &NbCollisions, min_dist, filters, SWEEP_PASS_SENSOR, touchedActor, touchedShape, contextID);
volume.mCenter = saved;
}
}
}
// ==========[ DOWN PASS ]===========================
mCachedTriIndexIndex = 2;
const bool PerformDownPass = true;
if(PerformDownPass)
{
NbCollisions=0;
// PT: we skipped the whole up pass in the walk experiment so we shouldn't take its contribution into
// account during the down pass.
if(!(mFlags & STF_WALK_EXPERIMENT))
{
if(!sideVectorIsZero) // We disabled that before so we don't have to undo it in that case
DownVector -= upDirection*stepOffset; // Undo our artificial up motion
}
mFlags &= ~STF_VALIDATE_TRIANGLE_DOWN;
touchedShape = NULL;
touchedActor = NULL;
mTouchedObstacleHandle = PX_INVALID_OBSTACLE_HANDLE;
// min_dist actually makes a big difference :(
// AAARRRGGH: if we get culled because of min_dist here, mValidateTriangle never becomes valid!
if(doSweepTest(userData, userHitData, userObstacles, volume, DownVector, SideVector, maxIterDown, &NbCollisions, min_dist, filters, SWEEP_PASS_DOWN, touchedActor, touchedShape, contextID))
{
if(NbCollisions)
{
if(dir_dot_up<=0.0f) // PT: fix attempt
CollisionFlags |= PxControllerCollisionFlag::eCOLLISION_DOWN;
if(mUserParams.mHandleSlope && !(mFlags & (STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE))) // PT: I think the following fix shouldn't be performed when mHandleSlope is false.
{
// PT: the following code is responsible for a weird capsule behaviour,
// when colliding against a highly tesselated terrain:
// - with a large direction vector, the capsule gets stuck against some part of the terrain
// - with a slower direction vector (but in the same direction!) the capsule manages to move
// I will keep that code nonetheless, since it seems to be useful for them.
//printf("%d\n", mFlags & STF_VALIDATE_TRIANGLE_SIDE);
// constrainedClimbingMode
if((mFlags & STF_VALIDATE_TRIANGLE_SIDE) && testSlope(mContactNormalSidePass, upDirection, mUserParams.mSlopeLimit))
{
//printf("%d\n", mFlags & STF_VALIDATE_TRIANGLE_SIDE);
if(constrainedClimbingMode && PxExtended(mContactPointHeight) > originalBottomPoint + PxExtended(stepOffset))
{
mFlags |= STF_HIT_NON_WALKABLE;
if(!(mFlags & STF_WALK_EXPERIMENT))
return CollisionFlags;
// printf("Contrained\n");
}
}
//~constrainedClimbingMode
}
}
}
//printf("AD:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic);
// printf("%d\n", mTouchOtherCCT);
// TEST: do another down pass if we're on a non-walkable poly
// ### kind of works but still not perfect
// ### could it be because we zero the Y impulse later?
// ### also check clamped response vectors
// if(mUserParams.mHandleSlope && mValidateTriangle && direction[upDirection]<0.0f)
// if(mUserParams.mHandleSlope && !mTouchOtherCCT && !mTouchObstacle && mValidateTriangle && dir_dot_up<0.0f)
if(mUserParams.mHandleSlope && !(mFlags & (STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE)) && (mFlags & STF_VALIDATE_TRIANGLE_DOWN) && dir_dot_up<=0.0f)
{
PxVec3 Normal;
#ifdef USE_CONTACT_NORMAL_FOR_SLOPE_TEST
Normal = mContactNormalDownPass;
#else
//mTouchedTriangle.normal(Normal);
Normal = mContactNormalDownPass;
#endif
const float touchedTriHeight = float(PxExtended(mTouchedTriMax) - originalBottomPoint);
/* if(touchedTriHeight>mUserParams.mStepOffset)
{
if(constrainedClimbingMode && mContactPointHeight > originalBottomPoint + stepOffset)
{
mFlags |= STF_HIT_NON_WALKABLE;
if(!(mFlags & STF_WALK_EXPERIMENT))
return CollisionFlags;
}
}*/
if(touchedTriHeight>mUserParams.mStepOffset && testSlope(Normal, upDirection, mUserParams.mSlopeLimit))
{
mFlags |= STF_HIT_NON_WALKABLE;
// Early exit if we're going to run this again anyway...
if(!(mFlags & STF_WALK_EXPERIMENT))
return CollisionFlags;
/* CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[0], mTouched.mVerts[1], ARGB_YELLOW);
CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[0], mTouched.mVerts[2], ARGB_YELLOW);
CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[1], mTouched.mVerts[2], ARGB_YELLOW);
*/
// ==========[ WALK EXPERIMENT ]===========================
mFlags |= STF_NORMALIZE_RESPONSE;
const PxExtended tmp = dot(volume.mCenter, upDirection);
float Delta = tmp > originalHeight ? float(tmp - originalHeight) : 0.0f;
Delta += fabsf(direction.dot(upDirection));
float Recover = Delta;
NbCollisions=0;
const float MD = Recover < min_dist ? Recover/float(maxIter) : min_dist;
PxVec3 RecoverPoint(0,0,0);
RecoverPoint = -upDirection*Recover;
// PT: we pass "SWEEP_PASS_UP" for compatibility with previous code, but it's technically wrong (this is a 'down' pass)
if(doSweepTest(userData, userHitData, userObstacles, volume, RecoverPoint, SideVector, maxIter, &NbCollisions, MD, filters, SWEEP_PASS_UP, touchedActor, touchedShape, contextID))
{
// if(NbCollisions) CollisionFlags |= COLLISION_Y_DOWN;
// PT: why did we do this ? Removed for now. It creates a bug (non registered event) when we land on a steep poly.
// However this might have been needed when we were sliding on those polygons, and we didn't want the land anim to
// start while we were sliding.
// if(NbCollisions) CollisionFlags &= ~PxControllerCollisionFlag::eCOLLISION_DOWN;
}
mFlags &= ~STF_NORMALIZE_RESPONSE;
}
}
}
return CollisionFlags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This is an interface between NX users and the internal character controller module.
#include "characterkinematic/PxControllerBehavior.h"
#include "PxActor.h"
#include "PxScene.h"
#include "CctInternalStructs.h"
#include "CctBoxController.h"
#include "CctCapsuleController.h"
#include "CctCharacterControllerManager.h"
#include "CctObstacleContext.h"
bool Controller::filterTouchedShape(const PxControllerFilters& filters)
{
if(filters.mFilterCallback && (filters.mFilterFlags & PxQueryFlag::ePREFILTER))
{
const PxQueryFlags filterFlags = PxQueryFlag::eDYNAMIC|PxQueryFlag::ePREFILTER;
const PxQueryFilterData filterData(filters.mFilterData ? *filters.mFilterData : PxFilterData(), filterFlags);
PxHitFlags hitFlags = PxHitFlags(0);
const PxQueryHitType::Enum retVal = filters.mFilterCallback->preFilter(filterData.data, mCctModule.mTouchedShape.get(), mCctModule.mTouchedActor.get(), hitFlags);
if(retVal != PxQueryHitType::eNONE)
return true;
else
return false;
}
return true;
}
void Controller::findTouchedObject(const PxControllerFilters& filters, const PxObstacleContext* obstacleContext, const PxVec3& upDirection)
{
PX_ASSERT(!mCctModule.mTouchedShape && (mCctModule.mTouchedObstacleHandle == PX_INVALID_OBSTACLE_HANDLE));
// PT: the CCT works perfectly on statics without this extra mechanism, so we only raycasts against dynamics.
// The pre-filter callback is used to filter out our own proxy actor shapes. We need to make sure our own filter
// doesn't disturb the user-provided filter(s).
// PT: for starter, if user doesn't want to collide against dynamics, we can skip the whole thing
if(filters.mFilterFlags & PxQueryFlag::eDYNAMIC)
{
// PT: we use a local class instead of making "Controller" a PxQueryFilterCallback, since it would waste more memory.
// Ideally we'd have a C-style callback and a user-data pointer, instead of being forced to create a class.
class ControllerFilter : public PxQueryFilterCallback
{
public:
virtual PxQueryHitType::Enum preFilter(const PxFilterData& filterData, const PxShape* shape, const PxRigidActor* actor, PxHitFlags& queryFlags)
{
// PT: ignore triggers
if(shape->getFlags() & physx::PxShapeFlag::eTRIGGER_SHAPE)
return PxQueryHitType::eNONE;
// PT: we want to discard our own internal shapes only
if(mShapeHashSet->contains(const_cast<PxShape*>(shape)))
return PxQueryHitType::eNONE;
// PT: otherwise we revert to the user-callback, if it exists, and if users enabled that call
if(mUserFilterCallback && (mUserFilterFlags & PxQueryFlag::ePREFILTER))
return mUserFilterCallback->preFilter(filterData, shape, actor, queryFlags);
return PxQueryHitType::eBLOCK;
}
virtual PxQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxQueryHit& hit, const PxShape* shape, const PxRigidActor* actor)
{
// PT: we may get called if users have asked for such a callback
if(mUserFilterCallback && (mUserFilterFlags & PxQueryFlag::ePOSTFILTER))
return mUserFilterCallback->postFilter(filterData, hit, shape, actor);
PX_ASSERT(0); // PT: otherwise we shouldn't have been called
return PxQueryHitType::eNONE;
}
PxHashSet<PxShape*>* mShapeHashSet;
PxQueryFilterCallback* mUserFilterCallback;
PxQueryFlags mUserFilterFlags;
};
ControllerFilter preFilter;
preFilter.mShapeHashSet = &mManager->mCCTShapes;
preFilter.mUserFilterCallback = filters.mFilterCallback;
preFilter.mUserFilterFlags = filters.mFilterFlags;
// PT: for our own purpose we just want dynamics & pre-filter
PxQueryFlags filterFlags = PxQueryFlag::eDYNAMIC|PxQueryFlag::ePREFILTER;
// PT: but we may need the post-filter callback as well if users want it
if(filters.mFilterFlags & PxQueryFlag::ePOSTFILTER)
filterFlags |= PxQueryFlag::ePOSTFILTER;
PxQueryFilterData filterData(filters.mFilterData ? *filters.mFilterData : PxFilterData(), filterFlags);
const PxF32 probeLength = getHalfHeightInternal(); // Distance to feet
const PxF32 extra = 0.0f;//probeLength * 0.1f;
const PxVec3 rayOrigin = toVec3(mPosition);
PxRaycastBuffer hit;
hit.block.distance = FLT_MAX;
if(mScene->raycast(rayOrigin, -upDirection, probeLength+extra, hit, PxHitFlags(0), filterData, &preFilter))
{
// copy touching hit to blocking so that the rest of the code works with .block
hit.block = hit.getAnyHit(0);
PX_ASSERT(hit.block.shape);
PX_ASSERT(hit.block.actor);
PX_ASSERT(hit.block.distance<=probeLength+extra);
mCctModule.mTouchedShape = hit.block.shape;
mCctModule.mTouchedActor = hit.block.actor;
// mCctModule.mTouchedPos = getShapeGlobalPose(*hit.shape).p - upDirection*(probeLength-hit.distance);
// PT: we only care about the up delta here
const PxTransform shapeTransform = getShapeGlobalPose(*hit.block.shape, *hit.block.actor);
mCctModule.mTouchedPosShape_World = PxVec3(0) - upDirection*(probeLength-hit.block.distance);
mCctModule.mTouchedPosShape_Local = shapeTransform.transformInv(PxVec3(0));
mPreviousSceneTimestamp = mScene->getTimestamp()-1; // PT: just make sure cached timestamp is different
}
if(obstacleContext)
{
const ObstacleContext* obstacles = static_cast<const ObstacleContext*>(obstacleContext);
PxGeomRaycastHit obstacleHit;
PxObstacleHandle obstacleHandle;
const PxObstacle* touchedObstacle = obstacles->raycastSingle(obstacleHit, rayOrigin, -upDirection, probeLength+extra, obstacleHandle);
// printf("Touched raycast obstacle: %d\n", int(touchedObstacle));
if(touchedObstacle && obstacleHit.distance<hit.block.distance)
{
PX_ASSERT(obstacleHit.distance<=probeLength+extra);
mCctModule.mTouchedObstacleHandle = obstacleHandle;
if(!gUseLocalSpace)
{
mCctModule.mTouchedPos = toVec3(touchedObstacle->mPos) - upDirection*(probeLength-obstacleHit.distance);
}
else
{
// PT: we only care about the up delta here
mCctModule.mTouchedPosObstacle_World = PxVec3(0) - upDirection*(probeLength-obstacleHit.distance);
mCctModule.mTouchedPosObstacle_Local = worldToLocal(*touchedObstacle, PxExtendedVec3(0,0,0));
}
}
}
}
}
bool Controller::rideOnTouchedObject(SweptVolume& volume, const PxVec3& upDirection, PxVec3& disp, const PxObstacleContext* obstacleContext)
{
PX_ASSERT(mCctModule.mTouchedShape || (mCctModule.mTouchedObstacleHandle != PX_INVALID_OBSTACLE_HANDLE));
bool standingOnMoving = false;
bool canDoUpdate = true; // Always true on obstacles
PxU32 behaviorFlags = 0; // Default on shapes
PxVec3 delta(0);
float timeCoeff = 1.0f;
if(mCctModule.mTouchedShape)
{
// PT: riding on a shape
// PT: it is important to skip this stuff for static meshes,
// otherwise accuracy issues create bugs like TA14007.
const PxRigidActor& rigidActor = *mCctModule.mTouchedActor.get();
if(rigidActor.getConcreteType()!=PxConcreteType::eRIGID_STATIC)
{
// PT: we only do the update when the timestamp has changed, otherwise "delta" will be zero
// even if the underlying shape is moving.
const PxU32 timestamp = mScene->getTimestamp();
// printf("TimeStamp: %d\n", timestamp);
canDoUpdate = timestamp!=mPreviousSceneTimestamp;
if(canDoUpdate)
{
mPreviousSceneTimestamp = timestamp;
timeCoeff = computeTimeCoeff();
if(mBehaviorCallback)
behaviorFlags = mBehaviorCallback->getBehaviorFlags(*mCctModule.mTouchedShape.get(), *mCctModule.mTouchedActor.get());
// delta = getShapeGlobalPose(*mCctModule.mTouchedShape).p - mCctModule.mTouchedPos;
const PxTransform shapeTransform = getShapeGlobalPose(*mCctModule.mTouchedShape.get(), rigidActor);
const PxVec3 posPreviousFrame = mCctModule.mTouchedPosShape_World;
const PxVec3 posCurrentFrame = shapeTransform.transform(mCctModule.mTouchedPosShape_Local);
delta = posCurrentFrame - posPreviousFrame;
}
}
}
else
{
// PT: riding on an obstacle
behaviorFlags = PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT; // Default on obstacles
timeCoeff = computeTimeCoeff();
const PxObstacle* touchedObstacle = obstacleContext->getObstacleByHandle(mCctModule.mTouchedObstacleHandle);
PX_ASSERT(touchedObstacle);
if(mBehaviorCallback)
behaviorFlags = mBehaviorCallback->getBehaviorFlags(*touchedObstacle);
if(!gUseLocalSpace)
{
delta = toVec3(touchedObstacle->mPos) - mCctModule.mTouchedPos;
}
else
{
PxVec3 posPreviousFrame = mCctModule.mTouchedPosObstacle_World;
PxVec3 posCurrentFrame = localToWorld(*touchedObstacle, mCctModule.mTouchedPosObstacle_Local);
delta = posCurrentFrame - posPreviousFrame;
}
}
if(canDoUpdate && !(behaviorFlags & PxControllerBehaviorFlag::eCCT_USER_DEFINED_RIDE))
{
// PT: amazingly enough even isAlmostZero doesn't solve this one.
// Moving on a static mesh sometimes produces delta bigger than 1e-6f!
// This may also explain the drift on some rotating platforms. It looks
// like this delta computation is not very accurate.
// standingOnMoving = !delta.isZero();
standingOnMoving = !isAlmostZero(delta);
mCachedStandingOnMoving = standingOnMoving;
//printf("%f %f %f\n", delta.x, delta.y, delta.z);
if(standingOnMoving)
{
const float dir_dot_up = delta.dot(upDirection);
const bool deltaMovingUp = dir_dot_up>0.0f;
PxVec3 deltaUpDisp, deltaSideDisp;
decomposeVector(deltaUpDisp, deltaSideDisp, delta, upDirection);
if(deltaMovingUp)
{
volume.mCenter.x += PxExtended(deltaUpDisp.x);
volume.mCenter.y += PxExtended(deltaUpDisp.y);
volume.mCenter.z += PxExtended(deltaUpDisp.z);
}
else
{
disp += deltaUpDisp;
}
if(behaviorFlags & PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT)
disp += deltaSideDisp;
}
// printf("delta in: %f %f %f (%f)\n", delta.x, delta.y, delta.z, 1.0f/timeCoeff);
mDeltaXP = delta * timeCoeff;
}
else
{
standingOnMoving = mCachedStandingOnMoving;
}
// mDelta = delta;
return standingOnMoving;
}
PxControllerCollisionFlags Controller::move(SweptVolume& volume, const PxVec3& originalDisp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacleContext, bool constrainedClimbingMode)
{
const bool lockWrite = mManager->mLockingEnabled;
if(lockWrite)
mWriteLock.lock();
mGlobalTime += PxF64(elapsedTime);
// Init CCT with per-controller settings
PxRenderBuffer* renderBuffer = mManager->mRenderBuffer;
const PxU32 debugRenderFlags = mManager->mDebugRenderingFlags;
mCctModule.mRenderBuffer = renderBuffer;
mCctModule.mRenderFlags = debugRenderFlags;
mCctModule.mUserParams = mUserParams;
mCctModule.mFlags |= STF_FIRST_UPDATE;
mCctModule.mUserParams.mMaxEdgeLength2 = mManager->mMaxEdgeLength * mManager->mMaxEdgeLength;
mCctModule.mUserParams.mTessellation = mManager->mTessellation;
mCctModule.mUserParams.mOverlapRecovery = mManager->mOverlapRecovery;
mCctModule.mUserParams.mPreciseSweeps = mManager->mPreciseSweeps;
mCctModule.mUserParams.mPreventVerticalSlidingAgainstCeiling = mManager->mPreventVerticalSlidingAgainstCeiling;
mCctModule.resetStats();
const PxVec3& upDirection = mUserParams.mUpDirection;
///////////
PxVec3 disp = originalDisp + mOverlapRecover;
mOverlapRecover = PxVec3(0.0f);
bool standingOnMoving = false; // PT: whether the CCT is currently standing on a moving object
//printf("Touched shape: %d\n", int(mCctModule.mTouchedShape));
//standingOnMoving=true;
// printf("Touched obstacle: %d\n", int(mCctModule.mTouchedObstacle));
if(mCctModule.mTouchedActor && mCctModule.mTouchedShape)
{
PxU32 nbShapes = mCctModule.mTouchedActor->getNbShapes();
bool found = false;
for(PxU32 i=0;i<nbShapes;i++)
{
PxShape* shape = NULL;
mCctModule.mTouchedActor->getShapes(&shape, 1, i);
if(mCctModule.mTouchedShape==shape)
{
found = true;
break;
}
}
if(!found)
{
mCctModule.mTouchedActor = NULL;
mCctModule.mTouchedShape = NULL;
}
else
{
// check if we are still in the same scene
if(mCctModule.mTouchedActor->getScene() != mScene)
{
mCctModule.mTouchedShape = NULL;
mCctModule.mTouchedActor = NULL;
}
else
{
// check if the shape still does have the sq flag
if(!(mCctModule.mTouchedShape->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE))
{
mCctModule.mTouchedShape = NULL;
mCctModule.mTouchedActor = NULL;
}
else
{
// invoke the CCT filtering for the shape
if(!filterTouchedShape(filters))
{
mCctModule.mTouchedShape = NULL;
mCctModule.mTouchedActor = NULL;
}
}
}
}
}
if(!mCctModule.mTouchedShape && (mCctModule.mTouchedObstacleHandle == PX_INVALID_OBSTACLE_HANDLE))
findTouchedObject(filters, obstacleContext, upDirection);
if(mCctModule.mTouchedShape || (mCctModule.mTouchedObstacleHandle != PX_INVALID_OBSTACLE_HANDLE))
{
standingOnMoving = rideOnTouchedObject(volume, upDirection, disp, obstacleContext);
}
else
{
mCachedStandingOnMoving = false;
mDeltaXP = PxVec3(0.0f);
}
// printf("standingOnMoving: %d\n", standingOnMoving);
///////////
PxArray<const void*>& boxUserData = mManager->mBoxUserData;
PxArray<PxExtendedBox>& boxes = mManager->mBoxes;
PxArray<const void*>& capsuleUserData = mManager->mCapsuleUserData;
PxArray<PxExtendedCapsule>& capsules = mManager->mCapsules;
PX_ASSERT(!boxUserData.size());
PX_ASSERT(!boxes.size());
PX_ASSERT(!capsuleUserData.size());
PX_ASSERT(!capsules.size());
{
PX_PROFILE_ZONE("CharacterController.filterCandidateControllers", getContextId());
// Experiment - to do better
const PxU32 nbControllers = mManager->getNbControllers();
Controller** controllers = mManager->getControllers();
for(PxU32 i=0;i<nbControllers;i++)
{
Controller* currentController = controllers[i];
if(currentController==this)
continue;
bool keepController = true;
if(filters.mCCTFilterCallback)
keepController = filters.mCCTFilterCallback->filter(*getPxController(), *currentController->getPxController());
if(keepController)
{
if(currentController->mType==PxControllerShapeType::eBOX)
{
// PT: TODO: optimize this
BoxController* BC = static_cast<BoxController*>(currentController);
PxExtendedBox obb;
BC->getOBB(obb);
boxes.pushBack(obb);
#ifdef REMOVED
if(renderBuffer /*&& (debugRenderFlags & PxControllerDebugRenderFlag::eOBSTACLES)*/)
{
RenderOutput out(*renderBuffer);
out << gCCTBoxDebugColor;
out << PxTransform(toVec3(obb.center), obb.rot);
out << DebugBox(obb.extents, true);
}
#endif
const size_t code = encodeUserObject(i, USER_OBJECT_CCT);
boxUserData.pushBack(reinterpret_cast<const void*>(code));
}
else if(currentController->mType==PxControllerShapeType::eCAPSULE)
{
CapsuleController* CC = static_cast<CapsuleController*>(currentController);
// PT: TODO: optimize this
PxExtendedCapsule worldCapule;
CC->getCapsule(worldCapule);
capsules.pushBack(worldCapule);
const size_t code = encodeUserObject(i, USER_OBJECT_CCT);
capsuleUserData.pushBack(reinterpret_cast<const void*>(code));
}
else PX_ASSERT(0);
}
}
}
const ObstacleContext* obstacles = NULL;
if(obstacleContext)
{
obstacles = static_cast<const ObstacleContext*>(obstacleContext);
// PT: TODO: optimize this
const PxU32 nbExtraBoxes = obstacles->mBoxObstacles.size();
for(PxU32 i=0;i<nbExtraBoxes;i++)
{
const PxBoxObstacle& userBoxObstacle = obstacles->mBoxObstacles[i].mData;
PxExtendedBox extraBox;
extraBox.center = userBoxObstacle.mPos;
extraBox.extents = userBoxObstacle.mHalfExtents;
extraBox.rot = userBoxObstacle.mRot;
boxes.pushBack(extraBox);
const size_t code = encodeUserObject(i, USER_OBJECT_BOX_OBSTACLE);
boxUserData.pushBack(reinterpret_cast<const void*>(code));
if(renderBuffer && (debugRenderFlags & PxControllerDebugRenderFlag::eOBSTACLES))
{
PxRenderOutput out(*renderBuffer);
out << gObstacleDebugColor;
out << PxTransform(toVec3(userBoxObstacle.mPos), userBoxObstacle.mRot);
renderOutputDebugBox(out, PxBounds3(-userBoxObstacle.mHalfExtents, userBoxObstacle.mHalfExtents));
}
}
const PxU32 nbExtraCapsules = obstacles->mCapsuleObstacles.size();
for(PxU32 i=0;i<nbExtraCapsules;i++)
{
const PxCapsuleObstacle& userCapsuleObstacle = obstacles->mCapsuleObstacles[i].mData;
PxExtendedCapsule extraCapsule;
const PxVec3 capsuleAxis = userCapsuleObstacle.mRot.getBasisVector0() * userCapsuleObstacle.mHalfHeight;
extraCapsule.p0 = PxExtendedVec3( userCapsuleObstacle.mPos.x - PxExtended(capsuleAxis.x),
userCapsuleObstacle.mPos.y - PxExtended(capsuleAxis.y),
userCapsuleObstacle.mPos.z - PxExtended(capsuleAxis.z));
extraCapsule.p1 = PxExtendedVec3( userCapsuleObstacle.mPos.x + PxExtended(capsuleAxis.x),
userCapsuleObstacle.mPos.y + PxExtended(capsuleAxis.y),
userCapsuleObstacle.mPos.z + PxExtended(capsuleAxis.z));
extraCapsule.radius = userCapsuleObstacle.mRadius;
capsules.pushBack(extraCapsule);
const size_t code = encodeUserObject(i, USER_OBJECT_CAPSULE_OBSTACLE);
capsuleUserData.pushBack(reinterpret_cast<const void*>(code));
if(renderBuffer && (debugRenderFlags & PxControllerDebugRenderFlag::eOBSTACLES))
{
PxRenderOutput out(*renderBuffer);
out << gObstacleDebugColor;
out.outputCapsule(userCapsuleObstacle.mRadius, userCapsuleObstacle.mHalfHeight, PxTransform(toVec3(userCapsuleObstacle.mPos), userCapsuleObstacle.mRot));
}
}
}
UserObstacles userObstacles;
const PxU32 nbBoxes = boxes.size();
userObstacles.mNbBoxes = nbBoxes;
userObstacles.mBoxes = nbBoxes ? boxes.begin() : NULL;
userObstacles.mBoxUserData = nbBoxes ? boxUserData.begin() : NULL;
const PxU32 nbCapsules = capsules.size();
userObstacles.mNbCapsules = nbCapsules;
userObstacles.mCapsules = nbCapsules ? capsules.begin() : NULL;
userObstacles.mCapsuleUserData = nbCapsules ? capsuleUserData.begin() : NULL;
PxInternalCBData_OnHit userHitData;
userHitData.controller = this;
userHitData.obstacles = obstacles;
///////////
PxControllerCollisionFlags collisionFlags = PxControllerCollisionFlags(0);
PxInternalCBData_FindTouchedGeom findGeomData;
findGeomData.scene = mScene;
findGeomData.renderBuffer = renderBuffer;
findGeomData.cctShapeHashSet = &mManager->mCCTShapes;
mCctModule.mFlags &= ~STF_WALK_EXPERIMENT;
// store new touched actor/shape. Then set new actor/shape to avoid register/unregister for same objects
const PxRigidActor* touchedActor = NULL;
const PxShape* touchedShape = NULL;
PxExtendedVec3 Backup = volume.mCenter;
collisionFlags = mCctModule.moveCharacter(&findGeomData, &userHitData, volume, disp, userObstacles, minDist, filters, constrainedClimbingMode, standingOnMoving, touchedActor, touchedShape, getContextId());
if(mCctModule.mFlags & STF_HIT_NON_WALKABLE)
{
// A bit slow, but everything else I tried was less convincing...
mCctModule.mFlags |= STF_WALK_EXPERIMENT;
volume.mCenter = Backup;
PxVec3 xpDisp;
if(mUserParams.mNonWalkableMode==PxControllerNonWalkableMode::ePREVENT_CLIMBING_AND_FORCE_SLIDING)
{
PxVec3 tangent_compo;
decomposeVector(xpDisp, tangent_compo, disp, upDirection);
}
else xpDisp = disp;
collisionFlags = mCctModule.moveCharacter(&findGeomData, &userHitData, volume, xpDisp, userObstacles, minDist, filters, constrainedClimbingMode, standingOnMoving, touchedActor, touchedShape, getContextId());
mCctModule.mFlags &= ~STF_WALK_EXPERIMENT;
}
mCctModule.mTouchedActor = touchedActor;
mCctModule.mTouchedShape = touchedShape;
mCollisionFlags = collisionFlags;
// Copy results back
mPosition = volume.mCenter;
// Update kinematic actor
if(mKineActor)
{
const PxVec3 delta = diff(Backup, volume.mCenter);
const PxF32 deltaM2 = delta.magnitudeSquared();
if(deltaM2!=0.0f)
{
PxTransform targetPose = mKineActor->getGlobalPose();
targetPose.p = toVec3(mPosition);
targetPose.q = mUserParams.mQuatFromUp;
mKineActor->setKinematicTarget(targetPose);
}
}
mManager->resetObstaclesBuffers();
if (lockWrite)
mWriteLock.unlock();
return collisionFlags;
}
PxControllerCollisionFlags BoxController::move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles)
{
PX_PROFILE_ZONE("CharacterController.move", getContextId());
PX_SIMD_GUARD;
// Create internal swept box
SweptBox sweptBox;
sweptBox.mCenter = mPosition;
sweptBox.mExtents = PxVec3(mHalfHeight, mHalfSideExtent, mHalfForwardExtent);
sweptBox.mHalfHeight = mHalfHeight; // UBI
return Controller::move(sweptBox, disp, minDist, elapsedTime, filters, obstacles, false);
}
PxControllerCollisionFlags CapsuleController::move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles)
{
PX_PROFILE_ZONE("CharacterController.move", getContextId());
PX_SIMD_GUARD;
// Create internal swept capsule
SweptCapsule sweptCapsule;
sweptCapsule.mCenter = mPosition;
sweptCapsule.mRadius = mRadius;
sweptCapsule.mHeight = mHeight;
sweptCapsule.mHalfHeight = mHeight*0.5f + mRadius; // UBI
return Controller::move(sweptCapsule, disp, minDist, elapsedTime, filters, obstacles, mClimbingMode==PxCapsuleClimbingMode::eCONSTRAINED);
}
| 97,143 | C++ | 36.035456 | 234 | 0.728833 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctController.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/PxMathUtils.h"
#include "extensions/PxRigidBodyExt.h"
#include "characterkinematic/PxController.h"
#include "PxPhysics.h"
#include "PxScene.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "CctController.h"
#include "CctBoxController.h"
#include "CctCharacterControllerManager.h"
#include "foundation/PxUtilities.h"
using namespace physx;
using namespace Cct;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Controller::Controller(const PxControllerDesc& desc, PxScene* s) :
mCctModule (desc.registerDeletionListener),
mScene (s),
mPreviousSceneTimestamp (0xffffffff),
mGlobalTime (0.0),
mPreviousGlobalTime (0.0),
mProxyDensity (0.0f),
mProxyScaleCoeff (0.0f),
mCollisionFlags (0),
mCachedStandingOnMoving (false),
mManager (NULL)
{
mType = PxControllerShapeType::eFORCE_DWORD;
mUserParams.mNonWalkableMode = desc.nonWalkableMode;
mUserParams.mSlopeLimit = desc.slopeLimit;
mUserParams.mContactOffset = desc.contactOffset;
mUserParams.mStepOffset = desc.stepOffset;
mUserParams.mInvisibleWallHeight = desc.invisibleWallHeight;
mUserParams.mMaxJumpHeight = desc.maxJumpHeight;
mUserParams.mHandleSlope = desc.slopeLimit!=0.0f;
mReportCallback = desc.reportCallback;
mBehaviorCallback = desc.behaviorCallback;
mUserData = desc.userData;
mKineActor = NULL;
mPosition = desc.position;
mProxyDensity = desc.density;
mProxyScaleCoeff = desc.scaleCoeff;
mCctModule.mVolumeGrowth = desc.volumeGrowth;
mRegisterDeletionListener = desc.registerDeletionListener;
mDeltaXP = PxVec3(0);
mOverlapRecover = PxVec3(0);
mUserParams.mUpDirection = PxVec3(0.0f);
setUpDirectionInternal(desc.upDirection);
}
Controller::~Controller()
{
if(mScene)
{
if(mKineActor)
mKineActor->release();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::onRelease(const PxBase& observed)
{
mCctModule.onRelease(observed);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::onOriginShift(const PxVec3& shift)
{
sub(mPosition, shift);
if(mManager && mManager->mLockingEnabled)
mWriteLock.lock();
mCctModule.onOriginShift(shift);
if(mManager && mManager->mLockingEnabled)
mWriteLock.unlock();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::setUpDirectionInternal(const PxVec3& up)
{
PX_CHECK_MSG(up.isNormalized(), "CCT: up direction must be normalized");
if(mUserParams.mUpDirection==up)
return;
const PxQuat q = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), up);
mUserParams.mQuatFromUp = q;
mUserParams.mUpDirection = up;
// Update kinematic actor
/*if(mKineActor)
{
PxTransform pose = mKineActor->getGlobalPose();
pose.q = q;
mKineActor->setGlobalPose(pose);
}*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::releaseInternal()
{
mManager->releaseController(*getPxController());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::getInternalState(PxControllerState& state) const
{
if(mManager->mLockingEnabled)
mWriteLock.lock();
state.deltaXP = mDeltaXP;
state.touchedShape = const_cast<PxShape*>(mCctModule.mTouchedShape.get());
state.touchedActor = const_cast<PxRigidActor*>(mCctModule.mTouchedActor.get());
state.touchedObstacleHandle = mCctModule.mTouchedObstacleHandle;
state.standOnAnotherCCT = (mCctModule.mFlags & STF_TOUCH_OTHER_CCT)!=0;
state.standOnObstacle = (mCctModule.mFlags & STF_TOUCH_OBSTACLE)!=0;
state.isMovingUp = (mCctModule.mFlags & STF_IS_MOVING_UP)!=0;
state.collisionFlags = mCollisionFlags;
if(mManager->mLockingEnabled)
mWriteLock.unlock();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Controller::getInternalStats(PxControllerStats& stats) const
{
stats.nbFullUpdates = mCctModule.mNbFullUpdates;
stats.nbPartialUpdates = mCctModule.mNbPartialUpdates;
stats.nbIterations = mCctModule.mNbIterations;
stats.nbTessellation = mCctModule.mNbTessellation;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Controller::setPos(const PxExtendedVec3& pos)
{
mPosition = pos;
// Update kinematic actor
if(mKineActor)
{
PxTransform targetPose = mKineActor->getGlobalPose();
targetPose.p = toVec3(mPosition); // LOSS OF ACCURACY
targetPose.q = mUserParams.mQuatFromUp;
mKineActor->setKinematicTarget(targetPose);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Controller::createProxyActor(PxPhysics& sdk, const PxGeometry& geometry, const PxMaterial& material, PxClientID clientID)
{
// PT: we don't disable raycasting or CD because:
// - raycasting is needed for visibility queries (the SDK otherwise doesn't know about the CCTS)
// - collision is needed because the only reason we create actors there is to handle collisions with dynamic shapes
// So it's actually wrong to disable any of those.
PxTransform globalPose;
globalPose.p = toVec3(mPosition); // LOSS OF ACCURACY
globalPose.q = mUserParams.mQuatFromUp;
mKineActor = sdk.createRigidDynamic(globalPose);
if(!mKineActor)
return false;
PxShape* shape = sdk.createShape(geometry, material, true);
mKineActor->attachShape(*shape);
shape->release();
mKineActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true);
PxRigidBodyExt::updateMassAndInertia(*mKineActor, mProxyDensity);
if(clientID!=PX_DEFAULT_CLIENT)
mKineActor->setOwnerClient(clientID);
mScene->addActor(*mKineActor);
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxShape* Controller::getKineShape() const
{
// PT: TODO: cache this and avoid the virtual call
PxShape* shape = NULL;
PxU32 nb = mKineActor->getShapes(&shape, 1);
PX_ASSERT(nb==1);
PX_UNUSED(nb);
return shape;
}
| 8,960 | C++ | 36.493724 | 199 | 0.585491 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCharacterController.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 CCT_CHARACTER_CONTROLLER
#define CCT_CHARACTER_CONTROLLER
//#define USE_CONTACT_NORMAL_FOR_SLOPE_TEST
#include "geometry/PxTriangle.h"
#include "foundation/PxHashSet.h"
#include "characterkinematic/PxController.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "CctCharacterControllerManager.h"
#include "CctUtils.h"
#include "foundation/PxArray.h"
namespace physx
{
struct PxFilterData;
class PxQueryFilterCallback;
class PxObstacle;
class RenderBuffer;
namespace Cct
{
struct CCTParams
{
CCTParams();
PxControllerNonWalkableMode::Enum mNonWalkableMode;
PxQuat mQuatFromUp;
PxVec3 mUpDirection;
PxF32 mSlopeLimit;
PxF32 mContactOffset;
PxF32 mStepOffset;
PxF32 mInvisibleWallHeight;
PxF32 mMaxJumpHeight;
PxF32 mMaxEdgeLength2;
bool mTessellation;
bool mHandleSlope; // True to handle walkable parts according to slope
bool mOverlapRecovery;
bool mPreciseSweeps;
bool mPreventVerticalSlidingAgainstCeiling;
};
// typedef PxArray<PxTriangle> TriArray;
typedef PxArray<PxU32> IntArray;
// PT: using private inheritance to control access, and make sure allocations are SIMD friendly
class TriArray : private PxArray<PxTriangle>
{
public:
PX_FORCE_INLINE PxTriangle* reserve(PxU32 nbTris)
{
// PT: customized version of "reserveContainerMemory"
const PxU32 maxNbEntries = PxArray<PxTriangle>::capacity();
const PxU32 realRequiredSize = PxArray<PxTriangle>::size() + nbTris;
// PT: allocate one more tri to make sure we can safely V4Load the last one...
const PxU32 requiredSize = realRequiredSize + 1;
if(requiredSize>maxNbEntries)
{
// PT: ok so the commented out growing policy was introduced by PX-837 but it produces
// large memory usage regressions (see PX-881) while not actually making things run
// faster. Our benchmarks show no performance difference, but up to +38% more memory
// used with this "standard" growing policy. So for now we just go back to the initial
// growing policy. It should be fine since PX-837 was not actually reported by a customer,
// it was just a concern that appeared while looking at the code. Ideally we'd use a pool
// with fixed-size slabs to get the best of both worlds but it would make iterating over
// triangles more complicated and would need more refactoring. So for now we don't bother,
// but we'll keep this note here for the next time this problem shows up.
// PT: new August 2018: turns out PX-837 was correct. Not doing this produces very large
// performance problems (like: the app freezes!) in SampleCCT. We didn't see it because
// it's an internal sample that it rarely used these days...
const PxU32 naturalGrowthSize = maxNbEntries ? maxNbEntries*2 : 2;
const PxU32 newSize = PxMax(requiredSize, naturalGrowthSize);
// const PxU32 newSize = requiredSize;
PxArray<PxTriangle>::reserve(newSize);
}
PxTriangle* buf = PxArray<PxTriangle>::end();
// ...but we still want the size to reflect the correct number
PxArray<PxTriangle>::forceSize_Unsafe(realRequiredSize);
return buf;
}
PX_FORCE_INLINE void pushBack(const PxTriangle& tri)
{
PxTriangle* memory = reserve(1);
memory->verts[0] = tri.verts[0];
memory->verts[1] = tri.verts[1];
memory->verts[2] = tri.verts[2];
}
PX_FORCE_INLINE PxU32 size() const
{
return PxArray<PxTriangle>::size();
}
PX_FORCE_INLINE const PxTriangle* begin() const
{
return PxArray<PxTriangle>::begin();
}
PX_FORCE_INLINE void clear()
{
PxArray<PxTriangle>::clear();
}
PX_FORCE_INLINE void forceSize_Unsafe(PxU32 size)
{
PxArray<PxTriangle>::forceSize_Unsafe(size);
}
PX_FORCE_INLINE const PxTriangle& getTriangle(PxU32 index) const
{
return (*this)[index];
}
};
/* Exclude from documentation */
/** \cond */
struct TouchedGeomType
{
enum Enum
{
eUSER_BOX,
eUSER_CAPSULE,
eMESH,
eBOX,
eSPHERE,
eCAPSULE,
eCUSTOM,
eLAST,
eFORCE_DWORD = 0x7fffffff
};
};
class SweptVolume;
struct TouchedGeom
{
TouchedGeomType::Enum mType;
const void* mTGUserData; // PxController or PxShape pointer
const PxRigidActor* mActor; // PxActor for PxShape pointers (mandatory with shared shapes)
PxExtendedVec3 mOffset; // Local origin, typically the center of the world bounds around the character. We translate both
// touched shapes & the character so that they are nearby this PxVec3, then add the offset back to
// computed "world" impacts.
protected:
~TouchedGeom(){}
};
struct TouchedUserBox : public TouchedGeom
{
PxExtendedBox mBox;
};
PX_COMPILE_TIME_ASSERT(sizeof(TouchedUserBox)==sizeof(TouchedGeom)+sizeof(PxExtendedBox));
struct TouchedUserCapsule : public TouchedGeom
{
PxExtendedCapsule mCapsule;
};
PX_COMPILE_TIME_ASSERT(sizeof(TouchedUserCapsule)==sizeof(TouchedGeom)+sizeof(PxExtendedCapsule));
struct TouchedMesh : public TouchedGeom
{
PxU32 mNbTris;
PxU32 mIndexWorldTriangles;
};
struct TouchedBox : public TouchedGeom
{
PxVec3 mCenter;
PxVec3 mExtents;
PxQuat mRot;
};
struct TouchedSphere : public TouchedGeom
{
PxVec3 mCenter; //!< Sphere's center
PxF32 mRadius; //!< Sphere's radius
};
struct TouchedCustom : public TouchedGeom
{
PxVec3 mCenter; //!< Custom geometry's center
PxCustomGeometry::Callbacks* mCustomCallbacks; //!< Custom geometry's callback object
};
struct TouchedCapsule : public TouchedGeom
{
PxVec3 mP0; //!< Start of segment
PxVec3 mP1; //!< End of segment
PxF32 mRadius; //!< Capsule's radius
};
struct SweptContact
{
PxExtendedVec3 mWorldPos; // Contact position in world space
PxVec3 mWorldNormal; // Contact normal in world space
PxF32 mDistance; // Contact distance
PxU32 mInternalIndex; // Reserved for internal usage
PxU32 mTriangleIndex; // Triangle index for meshes/heightfields
TouchedGeom* mGeom;
PX_FORCE_INLINE void setWorldPos(const PxVec3& localImpact, const PxExtendedVec3& offset)
{
mWorldPos.x = PxExtended(localImpact.x) + offset.x;
mWorldPos.y = PxExtended(localImpact.y) + offset.y;
mWorldPos.z = PxExtended(localImpact.z) + offset.z;
}
};
// PT: user-defined obstacles. Note that "user" is from the SweepTest class' point of view,
// i.e. the PhysX CCT module is the user in this case. This is to limit coupling between the
// core CCT module and the PhysX classes.
struct UserObstacles// : PxObstacleContext
{
PxU32 mNbBoxes;
const PxExtendedBox* mBoxes;
const void** mBoxUserData;
PxU32 mNbCapsules;
const PxExtendedCapsule* mCapsules;
const void** mCapsuleUserData;
};
struct InternalCBData_OnHit{};
struct InternalCBData_FindTouchedGeom{};
enum SweepTestFlag
{
STF_HIT_NON_WALKABLE = (1<<0),
STF_WALK_EXPERIMENT = (1<<1),
STF_VALIDATE_TRIANGLE_DOWN = (1<<2), // Validate touched triangle data (down pass)
STF_VALIDATE_TRIANGLE_SIDE = (1<<3), // Validate touched triangle data (side pass)
STF_TOUCH_OTHER_CCT = (1<<4), // Are we standing on another CCT or not? (only updated for down pass)
STF_TOUCH_OBSTACLE = (1<<5), // Are we standing on an obstacle or not? (only updated for down pass)
STF_NORMALIZE_RESPONSE = (1<<6),
STF_FIRST_UPDATE = (1<<7),
STF_IS_MOVING_UP = (1<<8)
};
enum SweepPass
{
SWEEP_PASS_UP,
SWEEP_PASS_SIDE,
SWEEP_PASS_DOWN,
SWEEP_PASS_SENSOR
};
class Controller;
template<class T>
struct TouchedObject
{
TouchedObject(bool regDl)
: mTouchedObject(NULL), mRegisterDeletionListener(regDl), mCctManager(NULL)
{
}
PX_FORCE_INLINE const T* operator->() const { return mTouchedObject; }
PX_FORCE_INLINE bool operator==(const TouchedObject& otherObject) { return mTouchedObject == otherObject.mTouchedObject; }
PX_FORCE_INLINE bool operator==(const T* otherObject) { return mTouchedObject == otherObject; }
PX_FORCE_INLINE bool operator==(const PxBase* otherObject) { return mTouchedObject == otherObject; }
PX_FORCE_INLINE operator bool() const { return mTouchedObject != NULL; }
PX_FORCE_INLINE TouchedObject& operator=(const T* assignedObject)
{
if(mRegisterDeletionListener && (mTouchedObject != assignedObject))
{
if(mTouchedObject)
mCctManager->unregisterObservedObject(mTouchedObject);
if(assignedObject)
mCctManager->registerObservedObject(assignedObject);
}
mTouchedObject = assignedObject;
return *this;
}
const T* get() const { return mTouchedObject; }
void setCctManager(CharacterControllerManager* cm) { mCctManager = cm; }
private:
TouchedObject& operator=(const TouchedObject&);
const T* mTouchedObject;
bool mRegisterDeletionListener;
CharacterControllerManager* mCctManager;
};
class SweepTest
{
public:
SweepTest(bool registerDeletionListener);
~SweepTest();
PxControllerCollisionFlags moveCharacter( const InternalCBData_FindTouchedGeom* userData,
InternalCBData_OnHit* user_data2,
SweptVolume& volume,
const PxVec3& direction,
const UserObstacles& userObstacles,
PxF32 min_dist,
const PxControllerFilters& filters,
bool constrainedClimbingMode,
bool standingOnMoving,
const PxRigidActor*& touchedActor,
const PxShape*& touchedShape,
PxU64 contextID);
bool doSweepTest(const InternalCBData_FindTouchedGeom* userDataTouchedGeom,
InternalCBData_OnHit* userDataOnHit,
const UserObstacles& userObstacles,
SweptVolume& swept_volume,
const PxVec3& direction, const PxVec3& sideVector, PxU32 max_iter,
PxU32* nb_collisions, PxF32 min_dist, const PxControllerFilters& filters, SweepPass sweepPass,
const PxRigidActor*& touchedActor, const PxShape*& touchedShape, PxU64 contextID);
void findTouchedObstacles(const UserObstacles& userObstacles, const PxExtendedBounds3& world_box);
void voidTestCache();
void onRelease(const PxBase& observed);
void updateCachedShapesRegistration(PxU32 startIndex, bool unregister);
// observer notifications
void onObstacleRemoved(PxObstacleHandle index);
void onObstacleUpdated(PxObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance);
void onObstacleAdded(PxObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance);
void onOriginShift(const PxVec3& shift);
PxRenderBuffer* mRenderBuffer;
PxU32 mRenderFlags;
TriArray mWorldTriangles;
IntArray mTriangleIndices;
IntArray mGeomStream;
PxExtendedBounds3 mCacheBounds;
PxU32 mCachedTriIndexIndex;
mutable PxU32 mCachedTriIndex[3];
PxU32 mNbCachedStatic;
PxU32 mNbCachedT;
public:
#ifdef USE_CONTACT_NORMAL_FOR_SLOPE_TEST
PxVec3 mContactNormalDownPass;
#else
PxVec3 mContactNormalDownPass;
PxVec3 mContactNormalSidePass;
float mTouchedTriMin;
float mTouchedTriMax;
//PxTriangle mTouchedTriangle;
#endif
//
TouchedObject<PxShape> mTouchedShape; // Shape on which the CCT is standing
TouchedObject<PxRigidActor> mTouchedActor; // Actor from touched shape
PxObstacleHandle mTouchedObstacleHandle; // Obstacle on which the CCT is standing
PxVec3 mTouchedPos; // Last known position of mTouchedShape/mTouchedObstacle
// PT: TODO: union those
PxVec3 mTouchedPosShape_Local;
PxVec3 mTouchedPosShape_World;
PxVec3 mTouchedPosObstacle_Local;
PxVec3 mTouchedPosObstacle_World;
//
CCTParams mUserParams;
PxF32 mVolumeGrowth; // Must be >1.0f and not too big
PxF32 mContactPointHeight; // UBI
PxU32 mSQTimeStamp;
PxU16 mNbFullUpdates;
PxU16 mNbPartialUpdates;
PxU16 mNbTessellation;
PxU16 mNbIterations;
PxU32 mFlags;
bool mRegisterDeletionListener;
PX_FORCE_INLINE void resetStats()
{
mNbFullUpdates = 0;
mNbPartialUpdates = 0;
mNbTessellation = 0;
mNbIterations = 0;
}
void setCctManager(CharacterControllerManager* cm)
{
mCctManager = cm;
mTouchedActor.setCctManager(cm);
mTouchedShape.setCctManager(cm);
}
private:
void updateTouchedGeoms( const InternalCBData_FindTouchedGeom* userData, const UserObstacles& userObstacles,
const PxExtendedBounds3& worldBox, const PxControllerFilters& filters, const PxVec3& sideVector);
CharacterControllerManager* mCctManager;
SweepTest(const SweepTest&);
SweepTest& operator=(const SweepTest& );
};
class CCTFilter // PT: internal filter data, could be replaced with PxControllerFilters eventually
{
public:
PX_FORCE_INLINE CCTFilter() :
mFilterData (NULL),
mFilterCallback (NULL),
mStaticShapes (false),
mDynamicShapes (false),
mPreFilter (false),
mPostFilter (false),
mCCTShapes (NULL)
{
}
const PxFilterData* mFilterData;
PxQueryFilterCallback* mFilterCallback;
bool mStaticShapes;
bool mDynamicShapes;
bool mPreFilter;
bool mPostFilter;
PxHashSet<PxShape>* mCCTShapes;
};
PxU32 getSceneTimestamp(const InternalCBData_FindTouchedGeom* userData);
void findTouchedGeometry(const InternalCBData_FindTouchedGeom* userData,
const PxExtendedBounds3& world_aabb,
TriArray& world_triangles,
IntArray& triIndicesArray,
IntArray& geomStream,
const CCTFilter& filter,
const CCTParams& params,
PxU16& nbTessellation);
PxU32 shapeHitCallback(const InternalCBData_OnHit* userData, const SweptContact& contact, const PxVec3& dir, PxF32 length);
PxU32 userHitCallback(const InternalCBData_OnHit* userData, const SweptContact& contact, const PxVec3& dir, PxF32 length);
} // namespace Cct
}
/** \endcond */
#endif
| 15,946 | C | 32.502101 | 157 | 0.709206 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCharacterControllerManager.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 CCT_CHARACTER_CONTROLLER_MANAGER
#define CCT_CHARACTER_CONTROLLER_MANAGER
//Exclude file from docs
/** \cond */
#include "geometry/PxMeshQuery.h"
#include "common/PxRenderBuffer.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxHashMap.h"
#include "characterkinematic/PxControllerManager.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "PxDeletionListener.h"
#include "CctUtils.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Cct
{
class Controller;
class ObstacleContext;
struct ObservedRefCounter
{
ObservedRefCounter(): refCount(0)
{
}
PxU32 refCount;
};
typedef PxHashMap<const PxBase*, ObservedRefCounter> ObservedRefCountMap;
//Implements the PxControllerManager interface, this class used to be called ControllerManager
class CharacterControllerManager : public PxControllerManager, public PxUserAllocated, public PxDeletionListener
{
public:
CharacterControllerManager(PxScene& scene, bool lockingEnabled = false);
private:
virtual ~CharacterControllerManager();
public:
// PxControllerManager
virtual void release() PX_OVERRIDE;
virtual PxScene& getScene() const PX_OVERRIDE;
virtual PxU32 getNbControllers() const PX_OVERRIDE;
virtual PxController* getController(PxU32 index) PX_OVERRIDE;
virtual PxController* createController(const PxControllerDesc& desc) PX_OVERRIDE;
virtual void purgeControllers() PX_OVERRIDE;
virtual PxRenderBuffer& getRenderBuffer() PX_OVERRIDE;
virtual void setDebugRenderingFlags(PxControllerDebugRenderFlags flags) PX_OVERRIDE;
virtual PxU32 getNbObstacleContexts() const PX_OVERRIDE;
virtual PxObstacleContext* getObstacleContext(PxU32 index) PX_OVERRIDE;
virtual PxObstacleContext* createObstacleContext() PX_OVERRIDE;
virtual void computeInteractions(PxF32 elapsedTime, PxControllerFilterCallback* cctFilterCb) PX_OVERRIDE;
virtual void setTessellation(bool flag, float maxEdgeLength) PX_OVERRIDE;
virtual void setOverlapRecoveryModule(bool flag) PX_OVERRIDE;
virtual void setPreciseSweeps(bool flag) PX_OVERRIDE;
virtual void setPreventVerticalSlidingAgainstCeiling(bool flag) PX_OVERRIDE;
virtual void shiftOrigin(const PxVec3& shift) PX_OVERRIDE;
//~PxControllerManager
// PxDeletionListener
virtual void onRelease(const PxBase* observed, void* userData, PxDeletionEventFlag::Enum deletionEvent) PX_OVERRIDE;
//~PxDeletionListener
void registerObservedObject(const PxBase* obj);
void unregisterObservedObject(const PxBase* obj);
// ObstacleContextNotifications
void onObstacleRemoved(PxObstacleHandle index) const;
void onObstacleUpdated(PxObstacleHandle index, const PxObstacleContext* ) const;
void onObstacleAdded(PxObstacleHandle index, const PxObstacleContext*) const;
void releaseController(PxController& controller);
Controller** getControllers();
void releaseObstacleContext(ObstacleContext& oc);
void resetObstaclesBuffers();
PxScene& mScene;
PxRenderBuffer* mRenderBuffer;
PxControllerDebugRenderFlags mDebugRenderingFlags;
// Shared buffers for obstacles
PxArray<const void*> mBoxUserData;
PxArray<PxExtendedBox> mBoxes;
PxArray<const void*> mCapsuleUserData;
PxArray<PxExtendedCapsule> mCapsules;
PxArray<Controller*> mControllers;
PxHashSet<PxShape*> mCCTShapes;
PxArray<ObstacleContext*> mObstacleContexts;
float mMaxEdgeLength;
bool mTessellation;
bool mOverlapRecovery;
bool mPreciseSweeps;
bool mPreventVerticalSlidingAgainstCeiling;
bool mLockingEnabled;
protected:
CharacterControllerManager &operator=(const CharacterControllerManager &);
CharacterControllerManager(const CharacterControllerManager& );
private:
ObservedRefCountMap mObservedRefCountMap;
mutable PxMutex mWriteLock; // Lock used for guarding pointers in observedrefcountmap
};
} // namespace Cct
}
/** \endcond */
#endif //CCT_CHARACTER_CONTROLLER_MANAGER
| 6,066 | C | 39.178808 | 126 | 0.739862 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCapsuleController.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxCapsuleGeometry.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "characterkinematic/PxController.h"
#include "CctCapsuleController.h"
#include "CctCharacterControllerManager.h"
using namespace physx;
using namespace Cct;
static PX_FORCE_INLINE float CCTtoProxyRadius(float r, PxF32 coeff) { return r * coeff; }
static PX_FORCE_INLINE float CCTtoProxyHeight(float h, PxF32 coeff) { return 0.5f * h * coeff; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CapsuleController::CapsuleController(const PxControllerDesc& desc, PxPhysics& sdk, PxScene* s) : Controller(desc, s)
{
mType = PxControllerShapeType::eCAPSULE;
const PxCapsuleControllerDesc& cc = static_cast<const PxCapsuleControllerDesc&>(desc);
mRadius = cc.radius;
mHeight = cc.height;
mClimbingMode = cc.climbingMode;
// Create kinematic actor under the hood
PxCapsuleGeometry capsGeom;
capsGeom.radius = CCTtoProxyRadius(cc.radius, mProxyScaleCoeff);
capsGeom.halfHeight = CCTtoProxyHeight(cc.height, mProxyScaleCoeff);
createProxyActor(sdk, capsGeom, *desc.material, desc.clientID);
}
CapsuleController::~CapsuleController()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CapsuleController::invalidateCache()
{
if(mManager->mLockingEnabled)
mWriteLock.lock();
mCctModule.voidTestCache();
if(mManager->mLockingEnabled)
mWriteLock.unlock();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CapsuleController::getWorldBox(PxExtendedBounds3& box) const
{
setCenterExtents(box, mPosition, PxVec3(mRadius, mRadius+mHeight*0.5f, mRadius));
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CapsuleController::setRadius(PxF32 r)
{
// Set radius for CCT volume
mRadius = r;
// Set radius for kinematic proxy
if(mKineActor)
{
PxShape* shape = getKineShape();
const PxGeometry& geom = shape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eCAPSULE);
PxCapsuleGeometry cg = static_cast<const PxCapsuleGeometry&>(geom);
cg.radius = CCTtoProxyRadius(r, mProxyScaleCoeff);
shape->setGeometry(cg);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CapsuleController::setHeight(PxF32 h)
{
// Set height for CCT volume
mHeight = h;
// Set height for kinematic proxy
if(mKineActor)
{
PxShape* shape = getKineShape();
const PxGeometry& geom = shape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eCAPSULE);
PxCapsuleGeometry cg = static_cast<const PxCapsuleGeometry&>(geom);
cg.halfHeight = CCTtoProxyHeight(h, mProxyScaleCoeff);
shape->setGeometry(cg);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxCapsuleClimbingMode::Enum CapsuleController::getClimbingMode() const
{
return mClimbingMode;
}
bool CapsuleController::setClimbingMode(PxCapsuleClimbingMode::Enum mode)
{
if(mode>=PxCapsuleClimbingMode::eLAST)
return false;
mClimbingMode = mode;
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxExtendedVec3 CapsuleController::getFootPosition() const
{
PxExtendedVec3 groundPosition = mPosition; // Middle of the CCT
sub(groundPosition, mUserParams.mUpDirection * (mUserParams.mContactOffset+mRadius+mHeight*0.5f)); // Ground
return groundPosition;
}
bool CapsuleController::setFootPosition(const PxExtendedVec3& position)
{
PxExtendedVec3 centerPosition = position;
add(centerPosition, mUserParams.mUpDirection * (mUserParams.mContactOffset+mRadius+mHeight*0.5f));
return setPosition(centerPosition);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CapsuleController::getCapsule(PxExtendedCapsule& capsule) const
{
// PT: TODO: optimize this
PxExtendedVec3 p0 = mPosition;
PxExtendedVec3 p1 = mPosition;
const PxVec3 extents = mUserParams.mUpDirection*mHeight*0.5f;
sub(p0, extents);
add(p1, extents);
capsule.p0 = p0;
capsule.p1 = p1;
capsule.radius = mRadius;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CapsuleController::resize(PxReal height)
{
const float oldHeight = getHeight();
setHeight(height);
const float delta = height - oldHeight;
PxExtendedVec3 pos = getPosition();
add(pos, mUserParams.mUpDirection * delta * 0.5f);
setPosition(pos);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 7,474 | C++ | 37.932291 | 199 | 0.556998 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctUtils.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 CCT_UTILS
#define CCT_UTILS
#include "extensions/PxShapeExt.h"
#include "characterkinematic/PxExtended.h"
namespace physx
{
PX_FORCE_INLINE bool testSlope(const PxVec3& normal, const PxVec3& upDirection, PxF32 slopeLimit)
{
const float dp = normal.dot(upDirection);
return dp>=0.0f && dp<slopeLimit;
}
PX_INLINE PxTransform getShapeGlobalPose(const PxShape& shape, const PxRigidActor& actor)
{
return PxShapeExt::getGlobalPose(shape, actor);
}
PX_INLINE void decomposeVector(PxVec3& normalCompo, PxVec3& tangentCompo, const PxVec3& outwardDir,
const PxVec3& outwardNormal)
{
normalCompo = outwardNormal * (outwardDir.dot(outwardNormal));
tangentCompo = outwardDir - normalCompo;
}
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;
}
#ifdef PX_BIG_WORLDS
PX_INLINE void add(PxExtendedVec3& p, const PxVec3& e)
{
p += PxExtendedVec3(PxExtended(e.x), PxExtended(e.y), PxExtended(e.z));
}
PX_INLINE void sub(PxExtendedVec3& p, const PxVec3& e)
{
p -= PxExtendedVec3(PxExtended(e.x), PxExtended(e.y), PxExtended(e.z));
}
PX_INLINE PxExtended dot(const PxExtendedVec3& p, const PxVec3& e)
{
return p.dot(PxExtendedVec3(PxExtended(e.x), PxExtended(e.y), PxExtended(e.z)));
}
class PxExtendedBox
{
public:
PX_INLINE PxExtendedBox() {}
PX_INLINE PxExtendedBox(const PxExtendedVec3& _center, const PxVec3& _extents, const PxQuat& _rot) : center(_center), extents(_extents), rot(_rot){}
PX_INLINE ~PxExtendedBox() {}
PxExtendedVec3 center;
PxVec3 extents;
PxQuat rot;
};
class PxExtendedSphere
{
public:
PX_INLINE PxExtendedSphere() {}
PX_INLINE ~PxExtendedSphere() {}
PX_INLINE PxExtendedSphere(const PxExtendedVec3& _center, PxF32 _radius) : center(_center), radius(_radius) {}
PX_INLINE PxExtendedSphere(const PxExtendedSphere& sphere) : center(sphere.center), radius(sphere.radius) {}
PxExtendedVec3 center; //!< Sphere's center
PxF32 radius; //!< Sphere's radius
};
struct PxExtendedSegment
{
PX_INLINE const PxExtendedVec3& getOrigin() const
{
return p0;
}
PX_INLINE void computeDirection(PxVec3& dir) const
{
dir = diff(p1, p0);
}
PX_INLINE void computePoint(PxExtendedVec3& pt, PxExtended t) const
{
pt.x = p0.x + t * (p1.x - p0.x);
pt.y = p0.y + t * (p1.y - p0.y);
pt.z = p0.z + t * (p1.z - p0.z);
}
PxExtendedVec3 p0; //!< Start of segment
PxExtendedVec3 p1; //!< End of segment
};
struct PxExtendedCapsule : public PxExtendedSegment
{
PxReal radius;
};
struct PxExtendedBounds3
{
PX_INLINE PxExtendedBounds3()
{
}
PX_INLINE void setEmpty()
{
// We now use this particular pattern for empty boxes
set(PX_MAX_EXTENDED, PX_MAX_EXTENDED, PX_MAX_EXTENDED,
-PX_MAX_EXTENDED, -PX_MAX_EXTENDED, -PX_MAX_EXTENDED);
}
PX_INLINE void set(PxExtended minx, PxExtended miny, PxExtended minz, PxExtended maxx, PxExtended maxy, PxExtended maxz)
{
minimum = PxExtendedVec3(minx, miny, minz);
maximum = PxExtendedVec3(maxx, maxy, maxz);
}
PX_INLINE bool isInside(const PxExtendedBounds3& box) const
{
if(box.minimum.x > minimum.x) return false;
if(box.minimum.y > minimum.y) return false;
if(box.minimum.z > minimum.z) return false;
if(box.maximum.x < maximum.x) return false;
if(box.maximum.y < maximum.y) return false;
if(box.maximum.z < maximum.z) return false;
return true;
}
PxExtendedVec3 minimum, maximum;
};
PX_INLINE void getCenter(const PxExtendedBounds3& b, PxExtendedVec3& center)
{
center = b.minimum + b.maximum;
center *= 0.5;
}
PX_INLINE void getExtents(const PxExtendedBounds3& b, PxVec3& extents)
{
extents = diff(b.maximum, b.minimum);
extents *= 0.5f;
}
PX_INLINE void setCenterExtents(PxExtendedBounds3& b, const PxExtendedVec3& c, const PxVec3& e)
{
const PxExtendedVec3 eExt(PxExtended(e.x), PxExtended(e.y), PxExtended(e.z));
b.minimum = c - eExt;
b.maximum = c + eExt;
}
PX_INLINE void add(PxExtendedBounds3& b, const PxExtendedBounds3& b2)
{
// - if we're empty, minimum = MAX,MAX,MAX => minimum will be b2 in all cases => it will copy b2, ok
// - if b2 is empty, the opposite happens => keep us unchanged => ok
// => same behaviour as before, automatically
b.minimum = b.minimum.minimum(b2.minimum);
b.maximum = b.maximum.maximum(b2.maximum);
}
#else
#include "foundation/PxBounds3.h"
#include "GuBox.h"
#include "GuCapsule.h"
#include "GuPlane.h"
typedef Gu::Box PxExtendedBox;
typedef Gu::Sphere PxExtendedSphere;
typedef Gu::Segment PxExtendedSegment;
typedef Gu::Capsule PxExtendedCapsule;
typedef PxBounds3 PxExtendedBounds3;
PX_INLINE void getCenter(const PxBounds3& b, PxVec3& center)
{
center = b.minimum + b.maximum;
center *= 0.5;
}
PX_INLINE void getExtents(const PxBounds3& b, PxVec3& extents)
{
extents = b.maximum - b.minimum;
extents *= 0.5f;
}
PX_INLINE void setCenterExtents(PxBounds3& b, const PxVec3& center, const PxVec3& extents)
{
b.minimum = center - extents;
b.maximum = center + extents;
}
PX_INLINE void add(PxBounds3& b, const PxBounds3& b2)
{
// - if we're empty, minimum = MAX,MAX,MAX => minimum will be b2 in all cases => it will copy b2, ok
// - if b2 is empty, the opposite happens => keep us unchanged => ok
// => same behaviour as before, automatically
b.minimum = b.minimum.minimum(b2.minimum);
b.maximum = b.maximum.maximum(b2.maximum);
}
#endif
}
#endif
| 7,238 | C | 29.544304 | 150 | 0.710003 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctObstacleContext.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 "CctObstacleContext.h"
#include "CctCharacterControllerManager.h"
#include "foundation/PxUtilities.h"
using namespace physx;
using namespace Cct;
//! Initial list size
#define DEFAULT_HANDLEMANAGER_SIZE 2
HandleManager::HandleManager() : mCurrentNbObjects(0), mNbFreeIndices(0)
{
mMaxNbObjects = DEFAULT_HANDLEMANAGER_SIZE;
mObjects = PX_ALLOCATE(void*, mMaxNbObjects, "HandleManager");
mOutToIn = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager");
mInToOut = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager");
mStamps = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager");
PxMemSet(mOutToIn, 0xff, mMaxNbObjects*sizeof(PxU16));
PxMemSet(mInToOut, 0xff, mMaxNbObjects*sizeof(PxU16));
PxMemZero(mStamps, mMaxNbObjects*sizeof(PxU16));
}
HandleManager::~HandleManager()
{
SetupLists();
}
bool HandleManager::SetupLists(void** objects, PxU16* oti, PxU16* ito, PxU16* stamps)
{
// Release old data
PX_FREE(mStamps);
PX_FREE(mInToOut);
PX_FREE(mOutToIn);
PX_FREE(mObjects);
// Assign new data
mObjects = objects;
mOutToIn = oti;
mInToOut = ito;
mStamps = stamps;
return true;
}
Handle HandleManager::Add(void* object)
{
// Are there any free indices I should recycle?
if(mNbFreeIndices)
{
const PxU16 FreeIndex = mInToOut[mCurrentNbObjects];// Get the recycled virtual index
mObjects[mCurrentNbObjects] = object; // The physical location is always at the end of the list (it never has holes).
mOutToIn[FreeIndex] = PxTo16(mCurrentNbObjects++); // Update virtual-to-physical remapping table.
mNbFreeIndices--;
return Handle((mStamps[FreeIndex]<<16)|FreeIndex); // Return virtual index (handle) to the client app
}
else
{
PX_ASSERT_WITH_MESSAGE(mCurrentNbObjects<0xffff ,"Internal error - 64K objects in HandleManager!");
// Is the array large enough for another entry?
if(mCurrentNbObjects==mMaxNbObjects)
{
// Nope! Resize all arrays (could be avoided with linked lists... one day)
mMaxNbObjects<<=1; // The more you eat, the more you're given
if(mMaxNbObjects>0xffff) mMaxNbObjects = 0xffff; // Clamp to 64K
void** NewList = PX_ALLOCATE(void*, mMaxNbObjects, "HandleManager"); // New physical list
PxU16* NewOTI = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager"); // New remapping table
PxU16* NewITO = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager"); // New remapping table
PxU16* NewStamps = PX_ALLOCATE(PxU16, mMaxNbObjects, "HandleManager"); // New stamps
PxMemCopy(NewList, mObjects, mCurrentNbObjects*sizeof(void*)); // Copy old data
PxMemCopy(NewOTI, mOutToIn, mCurrentNbObjects*sizeof(PxU16)); // Copy old data
PxMemCopy(NewITO, mInToOut, mCurrentNbObjects*sizeof(PxU16)); // Copy old data
PxMemCopy(NewStamps, mStamps, mCurrentNbObjects*sizeof(PxU16)); // Copy old data
PxMemSet(NewOTI+mCurrentNbObjects, 0xff, (mMaxNbObjects-mCurrentNbObjects)*sizeof(PxU16));
PxMemSet(NewITO+mCurrentNbObjects, 0xff, (mMaxNbObjects-mCurrentNbObjects)*sizeof(PxU16));
PxMemZero(NewStamps+mCurrentNbObjects, (mMaxNbObjects-mCurrentNbObjects)*sizeof(PxU16));
SetupLists(NewList, NewOTI, NewITO, NewStamps);
}
mObjects[mCurrentNbObjects] = object; // Store object at mCurrentNbObjects = physical index = virtual index
mOutToIn[mCurrentNbObjects] = PxTo16(mCurrentNbObjects); // Update virtual-to-physical remapping table.
mInToOut[mCurrentNbObjects] = PxTo16(mCurrentNbObjects); // Update physical-to-virtual remapping table.
PxU32 tmp = mCurrentNbObjects++;
return (mStamps[tmp]<<16)|tmp; // Return virtual index (handle) to the client app
}
}
void HandleManager::Remove(Handle handle)
{
const PxU16 VirtualIndex = PxU16(handle);
if(VirtualIndex>=mMaxNbObjects) return; // Invalid handle
const PxU16 PhysicalIndex = mOutToIn[VirtualIndex]; // Get the physical index
if(PhysicalIndex==0xffff) return; // Value has already been deleted
if(PhysicalIndex>=mMaxNbObjects) return; // Invalid index
// There must be at least one valid entry.
if(mCurrentNbObjects)
{
if(mStamps[VirtualIndex]!=handle>>16) return; // Stamp mismatch => index has been recycled
// Update list so that there's no hole
mObjects[PhysicalIndex] = mObjects[--mCurrentNbObjects];// Move the real object so that the array has no holes.
mOutToIn[mInToOut[mCurrentNbObjects]] = PhysicalIndex; // Update virtual-to-physical remapping table.
mInToOut[PhysicalIndex] = mInToOut[mCurrentNbObjects]; // Update physical-to-virtual remapping table.
// Keep track of the recyclable virtual index
mInToOut[mCurrentNbObjects] = VirtualIndex; // Store the free virtual index/handle at the end of mInToOut
mOutToIn[VirtualIndex] = 0xffff; // Invalidate the entry
mNbFreeIndices++; // One more free index
mStamps[VirtualIndex]++; // Update stamp
}
}
void* HandleManager::GetObject(Handle handle) const
{
const PxU16 VirtualIndex = PxU16(handle);
if(VirtualIndex>=mMaxNbObjects) return NULL; // Invalid handle
const PxU16 PhysicalIndex = mOutToIn[VirtualIndex]; // Get physical index
if(PhysicalIndex==0xffff) return NULL; // Object has been deleted
if(PhysicalIndex>=mMaxNbObjects) return NULL; // Index is invalid
if(mStamps[VirtualIndex]!=handle>>16) return NULL; // Index has been recycled
return mObjects[PhysicalIndex]; // Returns stored pointer
}
bool HandleManager::UpdateObject(Handle handle, void* object)
{
const PxU16 VirtualIndex = PxU16(handle);
if(VirtualIndex>=mMaxNbObjects) return false; // Invalid handle
const PxU16 PhysicalIndex = mOutToIn[VirtualIndex]; // Get physical index
if(PhysicalIndex==0xffff) return false; // Object has been deleted
if(PhysicalIndex>=mMaxNbObjects) return false; // Index is invalid
if(mStamps[VirtualIndex]!=handle>>16) return false; // Index has been recycled
mObjects[PhysicalIndex] = object; // Updates stored pointer
return true;
}
// PT: please do not expose these functions outside of this class,
// as we want to retain the ability to easily modify the handle format if necessary.
#define NEW_ENCODING
#ifdef NEW_ENCODING
static PX_FORCE_INLINE void* encodeInternalHandle(PxU32 index, PxGeometryType::Enum type)
{
PX_ASSERT(index<=0xffff);
PX_ASSERT(PxU32(type)<=0xffff);
// PT: we do type+1 to ban internal handles with a 0 value, since it's reserved for NULL pointers
return reinterpret_cast<void*>((size_t(index)<<16)|(size_t(type)+1));
}
static PX_FORCE_INLINE PxGeometryType::Enum decodeInternalType(void* handle)
{
return PxGeometryType::Enum((PxU32(size_t(handle)) & 0xffff)-1);
}
static PX_FORCE_INLINE PxU32 decodeInternalIndex(void* handle)
{
return (PxU32(size_t(handle)))>>16;
}
#else
static PX_FORCE_INLINE ObstacleHandle encodeHandle(PxU32 index, PxGeometryType::Enum type)
{
PX_ASSERT(index<=0xffff);
PX_ASSERT(type<=0xffff);
return (PxU16(index)<<16)|PxU32(type);
}
static PX_FORCE_INLINE PxGeometryType::Enum decodeType(ObstacleHandle handle)
{
return PxGeometryType::Enum(handle & 0xffff);
}
static PX_FORCE_INLINE PxU32 decodeIndex(ObstacleHandle handle)
{
return handle>>16;
}
#endif
ObstacleContext::ObstacleContext(CharacterControllerManager& cctMan)
: mCCTManager(cctMan)
{
}
ObstacleContext::~ObstacleContext()
{
}
void ObstacleContext::release()
{
mCCTManager.releaseObstacleContext(*this);
}
PxControllerManager& ObstacleContext::getControllerManager() const
{
return mCCTManager;
}
PxObstacleHandle ObstacleContext::addObstacle(const PxObstacle& obstacle)
{
const PxGeometryType::Enum type = obstacle.getType();
if(type==PxGeometryType::eBOX)
{
const PxU32 index = mBoxObstacles.size();
#ifdef NEW_ENCODING
const PxObstacleHandle handle = mHandleManager.Add(encodeInternalHandle(index, type));
#else
const PxObstacleHandle handle = encodeHandle(index, type);
#endif
mBoxObstacles.pushBack(InternalBoxObstacle(handle, static_cast<const PxBoxObstacle&>(obstacle)));
mCCTManager.onObstacleAdded(handle, this);
return handle;
}
else if(type==PxGeometryType::eCAPSULE)
{
const PxU32 index = mCapsuleObstacles.size();
#ifdef NEW_ENCODING
const PxObstacleHandle handle = mHandleManager.Add(encodeInternalHandle(index, type));
#else
const PxObstacleHandle handle = encodeHandle(index, type);
#endif
mCapsuleObstacles.pushBack(InternalCapsuleObstacle(handle, static_cast<const PxCapsuleObstacle&>(obstacle)));
mCCTManager.onObstacleAdded(handle, this);
return handle;
}
else return PX_INVALID_OBSTACLE_HANDLE;
}
#ifdef NEW_ENCODING
template<class T>
static PX_FORCE_INLINE void remove(HandleManager& manager, void* object, PxObstacleHandle handle, PxU32 index, PxU32 size, const PxArray<T>& obstacles)
{
manager.Remove(handle);
if(index!=size-1)
{
bool status = manager.UpdateObject(obstacles[size-1].mHandle, object);
PX_ASSERT(status);
PX_UNUSED(status);
}
}
#endif
bool ObstacleContext::removeObstacle(PxObstacleHandle handle)
{
#ifdef NEW_ENCODING
void* object = mHandleManager.GetObject(handle);
if(!object)
return false;
const PxGeometryType::Enum type = decodeInternalType(object);
const PxU32 index = decodeInternalIndex(object);
#else
const PxGeometryType::Enum type = decodeType(handle);
const PxU32 index = decodeIndex(handle);
#endif
if(type==PxGeometryType::eBOX)
{
const PxU32 size = mBoxObstacles.size();
PX_ASSERT(index<size);
if(index>=size)
return false;
#ifdef NEW_ENCODING
remove<InternalBoxObstacle>(mHandleManager, object, handle, index, size, mBoxObstacles);
#endif
mBoxObstacles.replaceWithLast(index);
#ifdef NEW_ENCODING
mCCTManager.onObstacleRemoved(handle);
#else
mCCTManager.onObstacleRemoved(handle, encodeHandle(size-1, type));
#endif
return true;
}
else if(type==PxGeometryType::eCAPSULE)
{
const PxU32 size = mCapsuleObstacles.size();
PX_ASSERT(index<size);
if(index>=size)
return false;
#ifdef NEW_ENCODING
remove<InternalCapsuleObstacle>(mHandleManager, object, handle, index, size, mCapsuleObstacles);
#endif
mCapsuleObstacles.replaceWithLast(index);
#ifdef NEW_ENCODING
mCCTManager.onObstacleRemoved(handle);
#else
mCCTManager.onObstacleRemoved(handle, encodeHandle(size-1, type));
#endif
return true;
}
else return false;
}
bool ObstacleContext::updateObstacle(PxObstacleHandle handle, const PxObstacle& obstacle)
{
#ifdef NEW_ENCODING
void* object = mHandleManager.GetObject(handle);
if(!object)
return false;
const PxGeometryType::Enum type = decodeInternalType(object);
PX_ASSERT(type==obstacle.getType());
if(type!=obstacle.getType())
return false;
const PxU32 index = decodeInternalIndex(object);
#else
const PxGeometryType::Enum type = decodeType(handle);
PX_ASSERT(type==obstacle.getType());
if(type!=obstacle.getType())
return false;
const PxU32 index = decodeIndex(handle);
#endif
if(type==PxGeometryType::eBOX)
{
const PxU32 size = mBoxObstacles.size();
PX_ASSERT(index<size);
if(index>=size)
return false;
mBoxObstacles[index].mData = static_cast<const PxBoxObstacle&>(obstacle);
mCCTManager.onObstacleUpdated(handle,this);
return true;
}
else if(type==PxGeometryType::eCAPSULE)
{
const PxU32 size = mCapsuleObstacles.size();
PX_ASSERT(index<size);
if(index>=size)
return false;
mCapsuleObstacles[index].mData = static_cast<const PxCapsuleObstacle&>(obstacle);
mCCTManager.onObstacleUpdated(handle,this);
return true;
}
else return false;
}
PxU32 ObstacleContext::getNbObstacles() const
{
return mBoxObstacles.size() + mCapsuleObstacles.size();
}
const PxObstacle* ObstacleContext::getObstacle(PxU32 i) const
{
const PxU32 nbBoxes = mBoxObstacles.size();
if(i<nbBoxes)
return &mBoxObstacles[i].mData;
i -= nbBoxes;
const PxU32 nbCapsules = mCapsuleObstacles.size();
if(i<nbCapsules)
return &mCapsuleObstacles[i].mData;
return NULL;
}
const PxObstacle* ObstacleContext::getObstacleByHandle(PxObstacleHandle handle) const
{
#ifdef NEW_ENCODING
void* object = mHandleManager.GetObject(handle);
if(!object)
return NULL;
const PxGeometryType::Enum type = decodeInternalType(object);
const PxU32 index = decodeInternalIndex(object);
#else
const PxGeometryType::Enum type = decodeType(handle);
const PxU32 index = decodeIndex(handle);
#endif
if(type == PxGeometryType::eBOX)
{
const PxU32 size = mBoxObstacles.size();
if(index>=size)
return NULL;
PX_ASSERT(mBoxObstacles[index].mHandle==handle);
return &mBoxObstacles[index].mData;
}
else if(type==PxGeometryType::eCAPSULE)
{
const PxU32 size = mCapsuleObstacles.size();
if(index>=size)
return NULL;
PX_ASSERT(mCapsuleObstacles[index].mHandle==handle);
return &mCapsuleObstacles[index].mData;
}
else return NULL;
}
#include "GuRaycastTests.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
using namespace Gu;
const PxObstacle* ObstacleContext::raycastSingle(PxGeomRaycastHit& hit, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxObstacleHandle& obstacleHandle) const
{
PxGeomRaycastHit localHit;
PxF32 t = FLT_MAX;
const PxObstacle* touchedObstacle = NULL;
const PxHitFlags hitFlags = PxHitFlags(0);
{
const RaycastFunc raycastFunc = Gu::getRaycastFuncTable()[PxGeometryType::eBOX];
PX_ASSERT(raycastFunc);
const PxU32 nbExtraBoxes = mBoxObstacles.size();
for(PxU32 i=0;i<nbExtraBoxes;i++)
{
const PxBoxObstacle& userBoxObstacle = mBoxObstacles[i].mData;
PxU32 status = raycastFunc( PxBoxGeometry(userBoxObstacle.mHalfExtents),
PxTransform(toVec3(userBoxObstacle.mPos), userBoxObstacle.mRot),
origin, unitDir, distance,
hitFlags,
1, &localHit, sizeof(PxGeomRaycastHit), UNUSED_RAYCAST_THREAD_CONTEXT);
if(status && localHit.distance<t)
{
t = localHit.distance;
hit = localHit;
obstacleHandle = mBoxObstacles[i].mHandle;
touchedObstacle = &userBoxObstacle;
}
}
}
{
const RaycastFunc raycastFunc = Gu::getRaycastFuncTable()[PxGeometryType::eCAPSULE];
PX_ASSERT(raycastFunc);
const PxU32 nbExtraCapsules = mCapsuleObstacles.size();
for(PxU32 i=0;i<nbExtraCapsules;i++)
{
const PxCapsuleObstacle& userCapsuleObstacle = mCapsuleObstacles[i].mData;
PxU32 status = raycastFunc( PxCapsuleGeometry(userCapsuleObstacle.mRadius, userCapsuleObstacle.mHalfHeight),
PxTransform(toVec3(userCapsuleObstacle.mPos), userCapsuleObstacle.mRot),
origin, unitDir, distance,
hitFlags,
1, &localHit, sizeof(PxGeomRaycastHit), UNUSED_RAYCAST_THREAD_CONTEXT);
if(status && localHit.distance<t)
{
t = localHit.distance;
hit = localHit;
obstacleHandle = mCapsuleObstacles[i].mHandle;
touchedObstacle = &userCapsuleObstacle;
}
}
}
return touchedObstacle;
}
const PxObstacle* ObstacleContext::raycastSingle(PxGeomRaycastHit& hit, const PxObstacleHandle& obstacleHandle, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance) const
{
const PxHitFlags hitFlags = PxHitFlags(0);
#ifdef NEW_ENCODING
void* object = mHandleManager.GetObject(obstacleHandle);
if(!object)
return NULL;
const PxGeometryType::Enum geomType = decodeInternalType(object);
const PxU32 index = decodeInternalIndex(object);
#else
const PxGeometryType::Enum geomType = decodeType(obstacleHandle);
const PxU32 index = decodeIndex(obstacleHandle);
#endif
if(geomType == PxGeometryType::eBOX)
{
const PxBoxObstacle& userBoxObstacle = mBoxObstacles[index].mData;
PxU32 status = Gu::getRaycastFuncTable()[PxGeometryType::eBOX](
PxBoxGeometry(userBoxObstacle.mHalfExtents),
PxTransform(toVec3(userBoxObstacle.mPos), userBoxObstacle.mRot),
origin, unitDir, distance,
hitFlags,
1, &hit, sizeof(PxGeomRaycastHit), UNUSED_RAYCAST_THREAD_CONTEXT);
if(status)
{
return &userBoxObstacle;
}
}
else
{
PX_ASSERT(geomType == PxGeometryType::eCAPSULE);
const PxCapsuleObstacle& userCapsuleObstacle = mCapsuleObstacles[index].mData;
PxU32 status = Gu::getRaycastFuncTable()[PxGeometryType::eCAPSULE](
PxCapsuleGeometry(userCapsuleObstacle.mRadius, userCapsuleObstacle.mHalfHeight),
PxTransform(toVec3(userCapsuleObstacle.mPos), userCapsuleObstacle.mRot),
origin, unitDir, distance,
hitFlags,
1, &hit, sizeof(PxGeomRaycastHit), UNUSED_RAYCAST_THREAD_CONTEXT);
if(status)
{
return &userCapsuleObstacle;
}
}
return NULL;
}
void ObstacleContext::onOriginShift(const PxVec3& shift)
{
for(PxU32 i=0; i < mBoxObstacles.size(); i++)
sub(mBoxObstacles[i].mData.mPos, shift);
for(PxU32 i=0; i < mCapsuleObstacles.size(); i++)
sub(mCapsuleObstacles[i].mData.mPos, shift);
}
| 18,312 | C++ | 33.102421 | 185 | 0.74929 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctObstacleContext.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 CCT_OBSTACLE_CONTEXT
#define CCT_OBSTACLE_CONTEXT
/* Exclude from documentation */
/** \cond */
#include "characterkinematic/PxControllerObstacles.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxArray.h"
namespace physx
{
struct PxGeomRaycastHit;
namespace Cct
{
class CharacterControllerManager;
typedef PxU32 Handle;
class HandleManager : public PxUserAllocated
{
public:
HandleManager();
~HandleManager();
Handle Add(void* object);
void Remove(Handle handle);
void* GetObject(Handle handle) const; // Returns object according to handle.
bool UpdateObject(Handle handle, void* object);
PX_FORCE_INLINE PxU32 GetMaxNbObjects() const { return mMaxNbObjects; } //!< Returns max number of objects
PX_FORCE_INLINE PxU32 GetNbObjects() const { return mCurrentNbObjects; } //!< Returns current number of objects
PX_FORCE_INLINE void** GetObjects() const { return mObjects; } //!< Gets the complete list of objects
PX_FORCE_INLINE void* PickObject(Handle handle) const { return mObjects[mOutToIn[PxU16(handle)]]; }
private:
// Physical list
void** mObjects; //!< Physical list, with no holes but unsorted.
PxU32 mCurrentNbObjects; //!< Current number of objects in the physical list.
PxU32 mMaxNbObjects; //!< Maximum possible number of objects in the physical list.
// Cross-references
PxU16* mOutToIn; //!< Maps virtual indices (handles) to real ones.
PxU16* mInToOut; //!< Maps real indices to virtual ones (handles).
PxU16* mStamps;
// Recycled locations
PxU32 mNbFreeIndices; //!< Current number of free indices
// Internal methods
bool SetupLists(void** objects=NULL, PxU16* oti=NULL, PxU16* ito=NULL, PxU16* stamps=NULL);
};
class ObstacleContext : public PxObstacleContext, public PxUserAllocated
{
public:
ObstacleContext(CharacterControllerManager& );
virtual ~ObstacleContext();
// PxObstacleContext
virtual void release() PX_OVERRIDE;
virtual PxControllerManager& getControllerManager() const PX_OVERRIDE;
virtual PxObstacleHandle addObstacle(const PxObstacle& obstacle) PX_OVERRIDE;
virtual bool removeObstacle(PxObstacleHandle handle) PX_OVERRIDE;
virtual bool updateObstacle(PxObstacleHandle handle, const PxObstacle& obstacle) PX_OVERRIDE;
virtual PxU32 getNbObstacles() const PX_OVERRIDE;
virtual const PxObstacle* getObstacle(PxU32 i) const PX_OVERRIDE;
virtual const PxObstacle* getObstacleByHandle(PxObstacleHandle handle) const PX_OVERRIDE;
//~PxObstacleContext
const PxObstacle* raycastSingle(PxGeomRaycastHit& hit, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxObstacleHandle& obstacleHandle) const;
const PxObstacle* raycastSingle(PxGeomRaycastHit& hit, const PxObstacleHandle& obstacleHandle, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance) const; // raycast just one obstacle handle
void onOriginShift(const PxVec3& shift);
struct InternalBoxObstacle
{
InternalBoxObstacle(PxObstacleHandle handle, const PxBoxObstacle& data) : mHandle(handle), mData(data) {}
PxObstacleHandle mHandle;
PxBoxObstacle mData;
};
PxArray<InternalBoxObstacle> mBoxObstacles;
struct InternalCapsuleObstacle
{
InternalCapsuleObstacle(PxObstacleHandle handle, const PxCapsuleObstacle& data) : mHandle(handle), mData(data) {}
PxObstacleHandle mHandle;
PxCapsuleObstacle mData;
};
PxArray<InternalCapsuleObstacle> mCapsuleObstacles;
private:
ObstacleContext& operator=(const ObstacleContext&);
HandleManager mHandleManager;
CharacterControllerManager& mCCTManager;
};
} // namespace Cct
}
/** \endcond */
#endif
| 5,547 | C | 40.096296 | 212 | 0.735713 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCharacterControllerManager.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 "CctCharacterControllerManager.h"
#include "CctBoxController.h"
#include "CctCapsuleController.h"
#include "CctObstacleContext.h"
#include "GuDistanceSegmentSegment.h"
#include "GuDistanceSegmentBox.h"
#include "foundation/PxUtilities.h"
#include "PxRigidDynamic.h"
#include "PxScene.h"
#include "PxPhysics.h"
#include "CmRenderBuffer.h"
#include "CmRadixSort.h"
using namespace physx;
using namespace Cct;
static const PxF32 gMaxOverlapRecover = 4.0f; // PT: TODO: expose this
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CharacterControllerManager::CharacterControllerManager(PxScene& scene, bool lockingEnabled) :
mScene (scene),
mRenderBuffer (NULL),
mDebugRenderingFlags (0),
mMaxEdgeLength (1.0f),
mTessellation (false),
mOverlapRecovery (true),
mPreciseSweeps (true),
mPreventVerticalSlidingAgainstCeiling (false),
mLockingEnabled (lockingEnabled)
{
// PT: register ourself as a deletion listener, to be called by the SDK whenever an object is deleted
PxPhysics& physics = scene.getPhysics();
physics.registerDeletionListener(*this, PxDeletionEventFlag::eUSER_RELEASE);
}
CharacterControllerManager::~CharacterControllerManager()
{
PX_DELETE(mRenderBuffer);
}
static PxArray<CharacterControllerManager*>* gControllerManagers = NULL;
void CharacterControllerManager::release()
{
if(gControllerManagers)
{
const bool found = gControllerManagers->findAndReplaceWithLast(this);
PX_ASSERT(found);
PX_UNUSED(found);
if(!gControllerManagers->size())
{
PX_DELETE(gControllerManagers);
}
}
// PT: TODO: use non virtual calls & move to dtor
while(getNbControllers()!= 0)
releaseController(*getController(0));
while(getNbObstacleContexts()!= 0)
mObstacleContexts[0]->release();
PxPhysics& physics = mScene.getPhysics();
physics.unregisterDeletionListener(*this);
PX_DELETE_THIS;
PxDecFoundationRefCount();
}
PX_C_EXPORT PxControllerManager* PX_CALL_CONV PxCreateControllerManager(PxScene& scene, bool lockingEnabled)
{
if(gControllerManagers)
{
// PT: make sure we cannot create two controller managers for the same scene
const PxU32 nbManagers = gControllerManagers->size();
for(PxU32 i=0;i<nbManagers;i++)
{
if(&scene==&(*gControllerManagers)[i]->getScene())
return NULL;
}
}
PxIncFoundationRefCount();
CharacterControllerManager* controllerManager = PX_NEW(CharacterControllerManager)(scene, lockingEnabled);
if(!gControllerManagers)
gControllerManagers = new PxArray<CharacterControllerManager*>;
gControllerManagers->pushBack(controllerManager);
return controllerManager;
}
PxScene& CharacterControllerManager::getScene() const
{
return mScene;
}
PxRenderBuffer& CharacterControllerManager::getRenderBuffer()
{
if(!mRenderBuffer)
mRenderBuffer = PX_NEW(Cm::RenderBuffer);
return *mRenderBuffer;
}
void CharacterControllerManager::setDebugRenderingFlags(PxControllerDebugRenderFlags flags)
{
mDebugRenderingFlags = flags;
if(!flags)
{
PX_DELETE(mRenderBuffer);
}
}
PxU32 CharacterControllerManager::getNbControllers() const
{
return mControllers.size();
}
Controller** CharacterControllerManager::getControllers()
{
return mControllers.begin();
}
PxController* CharacterControllerManager::getController(PxU32 index)
{
if(index>=mControllers.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxControllerManager::getController(): out-of-range index");
return NULL;
}
PX_ASSERT(mControllers[index]);
return mControllers[index]->getPxController();
}
PxController* CharacterControllerManager::createController(const PxControllerDesc& desc)
{
if(!desc.isValid())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxControllerManager::createController(): desc.isValid() fails.");
return NULL;
}
Controller* newController = NULL;
PxController* N = NULL;
if(desc.getType()==PxControllerShapeType::eBOX)
{
BoxController* boxController = PX_NEW(BoxController)(desc, mScene.getPhysics(), &mScene);
newController = boxController;
N = boxController;
}
else if(desc.getType()==PxControllerShapeType::eCAPSULE)
{
CapsuleController* capsuleController = PX_NEW(CapsuleController)(desc, mScene.getPhysics(), &mScene);
newController = capsuleController;
N = capsuleController;
}
else PX_ALWAYS_ASSERT_MESSAGE( "INTERNAL ERROR - invalid CCT type, should have been caught by isValid().");
if(newController)
{
mControllers.pushBack(newController);
newController->setCctManager(this);
PxShape* shape = NULL;
PxU32 nb = N->getActor()->getShapes(&shape, 1);
PX_ASSERT(nb==1);
PX_UNUSED(nb);
mCCTShapes.insert(shape);
}
return N;
}
void CharacterControllerManager::releaseController(PxController& controller)
{
for(PxU32 i = 0; i<mControllers.size(); i++)
{
if(mControllers[i]->getPxController() == &controller)
{
mControllers.replaceWithLast(i);
break;
}
}
PxShape* shape = NULL;
PxU32 nb = controller.getActor()->getShapes(&shape, 1);
PX_ASSERT(nb==1);
PX_UNUSED(nb);
mCCTShapes.erase(shape);
if(controller.getType() == PxControllerShapeType::eCAPSULE)
{
CapsuleController* cc = static_cast<CapsuleController*>(&controller);
PX_DELETE(cc);
}
else if(controller.getType() == PxControllerShapeType::eBOX)
{
BoxController* bc = static_cast<BoxController*>(&controller);
PX_DELETE(bc);
}
else PX_ASSERT(0);
}
void CharacterControllerManager::purgeControllers()
{
while(mControllers.size())
releaseController(*mControllers[0]->getPxController());
}
void CharacterControllerManager::onRelease(const PxBase* observed, void* , PxDeletionEventFlag::Enum deletionEvent)
{
PX_ASSERT(deletionEvent == PxDeletionEventFlag::eUSER_RELEASE); // the only type we registered for
PX_UNUSED(deletionEvent);
const PxType type = observed->getConcreteType();
if(type!=PxConcreteType:: eRIGID_DYNAMIC && type!=PxConcreteType:: eRIGID_STATIC && type!=PxConcreteType::eSHAPE && type!=PxConcreteType::eARTICULATION_LINK)
return;
// check if object was registered
if(mLockingEnabled)
mWriteLock.lock();
const ObservedRefCountMap::Entry* releaseEntry = mObservedRefCountMap.find(observed);
if(mLockingEnabled)
mWriteLock.unlock();
if(releaseEntry)
{
const PxU32 size = mControllers.size();
for(PxU32 i=0; i<size; i++)
{
Controller* controller = mControllers[i];
if(mLockingEnabled)
controller->mWriteLock.lock();
controller->onRelease(*observed);
if(mLockingEnabled)
controller->mWriteLock.unlock();
}
}
}
void CharacterControllerManager::registerObservedObject(const PxBase* obj)
{
if(mLockingEnabled)
mWriteLock.lock();
mObservedRefCountMap[obj].refCount++;
if(mLockingEnabled)
mWriteLock.unlock();
}
void CharacterControllerManager::unregisterObservedObject(const PxBase* obj)
{
if(mLockingEnabled)
mWriteLock.lock();
ObservedRefCounter& refCounter = mObservedRefCountMap[obj];
PX_ASSERT(refCounter.refCount);
refCounter.refCount--;
if(!refCounter.refCount)
mObservedRefCountMap.erase(obj);
if(mLockingEnabled)
mWriteLock.unlock();
}
PxU32 CharacterControllerManager::getNbObstacleContexts() const
{
return mObstacleContexts.size();
}
PxObstacleContext* CharacterControllerManager::getObstacleContext(PxU32 index)
{
if(index>=mObstacleContexts.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxControllerManager::getObstacleContext(): out-of-range index");
return NULL;
}
PX_ASSERT(mObstacleContexts[index]);
return mObstacleContexts[index];
}
PxObstacleContext* CharacterControllerManager::createObstacleContext()
{
ObstacleContext* oc = PX_NEW(ObstacleContext)(*this);
mObstacleContexts.pushBack(oc);
return oc;
}
void CharacterControllerManager::releaseObstacleContext(ObstacleContext& oc)
{
PX_ASSERT(mObstacleContexts.find(&oc) != mObstacleContexts.end());
mObstacleContexts.findAndReplaceWithLast(&oc);
ObstacleContext* ptr = &oc;
PX_DELETE(ptr);
}
void CharacterControllerManager::onObstacleRemoved(PxObstacleHandle index) const
{
for(PxU32 i = 0; i<mControllers.size(); i++)
{
mControllers[i]->mCctModule.onObstacleRemoved(index);
}
}
void CharacterControllerManager::onObstacleUpdated(PxObstacleHandle index, const PxObstacleContext* context) const
{
for(PxU32 i = 0; i<mControllers.size(); i++)
{
mControllers[i]->mCctModule.onObstacleUpdated(index,context, toVec3(mControllers[i]->mPosition), -mControllers[i]->mUserParams.mUpDirection, mControllers[i]->getHalfHeightInternal());
}
}
void CharacterControllerManager::onObstacleAdded(PxObstacleHandle index, const PxObstacleContext* context) const
{
for(PxU32 i = 0; i<mControllers.size(); i++)
{
mControllers[i]->mCctModule.onObstacleAdded(index,context, toVec3(mControllers[i]->mPosition), -mControllers[i]->mUserParams.mUpDirection, mControllers[i]->getHalfHeightInternal());
}
}
void CharacterControllerManager::resetObstaclesBuffers()
{
mBoxUserData.resetOrClear();
mBoxes.resetOrClear();
mCapsuleUserData.resetOrClear();
mCapsules.resetOrClear();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CharacterControllerManager::setTessellation(bool flag, float maxEdgeLength)
{
mTessellation = flag;
mMaxEdgeLength = maxEdgeLength;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CharacterControllerManager::setOverlapRecoveryModule(bool flag)
{
mOverlapRecovery = flag;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CharacterControllerManager::setPreciseSweeps(bool flag)
{
mPreciseSweeps = flag;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CharacterControllerManager::setPreventVerticalSlidingAgainstCeiling(bool flag)
{
mPreventVerticalSlidingAgainstCeiling = flag;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CharacterControllerManager::shiftOrigin(const PxVec3& shift)
{
for(PxU32 i=0; i < mControllers.size(); i++)
{
mControllers[i]->onOriginShift(shift);
}
for(PxU32 i=0; i < mObstacleContexts.size(); i++)
{
mObstacleContexts[i]->onOriginShift(shift);
}
if(mRenderBuffer)
mRenderBuffer->shift(-shift);
// assumption is that these are just used for temporary stuff
PX_ASSERT(!mBoxes.size());
PX_ASSERT(!mCapsules.size());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool computeMTD(PxVec3& mtd, PxF32& depth, const PxVec3& e0, const PxVec3& c0, const PxMat33& r0, const PxVec3& e1, const PxVec3& c1, const PxMat33& r1)
{
// 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, d;
PxReal overlap[15];
// 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]);
d = ra + rb - t;
if(d<0.0f)
return false;
overlap[i] = d;
}
// 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]);
d = ra + rb - t;
if(d<0.0f)
return false;
overlap[k+3] = d;
}
// PT: edge-edge tests are skipped, by design
PxU32 minIndex=0;
PxReal minD = overlap[0];
for(PxU32 i=1;i<6;i++)
{
if(overlap[i]<minD)
{
minD = overlap[i];
minIndex = i;
}
}
depth = minD;
switch(minIndex)
{
case 0: mtd = r0.column0; break;
case 1: mtd = r0.column1; break;
case 2: mtd = r0.column2; break;
case 3: mtd = r1.column0; break;
case 4: mtd = r1.column1; break;
case 5: mtd = r1.column2; break;
default: PX_ASSERT(0); break;
};
return true;
}
static PxVec3 fixDir(const PxVec3& dir, const PxVec3& up)
{
PxVec3 normalCompo, tangentCompo;
decomposeVector(normalCompo, tangentCompo, dir, up);
return tangentCompo.getNormalized();
}
static void InteractionCharacterCharacter(Controller* entity0, Controller* entity1, PxF32 elapsedTime)
{
PX_ASSERT(entity0);
PX_ASSERT(entity1);
PxF32 overlap=0.0f;
PxVec3 dir(0.0f);
if(entity0->mType>entity1->mType)
PxSwap(entity0, entity1);
if(entity0->mType==PxControllerShapeType::eCAPSULE && entity1->mType==PxControllerShapeType::eCAPSULE)
{
CapsuleController* cc0 = static_cast<CapsuleController*>(entity0);
CapsuleController* cc1 = static_cast<CapsuleController*>(entity1);
PxExtendedCapsule capsule0;
cc0->getCapsule(capsule0);
PxExtendedCapsule capsule1;
cc1->getCapsule(capsule1);
const PxF32 r = capsule0.radius + capsule1.radius;
const PxVec3 p00 = toVec3(capsule0.p0);
const PxVec3 p01 = toVec3(capsule0.p1);
const PxVec3 p10 = toVec3(capsule1.p0);
const PxVec3 p11 = toVec3(capsule1.p1);
PxF32 s,t;
const PxF32 d = sqrtf(Gu::distanceSegmentSegmentSquared(p00, p01 - p00, p10, p11 - p10, &s, &t));
if(d<r)
{
const PxVec3 center0 = s * p00 + (1.0f - s) * p01;
const PxVec3 center1 = t * p10 + (1.0f - t) * p11;
const PxVec3 up = entity0->mCctModule.mUserParams.mUpDirection;
dir = fixDir(center0 - center1, up);
overlap = r - d;
}
}
else if(entity0->mType==PxControllerShapeType::eBOX && entity1->mType==PxControllerShapeType::eCAPSULE)
{
BoxController* cc0 = static_cast<BoxController*>(entity0);
CapsuleController* cc1 = static_cast<CapsuleController*>(entity1);
PxExtendedBox obb;
cc0->getOBB(obb);
PxExtendedCapsule capsule;
cc1->getCapsule(capsule);
const PxVec3 p0 = toVec3(capsule.p0);
const PxVec3 p1 = toVec3(capsule.p1);
PxF32 t;
PxVec3 p;
const PxMat33 M(obb.rot);
const PxVec3 boxCenter = toVec3(obb.center);
const PxF32 d = sqrtf(Gu::distanceSegmentBoxSquared(p0, p1, boxCenter, obb.extents, M, &t, &p));
if(d<capsule.radius)
{
// const PxVec3 center0 = M.transform(p) + boxCenter;
// const PxVec3 center1 = t * p0 + (1.0f - t) * p1;
const PxVec3 center0 = boxCenter;
const PxVec3 center1 = (p0 + p1)*0.5f;
const PxVec3 up = entity0->mCctModule.mUserParams.mUpDirection;
dir = fixDir(center0 - center1, up);
overlap = capsule.radius - d;
}
}
else
{
PX_ASSERT(entity0->mType==PxControllerShapeType::eBOX);
PX_ASSERT(entity1->mType==PxControllerShapeType::eBOX);
BoxController* cc0 = static_cast<BoxController*>(entity0);
BoxController* cc1 = static_cast<BoxController*>(entity1);
PxExtendedBox obb0;
cc0->getOBB(obb0);
PxExtendedBox obb1;
cc1->getOBB(obb1);
PxVec3 mtd;
PxF32 depth;
if(computeMTD( mtd, depth,
obb0.extents, toVec3(obb0.center), PxMat33(obb0.rot),
obb1.extents, toVec3(obb1.center), PxMat33(obb1.rot)))
{
const PxVec3 center0 = toVec3(obb0.center);
const PxVec3 center1 = toVec3(obb1.center);
const PxVec3 witness = center0 - center1;
if(mtd.dot(witness)<0.0f)
dir = -mtd;
else
dir = mtd;
const PxVec3 up = entity0->mCctModule.mUserParams.mUpDirection;
dir = fixDir(dir, up);
overlap = depth;
}
}
if(overlap!=0.0f)
{
// We want to limit this to some reasonable amount, to avoid obvious "popping".
const PxF32 maxOverlap = gMaxOverlapRecover * elapsedTime;
if(overlap>maxOverlap)
overlap=maxOverlap;
const PxVec3 sep = dir * overlap * 0.5f;
entity0->mOverlapRecover += sep;
entity1->mOverlapRecover -= sep;
}
}
// PT: TODO: this is the very old version, revisit with newer one
static void completeBoxPruning(const PxBounds3* bounds, PxU32 nb, PxArray<PxU32>& pairs)
{
if(!nb)
return;
pairs.clear();
float* PosList = PX_ALLOCATE(float, nb, "completeBoxPruning");
for(PxU32 i=0;i<nb;i++)
PosList[i] = bounds[i].minimum.x;
/*static*/ Cm::RadixSortBuffered RS; // Static for coherence
const PxU32* Sorted = RS.Sort(PosList, nb).GetRanks();
const PxU32* const LastSorted = &Sorted[nb];
const PxU32* RunningAddress = Sorted;
PxU32 Index0, Index1;
while(RunningAddress<LastSorted && Sorted<LastSorted)
{
Index0 = *Sorted++;
while(RunningAddress<LastSorted && PosList[*RunningAddress++]<PosList[Index0]);
const PxU32* RunningAddress2 = RunningAddress;
while(RunningAddress2<LastSorted && PosList[Index1 = *RunningAddress2++]<=bounds[Index0].maximum.x)
{
if(Index0!=Index1)
{
if(bounds[Index0].intersects(bounds[Index1]))
{
pairs.pushBack(Index0);
pairs.pushBack(Index1);
}
}
}
}
PX_FREE(PosList);
}
void CharacterControllerManager::computeInteractions(PxF32 elapsedTime, PxControllerFilterCallback* cctFilterCb)
{
PxU32 nbControllers = mControllers.size();
Controller** controllers = mControllers.begin();
PxBounds3* boxes = PX_ALLOCATE(PxBounds3, nbControllers, "CharacterControllerManager::computeInteractions"); // PT: TODO: get rid of alloc
PxBounds3* runningBoxes = boxes;
while(nbControllers--)
{
Controller* current = *controllers++;
PxExtendedBounds3 extBox;
current->getWorldBox(extBox);
*runningBoxes++ = PxBounds3(toVec3(extBox.minimum), toVec3(extBox.maximum)); // ### LOSS OF ACCURACY
}
//
const PxU32 nbEntities = PxU32(runningBoxes - boxes);
PxArray<PxU32> pairs; // PT: TODO: get rid of alloc
completeBoxPruning(boxes, nbEntities, pairs);
PxU32 nbPairs = pairs.size()>>1;
const PxU32* indices = pairs.begin();
while(nbPairs--)
{
const PxU32 index0 = *indices++;
const PxU32 index1 = *indices++;
Controller* ctrl0 = mControllers[index0];
Controller* ctrl1 = mControllers[index1];
bool keep=true;
if(cctFilterCb)
keep = cctFilterCb->filter(*ctrl0->getPxController(), *ctrl1->getPxController());
if(keep)
InteractionCharacterCharacter(ctrl0, ctrl1, elapsedTime);
}
PX_FREE(boxes);
}
| 20,469 | C++ | 27.589385 | 199 | 0.676389 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctBoxController.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxBoxGeometry.h"
#include "characterkinematic/PxController.h"
#include "PxRigidDynamic.h"
#include "PxShape.h"
#include "CctBoxController.h"
#include "CctCharacterControllerManager.h"
using namespace physx;
using namespace Cct;
static PX_FORCE_INLINE PxVec3 CCTtoProxyExtents(PxF32 halfHeight, PxF32 halfSideExtent, PxF32 halfForwardExtent, PxF32 coeff)
{
// PT: because we now orient the box CCT using the same quat as for capsules...
// i.e. the identity quat corresponds to a up dir = 1,0,0 (which is like the worst choice we could have made, of course)
return PxVec3(halfHeight * coeff, halfSideExtent * coeff, halfForwardExtent * coeff);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BoxController::BoxController(const PxControllerDesc& desc, PxPhysics& sdk, PxScene* s) : Controller(desc, s)
{
mType = PxControllerShapeType::eBOX;
const PxBoxControllerDesc& bc = static_cast<const PxBoxControllerDesc&>(desc);
mHalfHeight = bc.halfHeight;
mHalfSideExtent = bc.halfSideExtent;
mHalfForwardExtent = bc.halfForwardExtent;
// Create kinematic actor under the hood
PxBoxGeometry boxGeom;
boxGeom.halfExtents = CCTtoProxyExtents(bc.halfHeight, bc.halfSideExtent, bc.halfForwardExtent, mProxyScaleCoeff);
createProxyActor(sdk, boxGeom, *desc.material, desc.clientID);
}
BoxController::~BoxController()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void BoxController::invalidateCache()
{
if(mManager->mLockingEnabled)
mWriteLock.lock();
mCctModule.voidTestCache();
if(mManager->mLockingEnabled)
mWriteLock.unlock();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool BoxController::getWorldBox(PxExtendedBounds3& box) const
{
setCenterExtents(box, mPosition, PxVec3(mHalfHeight, mHalfSideExtent, mHalfForwardExtent));
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxF32 BoxController::getHalfHeight() const
{
return mHalfHeight;
}
PxF32 BoxController::getHalfSideExtent() const
{
return mHalfSideExtent;
}
PxF32 BoxController::getHalfForwardExtent() const
{
return mHalfForwardExtent;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool BoxController::updateKinematicProxy()
{
// Set extents for kinematic proxy
if(mKineActor)
{
PxShape* shape = getKineShape();
const PxGeometry& geom = shape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eBOX);
PxBoxGeometry bg = static_cast<const PxBoxGeometry&>(geom);
bg.halfExtents = CCTtoProxyExtents(mHalfHeight, mHalfSideExtent, mHalfForwardExtent, mProxyScaleCoeff);
shape->setGeometry(bg);
}
return true;
}
bool BoxController::setHalfHeight(PxF32 halfHeight)
{
if(halfHeight<=0.0f)
return false;
mHalfHeight = halfHeight;
return updateKinematicProxy();
}
bool BoxController::setHalfSideExtent(PxF32 halfSideExtent)
{
if(halfSideExtent<=0.0f)
return false;
mHalfSideExtent = halfSideExtent;
return updateKinematicProxy();
}
bool BoxController::setHalfForwardExtent(PxF32 halfForwardExtent)
{
if(halfForwardExtent<=0.0f)
return false;
mHalfForwardExtent = halfForwardExtent;
return updateKinematicProxy();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxExtendedVec3 BoxController::getFootPosition() const
{
PxExtendedVec3 groundPosition = mPosition; // Middle of the CCT
sub(groundPosition, mUserParams.mUpDirection * (mHalfHeight + mUserParams.mContactOffset)); // Ground
return groundPosition;
}
bool BoxController::setFootPosition(const PxExtendedVec3& position)
{
PxExtendedVec3 centerPosition = position;
add(centerPosition, mUserParams.mUpDirection * (mHalfHeight + mUserParams.mContactOffset));
return setPosition(centerPosition);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void BoxController::getOBB(PxExtendedBox& obb) const
{
// PT: TODO: optimize this
PxExtendedBounds3 worldBox;
getWorldBox(worldBox);
getCenter(worldBox, obb.center);
getExtents(worldBox, obb.extents);
obb.rot = mUserParams.mQuatFromUp;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void BoxController::resize(PxReal height)
{
const float oldHeight = getHalfHeight();
setHalfHeight(height);
const float delta = height - oldHeight;
PxExtendedVec3 pos = getPosition();
add(pos, mUserParams.mUpDirection * delta);
setPosition(pos);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 7,379 | C++ | 36.272727 | 199 | 0.583412 |
NVIDIA-Omniverse/PhysX/physx/source/physxcharacterkinematic/src/CctCharacterControllerCallbacks.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/PxSphereGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxMeshQuery.h"
#include "common/PxRenderBuffer.h"
#include "common/PxRenderOutput.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxSIMDHelpers.h"
#include "extensions/PxTriangleMeshExt.h"
#include "PxScene.h"
#include "CctInternalStructs.h"
#include "GuIntersectionTriangleBox.h"
#include "CmUtils.h"
static const bool gVisualizeTouchedTris = false;
static const float gDebugVisOffset = 0.01f;
using namespace physx;
using namespace Cct;
using namespace Gu;
using namespace Cm;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PT: HINT: disable gUsePartialUpdates for easier visualization
static void visualizeTouchedTriangles(PxU32 nbTrisToRender, PxU32 startIndex, const PxTriangle* triangles, PxRenderBuffer* renderBuffer, const PxVec3& offset, const PxVec3& upDirection)
{
if(!renderBuffer)
return;
PxVec3 yy = -offset;
yy += upDirection * gDebugVisOffset; // PT: move slightly in the up direction
for(PxU32 i=0; i<nbTrisToRender; i++)
{
const PxTriangle& currentTriangle = triangles[i+startIndex];
// PxRenderOutput(*renderBuffer)
// << PxDebugColor::eARGB_GREEN << PxRenderOutput::TRIANGLES
// << currentTriangle.verts[0]+yy << currentTriangle.verts[1]+yy << currentTriangle.verts[2]+yy;
PxRenderOutput(*renderBuffer)
<< PxU32(PxDebugColor::eARGB_GREEN) << PxRenderOutput::LINES
<< currentTriangle.verts[0]+yy << currentTriangle.verts[1]+yy
<< currentTriangle.verts[1]+yy << currentTriangle.verts[2]+yy
<< currentTriangle.verts[2]+yy << currentTriangle.verts[0]+yy;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct TessParams
{
PxU32 nbNewTris;
PxU32 index;
TriArray* worldTriangles;
IntArray* triIndicesArray;
PxVec3 cullingBoxCenter; // PT: make sure we can read 4 bytes after this one
PxVec3 cullingBoxExtents; // PT: make sure we can read 4 bytes after this one
PxF32 maxEdgeLength2;
PxU16 nbTessellation;
};
static void tessellateTriangleRecursive(TessParams* tp, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2)
{
tp->nbTessellation++;
// PT: this one is safe, v0/v1/v2 can always be V4Loaded
if(!intersectTriangleBox_Unsafe(tp->cullingBoxCenter, tp->cullingBoxExtents, v0, v1, v2))
return;
PxU32 code;
{
const PxVec3 edge0 = v0 - v1;
const PxVec3 edge1 = v1 - v2;
const PxVec3 edge2 = v2 - v0;
const float maxEdgeLength2 = tp->maxEdgeLength2;
const bool split0 = edge0.magnitudeSquared()>maxEdgeLength2;
const bool split1 = edge1.magnitudeSquared()>maxEdgeLength2;
const bool split2 = edge2.magnitudeSquared()>maxEdgeLength2;
code = (PxU32(split2)<<2)|(PxU32(split1)<<1)|PxU32(split0);
}
// PT: using PxVec3p to make sure we can safely V4LoadU these vertices
const PxVec3p m0 = (v0 + v1)*0.5f;
const PxVec3p m1 = (v1 + v2)*0.5f;
const PxVec3p m2 = (v2 + v0)*0.5f;
switch(code)
{
case 0: // 000: no split
{
tp->worldTriangles->pushBack(PxTriangle(v0, v1, v2));
tp->triIndicesArray->pushBack(tp->index);
tp->nbNewTris++;
}
break;
case 1: // 001: split edge0
{
tessellateTriangleRecursive(tp, v0, m0, v2);
tessellateTriangleRecursive(tp, m0, v1, v2);
}
break;
case 2: // 010: split edge1
{
tessellateTriangleRecursive(tp, v0, v1, m1);
tessellateTriangleRecursive(tp, v0, m1, v2);
}
break;
case 3: // 011: split edge0/edge1
{
tessellateTriangleRecursive(tp, v0, m0, m1);
tessellateTriangleRecursive(tp, v0, m1, v2);
tessellateTriangleRecursive(tp, m0, v1, m1);
}
break;
case 4: // 100: split edge2
{
tessellateTriangleRecursive(tp, v0, v1, m2);
tessellateTriangleRecursive(tp, v1, v2, m2);
}
break;
case 5: // 101: split edge0/edge2
{
tessellateTriangleRecursive(tp, v0, m0, m2);
tessellateTriangleRecursive(tp, m0, v1, m2);
tessellateTriangleRecursive(tp, m2, v1, v2);
}
break;
case 6: // 110: split edge1/edge2
{
tessellateTriangleRecursive(tp, v0, v1, m1);
tessellateTriangleRecursive(tp, v0, m1, m2);
tessellateTriangleRecursive(tp, m2, m1, v2);
}
break;
case 7: // 111: split edge0/edge1/edge2
{
tessellateTriangleRecursive(tp, v0, m0, m2);
tessellateTriangleRecursive(tp, m0, v1, m1);
tessellateTriangleRecursive(tp, m2, m1, v2);
tessellateTriangleRecursive(tp, m0, m1, m2);
}
break;
};
}
static void tessellateTriangle(PxU32& nbNewTris, const PxTrianglePadded& tr, PxU32 index, TriArray& worldTriangles, IntArray& triIndicesArray, const PxBounds3& cullingBox, const CCTParams& params, PxU16& nbTessellation)
{
TessParams tp;
tp.nbNewTris = 0;
tp.index = index;
tp.worldTriangles = &worldTriangles;
tp.triIndicesArray = &triIndicesArray;
tp.cullingBoxCenter = cullingBox.getCenter();
tp.cullingBoxExtents = cullingBox.getExtents();
tp.maxEdgeLength2 = params.mMaxEdgeLength2;
tp.nbTessellation = 0;
tessellateTriangleRecursive(&tp, tr.verts[0], tr.verts[1], tr.verts[2]);
nbNewTris += tp.nbNewTris;
nbTessellation += tp.nbTessellation;
// nbTessellation += PxU16(tp.nbNewTris);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputPlaneToStream(PxShape* planeShape, const PxRigidActor* actor, const PxTransform& globalPose, IntArray& geomStream, TriArray& worldTriangles, IntArray& triIndicesArray,
const PxExtendedVec3& origin, const PxBounds3& tmpBounds, const CCTParams& params, PxRenderBuffer* renderBuffer)
{
PX_ASSERT(planeShape->getGeometry().getType() == PxGeometryType::ePLANE);
const PxF32 length = (tmpBounds.maximum - tmpBounds.minimum).magnitude();
PxVec3 center = toVec3(origin);
const PxPlane plane = PxPlaneEquationFromTransform(globalPose);
PxVec3 right, up;
PxComputeBasisVectors(plane.n, right, up);
right *= length;
up *= length;
const PxVec3 p = plane.project(center);
const PxVec3 p0 = p - right + up;
const PxVec3 p1 = p - right - up;
const PxVec3 p2 = p + right - up;
const PxVec3 p3 = p + right + up;
const PxU32 nbTouchedTris = 2;
const PxVec3 offset(float(-origin.x), float(-origin.y), float(-origin.z));
TouchedMesh* touchedMesh = reinterpret_cast<TouchedMesh*>(reserveContainerMemory(geomStream, sizeof(TouchedMesh)/sizeof(PxU32)));
touchedMesh->mType = TouchedGeomType::eMESH;
touchedMesh->mTGUserData = planeShape;
touchedMesh->mActor = actor;
touchedMesh->mOffset = origin;
touchedMesh->mNbTris = nbTouchedTris;
touchedMesh->mIndexWorldTriangles = worldTriangles.size();
// Reserve memory for incoming triangles
PxTriangle* TouchedTriangles = worldTriangles.reserve(nbTouchedTris);
triIndicesArray.pushBack(0);
triIndicesArray.pushBack(1);
TouchedTriangles[0].verts[0] = p0 + offset;
TouchedTriangles[0].verts[1] = p1 + offset;
TouchedTriangles[0].verts[2] = p2 + offset;
TouchedTriangles[1].verts[0] = p0 + offset;
TouchedTriangles[1].verts[1] = p2 + offset;
TouchedTriangles[1].verts[2] = p3 + offset;
if(gVisualizeTouchedTris)
visualizeTouchedTriangles(touchedMesh->mNbTris, touchedMesh->mIndexWorldTriangles, worldTriangles.begin(), renderBuffer, offset, params.mUpDirection);
}
static void outputSphereToStream(PxShape* sphereShape, const PxRigidActor* actor, const PxTransform& globalPose, IntArray& geomStream, const PxExtendedVec3& origin)
{
const PxGeometry& geom = sphereShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eSPHERE);
PxExtendedSphere WorldSphere;
{
const PxSphereGeometry& sg = static_cast<const PxSphereGeometry&>(geom);
WorldSphere.radius = sg.radius;
WorldSphere.center.x = PxExtended(globalPose.p.x);
WorldSphere.center.y = PxExtended(globalPose.p.y);
WorldSphere.center.z = PxExtended(globalPose.p.z);
}
TouchedSphere* PX_RESTRICT touchedSphere = reinterpret_cast<TouchedSphere*>(reserveContainerMemory(geomStream, sizeof(TouchedSphere)/sizeof(PxU32)));
touchedSphere->mType = TouchedGeomType::eSPHERE;
touchedSphere->mTGUserData = sphereShape;
touchedSphere->mActor = actor;
touchedSphere->mOffset = origin;
touchedSphere->mRadius = WorldSphere.radius;
touchedSphere->mCenter.x = float(WorldSphere.center.x - origin.x);
touchedSphere->mCenter.y = float(WorldSphere.center.y - origin.y);
touchedSphere->mCenter.z = float(WorldSphere.center.z - origin.z);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputCustomToStream(PxShape* customShape, const PxRigidActor* actor, const PxTransform& globalPose, IntArray& geomStream, const PxExtendedVec3& origin)
{
PX_ASSERT_WITH_MESSAGE(static_cast<const PxCustomGeometry&>(customShape->getGeometry()).isValid(), "Character controller touched invalid PxGeometryType::eCUSTOM");
TouchedCustom* PX_RESTRICT touchedCustom = reinterpret_cast<TouchedCustom*>(reserveContainerMemory(geomStream, sizeof(TouchedCustom) / sizeof(PxU32)));
touchedCustom->mType = TouchedGeomType::eCUSTOM;
touchedCustom->mTGUserData = customShape;
touchedCustom->mActor = actor;
touchedCustom->mOffset = origin;
touchedCustom->mCustomCallbacks = static_cast<const PxCustomGeometry&>(customShape->getGeometry()).callbacks;
touchedCustom->mCenter.x = static_cast<float>(PxExtended(globalPose.p.x) - origin.x);
touchedCustom->mCenter.y = static_cast<float>(PxExtended(globalPose.p.y) - origin.y);
touchedCustom->mCenter.z = static_cast<float>(PxExtended(globalPose.p.z) - origin.z);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputCapsuleToStream(PxShape* capsuleShape, const PxRigidActor* actor, const PxTransform& globalPose, IntArray& geomStream, const PxExtendedVec3& origin)
{
const PxGeometry& geom = capsuleShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eCAPSULE);
PxExtendedCapsule WorldCapsule;
{
const PxCapsuleGeometry& cg = static_cast<const PxCapsuleGeometry&>(geom);
PxVec3 p0 = cg.halfHeight * globalPose.q.getBasisVector0();
PxVec3 p1 = -p0;
p0 += globalPose.p;
p1 += globalPose.p;
WorldCapsule.radius = cg.radius;
WorldCapsule.p0.x = PxExtended(p0.x);
WorldCapsule.p0.y = PxExtended(p0.y);
WorldCapsule.p0.z = PxExtended(p0.z);
WorldCapsule.p1.x = PxExtended(p1.x);
WorldCapsule.p1.y = PxExtended(p1.y);
WorldCapsule.p1.z = PxExtended(p1.z);
}
TouchedCapsule* PX_RESTRICT touchedCapsule = reinterpret_cast<TouchedCapsule*>(reserveContainerMemory(geomStream, sizeof(TouchedCapsule)/sizeof(PxU32)));
touchedCapsule->mType = TouchedGeomType::eCAPSULE;
touchedCapsule->mTGUserData = capsuleShape;
touchedCapsule->mActor = actor;
touchedCapsule->mOffset = origin;
touchedCapsule->mRadius = WorldCapsule.radius;
touchedCapsule->mP0.x = float(WorldCapsule.p0.x - origin.x);
touchedCapsule->mP0.y = float(WorldCapsule.p0.y - origin.y);
touchedCapsule->mP0.z = float(WorldCapsule.p0.z - origin.z);
touchedCapsule->mP1.x = float(WorldCapsule.p1.x - origin.x);
touchedCapsule->mP1.y = float(WorldCapsule.p1.y - origin.y);
touchedCapsule->mP1.z = float(WorldCapsule.p1.z - origin.z);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputBoxToStream( PxShape* boxShape, const PxRigidActor* actor, const PxTransform& globalPose, IntArray& geomStream, TriArray& worldTriangles, IntArray& triIndicesArray,
const PxExtendedVec3& origin, const PxBounds3& tmpBounds, const CCTParams& params, PxU16& nbTessellation)
{
const PxGeometry& geom = boxShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eBOX);
const PxBoxGeometry& bg = static_cast<const PxBoxGeometry&>(geom);
//8 verts in local space.
const PxF32 dx = bg.halfExtents.x;
const PxF32 dy = bg.halfExtents.y;
const PxF32 dz = bg.halfExtents.z;
PxVec3 boxVerts[8]=
{
PxVec3(-dx,-dy,-dz),
PxVec3(+dx,-dy,-dz),
PxVec3(+dx,+dy,-dz),
PxVec3(-dx,+dy,-dz),
PxVec3(-dx,-dy,+dz),
PxVec3(+dx,-dy,+dz),
PxVec3(+dx,+dy,+dz),
PxVec3(-dx,+dy,+dz)
};
//Transform verts into world space.
const PxVec3 pxOrigin = toVec3(origin);
for(PxU32 i = 0; i < 8; i++)
{
boxVerts[i] = globalPose.transform(boxVerts[i]) - pxOrigin;
}
//Index of triangles.
const PxU32 boxTris[12][3]=
{
{0,2,1},
{2,0,3}, //0,1,2,3
{3,6,2},
{6,3,7}, //3,2,6,7
{7,5,6},
{5,7,4}, //7,6,5,4
{4,1,5},
{1,4,0}, //4,5,1,0
{0,7,3},
{7,0,4}, //0,3,7,4
{2,5,1},
{5,2,6} //2,1,5,6
};
TouchedMesh* touchedMesh = reinterpret_cast<TouchedMesh*>(reserveContainerMemory(geomStream, sizeof(TouchedMesh)/sizeof(PxU32)));
touchedMesh->mType = TouchedGeomType::eMESH;
touchedMesh->mTGUserData = boxShape;
touchedMesh->mActor = actor;
touchedMesh->mOffset = origin;
touchedMesh->mIndexWorldTriangles = worldTriangles.size();
if(params.mTessellation)
{
const PxBoxGeometry boxGeom(tmpBounds.getExtents());
const PxVec3 offset(float(-origin.x), float(-origin.y), float(-origin.z));
const PxBounds3 cullingBox = PxBounds3::centerExtents(tmpBounds.getCenter() + offset, boxGeom.halfExtents);
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i<12; i++)
{
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
currentTriangle.verts[0] = boxVerts[boxTris[i][0]];
currentTriangle.verts[1] = boxVerts[boxTris[i][1]];
currentTriangle.verts[2] = boxVerts[boxTris[i][2]];
PxU32 nbNewTris = 0;
tessellateTriangle(nbNewTris, currentTriangle, PX_INVALID_U32, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
nbCreatedTris += nbNewTris;
}
touchedMesh->mNbTris = nbCreatedTris;
}
else
{
touchedMesh->mNbTris = 12;
// Reserve memory for incoming triangles
PxTriangle* TouchedTriangles = worldTriangles.reserve(12);
for(PxU32 i=0; i<12; i++)
{
PxTriangle& currentTriangle = TouchedTriangles[i];
currentTriangle.verts[0] = boxVerts[boxTris[i][0]];
currentTriangle.verts[1] = boxVerts[boxTris[i][1]];
currentTriangle.verts[2] = boxVerts[boxTris[i][2]];
triIndicesArray.pushBack(PX_INVALID_U32);
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PxU32 createInvisibleWalls(const CCTParams& params, const PxTriangle& currentTriangle, TriArray& worldTriangles, IntArray& triIndicesArray)
{
const PxF32 wallHeight = params.mInvisibleWallHeight;
if(wallHeight==0.0f)
return 0;
PxU32 nbNewTris = 0; // Number of newly created tris
const PxVec3& upDirection = params.mUpDirection;
PxVec3 normal;
currentTriangle.normal(normal);
if(testSlope(normal, upDirection, params.mSlopeLimit))
{
const PxVec3 upWall = upDirection*wallHeight;
PxVec3 v0p = currentTriangle.verts[0] + upWall;
PxVec3 v1p = currentTriangle.verts[1] + upWall;
PxVec3 v2p = currentTriangle.verts[2] + upWall;
// Extrude edge 0-1
PxVec3 faceNormal01;
{
// 0-1-0p
const PxTriangle tri0_1_0p(currentTriangle.verts[0], currentTriangle.verts[1], v0p);
worldTriangles.pushBack(tri0_1_0p);
// 0p-1-1p
const PxTriangle tri0p_1_1p(v0p, currentTriangle.verts[1], v1p);
worldTriangles.pushBack(tri0p_1_1p);
tri0p_1_1p.normal(faceNormal01);
}
// Extrude edge 1-2
PxVec3 faceNormal12;
{
// 1p-1-2p
const PxTriangle tri1p_1_2p(v1p, currentTriangle.verts[1], v2p);
worldTriangles.pushBack(tri1p_1_2p);
// 2p-1-2
const PxTriangle tri2p_1_2(v2p, currentTriangle.verts[1], currentTriangle.verts[2]);
worldTriangles.pushBack(tri2p_1_2);
tri2p_1_2.normal(faceNormal12);
}
// Extrude edge 2-0
PxVec3 faceNormal20;
{
// 0p-2-0
const PxTriangle tri0p_2_0(v0p, currentTriangle.verts[2], currentTriangle.verts[0]);
worldTriangles.pushBack(tri0p_2_0);
// 0p-2p-2
const PxTriangle tri0p_2p_2(v0p, v2p, currentTriangle.verts[2]);
worldTriangles.pushBack(tri0p_2p_2);
tri0p_2p_2.normal(faceNormal20);
}
const PxU32 triIndex = PX_INVALID_U32;
for(PxU32 i=0;i<6;i++)
triIndicesArray.pushBack(triIndex);
nbNewTris += 6;
}
return nbNewTris;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputMeshToStream( PxShape* meshShape, const PxRigidActor* actor, const PxTransform& meshPose, IntArray& geomStream, TriArray& worldTriangles, IntArray& triIndicesArray,
const PxExtendedVec3& origin, const PxBounds3& tmpBounds, const CCTParams& params, PxRenderBuffer* renderBuffer, PxU16& nbTessellation)
{
const PxGeometry& geom = meshShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eTRIANGLEMESH);
// Do AABB-mesh query
const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom);
const PxBoxGeometry boxGeom(tmpBounds.getExtents());
const PxTransform boxPose(tmpBounds.getCenter());
// Collide AABB against current mesh
PxMeshOverlapUtil overlapUtil;
const PxU32 nbTouchedTris = overlapUtil.findOverlap(boxGeom, boxPose, triGeom, meshPose);
const PxVec3 offset(float(-origin.x), float(-origin.y), float(-origin.z));
TouchedMesh* touchedMesh = reinterpret_cast<TouchedMesh*>(reserveContainerMemory(geomStream, sizeof(TouchedMesh)/sizeof(PxU32)));
touchedMesh->mType = TouchedGeomType::eMESH;
touchedMesh->mTGUserData = meshShape;
touchedMesh->mActor = actor;
touchedMesh->mOffset = origin;
touchedMesh->mNbTris = nbTouchedTris;
touchedMesh->mIndexWorldTriangles = worldTriangles.size();
const PxU32* PX_RESTRICT indices = overlapUtil.getResults();
if(params.mSlopeLimit!=0.0f)
{
if(!params.mTessellation)
{
// Loop through touched triangles
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(triGeom, meshPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
const PxU32 nbNewTris = createInvisibleWalls(params, currentTriangle, worldTriangles, triIndicesArray);
nbCreatedTris += nbNewTris;
if(!nbNewTris)
{
worldTriangles.pushBack(currentTriangle);
triIndicesArray.pushBack(triangleIndex);
nbCreatedTris++;
}
}
touchedMesh->mNbTris = nbCreatedTris;
}
else
{
const PxBounds3 cullingBox = PxBounds3::centerExtents(boxPose.p + offset, boxGeom.halfExtents);
// Loop through touched triangles
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(triGeom, meshPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
PxU32 nbNewTris = createInvisibleWalls(params, currentTriangle, worldTriangles, triIndicesArray);
nbCreatedTris += nbNewTris;
if(!nbNewTris)
{
/* worldTriangles.pushBack(currentTriangle);
triIndicesArray.pushBack(triangleIndex);
nbCreatedTris++;*/
tessellateTriangle(nbNewTris, currentTriangle, triangleIndex, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
nbCreatedTris += nbNewTris;
// printf("Tesselate: %d new tris\n", nbNewTris);
}
}
touchedMesh->mNbTris = nbCreatedTris;
}
}
else
{
if(!params.mTessellation)
{
// Reserve memory for incoming triangles
PxTriangle* TouchedTriangles = worldTriangles.reserve(nbTouchedTris);
// Loop through touched triangles
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTriangle& currentTriangle = *TouchedTriangles++;
PxMeshQuery::getTriangle(triGeom, meshPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
triIndicesArray.pushBack(triangleIndex);
}
}
else
{
const PxBounds3 cullingBox = PxBounds3::centerExtents(boxPose.p + offset, boxGeom.halfExtents);
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(triGeom, meshPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
PxU32 nbNewTris = 0;
tessellateTriangle(nbNewTris, currentTriangle, triangleIndex, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
// printf("Tesselate: %d new tris\n", nbNewTris);
nbCreatedTris += nbNewTris;
}
touchedMesh->mNbTris = nbCreatedTris;
}
}
if(gVisualizeTouchedTris)
visualizeTouchedTriangles(touchedMesh->mNbTris, touchedMesh->mIndexWorldTriangles, worldTriangles.begin(), renderBuffer, offset, params.mUpDirection);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputHeightFieldToStream( PxShape* hfShape, const PxRigidActor* actor, const PxTransform& heightfieldPose, IntArray& geomStream, TriArray& worldTriangles, IntArray& triIndicesArray,
const PxExtendedVec3& origin, const PxBounds3& tmpBounds, const CCTParams& params, PxRenderBuffer* renderBuffer, PxU16& nbTessellation)
{
const PxGeometry& geom = hfShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD);
// Do AABB-mesh query
const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom);
const PxBoxGeometry boxGeom(tmpBounds.getExtents());
const PxTransform boxPose(tmpBounds.getCenter());
// Collide AABB against current heightfield
PxMeshOverlapUtil overlapUtil;
const PxU32 nbTouchedTris = overlapUtil.findOverlap(boxGeom, boxPose, hfGeom, heightfieldPose);
const PxVec3 offset(float(-origin.x), float(-origin.y), float(-origin.z));
TouchedMesh* touchedMesh = reinterpret_cast<TouchedMesh*>(reserveContainerMemory(geomStream, sizeof(TouchedMesh)/sizeof(PxU32)));
touchedMesh->mType = TouchedGeomType::eMESH; // ptchernev: seems to work
touchedMesh->mTGUserData = hfShape;
touchedMesh->mActor = actor;
touchedMesh->mOffset = origin;
touchedMesh->mNbTris = nbTouchedTris;
touchedMesh->mIndexWorldTriangles = worldTriangles.size();
const PxU32* PX_RESTRICT indices = overlapUtil.getResults();
if(params.mSlopeLimit!=0.0f)
{
if(!params.mTessellation)
{
// Loop through touched triangles
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(hfGeom, heightfieldPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
const PxU32 nbNewTris = createInvisibleWalls(params, currentTriangle, worldTriangles, triIndicesArray);
nbCreatedTris += nbNewTris;
if(!nbNewTris)
{
worldTriangles.pushBack(currentTriangle);
triIndicesArray.pushBack(triangleIndex);
nbCreatedTris++;
}
}
touchedMesh->mNbTris = nbCreatedTris;
}
else
{
const PxBounds3 cullingBox = PxBounds3::centerExtents(boxPose.p + offset, boxGeom.halfExtents);
// Loop through touched triangles
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(hfGeom, heightfieldPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
PxU32 nbNewTris = createInvisibleWalls(params, currentTriangle, worldTriangles, triIndicesArray);
nbCreatedTris += nbNewTris;
if(!nbNewTris)
{
tessellateTriangle(nbNewTris, currentTriangle, triangleIndex, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
nbCreatedTris += nbNewTris;
// printf("Tesselate: %d new tris\n", nbNewTris);
}
}
touchedMesh->mNbTris = nbCreatedTris;
}
}
else
{
if(!params.mTessellation)
{
// Reserve memory for incoming triangles
PxTriangle* TouchedTriangles = worldTriangles.reserve(nbTouchedTris);
// Loop through touched triangles
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTriangle& currentTriangle = *TouchedTriangles++;
PxMeshQuery::getTriangle(hfGeom, heightfieldPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
triIndicesArray.pushBack(triangleIndex);
}
}
else
{
const PxBounds3 cullingBox = PxBounds3::centerExtents(boxPose.p + offset, boxGeom.halfExtents);
PxU32 nbCreatedTris = 0;
for(PxU32 i=0; i < nbTouchedTris; i++)
{
const PxU32 triangleIndex = indices[i];
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
PxMeshQuery::getTriangle(hfGeom, heightfieldPose, triangleIndex, currentTriangle);
currentTriangle.verts[0] += offset;
currentTriangle.verts[1] += offset;
currentTriangle.verts[2] += offset;
PxU32 nbNewTris = 0;
tessellateTriangle(nbNewTris, currentTriangle, triangleIndex, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
// printf("Tesselate: %d new tris\n", nbNewTris);
nbCreatedTris += nbNewTris;
}
touchedMesh->mNbTris = nbCreatedTris;
}
}
if(gVisualizeTouchedTris)
visualizeTouchedTriangles(touchedMesh->mNbTris, touchedMesh->mIndexWorldTriangles, worldTriangles.begin(), renderBuffer, offset, params.mUpDirection);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void outputConvexToStream(PxShape* convexShape, const PxRigidActor* actor, const PxTransform& absPose_, IntArray& geomStream, TriArray& worldTriangles, IntArray& triIndicesArray,
const PxExtendedVec3& origin, const PxBounds3& tmpBounds, const CCTParams& params, PxRenderBuffer* renderBuffer, PxU16& nbTessellation)
{
const PxGeometry& geom = convexShape->getGeometry();
PX_ASSERT(geom.getType() == PxGeometryType::eCONVEXMESH);
const PxConvexMeshGeometry& cg = static_cast<const PxConvexMeshGeometry&>(geom);
PX_ASSERT(cg.convexMesh);
// Do AABB-mesh query
PxU32* TF;
// Collide AABB against current mesh
// The overlap function doesn't exist for convexes so let's just dump all tris
PxConvexMesh& cm = *cg.convexMesh;
// PT: convex triangles are not exposed anymore so we need to access convex polygons & triangulate them
// PT: TODO: this is copied from "DrawObjects", move this to a shared place. Actually a helper directly in PxConvexMesh would be useful.
PxU32 Nb = 0;
{
const PxU32 nbPolys = cm.getNbPolygons();
const PxU8* polygons = cm.getIndexBuffer();
for(PxU32 i=0;i<nbPolys;i++)
{
PxHullPolygon data;
cm.getPolygonData(i, data);
Nb += data.mNbVerts - 2;
}
// PT: revisit this code. We don't use the polygon offset?
TF = reinterpret_cast<PxU32*>(PxAlloca(sizeof(PxU32)*Nb*3));
PxU32* t = TF;
for(PxU32 i=0;i<nbPolys;i++)
{
PxHullPolygon data;
cm.getPolygonData(i, data);
const PxU32 nbV = data.mNbVerts;
const PxU32 nbTris = nbV - 2;
const PxU8 vref0 = *polygons;
for(PxU32 j=0;j<nbTris;j++)
{
const PxU32 vref1 = polygons[(j+1)%nbV];
const PxU32 vref2 = polygons[(j+2)%nbV];
*t++ = vref0;
*t++ = vref1;
*t++ = vref2;
}
polygons += nbV;
}
}
// PT: you can't use PxTransform with a non-uniform scaling
const PxMat33 rot = PxMat33Padded(absPose_.q) * cg.scale.toMat33();
const PxMat44 absPose(rot, absPose_.p);
const PxVec3 absPosTmp = absPose.getPosition();
const PxExtendedVec3 absPos(PxExtended(absPosTmp.x), PxExtended(absPosTmp.y), PxExtended(absPosTmp.z));
const PxVec3 MeshOffset(diff(absPos, origin)); // LOSS OF ACCURACY
const PxVec3 offset(float(-origin.x), float(-origin.y), float(-origin.z));
TouchedMesh* touchedMesh = reinterpret_cast<TouchedMesh*>(reserveContainerMemory(geomStream, sizeof(TouchedMesh)/sizeof(PxU32)));
touchedMesh->mType = TouchedGeomType::eMESH;
touchedMesh->mTGUserData = convexShape;
touchedMesh->mActor = actor;
touchedMesh->mOffset = origin;
touchedMesh->mIndexWorldTriangles = worldTriangles.size();
const PxVec3* verts = cm.getVertices();
// Loop through touched triangles
if(params.mTessellation)
{
const PxBoxGeometry boxGeom(tmpBounds.getExtents());
const PxBounds3 cullingBox = PxBounds3::centerExtents(tmpBounds.getCenter() + offset, boxGeom.halfExtents);
PxU32 nbCreatedTris = 0;
while(Nb--)
{
// Compute triangle in world space, add to array
PxTrianglePadded currentTriangle;
const PxU32 vref0 = *TF++;
const PxU32 vref1 = *TF++;
const PxU32 vref2 = *TF++;
currentTriangle.verts[0] = MeshOffset + absPose.rotate(verts[vref0]);
currentTriangle.verts[1] = MeshOffset + absPose.rotate(verts[vref1]);
currentTriangle.verts[2] = MeshOffset + absPose.rotate(verts[vref2]);
PxU32 nbNewTris = 0;
tessellateTriangle(nbNewTris, currentTriangle, PX_INVALID_U32, worldTriangles, triIndicesArray, cullingBox, params, nbTessellation);
nbCreatedTris += nbNewTris;
}
touchedMesh->mNbTris = nbCreatedTris;
}
else
{
// Reserve memory for incoming triangles
PxTriangle* TouchedTriangles = worldTriangles.reserve(Nb);
touchedMesh->mNbTris = Nb;
while(Nb--)
{
// Compute triangle in world space, add to array
PxTriangle& currentTriangle = *TouchedTriangles++;
const PxU32 vref0 = *TF++;
const PxU32 vref1 = *TF++;
const PxU32 vref2 = *TF++;
currentTriangle.verts[0] = MeshOffset + absPose.rotate(verts[vref0]);
currentTriangle.verts[1] = MeshOffset + absPose.rotate(verts[vref1]);
currentTriangle.verts[2] = MeshOffset + absPose.rotate(verts[vref2]);
triIndicesArray.pushBack(PX_INVALID_U32);
}
}
if(gVisualizeTouchedTris)
visualizeTouchedTriangles(touchedMesh->mNbTris, touchedMesh->mIndexWorldTriangles, worldTriangles.begin(), renderBuffer, offset, params.mUpDirection);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxU32 Cct::getSceneTimestamp(const InternalCBData_FindTouchedGeom* userData)
{
PX_ASSERT(userData);
const PxInternalCBData_FindTouchedGeom* internalData = static_cast<const PxInternalCBData_FindTouchedGeom*>(userData);
PxScene* scene = internalData->scene;
return scene->getSceneQueryStaticTimestamp();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Cct::findTouchedGeometry(
const InternalCBData_FindTouchedGeom* userData,
const PxExtendedBounds3& worldBounds, // ### we should also accept other volumes
TriArray& worldTriangles,
IntArray& triIndicesArray,
IntArray& geomStream,
const CCTFilter& filter,
const CCTParams& params,
PxU16& nbTessellation)
{
PX_ASSERT(userData);
const PxInternalCBData_FindTouchedGeom* internalData = static_cast<const PxInternalCBData_FindTouchedGeom*>(userData);
PxScene* scene = internalData->scene;
PX_PROFILE_ZONE("CharacterController.findTouchedGeometry", PxU64(scene));
PxRenderBuffer* renderBuffer = internalData->renderBuffer;
PxExtendedVec3 Origin; // Will be TouchedGeom::mOffset
getCenter(worldBounds, Origin);
// Find touched *boxes* i.e. touched objects' AABBs in the world
// We collide against dynamic shapes too, to get back dynamic boxes/etc
// TODO: add active groups in interface!
PxQueryFlags sqFilterFlags;
if(filter.mStaticShapes) sqFilterFlags |= PxQueryFlag::eSTATIC;
if(filter.mDynamicShapes) sqFilterFlags |= PxQueryFlag::eDYNAMIC;
if(filter.mFilterCallback)
{
if(filter.mPreFilter)
sqFilterFlags |= PxQueryFlag::ePREFILTER;
if(filter.mPostFilter)
sqFilterFlags |= PxQueryFlag::ePOSTFILTER;
}
// ### this one is dangerous
const PxBounds3 tmpBounds(toVec3(worldBounds.minimum), toVec3(worldBounds.maximum)); // LOSS OF ACCURACY
// PT: unfortunate conversion forced by the PxGeometry API
const PxVec3 center = tmpBounds.getCenter();
const PxVec3 extents = tmpBounds.getExtents();
const PxU32 size = 100;
PxOverlapHit hits[size];
PxQueryFilterData sceneQueryFilterData = filter.mFilterData ? PxQueryFilterData(*filter.mFilterData, sqFilterFlags) : PxQueryFilterData(sqFilterFlags);
PxOverlapBuffer hitBuffer(hits, size);
sceneQueryFilterData.flags |= PxQueryFlag::eNO_BLOCK; // fix for DE8255
PxU32 numberHits = 0;
if (extents.x > 0.0f && extents.y > 0.0f && extents.z > 0.0f)
{
scene->overlap(PxBoxGeometry(extents), PxTransform(center), hitBuffer, sceneQueryFilterData, filter.mFilterCallback);
numberHits = hitBuffer.getNbAnyHits();
}
for(PxU32 i = 0; i < numberHits; i++)
{
const PxOverlapHit& hit = hitBuffer.getAnyHit(i);
PxShape* shape = hit.shape;
PxRigidActor* actor = hit.actor;
if(!shape || !actor)
continue;
// Filtering
// Discard all CCT shapes, i.e. kinematic actors we created ourselves. We don't need to collide with them since they're surrounded
// by the real CCT volume - and collisions with those are handled elsewhere.
if(internalData->cctShapeHashSet->contains(shape))
continue;
// Ubi (EA) : Discarding Triggers :
if(shape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)
continue;
// PT: here you might want to disable kinematic objects.
// Output shape to stream
const PxTransform globalPose = getShapeGlobalPose(*shape, *actor);
const PxGeometryType::Enum type = shape->getGeometry().getType(); // ### VIRTUAL!
if(type==PxGeometryType::eSPHERE) outputSphereToStream (shape, actor, globalPose, geomStream, Origin);
else if(type==PxGeometryType::eCAPSULE) outputCapsuleToStream (shape, actor, globalPose, geomStream, Origin);
else if(type==PxGeometryType::eBOX) outputBoxToStream (shape, actor, globalPose, geomStream, worldTriangles, triIndicesArray, Origin, tmpBounds, params, nbTessellation);
else if(type==PxGeometryType::eTRIANGLEMESH) outputMeshToStream (shape, actor, globalPose, geomStream, worldTriangles, triIndicesArray, Origin, tmpBounds, params, renderBuffer, nbTessellation);
else if(type==PxGeometryType::eHEIGHTFIELD) outputHeightFieldToStream (shape, actor, globalPose, geomStream, worldTriangles, triIndicesArray, Origin, tmpBounds, params, renderBuffer, nbTessellation);
else if(type==PxGeometryType::eCONVEXMESH) outputConvexToStream (shape, actor, globalPose, geomStream, worldTriangles, triIndicesArray, Origin, tmpBounds, params, renderBuffer, nbTessellation);
else if(type==PxGeometryType::ePLANE) outputPlaneToStream (shape, actor, globalPose, geomStream, worldTriangles, triIndicesArray, Origin, tmpBounds, params, renderBuffer);
else if(type==PxGeometryType::eCUSTOM) outputCustomToStream (shape, actor, globalPose, geomStream, Origin);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "characterkinematic/PxControllerBehavior.h"
#include "CctCharacterControllerManager.h"
#include "CctObstacleContext.h"
// #### hmmm, in the down case, isn't reported length too big ? It contains our artificial up component,
// that might confuse the user
static void fillCCTHit(PxControllerHit& hit, const SweptContact& contact, const PxVec3& dir, float length, Controller* controller)
{
hit.controller = controller->getPxController();
hit.worldPos = contact.mWorldPos;
hit.worldNormal = contact.mWorldNormal;
hit.dir = dir;
hit.length = length;
}
static const PxU32 defaultBehaviorFlags = 0;
PxU32 Cct::shapeHitCallback(const InternalCBData_OnHit* userData, const SweptContact& contact, const PxVec3& dir, float length)
{
Controller* controller = static_cast<const PxInternalCBData_OnHit*>(userData)->controller;
PxControllerShapeHit hit;
fillCCTHit(hit, contact, dir, length, controller);
hit.shape = const_cast<PxShape*>(reinterpret_cast<const PxShape*>(contact.mGeom->mTGUserData));
hit.actor = const_cast<PxRigidActor*>(contact.mGeom->mActor);
hit.triangleIndex = contact.mTriangleIndex;
if(controller->mReportCallback)
controller->mReportCallback->onShapeHit(hit);
PxControllerBehaviorCallback* behaviorCB = controller->mBehaviorCallback;
return behaviorCB ? behaviorCB->getBehaviorFlags(*hit.shape, *hit.actor) : defaultBehaviorFlags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE PxU32 handleObstacleHit(const PxObstacle& touchedObstacle, const PxObstacleHandle& obstacleHandle, PxControllerObstacleHit& hit, const PxInternalCBData_OnHit* internalData, Controller* controller)
{
hit.userData = touchedObstacle.mUserData;
const_cast<PxInternalCBData_OnHit*>(internalData)->touchedObstacle = &touchedObstacle; // (*) PT: TODO: revisit
const_cast<PxInternalCBData_OnHit*>(internalData)->touchedObstacleHandle = obstacleHandle;
if(controller->mReportCallback)
controller->mReportCallback->onObstacleHit(hit);
PxControllerBehaviorCallback* behaviorCB = controller->mBehaviorCallback;
return behaviorCB ? behaviorCB->getBehaviorFlags(touchedObstacle) : defaultBehaviorFlags;
}
PxU32 Cct::userHitCallback(const InternalCBData_OnHit* userData, const SweptContact& contact, const PxVec3& dir, float length)
{
const PxInternalCBData_OnHit* internalData = static_cast<const PxInternalCBData_OnHit*>(userData);
Controller* controller = internalData->controller;
const PxU32 objectCode = PxU32(size_t(contact.mGeom->mTGUserData));
const UserObjectType type = decodeType(objectCode);
const PxU32 index = decodeIndex(objectCode);
if(type==USER_OBJECT_CCT)
{
PX_ASSERT(index<controller->getCctManager()->getNbControllers());
Controller** controllers = controller->getCctManager()->getControllers();
Controller* other = controllers[index];
PxControllersHit hit;
fillCCTHit(hit, contact, dir, length, controller);
hit.other = other->getPxController();
if(controller->mReportCallback)
controller->mReportCallback->onControllerHit(hit);
PxControllerBehaviorCallback* behaviorCB = controller->mBehaviorCallback;
return behaviorCB ? behaviorCB->getBehaviorFlags(*hit.other) : defaultBehaviorFlags;
}
else if(type==USER_OBJECT_BOX_OBSTACLE)
{
PX_ASSERT(internalData->obstacles);
PX_ASSERT(index<internalData->obstacles->mBoxObstacles.size());
PxControllerObstacleHit hit;
fillCCTHit(hit, contact, dir, length, controller);
const ObstacleContext::InternalBoxObstacle& obstacle = internalData->obstacles->mBoxObstacles[index];
const PxBoxObstacle& touchedObstacle = obstacle.mData;
return handleObstacleHit(touchedObstacle, obstacle.mHandle , hit, internalData, controller);
}
else if(type==USER_OBJECT_CAPSULE_OBSTACLE)
{
PX_ASSERT(internalData->obstacles);
PX_ASSERT(index<internalData->obstacles->mCapsuleObstacles.size());
PxControllerObstacleHit hit;
fillCCTHit(hit, contact, dir, length, controller);
const ObstacleContext::InternalCapsuleObstacle& obstacle = internalData->obstacles->mCapsuleObstacles[index];
const PxCapsuleObstacle& touchedObstacle = obstacle.mData;
return handleObstacleHit(touchedObstacle, obstacle.mHandle, hit, internalData, controller);
}
else PX_ASSERT(0);
return defaultBehaviorFlags;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 43,512 | C++ | 37.439046 | 219 | 0.689557 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsContext.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 "PxvConfig.h"
#include "PxcContactCache.h"
#include "PxsRigidBody.h"
#include "PxsContactManager.h"
#include "PxsContext.h"
#include "PxPhysXConfig.h"
#include "foundation/PxBitMap.h"
#include "CmFlushPool.h"
#include "PxsMaterialManager.h"
#include "PxSceneDesc.h"
#include "PxsCCD.h"
#include "PxvGeometry.h"
#include "PxvManager.h"
#include "PxsSimpleIslandManager.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
#endif
#include "PxcNpContactPrepShared.h"
#include "PxcNpCache.h"
using namespace physx;
PxsContext::PxsContext(const PxSceneDesc& desc, PxTaskManager* taskManager, Cm::FlushPool& taskPool, PxCudaContextManager* cudaContextManager, PxU32 poolSlabSize, PxU64 contextID) :
mNpThreadContextPool (this),
mContactManagerPool ("mContactManagerPool", this, poolSlabSize),
mManifoldPool ("mManifoldPool", poolSlabSize),
mSphereManifoldPool ("mSphereManifoldPool", poolSlabSize),
mContactModifyCallback (NULL),
mNpImplementationContext (NULL),
mNpFallbackImplementationContext(NULL),
mTaskManager (taskManager),
mTaskPool (taskPool),
mCudaContextManager (cudaContextManager),
mPCM (desc.flags & PxSceneFlag::eENABLE_PCM),
mContactCache (false),
mCreateAveragePoint (desc.flags & PxSceneFlag::eENABLE_AVERAGE_POINT),
mContextID (contextID)
{
clearManagerTouchEvents();
mVisualizationCullingBox.setEmpty();
PxMemZero(mVisualizationParams, sizeof(PxReal) * PxVisualizationParameter::eNUM_VALUES);
mNpMemBlockPool.init(desc.nbContactDataBlocks, desc.maxNbContactDataBlocks);
}
PxsContext::~PxsContext()
{
PX_DELETE(mTransformCache);
mContactManagerPool.destroy(); //manually destroy the contact manager pool, otherwise pool deletion order is random and we can get into trouble with references into other pools needed during destruction.
}
// =========================== Create methods
namespace physx
{
bool gEnablePCMCaching[][PxGeometryType::eGEOMETRY_COUNT] =
{
//eSPHERE,
{
false, //eSPHERE
false, //ePLANE
false, //eCAPSULE
false, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
true, //eTRIANGLEMESH
true, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//ePLANE
{
false, //eSPHERE
false, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//eCAPSULE,
{
false, //eSPHERE
true, //ePLANE
false, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
true, //eTRIANGLEMESH
true, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//eBOX,
{
false, //eSPHERE
true, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
true, //eTRIANGLEMESH
true, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//eCONVEXMESH,
{
true, //eSPHERE
true, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
true, //eTRIANGLEMESH
true, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//ePARTICLESYSTEM
{
false, //eSPHERE
false, //ePLANE
false, //eCAPSULE
false, //eBOX
false, //eCONVEXMESH
false, //ePARTICLESYSTEM
false, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
false, //eCUSTOM
},
//eSOFTBODY
{
false, //eSPHERE
false, //ePLANE
false, //eCAPSULE
false, //eBOX
false, //eCONVEXMESH
false, //ePARTICLESYSTEM
false, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
false, //eCUSTOM
},
//eTRIANGLEMESH,
{
true, //eSPHERE
false, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//eHEIGHTFIELD,
{
true, //eSPHERE
false, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
true, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
},
//eHAIRSYSTEM
{
false, //eSPHERE
false, //ePLANE
false, //eCAPSULE
false, //eBOX
false, //eCONVEXMESH
false, //ePARTICLESYSTEM
false, //eSOFTBODY,
false, //eTRIANGLEMESH
false, //eHEIGHTFIELD
false, //eHAIRSYSTEM
false, //eCUSTOM
},
//eCUSTOM,
{
true, //eSPHERE
true, //ePLANE
true, //eCAPSULE
true, //eBOX
true, //eCONVEXMESH
false, //ePARTICLESYSTEM
false, //eSOFTBODY,
true, //eTRIANGLEMESH
true, //eHEIGHTFIELD
false, //eHAIRSYSTEM
true, //eCUSTOM
}
};
PX_COMPILE_TIME_ASSERT(sizeof(gEnablePCMCaching) / sizeof(gEnablePCMCaching[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
void PxsContext::createTransformCache(PxVirtualAllocatorCallback& allocatorCallback)
{
mTransformCache = PX_NEW(PxsTransformCache)(allocatorCallback);
}
PxsContactManager* PxsContext::createContactManager(PxsContactManager* contactManager, bool useCCD)
{
PxsContactManager* cm = contactManager? contactManager : mContactManagerPool.get();
if(cm)
{
cm->getWorkUnit().clearCachedState();
if(!contactManager)
setActiveContactManager(cm, useCCD);
}
else
{
PX_WARN_ONCE("Reached limit of contact pairs.");
}
return cm;
}
void PxsContext::createCache(Gu::Cache& cache, PxGeometryType::Enum geomType0, PxGeometryType::Enum geomType1)
{
if(mPCM)
{
if(gEnablePCMCaching[geomType0][geomType1])
{
if(geomType0 <= PxGeometryType::eCONVEXMESH && geomType1 <= PxGeometryType::eCONVEXMESH)
{
if(geomType0 == PxGeometryType::eSPHERE || geomType1 == PxGeometryType::eSPHERE)
{
Gu::PersistentContactManifold* manifold = mSphereManifoldPool.allocate();
PX_PLACEMENT_NEW(manifold, Gu::SpherePersistentContactManifold());
cache.setManifold(manifold);
}
else
{
Gu::PersistentContactManifold* manifold = mManifoldPool.allocate();
PX_PLACEMENT_NEW(manifold, Gu::LargePersistentContactManifold());
cache.setManifold(manifold);
}
cache.getManifold().clearManifold();
}
else
{
//ML: raised 1 to indicate the manifold is multiManifold which is for contact gen in mesh/height field
//cache.manifold = 1;
cache.setMultiManifold(NULL);
}
}
else
{
//cache.manifold = 0;
cache.mCachedData = NULL;
cache.mManifoldFlags = 0;
}
}
}
void PxsContext::destroyContactManager(PxsContactManager* cm)
{
const PxU32 idx = cm->getIndex();
if(cm->getCCD())
mActiveContactManagersWithCCD.growAndReset(idx);
//mActiveContactManager.growAndReset(idx);
mContactManagerTouchEvent.growAndReset(idx);
mContactManagerPool.put(cm);
}
void PxsContext::destroyCache(Gu::Cache& cache)
{
if(cache.isManifold())
{
if(!cache.isMultiManifold())
{
Gu::PersistentContactManifold& manifold = cache.getManifold();
if(manifold.mCapacity == GU_SPHERE_MANIFOLD_CACHE_SIZE)
mSphereManifoldPool.deallocate(static_cast<Gu::SpherePersistentContactManifold*>(&manifold));
else
mManifoldPool.deallocate(static_cast<Gu::LargePersistentContactManifold*>(&manifold));
}
cache.mCachedData = NULL;
cache.mManifoldFlags = 0;
}
}
void PxsContext::setScratchBlock(void* addr, PxU32 size)
{
mScratchAllocator.setBlock(addr, size);
}
void PxsContext::shiftOrigin(const PxVec3& shift)
{
// transform cache
mTransformCache->shiftTransforms(-shift);
#if 0
if (getContactCacheFlag())
{
//Iterate all active contact managers
PxBitMap::Iterator it(mActiveContactManager);
PxU32 index = it.getNext();
while(index != PxBitMap::Iterator::DONE)
{
PxsContactManager* cm = mContactManagerPool.findByIndexFast(index);
PxcNpWorkUnit& npwUnit = cm->getWorkUnit();
// contact cache
if(!npwUnit.pairCache.isManifold())
{
PxU8* contactCachePtr = npwUnit.pairCache.mCachedData;
if (contactCachePtr)
{
PxcLocalContactsCache* lcc;
PxU8* contacts = PxcNpCacheRead(npwUnit.pairCache, lcc);
#ifdef _DEBUG
PxcLocalContactsCache testCache;
PxU32 testBytes;
const PxU8* testPtr = PxcNpCacheRead2(npwUnit.pairCache, testCache, testBytes);
#endif
lcc->mTransform0.p -= shift;
lcc->mTransform1.p -= shift;
const PxU32 nbContacts = lcc->mNbCachedContacts;
const bool sameNormal = lcc->mSameNormal;
const bool useFaceIndices = lcc->mUseFaceIndices;
for(PxU32 i=0; i < nbContacts; i++)
{
if (i != nbContacts-1)
PxPrefetchLine(contacts, 128);
if(!i || !sameNormal)
contacts += sizeof(PxVec3);
PxVec3* cachedPoint = reinterpret_cast<PxVec3*>(contacts);
*cachedPoint -= shift;
contacts += sizeof(PxVec3);
contacts += sizeof(PxReal);
if(useFaceIndices)
contacts += 2 * sizeof(PxU32);
}
#ifdef _DEBUG
PX_ASSERT(contacts == (testPtr + testBytes));
#endif
}
}
index = it.getNext();
}
}
#endif
// adjust visualization culling box
if(!mVisualizationCullingBox.isEmpty())
{
mVisualizationCullingBox.minimum -= shift;
mVisualizationCullingBox.maximum -= shift;
}
}
void PxsContext::swapStreams()
{
mNpMemBlockPool.swapNpCacheStreams();
}
void PxsContext::mergeCMDiscreteUpdateResults(PxBaseTask* /*continuation*/)
{
PX_PROFILE_ZONE("Sim.narrowPhaseMerge", mContextID);
this->mNpImplementationContext->appendContactManagers();
//Note: the iterator extracts all the items and returns them to the cache on destruction(for thread safety).
PxcThreadCoherentCacheIterator<PxcNpThreadContext, PxcNpContext> threadContextIt(mNpThreadContextPool);
for(PxcNpThreadContext* threadContext = threadContextIt.getNext(); threadContext; threadContext = threadContextIt.getNext())
{
mCMTouchEventCount[PXS_LOST_TOUCH_COUNT] += threadContext->getLocalLostTouchCount();
mCMTouchEventCount[PXS_NEW_TOUCH_COUNT] += threadContext->getLocalNewTouchCount();
#if PX_ENABLE_SIM_STATS
for(PxU32 i=0;i<PxGeometryType::eGEOMETRY_COUNT;i++)
{
#if PX_DEBUG
for(PxU32 j=0; j<i; j++)
PX_ASSERT(!threadContext->mDiscreteContactPairs[i][j]);
#endif
for(PxU32 j=i; j<PxGeometryType::eGEOMETRY_COUNT; j++)
{
const PxU32 nb = threadContext->mDiscreteContactPairs[i][j];
const PxU32 nbModified = threadContext->mModifiedContactPairs[i][j];
mSimStats.mNbDiscreteContactPairs[i][j] += nb;
mSimStats.mNbModifiedContactPairs[i][j] += nbModified;
mSimStats.mNbDiscreteContactPairsTotal += nb;
}
}
mSimStats.mNbDiscreteContactPairsWithCacheHits += threadContext->mNbDiscreteContactPairsWithCacheHits;
mSimStats.mNbDiscreteContactPairsWithContacts += threadContext->mNbDiscreteContactPairsWithContacts;
mSimStats.mTotalCompressedContactSize += threadContext->mCompressedCacheSize;
//KS - this data is not available yet
//mSimStats.mTotalConstraintSize += threadContext->mConstraintSize;
threadContext->clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mContactManagerTouchEvent.combineInPlace<PxBitMap::OR>(threadContext->getLocalChangeTouch());
//mContactManagerPatchChangeEvent.combineInPlace<PxBitMap::OR>(threadContext->getLocalPatchChangeMap());
mTotalCompressedCacheSize += threadContext->mTotalCompressedCacheSize;
mMaxPatches = PxMax(mMaxPatches, threadContext->mMaxPatches);
threadContext->mTotalCompressedCacheSize = threadContext->mMaxPatches = 0;
}
}
void PxsContext::updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation, PxBaseTask* firstPassContinuation,
Cm::FanoutTask* updateBoundAndShapeTask)
{
PX_ASSERT(mNpImplementationContext);
return mNpImplementationContext->updateContactManager(dt, hasContactDistanceChanged, continuation,
firstPassContinuation, updateBoundAndShapeTask);
}
void PxsContext::secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation)
{
PX_ASSERT(mNpImplementationContext);
mNpImplementationContext->secondPassUpdateContactManager(dt, continuation);
}
void PxsContext::fetchUpdateContactManager()
{
PX_ASSERT(mNpImplementationContext);
mNpImplementationContext->fetchUpdateContactManager();
mergeCMDiscreteUpdateResults(NULL);
}
void PxsContext::resetThreadContexts()
{
//Note: the iterator extracts all the items and returns them to the cache on destruction(for thread safety).
PxcThreadCoherentCacheIterator<PxcNpThreadContext, PxcNpContext> threadContextIt(mNpThreadContextPool);
PxcNpThreadContext* threadContext = threadContextIt.getNext();
while(threadContext != NULL)
{
threadContext->reset(mContactManagerTouchEvent.size());
threadContext = threadContextIt.getNext();
}
}
bool PxsContext::getManagerTouchEventCount(int* newTouch, int* lostTouch, int* ccdTouch) const
{
if(newTouch)
*newTouch = int(mCMTouchEventCount[PXS_NEW_TOUCH_COUNT]);
if(lostTouch)
*lostTouch = int(mCMTouchEventCount[PXS_LOST_TOUCH_COUNT]);
if(ccdTouch)
*ccdTouch = int(mCMTouchEventCount[PXS_CCD_RETOUCH_COUNT]);
return true;
}
bool PxsContext::fillManagerTouchEvents(PxvContactManagerTouchEvent* newTouch, PxI32& newTouchCount, PxvContactManagerTouchEvent* lostTouch, PxI32& lostTouchCount,
PxvContactManagerTouchEvent* ccdTouch, PxI32& ccdTouchCount)
{
const PxvContactManagerTouchEvent* newTouchStart = newTouch;
const PxvContactManagerTouchEvent* lostTouchStart = lostTouch;
const PxvContactManagerTouchEvent* ccdTouchStart = ccdTouch;
const PxvContactManagerTouchEvent* newTouchEnd = newTouch + newTouchCount;
const PxvContactManagerTouchEvent* lostTouchEnd = lostTouch + lostTouchCount;
const PxvContactManagerTouchEvent* ccdTouchEnd = ccdTouch + ccdTouchCount;
PX_UNUSED(newTouchEnd);
PX_UNUSED(lostTouchEnd);
PX_UNUSED(ccdTouchEnd);
PxU32 index;
PxBitMap::Iterator it(mContactManagerTouchEvent);
while((index = it.getNext()) != PxBitMap::Iterator::DONE)
{
PxsContactManager* cm = mContactManagerPool.findByIndexFast(index);
if(cm->getTouchStatus())
{
if(!cm->getHasCCDRetouch())
{
PX_ASSERT(newTouch < newTouchEnd);
newTouch->setCMTouchEventUserData(cm->getShapeInteraction());
newTouch++;
}
else
{
PX_ASSERT(ccdTouch);
PX_ASSERT(ccdTouch < ccdTouchEnd);
ccdTouch->setCMTouchEventUserData(cm->getShapeInteraction());
cm->clearCCDRetouch();
ccdTouch++;
}
}
else
{
PX_ASSERT(lostTouch < lostTouchEnd);
lostTouch->setCMTouchEventUserData(cm->getShapeInteraction());
lostTouch++;
}
}
newTouchCount = PxI32(newTouch - newTouchStart);
lostTouchCount = PxI32(lostTouch - lostTouchStart);
ccdTouchCount = PxI32(ccdTouch - ccdTouchStart);
return true;
}
void PxsContext::beginUpdate()
{
#if PX_ENABLE_SIM_STATS
mSimStats.clearAll();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
| 17,041 | C++ | 27.835871 | 204 | 0.713632 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsSimpleIslandManager.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 "PxsSimpleIslandManager.h"
#include "foundation/PxSort.h"
#include "PxsContactManager.h"
#include "CmTask.h"
#include "DyVArticulation.h"
#define IG_SANITY_CHECKS 0
using namespace physx;
using namespace IG;
ThirdPassTask::ThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager, IslandSim& islandSim) : Cm::Task(contextID), mIslandManager(islandManager), mIslandSim(islandSim)
{
}
PostThirdPassTask::PostThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager) : Cm::Task(contextID), mIslandManager(islandManager)
{
}
SimpleIslandManager::SimpleIslandManager(bool useEnhancedDeterminism, PxU64 contextID) :
mDestroyedNodes ("mDestroyedNodes"),
mDestroyedEdges ("mDestroyedEdges"),
mFirstPartitionEdges ("mFirstPartitionEdges"),
mDestroyedPartitionEdges ("IslandSim::mDestroyedPartitionEdges"),
mIslandManager (&mFirstPartitionEdges, mEdgeNodeIndices, &mDestroyedPartitionEdges, contextID),
mSpeculativeIslandManager (NULL, mEdgeNodeIndices, NULL, contextID),
mSpeculativeThirdPassTask (contextID, *this, mSpeculativeIslandManager),
mAccurateThirdPassTask (contextID, *this, mIslandManager),
mPostThirdPassTask (contextID, *this),
mContextID (contextID)
{
mFirstPartitionEdges.resize(1024);
mMaxDirtyNodesPerFrame = useEnhancedDeterminism ? 0xFFFFFFFF : 1000u;
}
SimpleIslandManager::~SimpleIslandManager()
{
}
PxNodeIndex SimpleIslandManager::addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addRigidBody(body, isKinematic, isActive, nodeIndex);
mSpeculativeIslandManager.addRigidBody(body, isKinematic, isActive, nodeIndex);
return nodeIndex;
}
void SimpleIslandManager::removeNode(const PxNodeIndex index)
{
PX_ASSERT(mNodeHandles.isValidHandle(index.index()));
mDestroyedNodes.pushBack(index);
}
PxNodeIndex SimpleIslandManager::addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addArticulation(llArtic, isActive, nodeIndex);
mSpeculativeIslandManager.addArticulation(llArtic, isActive, nodeIndex);
return nodeIndex;
}
#if PX_SUPPORT_GPU_PHYSX
PxNodeIndex SimpleIslandManager::addSoftBody(Dy::SoftBody* llSoftBody, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addSoftBody(llSoftBody, isActive, nodeIndex);
mSpeculativeIslandManager.addSoftBody(llSoftBody, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addFEMCloth(llFEMCloth, isActive, nodeIndex);
mSpeculativeIslandManager.addFEMCloth(llFEMCloth, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addParticleSystem(llParticleSystem, isActive, nodeIndex);
mSpeculativeIslandManager.addParticleSystem(llParticleSystem, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addHairSystem(Dy::HairSystem* llHairSystem, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addHairSystem(llHairSystem, isActive, nodeIndex);
mSpeculativeIslandManager.addHairSystem(llHairSystem, isActive, nodeIndex);
return nodeIndex;
}
#endif //PX_SUPPORT_GPU_PHYSX
EdgeIndex SimpleIslandManager::addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction, Edge::EdgeType edgeType)
{
const EdgeIndex handle = mEdgeHandles.getHandle();
const PxU32 nodeIds = 2 * handle;
if (mEdgeNodeIndices.size() == nodeIds)
{
PX_PROFILE_ZONE("ReserveEdges", getContextId());
const PxU32 newSize = nodeIds + 2048;
mEdgeNodeIndices.resize(newSize);
mConstraintOrCm.resize(newSize);
mInteractions.resize(newSize);
}
mEdgeNodeIndices[nodeIds] = nodeHandle1;
mEdgeNodeIndices[nodeIds+1] = nodeHandle2;
mConstraintOrCm[handle] = manager;
mInteractions[handle] = interaction;
mSpeculativeIslandManager.addConnection(nodeHandle1, nodeHandle2, edgeType, handle);
if (manager)
manager->getWorkUnit().mEdgeIndex = handle;
if (mConnectedMap.size() == handle)
mConnectedMap.resize(2 * (handle + 1));
if (mFirstPartitionEdges.capacity() == handle)
mFirstPartitionEdges.resize(2 * (handle + 1));
mConnectedMap.reset(handle);
return handle;
}
EdgeIndex SimpleIslandManager::addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction)
{
const EdgeIndex handle = mEdgeHandles.getHandle();
const PxU32 nodeIds = 2 * handle;
if (mEdgeNodeIndices.size() == nodeIds)
{
const PxU32 newSize = nodeIds + 2048;
mEdgeNodeIndices.resize(newSize);
mConstraintOrCm.resize(newSize);
mInteractions.resize(newSize);
}
mEdgeNodeIndices[nodeIds] = nodeHandle1;
mEdgeNodeIndices[nodeIds + 1] = nodeHandle2;
mConstraintOrCm[handle] = constraint;
mInteractions[handle] = interaction;
mIslandManager.addConstraint(constraint, nodeHandle1, nodeHandle2, handle);
mSpeculativeIslandManager.addConstraint(constraint, nodeHandle1, nodeHandle2, handle);
if(mConnectedMap.size() == handle)
mConnectedMap.resize(2*(mConnectedMap.size()+1));
if (mFirstPartitionEdges.capacity() == handle)
mFirstPartitionEdges.resize(2 * (mFirstPartitionEdges.capacity() + 1));
mConnectedMap.set(handle);
return handle;
}
void SimpleIslandManager::activateNode(PxNodeIndex index)
{
mIslandManager.activateNode(index);
mSpeculativeIslandManager.activateNode(index);
}
void SimpleIslandManager::deactivateNode(PxNodeIndex index)
{
mIslandManager.deactivateNode(index);
mSpeculativeIslandManager.deactivateNode(index);
}
void SimpleIslandManager::putNodeToSleep(PxNodeIndex index)
{
mIslandManager.putNodeToSleep(index);
mSpeculativeIslandManager.putNodeToSleep(index);
}
void SimpleIslandManager::removeConnection(EdgeIndex edgeIndex)
{
if(edgeIndex == IG_INVALID_EDGE)
return;
mDestroyedEdges.pushBack(edgeIndex);
mSpeculativeIslandManager.removeConnection(edgeIndex);
if(mConnectedMap.test(edgeIndex))
{
mIslandManager.removeConnection(edgeIndex);
mConnectedMap.reset(edgeIndex);
}
mConstraintOrCm[edgeIndex] = NULL;
mInteractions[edgeIndex] = NULL;
}
void SimpleIslandManager::firstPassIslandGen()
{
PX_PROFILE_ZONE("Basic.firstPassIslandGen", getContextId());
mSpeculativeIslandManager.clearDeactivations();
mSpeculativeIslandManager.wakeIslands();
mSpeculativeIslandManager.processNewEdges();
mSpeculativeIslandManager.removeDestroyedEdges();
mSpeculativeIslandManager.processLostEdges(mDestroyedNodes, false, false, mMaxDirtyNodesPerFrame);
}
void SimpleIslandManager::additionalSpeculativeActivation()
{
mSpeculativeIslandManager.wakeIslands2();
}
void SimpleIslandManager::secondPassIslandGen()
{
PX_PROFILE_ZONE("Basic.secondPassIslandGen", getContextId());
mIslandManager.wakeIslands();
mIslandManager.processNewEdges();
mIslandManager.removeDestroyedEdges();
mIslandManager.processLostEdges(mDestroyedNodes, false, false, mMaxDirtyNodesPerFrame);
for(PxU32 a = 0; a < mDestroyedNodes.size(); ++a)
mNodeHandles.freeHandle(mDestroyedNodes[a].index());
mDestroyedNodes.clear();
//mDestroyedEdges.clear();
}
bool SimpleIslandManager::validateDeactivations() const
{
//This method sanity checks the deactivations produced by third-pass island gen. Specifically, it ensures that any bodies that
//the speculative IG wants to deactivate are also candidates for deactivation in the accurate island gen. In practice, both should be the case. If this fails, something went wrong...
const PxNodeIndex* const nodeIndices = mSpeculativeIslandManager.getNodesToDeactivate(Node::eRIGID_BODY_TYPE);
const PxU32 nbNodesToDeactivate = mSpeculativeIslandManager.getNbNodesToDeactivate(Node::eRIGID_BODY_TYPE);
for(PxU32 i = 0; i < nbNodesToDeactivate; ++i)
{
//Node is active in accurate sim => mismatch between accurate and inaccurate sim!
const Node& node = mIslandManager.getNode(nodeIndices[i]);
const Node& speculativeNode = mSpeculativeIslandManager.getNode(nodeIndices[i]);
//KS - we need to verify that the bodies in the "deactivating" list are still candidates for deactivation. There are cases where they may not no longer be candidates, e.g. if the application
//put bodies to sleep and activated them
if(node.isActive() && !speculativeNode.isActive())
return false;
}
return true;
}
void ThirdPassTask::runInternal()
{
PX_PROFILE_ZONE("Basic.thirdPassIslandGen", mIslandSim.getContextId());
mIslandSim.removeDestroyedEdges();
mIslandSim.processLostEdges(mIslandManager.mDestroyedNodes, true, true, mIslandManager.mMaxDirtyNodesPerFrame);
}
void PostThirdPassTask::runInternal()
{
for (PxU32 a = 0; a < mIslandManager.mDestroyedNodes.size(); ++a)
mIslandManager.mNodeHandles.freeHandle(mIslandManager.mDestroyedNodes[a].index());
mIslandManager.mDestroyedNodes.clear();
for (PxU32 a = 0; a < mIslandManager.mDestroyedEdges.size(); ++a)
mIslandManager.mEdgeHandles.freeHandle(mIslandManager.mDestroyedEdges[a]);
mIslandManager.mDestroyedEdges.clear();
PX_ASSERT(mIslandManager.validateDeactivations());
}
void SimpleIslandManager::thirdPassIslandGen(PxBaseTask* continuation)
{
mIslandManager.clearDeactivations();
mPostThirdPassTask.setContinuation(continuation);
mSpeculativeThirdPassTask.setContinuation(&mPostThirdPassTask);
mAccurateThirdPassTask.setContinuation(&mPostThirdPassTask);
mSpeculativeThirdPassTask.removeReference();
mAccurateThirdPassTask.removeReference();
mPostThirdPassTask.removeReference();
//PX_PROFILE_ZONE("Basic.thirdPassIslandGen", getContextId());
//mSpeculativeIslandManager.removeDestroyedEdges();
//mSpeculativeIslandManager.processLostEdges(mDestroyedNodes, true, true);
//mIslandManager.removeDestroyedEdges();
//mIslandManager.processLostEdges(mDestroyedNodes, true, true);
}
bool SimpleIslandManager::checkInternalConsistency()
{
return mIslandManager.checkInternalConsistency() && mSpeculativeIslandManager.checkInternalConsistency();
}
void SimpleIslandManager::setEdgeConnected(EdgeIndex edgeIndex, Edge::EdgeType edgeType)
{
if(!mConnectedMap.test(edgeIndex))
{
mIslandManager.addConnection(mEdgeNodeIndices[edgeIndex * 2], mEdgeNodeIndices[edgeIndex * 2 + 1], edgeType, edgeIndex);
mConnectedMap.set(edgeIndex);
}
}
bool SimpleIslandManager::getIsEdgeConnected(EdgeIndex edgeIndex)
{
return !!mConnectedMap.test(edgeIndex);
}
void SimpleIslandManager::deactivateEdge(const EdgeIndex edgeIndex)
{
if (mFirstPartitionEdges[edgeIndex])
{
mDestroyedPartitionEdges.pushBack(mFirstPartitionEdges[edgeIndex]);
mFirstPartitionEdges[edgeIndex] = NULL;
}
}
void SimpleIslandManager::setEdgeDisconnected(EdgeIndex edgeIndex)
{
if(mConnectedMap.test(edgeIndex))
{
//PX_ASSERT(!mIslandManager.getEdge(edgeIndex).isInDirtyList());
mIslandManager.removeConnection(edgeIndex);
mConnectedMap.reset(edgeIndex);
}
}
void SimpleIslandManager::setEdgeRigidCM(const EdgeIndex edgeIndex, PxsContactManager* cm)
{
mConstraintOrCm[edgeIndex] = cm;
cm->getWorkUnit().mEdgeIndex = edgeIndex;
}
void SimpleIslandManager::clearEdgeRigidCM(const EdgeIndex edgeIndex)
{
mConstraintOrCm[edgeIndex] = NULL;
if (mFirstPartitionEdges[edgeIndex])
{
//this is the partition edges created/updated by the gpu solver
mDestroyedPartitionEdges.pushBack(mFirstPartitionEdges[edgeIndex]);
mFirstPartitionEdges[edgeIndex] = NULL;
}
}
void SimpleIslandManager::setKinematic(PxNodeIndex nodeIndex)
{
mIslandManager.setKinematic(nodeIndex);
mSpeculativeIslandManager.setKinematic(nodeIndex);
}
void SimpleIslandManager::setDynamic(PxNodeIndex nodeIndex)
{
mIslandManager.setDynamic(nodeIndex);
mSpeculativeIslandManager.setDynamic(nodeIndex);
}
| 13,879 | C++ | 34.228426 | 192 | 0.797824 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsContactManager.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 "PxsContactManager.h"
using namespace physx;
PxsContactManager::PxsContactManager(PxsContext*, PxU32 index)
{
mFlags = 0;
// PT: TODO: any reason why we don't initialize all members here, e.g. shapeCore pointers?
mNpUnit.index = index;
mNpUnit.rigidCore0 = NULL;
mNpUnit.rigidCore1 = NULL;
mNpUnit.restDistance = 0;
mNpUnit.dominance0 = 1u;
mNpUnit.dominance1 = 1u;
mNpUnit.frictionDataPtr = NULL;
mNpUnit.frictionPatchCount = 0;
}
PxsContactManager::~PxsContactManager()
{
}
void PxsContactManager::setCCD(bool enable)
{
PxU32 flags = mFlags & (~PXS_CM_CCD_CONTACT);
if (enable)
flags |= PXS_CM_CCD_LINEAR;
else
flags &= ~PXS_CM_CCD_LINEAR;
mFlags = flags;
}
| 2,405 | C++ | 37.190476 | 91 | 0.75052 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsNphaseImplementationContext.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 "PxsContext.h"
#include "CmFlushPool.h"
#include "PxsSimpleIslandManager.h"
#include "common/PxProfileZone.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
#endif
#include "PxsContactManagerState.h"
#include "PxsNphaseImplementationContext.h"
#include "PxvGeometry.h"
#include "PxvDynamics.h"
#include "PxvGlobals.h"
#include "PxcNpContactPrepShared.h"
using namespace physx;
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4324)
#endif
class PxsCMUpdateTask : public Cm::Task
{
public:
static const PxU32 BATCH_SIZE = 128;
//static const PxU32 BATCH_SIZE = 32;
PxsCMUpdateTask(PxsContext* context, PxReal dt, PxsContactManager** cmArray, PxsContactManagerOutput* cmOutputs, Gu::Cache* caches, PxU32 cmCount, PxContactModifyCallback* callback) :
Cm::Task (context->getContextId()),
mCmArray (cmArray),
mCmOutputs (cmOutputs),
mCaches (caches),
mContext (context),
mCallback (callback),
mCmCount (cmCount),
mDt (dt),
mNbPatchChanged(0)
{
}
virtual void release();
/*PX_FORCE_INLINE void insert(PxsContactManager* cm)
{
PX_ASSERT(mCmCount < BATCH_SIZE);
mCmArray[mCmCount++]=cm;
}*/
public:
//PxsContactManager* mCmArray[BATCH_SIZE];
PxsContactManager** mCmArray;
PxsContactManagerOutput* mCmOutputs;
Gu::Cache* mCaches;
PxsContext* mContext;
PxContactModifyCallback* mCallback;
PxU32 mCmCount;
PxReal mDt; //we could probably retrieve from context to save space?
PxU32 mNbPatchChanged;
PxsContactManagerOutputCounts mPatchChangedOutputCounts[BATCH_SIZE];
PxsContactManager* mPatchChangedCms[BATCH_SIZE];
};
#if PX_VC
#pragma warning(pop)
#endif
void PxsCMUpdateTask::release()
{
// We used to do Task::release(); here before fixing DE1106 (xbox pure virtual crash)
// Release in turn causes the dependent tasks to start running
// The problem was that between the time release was called and by the time we got to the destructor
// The task chain would get all the way to scene finalization code which would reset the allocation pool
// And a new task would get allocated at the same address, then we would invoke the destructor on that freshly created task
// This could potentially cause any number of other problems, it is suprising that it only manifested itself
// as a pure virtual crash
PxBaseTask* saveContinuation = mCont;
this->~PxsCMUpdateTask();
if (saveContinuation)
saveContinuation->removeReference();
}
static const bool gUseNewTaskAllocationScheme = false;
class PxsCMDiscreteUpdateTask : public PxsCMUpdateTask
{
public:
PxsCMDiscreteUpdateTask(PxsContext* context, PxReal dt, PxsContactManager** cms, PxsContactManagerOutput* cmOutputs, Gu::Cache* caches, PxU32 nbCms,
PxContactModifyCallback* callback):
PxsCMUpdateTask(context, dt, cms, cmOutputs, caches, nbCms, callback)
{}
virtual ~PxsCMDiscreteUpdateTask()
{}
void runModifiableContactManagers(PxU32* modifiableIndices, PxU32 nbModifiableManagers, PxcNpThreadContext& threadContext, PxU32& maxPatches_)
{
PX_ASSERT(nbModifiableManagers != 0);
PxU32 maxPatches = maxPatches_;
class PxcContactSet: public PxContactSet
{
public:
PxcContactSet(PxU32 count, PxModifiableContact *contacts)
{
mContacts = contacts;
mCount = count;
}
PxModifiableContact* getContacts() { return mContacts; }
PxU32 getCount() { return mCount; }
};
if(mCallback)
{
PX_ALLOCA(mModifiablePairArray, PxContactModifyPair, nbModifiableManagers);
PxsTransformCache& transformCache = mContext->getTransformCache();
for(PxU32 i = 0; i < nbModifiableManagers; ++i)
{
PxU32 index = modifiableIndices[i];
PxsContactManager& cm = *mCmArray[index];
PxsContactManagerOutput& output = mCmOutputs[index];
PxU32 count = output.nbContacts;
if(count)
{
PxContactModifyPair& p = mModifiablePairArray[i];
PxcNpWorkUnit &unit = cm.getWorkUnit();
p.shape[0] = gPxvOffsetTable.convertPxsShape2Px(unit.shapeCore0);
p.shape[1] = gPxvOffsetTable.convertPxsShape2Px(unit.shapeCore1);
p.actor[0] = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(unit.rigidCore0)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(unit.rigidCore0);
p.actor[1] = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(unit.rigidCore1)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(unit.rigidCore1);
p.transform[0] = transformCache.getTransformCache(unit.mTransformCache0).transform;
p.transform[1] = transformCache.getTransformCache(unit.mTransformCache1).transform;
PxModifiableContact* contacts = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
static_cast<PxcContactSet&>(p.contacts) = PxcContactSet(count, contacts);
PxReal mi0 = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : PX_MAX_F32;
PxReal mi1 = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : PX_MAX_F32;
PxReal maxImpulse = PxMin(mi0, mi1);
for (PxU32 j = 0; j < count; j++)
contacts[j].maxImpulse = maxImpulse;
#if PX_ENABLE_SIM_STATS
PxU8 gt0 = PxTo8(unit.geomType0), gt1 = PxTo8(unit.geomType1);
threadContext.mModifiedContactPairs[PxMin(gt0, gt1)][PxMax(gt0, gt1)]++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
}
mCallback->onContactModify(mModifiablePairArray, nbModifiableManagers);
}
for(PxU32 i = 0; i < nbModifiableManagers; ++i)
{
PxU32 index = modifiableIndices[i];
PxsContactManager& cm = *mCmArray[index];
//Loop through the contacts in the contact stream and update contact count!
PxU32 numContacts = 0;
PxcNpWorkUnit& unit = cm.getWorkUnit();
PxsContactManagerOutput& output = mCmOutputs[index];
PxU32 numPatches = output.nbPatches;
if (output.nbContacts)
{
//PxU8* compressedContacts = cm.getWorkUnit().compressedContacts;
//PxModifyContactHeader* header = reinterpret_cast<PxModifyContactHeader*>(compressedContacts);
PxContactPatch* patches = reinterpret_cast<PxContactPatch*>(output.contactPatches);
PxModifiableContact* points = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
if (patches->internalFlags & PxContactPatch::eREGENERATE_PATCHES)
{
//Some data was modified that must trigger patch re-generation...
for (PxU8 k = 0; k < numPatches; ++k)
{
PxU32 startIndex = patches[k].startContactIndex;
patches[k].normal = points[startIndex].normal;
patches[k].dynamicFriction = points[startIndex].dynamicFriction;
patches[k].staticFriction = points[startIndex].staticFriction;
patches[k].restitution = points[startIndex].restitution;
for (PxU32 j = 1; j < patches[k].nbContacts; ++j)
{
if (points[startIndex].normal.dot(points[j + startIndex].normal) < PXC_SAME_NORMAL
&& points[j + startIndex].maxImpulse > 0.f) //TODO - this needs extending for material indices but we don't support modifying those yet
{
//The points are now in a separate friction patch...
// Shift all patches above index k up by one to make space
for (PxU32 c = numPatches - 1; c > k; --c)
{
patches[c + 1] = patches[c];
}
numPatches++;
patches[k + 1].materialFlags = patches[k].materialFlags;
patches[k + 1].internalFlags = patches[k].internalFlags;
patches[k + 1].startContactIndex = PxTo8(j + startIndex);
patches[k + 1].nbContacts = PxTo8(patches[k].nbContacts - j);
//Fill in patch information now that final patches are available
patches[k].nbContacts = PxU8(j);
break; // we're done with all contacts in patch k because the remaining were just transferrred to patch k+1
}
}
}
}
maxPatches = PxMax(maxPatches, PxU32(numPatches));
output.nbPatches = PxU8(numPatches);
for (PxU32 a = 0; a < output.nbContacts; ++a)
{
numContacts += points[a].maxImpulse != 0.f;
}
}
if (!numContacts)
{
output.nbPatches = 0;
output.nbContacts = 0;
}
if(output.nbPatches != output.prevPatches)
{
mPatchChangedCms[mNbPatchChanged] = &cm;
PxsContactManagerOutputCounts& counts = mPatchChangedOutputCounts[mNbPatchChanged++];
counts.nbPatches = PxU8(numPatches);
counts.prevPatches = output.prevPatches;
counts.statusFlag = output.statusFlag;
//counts.nbContacts = output.nbContacts16;
}
if(!numContacts)
{
//KS - we still need to retain the patch count from the previous frame to detect found/lost events...
unit.clearCachedState();
continue;
}
if(threadContext.mContactStreamPool)
{
//We need to allocate a new structure inside the contact stream pool
PxU32 patchSize = output.nbPatches * sizeof(PxContactPatch);
PxU32 contactSize = output.nbContacts * sizeof(PxExtendedContact);
/*PxI32 increment = (PxI32)(patchSize + contactSize);
PxI32 index = PxAtomicAdd(&mContactStreamPool->mSharedContactIndex, increment) - increment;
PxU8* address = mContactStreamPool->mContactStream + index;*/
bool isOverflown = false;
PxI32 contactIncrement = PxI32(contactSize);
PxI32 contactIndex = PxAtomicAdd(&threadContext.mContactStreamPool->mSharedDataIndex, contactIncrement);
if (threadContext.mContactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
PxU8* contactAddress = threadContext.mContactStreamPool->mDataStream + threadContext.mContactStreamPool->mDataStreamSize - contactIndex;
PxI32 patchIncrement = PxI32(patchSize);
PxI32 patchIndex = PxAtomicAdd(&threadContext.mPatchStreamPool->mSharedDataIndex, patchIncrement);
if (threadContext.mPatchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
PxU8* patchAddress = threadContext.mPatchStreamPool->mDataStream + threadContext.mPatchStreamPool->mDataStreamSize - patchIndex;
PxU32 internalFlags = reinterpret_cast<PxContactPatch*>(output.contactPatches)->internalFlags;
PxI32 increment2 = PxI32(output.nbContacts * sizeof(PxReal));
PxI32 index2 = PxAtomicAdd(&threadContext.mForceAndIndiceStreamPool->mSharedDataIndex, increment2);
if (threadContext.mForceAndIndiceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
if (isOverflown)
{
output.contactPoints = NULL;
output.contactPatches = NULL;
output.contactForces = NULL;
output.nbContacts = output.nbPatches = 0;
}
else
{
output.contactForces = reinterpret_cast<PxReal*>(threadContext.mForceAndIndiceStreamPool->mDataStream + threadContext.mForceAndIndiceStreamPool->mDataStreamSize - index2);
PxMemZero(output.contactForces, sizeof(PxReal) * output.nbContacts);
PxExtendedContact* contacts = reinterpret_cast<PxExtendedContact*>(contactAddress);
PxMemCopy(patchAddress, output.contactPatches, sizeof(PxContactPatch) * output.nbPatches);
PxContactPatch* newPatches = reinterpret_cast<PxContactPatch*>(patchAddress);
internalFlags |= PxContactPatch::eCOMPRESSED_MODIFIED_CONTACT;
for(PxU32 a = 0; a < output.nbPatches; ++a)
{
newPatches[a].internalFlags = PxU8(internalFlags);
}
//KS - only the first patch will have mass modification properties set. For the GPU solver, this must be propagated to the remaining patches
for(PxU32 a = 1; a < output.nbPatches; ++a)
{
newPatches[a].mMassModification = newPatches->mMassModification;
}
PxModifiableContact* sourceContacts = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
for(PxU32 a = 0; a < output.nbContacts; ++a)
{
PxExtendedContact& contact = contacts[a];
PxModifiableContact& srcContact = sourceContacts[a];
contact.contact = srcContact.contact;
contact.separation = srcContact.separation;
contact.targetVelocity = srcContact.targetVelocity;
contact.maxImpulse = srcContact.maxImpulse;
}
output.contactPatches = patchAddress;
output.contactPoints = reinterpret_cast<PxU8*>(contacts);
}
}
}
maxPatches_ = maxPatches;
}
template < void (*NarrowPhase)(PxcNpThreadContext&, const PxcNpWorkUnit&, Gu::Cache&, PxsContactManagerOutput&, PxU64)>
void processCms(PxcNpThreadContext* threadContext)
{
const PxU64 contextID = mContext->getContextId();
//PX_PROFILE_ZONE("processCms", mContext->getContextId());
// PT: use local variables to avoid reading class members N times, if possible
const PxU32 nb = mCmCount;
PxsContactManager** PX_RESTRICT cmArray = mCmArray;
PxU32 maxPatches = threadContext->mMaxPatches;
PxU32 newTouchCMCount = 0, lostTouchCMCount = 0;
PxBitMap& localChangeTouchCM = threadContext->getLocalChangeTouch();
PX_ALLOCA(modifiableIndices, PxU32, nb);
PxU32 modifiableCount = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 prefetch1 = PxMin(i + 1, nb - 1);
const PxU32 prefetch2 = PxMin(i + 2, nb - 1);
PxPrefetchLine(cmArray[prefetch2]);
PxPrefetchLine(&mCmOutputs[prefetch2]);
PxPrefetchLine(cmArray[prefetch1]->getWorkUnit().shapeCore0);
PxPrefetchLine(cmArray[prefetch1]->getWorkUnit().shapeCore1);
PxPrefetchLine(&threadContext->mTransformCache->getTransformCache(cmArray[prefetch1]->getWorkUnit().mTransformCache0));
PxPrefetchLine(&threadContext->mTransformCache->getTransformCache(cmArray[prefetch1]->getWorkUnit().mTransformCache1));
PxsContactManager* const cm = cmArray[i];
if(cm)
{
PxsContactManagerOutput& output = mCmOutputs[i];
PxcNpWorkUnit& unit = cm->getWorkUnit();
output.prevPatches = output.nbPatches;
PxU8 oldStatusFlag = output.statusFlag;
PxU8 oldTouch = PxTo8(oldStatusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH);
Gu::Cache& cache = mCaches[i];
NarrowPhase(*threadContext, unit, cache, output, contextID);
PxU16 newTouch = PxTo8(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH);
bool modifiable = output.nbPatches != 0 && unit.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT;
if(modifiable)
{
modifiableIndices[modifiableCount++] = i;
}
else
{
maxPatches = PxMax(maxPatches, PxTo32(output.nbPatches));
if(output.prevPatches != output.nbPatches)
{
mPatchChangedCms[mNbPatchChanged] = cm;
PxsContactManagerOutputCounts& counts = mPatchChangedOutputCounts[mNbPatchChanged++];
counts.nbPatches = output.nbPatches;
counts.prevPatches = output.prevPatches;
counts.statusFlag = output.statusFlag;
//counts.nbContacts = output.nbContacts;
}
}
if (newTouch ^ oldTouch)
{
unit.statusFlags = PxU8(output.statusFlag | (unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)); //KS - todo - remove the need to access the work unit at all!
localChangeTouchCM.growAndSet(cmArray[i]->getIndex());
if(newTouch)
newTouchCMCount++;
else
lostTouchCMCount++;
}
else if (!(oldStatusFlag&PxsContactManagerStatusFlag::eTOUCH_KNOWN))
{
unit.statusFlags = PxU8(output.statusFlag | (unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)); //KS - todo - remove the need to access the work unit at all!
}
}
}
if(modifiableCount)
runModifiableContactManagers(modifiableIndices, modifiableCount, *threadContext, maxPatches);
threadContext->addLocalNewTouchCount(newTouchCMCount);
threadContext->addLocalLostTouchCount(lostTouchCMCount);
threadContext->mMaxPatches = maxPatches;
}
virtual void runInternal()
{
PX_PROFILE_ZONE("Sim.narrowPhase", mContext->getContextId());
PxcNpThreadContext* PX_RESTRICT threadContext = mContext->getNpThreadContext();
threadContext->mDt = mDt;
const bool pcm = mContext->getPCM();
threadContext->mPCM = pcm;
threadContext->mCreateAveragePoint = mContext->getCreateAveragePoint();
threadContext->mContactCache = mContext->getContactCacheFlag();
threadContext->mTransformCache = &mContext->getTransformCache();
threadContext->mContactDistances = mContext->getContactDistances();
if(pcm)
processCms<PxcDiscreteNarrowPhasePCM>(threadContext);
else
processCms<PxcDiscreteNarrowPhase>(threadContext);
mContext->putNpThreadContext(threadContext);
}
virtual const char* getName() const
{
return "PxsContext.contactManagerDiscreteUpdate";
}
};
static void processContactManagers(PxsContext& context, PxsContactManagers& narrowPhasePairs, PxArray<PxsCMDiscreteUpdateTask*>& tasks, PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation, PxContactModifyCallback* modifyCallback)
{
Cm::FlushPool& taskPool = context.getTaskPool();
//Iterate all active contact managers
taskPool.lock();
/*const*/ PxU32 nbCmsToProcess = narrowPhasePairs.mContactManagerMapping.size();
// PT: TASK-CREATION TAG
if(!gUseNewTaskAllocationScheme)
{
for(PxU32 a=0; a<nbCmsToProcess;)
{
void* ptr = taskPool.allocateNotThreadSafe(sizeof(PxsCMDiscreteUpdateTask));
PxU32 nbToProcess = PxMin(nbCmsToProcess - a, PxsCMUpdateTask::BATCH_SIZE);
PxsCMDiscreteUpdateTask* task = PX_PLACEMENT_NEW(ptr, PxsCMDiscreteUpdateTask)(&context, dt, narrowPhasePairs.mContactManagerMapping.begin() + a,
cmOutputs + a, narrowPhasePairs.mCaches.begin() + a, nbToProcess, modifyCallback);
a += nbToProcess;
task->setContinuation(continuation);
task->removeReference();
tasks.pushBack(task);
}
}
else
{
// PT:
const PxU32 numCpuTasks = continuation->getTaskManager()->getCpuDispatcher()->getWorkerCount();
PxU32 nbPerTask;
if(numCpuTasks)
nbPerTask = nbCmsToProcess > numCpuTasks ? nbCmsToProcess / numCpuTasks : nbCmsToProcess;
else
nbPerTask = nbCmsToProcess;
// PT: we need to respect that limit even with a single thread, because of hardcoded buffer limits in ScAfterIntegrationTask.
if(nbPerTask>PxsCMUpdateTask::BATCH_SIZE)
nbPerTask = PxsCMUpdateTask::BATCH_SIZE;
PxU32 start = 0;
while(nbCmsToProcess)
{
const PxU32 nb = nbCmsToProcess < nbPerTask ? nbCmsToProcess : nbPerTask;
void* ptr = taskPool.allocateNotThreadSafe(sizeof(PxsCMDiscreteUpdateTask));
PxsCMDiscreteUpdateTask* task = PX_PLACEMENT_NEW(ptr, PxsCMDiscreteUpdateTask)(&context, dt, narrowPhasePairs.mContactManagerMapping.begin() + start,
cmOutputs + start, narrowPhasePairs.mCaches.begin() + start, nb, modifyCallback);
task->setContinuation(continuation);
task->removeReference();
tasks.pushBack(task);
start += nb;
nbCmsToProcess -= nb;
}
}
taskPool.unlock();
}
void PxsNphaseImplementationContext::processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation)
{
processContactManagers(mContext, mNarrowPhasePairs, mCmTasks, dt, cmOutputs, continuation, mModifyCallback);
}
void PxsNphaseImplementationContext::processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation)
{
processContactManagers(mContext, mNewNarrowPhasePairs, mCmTasks, dt, mNewNarrowPhasePairs.mOutputContactManagers.begin(), continuation, mModifyCallback);
}
void PxsNphaseImplementationContext::updateContactManager(PxReal dt, bool /*hasContactDistanceChanged*/, PxBaseTask* continuation,
PxBaseTask* firstPassNpContinuation, Cm::FanoutTask* /*updateBoundAndShapeTask*/)
{
PX_PROFILE_ZONE("Sim.queueNarrowPhase", mContext.mContextID);
firstPassNpContinuation->removeReference();
mContext.clearManagerTouchEvents();
#if PX_ENABLE_SIM_STATS
mContext.mSimStats.mNbDiscreteContactPairsTotal = 0;
mContext.mSimStats.mNbDiscreteContactPairsWithCacheHits = 0;
mContext.mSimStats.mNbDiscreteContactPairsWithContacts = 0;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//KS - temporarily put this here. TODO - move somewhere better
mContext.mTotalCompressedCacheSize = 0;
mContext.mMaxPatches = 0;
processContactManager(dt, mNarrowPhasePairs.mOutputContactManagers.begin(), continuation);
}
void PxsNphaseImplementationContext::secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation)
{
PX_PROFILE_ZONE("Sim.queueNarrowPhase", mContext.mContextID);
processContactManagerSecondPass(dt, continuation);
}
void PxsNphaseImplementationContext::destroy()
{
this->~PxsNphaseImplementationContext();
PX_FREE_THIS;
}
/*void PxsNphaseImplementationContext::registerContactManagers(PxsContactManager** cms, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId)
{
PX_UNUSED(maxContactManagerId);
for (PxU32 a = 0; a < nbContactManagers; ++a)
{
registerContactManager(cms[a], shapeInteractions[a], 0, 0);
}
}*/
void PxsNphaseImplementationContext::registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 patchCount)
{
PX_ASSERT(cm);
PxcNpWorkUnit& workUnit = cm->getWorkUnit();
PxsContactManagerOutput output;
PX_ASSERT(workUnit.geomType0<PxGeometryType::eGEOMETRY_COUNT);
PX_ASSERT(workUnit.geomType1<PxGeometryType::eGEOMETRY_COUNT);
const PxGeometryType::Enum geomType0 = PxGeometryType::Enum(workUnit.geomType0);
const PxGeometryType::Enum geomType1 = PxGeometryType::Enum(workUnit.geomType1);
Gu::Cache cache;
mContext.createCache(cache, geomType0, geomType1);
PxMemZero(&output, sizeof(output));
output.nbPatches = PxTo8(patchCount);
if(workUnit.flags & PxcNpWorkUnitFlag::eOUTPUT_CONSTRAINTS)
output.statusFlag |= PxsContactManagerStatusFlag::eREQUEST_CONSTRAINTS;
if (touching > 0)
output.statusFlag |= PxsContactManagerStatusFlag::eHAS_TOUCH;
else if (touching < 0)
output.statusFlag |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
output.statusFlag |= PxsContactManagerStatusFlag::eDIRTY_MANAGER;
if (workUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH)
workUnit.statusFlags |= PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH;
output.flags = workUnit.flags;
mNewNarrowPhasePairs.mOutputContactManagers.pushBack(output);
mNewNarrowPhasePairs.mCaches.pushBack(cache);
mNewNarrowPhasePairs.mContactManagerMapping.pushBack(cm);
if(mGPU)
{
mNewNarrowPhasePairs.mShapeInteractions.pushBack(shapeInteraction);
mNewNarrowPhasePairs.mRestDistances.pushBack(cm->getRestDistance());
mNewNarrowPhasePairs.mTorsionalProperties.pushBack(PxsTorsionalFrictionData(workUnit.mTorsionalPatchRadius, workUnit.mMinTorsionalPatchRadius));
}
PxU32 newSz = mNewNarrowPhasePairs.mOutputContactManagers.size();
workUnit.mNpIndex = mNewNarrowPhasePairs.computeId(newSz - 1) | PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK;
}
void PxsNphaseImplementationContext::removeContactManagersFallback(PxsContactManagerOutput* cmOutputs)
{
if (mRemovedContactManagers.size())
{
lock();
PxSort(mRemovedContactManagers.begin(), mRemovedContactManagers.size(), PxGreater<PxU32>());
for (PxU32 a = 0; a < mRemovedContactManagers.size(); ++a)
{
#if PX_DEBUG
if (a > 0)
PX_ASSERT(mRemovedContactManagers[a] < mRemovedContactManagers[a - 1]);
#endif
unregisterContactManagerInternal(mRemovedContactManagers[a], mNarrowPhasePairs, cmOutputs);
}
mRemovedContactManagers.forceSize_Unsafe(0);
unlock();
}
}
void PxsNphaseImplementationContext::unregisterContactManager(PxsContactManager* cm)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
unregisterAndForceSize(mNarrowPhasePairs, index);
}
else
{
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
}
void PxsNphaseImplementationContext::refreshContactManager(PxsContactManager* cm)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
PxsContactManagerOutput output;
Sc::ShapeInteraction* interaction;
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
output = mNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index)];
interaction = mGPU ? mNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index)] : cm->getShapeInteraction();
unregisterAndForceSize(mNarrowPhasePairs, index);
}
else
{
output = mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
interaction = mGPU ? mNewNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
PxI32 touching = 0;
if(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH)
touching = 1;
else if (output.statusFlag & PxsContactManagerStatusFlag::eHAS_NO_TOUCH)
touching = -1;
registerContactManager(cm, interaction, touching, output.nbPatches);
}
void PxsNphaseImplementationContext::unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* /*cmOutputs*/)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
mRemovedContactManagers.pushBack(index);
}
else
{
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
}
void PxsNphaseImplementationContext::refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
PxsContactManagerOutput output;
Sc::ShapeInteraction* interaction;
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
output = cmOutputs[PxsContactManagerBase::computeIndexFromId(index)];
interaction = mGPU ? mNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
//unregisterContactManagerInternal(index, mNarrowPhasePairs, cmOutputs);
unregisterContactManagerFallback(cm, cmOutputs);
}
else
{
//KS - the index in the "new" list will be the index
output = mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
interaction = mGPU ? mNewNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
PxI32 touching = 0;
if(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH)
{
touching = 1;
unit.statusFlags |= PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH;
}
else if (output.statusFlag & PxsContactManagerStatusFlag::eHAS_NO_TOUCH)
touching = -1;
registerContactManager(cm, interaction, touching, output.nbPatches);
}
void PxsNphaseImplementationContext::appendContactManagers()
{
//Copy new pairs to end of old pairs. Clear new flag, update npIndex on CM and clear the new pair buffer
const PxU32 existingSize = mNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 nbToAdd = mNewNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 newSize = existingSize + nbToAdd;
if(newSize > mNarrowPhasePairs.mContactManagerMapping.capacity())
{
PxU32 newSz = PxMax(256u, PxMax(mNarrowPhasePairs.mContactManagerMapping.capacity()*2, newSize));
mNarrowPhasePairs.mContactManagerMapping.reserve(newSz);
mNarrowPhasePairs.mOutputContactManagers.reserve(newSz);
mNarrowPhasePairs.mCaches.reserve(newSz);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.reserve(newSz);
mNarrowPhasePairs.mRestDistances.reserve(newSz);
mNarrowPhasePairs.mTorsionalProperties.reserve(newSz);
}
}
mNarrowPhasePairs.mContactManagerMapping.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mOutputContactManagers.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mCaches.forceSize_Unsafe(newSize);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mRestDistances.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mTorsionalProperties.forceSize_Unsafe(newSize);
}
PxMemCopy(mNarrowPhasePairs.mContactManagerMapping.begin() + existingSize, mNewNarrowPhasePairs.mContactManagerMapping.begin(), sizeof(PxsContactManager*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mOutputContactManagers.begin() + existingSize, mNewNarrowPhasePairs.mOutputContactManagers.begin(), sizeof(PxsContactManagerOutput)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mCaches.begin() + existingSize, mNewNarrowPhasePairs.mCaches.begin(), sizeof(Gu::Cache)*nbToAdd);
if(mGPU)
{
PxMemCopy(mNarrowPhasePairs.mShapeInteractions.begin() + existingSize, mNewNarrowPhasePairs.mShapeInteractions.begin(), sizeof(Sc::ShapeInteraction*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mRestDistances.begin() + existingSize, mNewNarrowPhasePairs.mRestDistances.begin(), sizeof(PxReal)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mTorsionalProperties.begin() + existingSize, mNewNarrowPhasePairs.mTorsionalProperties.begin(), sizeof(PxsTorsionalFrictionData)*nbToAdd);
}
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
for(PxU32 a = 0; a < mNewNarrowPhasePairs.mContactManagerMapping.size(); ++a)
{
PxsContactManager* cm = mNewNarrowPhasePairs.mContactManagerMapping[a];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.mNpIndex = mNarrowPhasePairs.computeId(existingSize + a);
if(unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)
{
unit.statusFlags &= (~PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH);
if(!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(unit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = unit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
}
mNewNarrowPhasePairs.clear();
appendNewLostPairs();
}
void PxsNphaseImplementationContext::appendContactManagersFallback(PxsContactManagerOutput* cmOutputs)
{
PX_PROFILE_ZONE("PxsNphaseImplementationContext.appendContactManagersFallback", mContext.mContextID);
//Copy new pairs to end of old pairs. Clear new flag, update npIndex on CM and clear the new pair buffer
const PxU32 existingSize = mNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 nbToAdd = mNewNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 newSize =existingSize + nbToAdd;
if(newSize > mNarrowPhasePairs.mContactManagerMapping.capacity())
{
PxU32 newSz = PxMax(mNarrowPhasePairs.mContactManagerMapping.capacity()*2, newSize);
mNarrowPhasePairs.mContactManagerMapping.reserve(newSz);
mNarrowPhasePairs.mCaches.reserve(newSz);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.reserve(newSz);
mNarrowPhasePairs.mRestDistances.reserve(newSz);
mNarrowPhasePairs.mTorsionalProperties.reserve(newSz);
}
}
mNarrowPhasePairs.mContactManagerMapping.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mCaches.forceSize_Unsafe(newSize);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mRestDistances.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mTorsionalProperties.forceSize_Unsafe(newSize);
}
PxMemCopy(mNarrowPhasePairs.mContactManagerMapping.begin() + existingSize, mNewNarrowPhasePairs.mContactManagerMapping.begin(), sizeof(PxsContactManager*)*nbToAdd);
PxMemCopy(cmOutputs + existingSize, mNewNarrowPhasePairs.mOutputContactManagers.begin(), sizeof(PxsContactManagerOutput)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mCaches.begin() + existingSize, mNewNarrowPhasePairs.mCaches.begin(), sizeof(Gu::Cache)*nbToAdd);
if(mGPU)
{
PxMemCopy(mNarrowPhasePairs.mShapeInteractions.begin() + existingSize, mNewNarrowPhasePairs.mShapeInteractions.begin(), sizeof(Sc::ShapeInteraction*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mRestDistances.begin() + existingSize, mNewNarrowPhasePairs.mRestDistances.begin(), sizeof(PxReal)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mTorsionalProperties.begin() + existingSize, mNewNarrowPhasePairs.mTorsionalProperties.begin(), sizeof(PxsTorsionalFrictionData)*nbToAdd);
}
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
for(PxU32 a = 0; a < mNewNarrowPhasePairs.mContactManagerMapping.size(); ++a)
{
PxsContactManager* cm = mNewNarrowPhasePairs.mContactManagerMapping[a];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.mNpIndex = mNarrowPhasePairs.computeId(existingSize + a);
if(unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)
{
unit.statusFlags &= (~PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH);
if(!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(unit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = unit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
}
mNewNarrowPhasePairs.clear();
appendNewLostPairs();
}
void PxsNphaseImplementationContext::appendNewLostPairs()
{
mCmFoundLostOutputCounts.forceSize_Unsafe(0);
mCmFoundLost.forceSize_Unsafe(0);
PxU32 count = 0;
for (PxU32 i = 0, taskSize = mCmTasks.size(); i < taskSize; ++i)
{
PxsCMDiscreteUpdateTask* task = mCmTasks[i];
const PxU32 patchCount = task->mNbPatchChanged;
if (patchCount)
{
const PxU32 newSize = mCmFoundLostOutputCounts.size() + patchCount;
//KS - TODO - consider switching to 2x loops to avoid frequent allocations. However, we'll probably only grow this rarely,
//so may not be worth the effort!
if (mCmFoundLostOutputCounts.capacity() < newSize)
{
//Allocate more memory!!!
const PxU32 newCapacity = PxMax(mCmFoundLostOutputCounts.capacity() * 2, newSize);
mCmFoundLostOutputCounts.reserve(newCapacity);
mCmFoundLost.reserve(newCapacity);
}
mCmFoundLostOutputCounts.forceSize_Unsafe(newSize);
mCmFoundLost.forceSize_Unsafe(newSize);
PxMemCopy(&mCmFoundLost[count], task->mPatchChangedCms, sizeof(PxsContactManager*)*patchCount);
PxMemCopy(&mCmFoundLostOutputCounts[count], task->mPatchChangedOutputCounts, sizeof(PxsContactManagerOutputCounts)*patchCount);
count += patchCount;
}
}
mCmTasks.forceSize_Unsafe(0);
}
void PxsNphaseImplementationContext::unregisterContactManagerInternal(PxU32 npIndex, PxsContactManagers& managers, PxsContactManagerOutput* cmOutputs)
{
// PX_PROFILE_ZONE("unregisterContactManagerInternal", 0);
//TODO - remove this element from the list.
const PxU32 index = PxsContactManagerBase::computeIndexFromId((npIndex & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK)));
//Now we replace-with-last and remove the elements...
const PxU32 replaceIndex = managers.mContactManagerMapping.size()-1;
PxsContactManager* replaceManager = managers.mContactManagerMapping[replaceIndex];
mContext.destroyCache(managers.mCaches[index]);
managers.mContactManagerMapping[index] = replaceManager;
managers.mCaches[index] = managers.mCaches[replaceIndex];
cmOutputs[index] = cmOutputs[replaceIndex];
if(mGPU)
{
managers.mShapeInteractions[index] = managers.mShapeInteractions[replaceIndex];
managers.mRestDistances[index] = managers.mRestDistances[replaceIndex];
managers.mTorsionalProperties[index] = managers.mTorsionalProperties[replaceIndex];
}
managers.mCaches[replaceIndex].reset();
PxcNpWorkUnit& replaceUnit = replaceManager->getWorkUnit();
replaceUnit.mNpIndex = npIndex;
if(replaceUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH)
{
if(!(replaceUnit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(replaceUnit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = replaceUnit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
managers.mContactManagerMapping.forceSize_Unsafe(replaceIndex);
managers.mCaches.forceSize_Unsafe(replaceIndex);
if(mGPU)
{
managers.mShapeInteractions.forceSize_Unsafe(replaceIndex);
managers.mRestDistances.forceSize_Unsafe(replaceIndex);
managers.mTorsionalProperties.forceSize_Unsafe(replaceIndex);
}
}
PxsContactManagerOutput& PxsNphaseImplementationContext::getNewContactManagerOutput(PxU32 npId)
{
PX_ASSERT(npId & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK);
return mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(npId & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
}
PxsContactManagerOutputIterator PxsNphaseImplementationContext::getContactManagerOutputs()
{
PxU32 offsets[1] = {0};
return PxsContactManagerOutputIterator(offsets, 1, mNarrowPhasePairs.mOutputContactManagers.begin());
}
PxvNphaseImplementationContextUsableAsFallback* physx::createNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* allocator, bool gpuDynamics)
{
// PT: TODO: remove useless placement new
PxsNphaseImplementationContext* npImplContext = reinterpret_cast<PxsNphaseImplementationContext*>(
PX_ALLOC(sizeof(PxsNphaseImplementationContext), "PxsNphaseImplementationContext"));
if(npImplContext)
npImplContext = PX_PLACEMENT_NEW(npImplContext, PxsNphaseImplementationContext)(context, islandSim, allocator, 0, gpuDynamics);
return npImplContext;
}
| 39,916 | C++ | 37.01619 | 249 | 0.761249 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsCCD.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 "geomutils/PxContactPoint.h"
#include "PxsContactManager.h"
#include "PxsContext.h"
#include "PxsRigidBody.h"
#include "PxsMaterialManager.h"
#include "PxsCCD.h"
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcContactMethodImpl.h"
#include "PxcMaterialMethodImpl.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "PxvGlobals.h"
#include "foundation/PxSort.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxMathUtils.h"
#include "CmFlushPool.h"
#include "DyThresholdTable.h"
#include "GuCCDSweepConvexMesh.h"
#include "GuBounds.h"
#include "GuConvexMesh.h"
#include "geometry/PxGeometryQuery.h"
#include "PxsIslandSim.h"
// PT: this one currently makes these UTs fail
// [ FAILED ] CCDReportTest.CCD_soakTest_mesh
// [ FAILED ] CCDReportTest.CCD_soakTest_heightfield
// [ FAILED ] CCDNegativeScalingTest.SLOW_ccdNegScaledMesh
// [ FAILED ] OriginShift.CCD
static const bool gUseGeometryQuery = false;
#if DEBUG_RENDER_CCD
#include "common/PxRenderOutput.h"
#include "common/PxRenderBuffer.h"
#include "PxPhysics.h"
#include "PxScene.h"
#endif
#define DEBUG_RENDER_CCD_FIRST_PASS_ONLY 1
#define DEBUG_RENDER_CCD_ATOM_PTR 0
#define DEBUG_RENDER_CCD_NORMAL 1
#define CCD_ANGULAR_IMPULSE 0 // PT: this doesn't compile anymore
using namespace physx;
using namespace physx::Dy;
using namespace Gu;
static PX_FORCE_INLINE void verifyCCDPair(const PxsCCDPair& /*pair*/)
{
#if 0
if (pair.mBa0)
pair.mBa0->getPose();
if (pair.mBa1)
pair.mBa1->getPose();
#endif
}
#if CCD_DEBUG_PRINTS
// PT: this is copied from PxsRigidBody.h and will need to be adapted if we ever need it again
// AP newccd todo: merge into get both velocities, compute inverse transform once, precompute mLastTransform.getInverse()
PX_FORCE_INLINE PxVec3 getLinearMotionVelocity(PxReal invDt) const
{
// delta(t0(x))=t1(x)
// delta(t0(t0`(x)))=t1(t0`(x))
// delta(x)=t1(t0`(x))
const PxVec3 deltaP = mCore->body2World.p - getLastCCDTransform().p;
return deltaP * invDt;
}
PX_FORCE_INLINE PxVec3 getAngularMotionVelocity(PxReal invDt) const
{
const PxQuat deltaQ = mCore->body2World.q * getLastCCDTransform().q.getConjugate();
PxVec3 axis;
PxReal angle;
deltaQ.toRadiansAndUnitAxis(angle, axis);
return axis * angle * invDt;
}
PX_FORCE_INLINE PxVec3 getLinearMotionVelocity(PxReal dt, const PxsBodyCore* PX_RESTRICT bodyCore) const
{
// delta(t0(x))=t1(x)
// delta(t0(t0`(x)))=t1(t0`(x))
// delta(x)=t1(t0`(x))
const PxVec3 deltaP = bodyCore->body2World.p - getLastCCDTransform().p;
return deltaP * 1.0f / dt;
}
PX_FORCE_INLINE PxVec3 getAngularMotionVelocity(PxReal dt, const PxsBodyCore* PX_RESTRICT bodyCore) const
{
const PxQuat deltaQ = bodyCore->body2World.q * getLastCCDTransform().q.getConjugate();
PxVec3 axis;
PxReal angle;
deltaQ.toRadiansAndUnitAxis(angle, axis);
return axis * angle * 1.0f/dt;
}
#include <stdio.h>
#pragma warning(disable: 4313)
namespace physx {
static const char* gGeomTypes[PxGeometryType::eGEOMETRY_COUNT+1] = {
"sphere", "plane", "capsule", "box", "convex", "trimesh", "heightfield", "*"
};
FILE* gCCDLog = NULL;
static inline void openCCDLog()
{
if (gCCDLog)
{
fclose(gCCDLog);
gCCDLog = NULL;
}
gCCDLog = fopen("c:\\ccd.txt", "wt");
fprintf(gCCDLog, ">>>>>>>>>>>>>>>>>>>>>>>>>>> CCD START FRAME <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
static inline void printSeparator(
const char* prefix, PxU32 pass, PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1)
{
fprintf(gCCDLog, "------- %s pass %d (%s %x) vs (%s %x)\n", prefix, pass, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1);
fflush(gCCDLog);
}
static inline void printCCDToi(
const char* header, PxF32 t, const PxVec3& v,
PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1
)
{
fprintf(gCCDLog, "%s (%s %x vs %s %x): %.5f, (%.2f, %.2f, %.2f)\n", header, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1, t, v.x, v.y, v.z);
fflush(gCCDLog);
}
static inline void printCCDPair(const char* header, PxsCCDPair& pair)
{
printCCDToi(header, pair.mMinToi, pair.mMinToiNormal, pair.mBa0, pair.mG0, pair.mBa1, pair.mG1);
}
// also used in PxcSweepConvexMesh.cpp
void printCCDDebug(const char* msg, const PxsRigidBody* atom0, PxGeometryType::Enum g0, bool printPtr)
{
fprintf(gCCDLog, " %s (%s %x)\n", msg, gGeomTypes[g0], printPtr ? atom0 : 0);
fflush(gCCDLog);
}
// also used in PxcSweepConvexMesh.cpp
void printShape(
PxsRigidBody* atom0, PxGeometryType::Enum g0, const char* annotation, PxReal dt, PxU32 pass, bool printPtr)
{
PX_UNUSED(pass);
// PT: I'm leaving this here but I doubt it works. The code passes "dt" to a function that wants "invDt"....
fprintf(gCCDLog, "%s (%s %x) atom=(%.2f, %.2f, %.2f)>(%.2f, %.2f, %.2f) v=(%.1f, %.1f, %.1f), mv=(%.1f, %.1f, %.1f)\n",
annotation, gGeomTypes[g0], printPtr ? atom0 : 0,
atom0->getLastCCDTransform().p.x, atom0->getLastCCDTransform().p.y, atom0->getLastCCDTransform().p.z,
atom0->getPose().p.x, atom0->getPose().p.y, atom0->getPose().p.z,
atom0->getLinearVelocity().x, atom0->getLinearVelocity().y, atom0->getLinearVelocity().z,
atom0->getLinearMotionVelocity(dt).x, atom0->getLinearMotionVelocity(dt).y, atom0->getLinearMotionVelocity(dt).z );
fflush(gCCDLog);
#if DEBUG_RENDER_CCD && DEBUG_RENDER_CCD_ATOM_PTR
if (!DEBUG_RENDER_CCD_FIRST_PASS_ONLY || pass == 0)
{
PxScene *s; PxGetPhysics()->getScenes(&s, 1, 0);
PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer())
<< DebugText(atom0->getPose().p, 0.05f, "%x", atom0);
}
#endif
}
static inline void flushCCDLog()
{
fflush(gCCDLog);
}
} // namespace physx
#else
namespace physx
{
void printShape(PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, const char* /*annotation*/, PxReal /*dt*/, PxU32 /*pass*/, bool printPtr = true)
{PX_UNUSED(printPtr);}
static inline void openCCDLog() {}
static inline void flushCCDLog() {}
void printCCDDebug(const char* /*msg*/, const PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, bool printPtr = true) {PX_UNUSED(printPtr);}
static inline void printSeparator(
const char* /*prefix*/, PxU32 /*pass*/, PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/,
PxsRigidBody* /*atom1*/, PxGeometryType::Enum /*g1*/) {}
} // namespace physx
#endif
float physx::computeCCDThreshold(const PxGeometry& geometry)
{
// Box, Convex, Mesh and HeightField will compute local bounds and pose to world space.
// Sphere, Capsule & Plane will compute world space bounds directly.
const PxReal inSphereRatio = 0.75f;
//The CCD thresholds are as follows:
//(1) sphere = inSphereRatio * radius
//(2) plane = inf (we never need CCD against this shape)
//(3) capsule = inSphereRatio * radius
//(4) box = inSphereRatio * (box minimum extent axis)
//(5) convex = inSphereRatio * convex in-sphere * min scale
//(6) triangle mesh = 0.0f (polygons have 0 thickness)
//(7) heightfields = 0.0f (polygons have 0 thickness)
//The decision to enter CCD depends on the sum of the shapes' CCD thresholds. One of the 2 shapes must be a
//sphere/capsule/box/convex so the sum of the CCD thresholds will be non-zero.
switch (geometry.getType())
{
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& shape = static_cast<const PxSphereGeometry&>(geometry);
return shape.radius*inSphereRatio;
}
case PxGeometryType::ePLANE:
{
return PX_MAX_REAL;
}
case PxGeometryType::eCAPSULE:
{
const PxCapsuleGeometry& shape = static_cast<const PxCapsuleGeometry&>(geometry);
return shape.radius * inSphereRatio;
}
case PxGeometryType::eBOX:
{
const PxBoxGeometry& shape = static_cast<const PxBoxGeometry&>(geometry);
return PxMin(PxMin(shape.halfExtents.x, shape.halfExtents.y), shape.halfExtents.z)*inSphereRatio;
}
case PxGeometryType::eCONVEXMESH:
{
const PxConvexMeshGeometry& shape = static_cast<const PxConvexMeshGeometry&>(geometry);
const Gu::ConvexHullData& hullData = static_cast<const Gu::ConvexMesh*>(shape.convexMesh)->getHull();
return PxMin(shape.scale.scale.z, PxMin(shape.scale.scale.x, shape.scale.scale.y)) * hullData.mInternal.mRadius * inSphereRatio;
}
case PxGeometryType::eTRIANGLEMESH: { return 0.0f; }
case PxGeometryType::eHEIGHTFIELD: { return 0.0f; }
case PxGeometryType::eTETRAHEDRONMESH: { return 0.0f; }
case PxGeometryType::ePARTICLESYSTEM: { return 0.0f; }
case PxGeometryType::eHAIRSYSTEM: { return 0.0f; }
case PxGeometryType::eCUSTOM: { return 0.0f; }
default:
{
PX_ASSERT(0);
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Gu::computeBoundsWithCCDThreshold::computeBounds: Unknown shape type.");
}
}
return PX_MAX_REAL;
}
static float computeBoundsWithCCDThreshold(PxVec3p& origin, PxVec3p& extent, const PxGeometry& geometry, const PxTransform& transform) //AABB in world space.
{
const PxBounds3 bounds = computeBounds(geometry, transform);
origin = bounds.getCenter();
extent = bounds.getExtents();
return computeCCDThreshold(geometry);
}
static PX_FORCE_INLINE void trTr(PxTransform& out, const PxTransform& a, const PxTransform& b)
{
// PT:: tag: scalar transform*transform
out = a * b;
}
static PX_FORCE_INLINE void trInvTr(PxTransform& out, const PxTransform& a, const PxTransform& b, const PxTransform& c)
{
// PT:: tag: scalar transform*transform
out = a * b.getInverse() * c;
}
// PT: TODO: refactor with ShapeSim version (SIMD), simplify code when shape local pose = idt
static PX_INLINE void getShapeAbsPose(PxTransform& out, const PxsShapeCore* shapeCore, const PxsRigidCore* rigidCore, const void* isDynamic)
{
if(isDynamic)
{
const PxsBodyCore* PX_RESTRICT bodyCore = static_cast<const PxsBodyCore*>(rigidCore);
trInvTr(out, bodyCore->body2World, bodyCore->getBody2Actor(), shapeCore->getTransform());
}
else
trTr(out, rigidCore->body2World, shapeCore->getTransform());
}
// \brief Returns the world-space pose for this shape
// \param[in] atom The rigid body that this CCD shape is associated with
static void getAbsPose(PxTransform32& out, const PxsCCDShape* ccdShape, const PxsRigidBody* atom)
{
// PT: TODO: refactor with ShapeSim version (SIMD) - or with redundant getShapeAbsPose() above in this same file!
// PT: TODO: simplify code when shape local pose = idt
if(atom)
trInvTr(out, atom->getPose(), atom->getCore().getBody2Actor(), ccdShape->mShapeCore->getTransform());
else
trTr(out, ccdShape->mRigidCore->body2World, ccdShape->mShapeCore->getTransform());
}
// \brief Returns the world-space previous pose for this shape
// \param[in] atom The rigid body that this CCD shape is associated with
static void getLastCCDAbsPose(PxTransform32& out, const PxsCCDShape* ccdShape, const PxsRigidBody* atom)
{
// PT: TODO: refactor with ShapeSim version (SIMD)
// PT: TODO: simplify code when shape local pose = idt
// PT:: tag: scalar transform*transform
trInvTr(out, atom->getLastCCDTransform(), atom->getCore().getBody2Actor(), ccdShape->mShapeCore->getTransform());
}
PxsCCDContext::PxsCCDContext(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext, PxReal ccdThreshold) :
mPostCCDSweepTask (context->getContextId(), this, "PxsContext.postCCDSweep"),
mPostCCDAdvanceTask (context->getContextId(), this, "PxsContext.postCCDAdvance"),
mPostCCDDepenetrateTask (context->getContextId(), this, "PxsContext.postCCDDepenetrate"),
mDisableCCDResweep (false),
miCCDPass (0),
mSweepTotalHits (0),
mCCDThreadContext (NULL),
mCCDPairsPerBatch (0),
mCCDMaxPasses (1),
mContext (context),
mThresholdStream (thresholdStream),
mNphaseContext (nPhaseContext),
mCCDThreshold (ccdThreshold)
{
}
PxsCCDContext::~PxsCCDContext()
{
}
void combineMaterials(const PxsMaterialManager* materialManager, PxU16 origMatIndex0, PxU16 origMatIndex1, PxReal& staticFriction, PxReal& dynamicFriction, PxReal& combinedRestitution, PxU32& materialFlags, PxReal& combinedDamping);
PxReal PxsCCDPair::sweepFindToi(PxcNpThreadContext& context, PxReal dt, PxU32 pass, PxReal ccdThreshold)
{
printSeparator("findToi", pass, mBa0, mG0, NULL, PxGeometryType::eGEOMETRY_COUNT);
//Update shape transforms if necessary
updateShapes();
//Extract the bodies
PxsRigidBody* atom0 = mBa0;
PxsRigidBody* atom1 = mBa1;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
//If necessary, flip the bodies to make sure that g0 <= g1
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
atom0 = mBa1;
atom1 = mBa0;
}
const PxTransform32 tm0(ccdShape0->mCurrentTransform);
const PxTransform32 lastTm0(ccdShape0->mPrevTransform);
const PxTransform32 tm1(ccdShape1->mCurrentTransform);
const PxTransform32 lastTm1(ccdShape1->mPrevTransform);
const PxVec3 trA = tm0.p - lastTm0.p;
const PxVec3 trB = tm1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
// Do the sweep
PxVec3 sweepNormal(0.0f);
PxVec3 sweepPoint(0.0f);
context.mDt = dt;
context.mCCDFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
//Cull the sweep hit based on the relative velocity along the normal
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = PxMin(fastMovingThresh0 + fastMovingThresh1, ccdThreshold);
PxReal toi = PX_MAX_REAL;
if(gUseGeometryQuery)
{
// PT: TODO: support restDistance & sumFastMovingThresh here
PxVec3 unitDir = relTr;
const PxReal length = unitDir.normalize();
PxGeomSweepHit sweepHit;
if(PxGeometryQuery::sweep(unitDir, length, *ccdShape0->mGeometry, lastTm0, *ccdShape1->mGeometry, lastTm1, sweepHit, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, 0.0f, PxGeometryQueryFlag::Enum(0), NULL))
{
sweepNormal = sweepHit.normal;
sweepPoint = sweepHit.position;
context.mCCDFaceIndex = sweepHit.faceIndex;
toi = sweepHit.distance/length;
}
}
else
{
const PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.0f);
toi = Gu::SweepShapeShape(*ccdShape0, *ccdShape1, tm0, tm1, lastTm0, lastTm1, restDistance, sweepNormal, sweepPoint, mMinToi, context.mCCDFaceIndex, sumFastMovingThresh);
}
//If toi is after the end of TOI, return no hit
if (toi >= 1.0f)
{
mToiType = PxsCCDPair::ePrecise;
mPenetration = 0.0f;
mPenetrationPostStep = 0.0f;
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return toi;
}
PX_ASSERT(PxIsFinite(toi));
PX_ASSERT(sweepNormal.isFinite());
mFaceIndex = context.mCCDFaceIndex;
//Work out linear motion (used to cull the sweep hit)
const PxReal linearMotion = relTr.dot(-sweepNormal);
//If we swapped the shapes, swap them back
if(mG1 >= mG0)
sweepNormal = -sweepNormal;
mToiType = PxsCCDPair::ePrecise;
PxReal penetration = 0.0f;
PxReal penetrationPostStep = 0.0f;
//If linear motion along normal < the CCD threshold, set toi to no-hit.
if((linearMotion) < sumFastMovingThresh)
{
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return PX_MAX_REAL;
}
else if(toi <= 0.0f)
{
//If the toi <= 0.0f, this implies an initial overlap. If the value < 0.0f, it implies penetration
PxReal stepRatio0 = atom0 ? atom0->mCCD->mTimeLeft : 1.0f;
PxReal stepRatio1 = atom1 ? atom1->mCCD->mTimeLeft : 1.0f;
PxReal stepRatio = PxMin(stepRatio0, stepRatio1);
penetration = -toi;
toi = 0.0f;
if(stepRatio == 1.0f)
{
//If stepRatio == 1.f (i.e. neither body has stepped forwards any time at all)
//we extract the advance coefficients from the bodies and permit the bodies to step forwards a small amount
//to ensure that they won't remain jammed because TOI = 0.0
const PxReal advance0 = atom0 ? atom0->mCore->ccdAdvanceCoefficient : 1.0f;
const PxReal advance1 = atom1 ? atom1->mCore->ccdAdvanceCoefficient : 1.0f;
const PxReal advance = PxMin(advance0, advance1);
PxReal fastMoving = PxMin(fastMovingThresh0, atom1 ? fastMovingThresh1 : PX_MAX_REAL);
PxReal advanceCoeff = advance * fastMoving;
penetrationPostStep = advanceCoeff/linearMotion;
}
PX_ASSERT(PxIsFinite(toi));
}
//Store TOI, penetration and post-step (how much to step forward in initial overlap conditions)
mMinToi = toi;
mPenetration = penetration;
mPenetrationPostStep = penetrationPostStep;
mMinToiPoint = sweepPoint;
mMinToiNormal = sweepNormal;
//Work out the materials for the contact (restitution, friction etc.)
context.mContactBuffer.count = 0;
context.mContactBuffer.contact(mMinToiPoint, mMinToiNormal, 0.0f,
g0 == PxGeometryType::eTRIANGLEMESH || g0 == PxGeometryType::eHEIGHTFIELD ||
g1 == PxGeometryType::eTRIANGLEMESH || g1 == PxGeometryType::eHEIGHTFIELD ? mFaceIndex : PXC_CONTACT_NO_FACE_INDEX);
PxsMaterialInfo materialInfo;
g_GetSingleMaterialMethodTable[g0](ccdShape0->mShapeCore, 0, context, &materialInfo);
g_GetSingleMaterialMethodTable[g1](ccdShape1->mShapeCore, 1, context, &materialInfo);
PxU32 materialFlags;
PxReal combinedDamping;
combineMaterials(context.mMaterialManager, materialInfo.mMaterialIndex0, materialInfo.mMaterialIndex1, mStaticFriction, mDynamicFriction, mRestitution, materialFlags, combinedDamping);
mMaterialIndex0 = materialInfo.mMaterialIndex0;
mMaterialIndex1 = materialInfo.mMaterialIndex1;
return toi;
}
static void updateShape(PxsRigidBody* body, PxsCCDShape* shape)
{
if(body)
{
//If the CCD shape's update count doesn't match the body's update count, this shape needs its transforms and bounds re-calculated
if(body->mCCD->mUpdateCount != shape->mUpdateCount)
{
PxTransform32 tm;
getAbsPose(tm, shape, body);
PxTransform32 lastTm;
getLastCCDAbsPose(lastTm, shape, body);
const PxVec3 trA = tm.p - lastTm.p;
PxVec3p origin, extents;
computeBoundsWithCCDThreshold(origin, extents, shape->mShapeCore->mGeometry.getGeometry(), tm);
shape->mCenter = origin - trA;
shape->mExtents = extents;
shape->mPrevTransform = lastTm;
shape->mCurrentTransform = tm;
shape->mUpdateCount = body->mCCD->mUpdateCount;
}
}
}
void PxsCCDPair::updateShapes()
{
updateShape(mBa0, mCCDShape0);
updateShape(mBa1, mCCDShape1);
}
PxReal PxsCCDPair::sweepEstimateToi(PxReal ccdThreshold)
{
//Update shape transforms if necessary
updateShapes();
//PxsRigidBody* atom1 = mBa1;
//PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
PX_UNUSED(g0);
//Flip shapes if necessary
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
/*atom0 = mBa1;
atom1 = mBa0;*/
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
}
//Extract previous/current transforms, translations etc.
const PxVec3 trA = ccdShape0->mCurrentTransform.p - ccdShape0->mPrevTransform.p;
const PxVec3 trB = ccdShape1->mCurrentTransform.p - ccdShape1->mPrevTransform.p;
const PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.0f);
const PxVec3 relTr = trA - trB;
//Work out the sum of the fast moving thresholds scaled by the step ratio
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = PxMin(fastMovingThresh0 + fastMovingThresh1, ccdThreshold);
mToiType = eEstimate;
//If the objects are not moving fast-enough relative to each-other to warrant CCD, set estimated time as PX_MAX_REAL
if((relTr.magnitudeSquared()) <= (sumFastMovingThresh * sumFastMovingThresh))
{
mToiType = eEstimate;
mMinToi = PX_MAX_REAL;
return PX_MAX_REAL;
}
//Otherwise, the objects *are* moving fast-enough so perform estimation pass
if(g1 == PxGeometryType::eTRIANGLEMESH)
{
//Special-case estimation code for meshes
const PxF32 toi = Gu::SweepEstimateAnyShapeMesh(*ccdShape0, *ccdShape1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
else if (g1 == PxGeometryType::eHEIGHTFIELD)
{
//Special-case estimation code for heightfields
const PxF32 toi = Gu::SweepEstimateAnyShapeHeightfield(*ccdShape0, *ccdShape1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
//Generic estimation code for prim-prim sweeps
const PxVec3& centreA = ccdShape0->mCenter;
const PxVec3 extentsA = ccdShape0->mExtents + PxVec3(restDistance);
const PxVec3& centreB = ccdShape1->mCenter;
const PxVec3& extentsB = ccdShape1->mExtents;
const PxF32 toi = Gu::sweepAABBAABB(centreA, extentsA * 1.1f, centreB, extentsB * 1.1f, trA, trB);
mMinToi = toi;
return toi;
}
bool PxsCCDPair::sweepAdvanceToToi(PxReal dt, bool clipTrajectoryToToi)
{
PxsCCDShape* ccds0 = mCCDShape0;
PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccds1 = mCCDShape1;
PxsRigidBody* atom1 = mBa1;
const PxsCCDPair* thisPair = this;
//Both already had a pass so don't do anything
if ((atom0 == NULL || atom0->mCCD->mPassDone) && (atom1 == NULL || atom1->mCCD->mPassDone))
return false;
//Test to validate that they're both infinite mass objects. If so, there can be no response so terminate on a notification-only
if((atom0 == NULL || atom0->mCore->inverseMass == 0.0f) && (atom1 == NULL || atom1->mCore->inverseMass == 0.0f))
return false;
//If the TOI < 1.f. If not, this hit happens after this frame or at the very end of the frame. Either way, next frame can handle it
if (thisPair->mMinToi < 1.0f)
{
if(thisPair->mCm->getWorkUnit().flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE || thisPair->mMaxImpulse == 0.0f)
{
//Don't mark pass as done on either body
return true;
}
const PxReal minToi = thisPair->mMinToi;
const PxF32 penetration = -mPenetration * 10.0f;
const PxVec3 minToiNormal = thisPair->mMinToiNormal;
if (!minToiNormal.isNormalized())
{
// somehow we got zero normal. This can happen for instance if two identical objects spawn exactly on top of one another
// abort ccd and clip to current toi
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, true);
atom0->mCCD->mUpdateCount++;
}
return true;
}
//Get the material indices...
const PxReal restitution = mRestitution;
const PxReal sFriction = mStaticFriction;
const PxReal dFriction = mDynamicFriction;
PxVec3 v0(0.0f), v1(0.0f);
PxReal invMass0(0.0f), invMass1(0.0f);
#if CCD_ANGULAR_IMPULSE
PxMat33 invInertia0(PxVec3(0.0f), PxVec3(0.0f), PxVec3(0.0f)), invInertia1(PxVec3(0.0f), PxVec3(0.0f), PxVec3(0.0f));
PxVec3 localPoint0(0.0f), localPoint1(0.0f);
#endif
const PxReal dom0 = mCm->getDominance0();
const PxReal dom1 = mCm->getDominance1();
//Work out velocity and invMass for body 0
if(atom0)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint0 = mMinToiPoint - trA.p;
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(localPoint0);
physx::Cm::transformInertiaTensor(atom0->mCore->inverseInertia, PxMat33(trA.q),invInertia0);
invInertia0 *= dom0;
#else
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(ccds0->mCurrentTransform.p - atom0->mCore->body2World.p);
#endif
invMass0 = atom0->getInvMass() * dom0;
}
//Work out velocity and invMass for body 1
if(atom1)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint1 = mMinToiPoint - trB.p;
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(localPoint1);
physx::Cm::transformInertiaTensor(atom1->mCore->inverseInertia, PxMat33(trB.q),invInertia1);
invInertia1 *= dom1;
#else
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(ccds1->mCurrentTransform.p - atom1->mCore->body2World.p);
#endif
invMass1 = atom1->getInvMass() * dom1;
}
PX_ASSERT(v0.isFinite() && v1.isFinite());
//Work out relative velocity
const PxVec3 vRel = v1 - v0;
//Project relative velocity onto contact normal and bias with penetration
const PxReal relNorVel = vRel.dot(minToiNormal);
const PxReal relNorVelPlusPen = relNorVel + penetration;
#if CCD_ANGULAR_IMPULSE
if(relNorVelPlusPen >= -1e-6f)
{
//we fall back on linear only parts...
localPoint0 = PxVec3(0.0f);
localPoint1 = PxVec3(0.0f);
v0 = atom0 ? atom0->getLinearVelocity() : PxVec3(0.0f);
v1 = atom1 ? atom1->getLinearVelocity() : PxVec3(0.0f);
vRel = v1 - v0;
relNorVel = vRel.dot(minToiNormal);
relNorVelPlusPen = relNorVel + penetration;
}
#endif
//If the relative motion is moving towards each-other, respond
if(relNorVelPlusPen < -1e-6f)
{
PxReal sumRecipMass = invMass0 + invMass1;
const PxReal jLin = relNorVelPlusPen;
const PxReal normalResponse = (1.0f + restitution) * jLin;
#if CCD_ANGULAR_IMPULSE
const PxVec3 angularMom0 = invInertia0 * (localPoint0.cross(mMinToiNormal));
const PxVec3 angularMom1 = invInertia1 * (localPoint1.cross(mMinToiNormal));
const PxReal jAng = minToiNormal.dot(angularMom0.cross(localPoint0) + angularMom1.cross(localPoint1));
const PxReal impulseDivisor = sumRecipMass + jAng;
#else
const PxReal impulseDivisor = sumRecipMass;
#endif
const PxReal jImp = PxMax(-mMaxImpulse, normalResponse/impulseDivisor);
PxVec3 j(0.0f);
//If the user requested CCD friction, calculate friction forces.
//Note, CCD is *linear* so friction is also linear. The net result is that CCD friction can stop bodies' lateral motion so its better to have it disabled
//unless there's a real need for it.
if(mHasFriction)
{
const PxVec3 vPerp = vRel - relNorVel * minToiNormal;
PxVec3 tDir = vPerp;
const PxReal length = tDir.normalize();
const PxReal vPerpImp = length/impulseDivisor;
PxF32 fricResponse = 0.0f;
const PxF32 staticResponse = (jImp*sFriction);
const PxF32 dynamicResponse = (jImp*dFriction);
if (PxAbs(staticResponse) >= vPerpImp)
fricResponse = vPerpImp;
else
{
fricResponse = -dynamicResponse /* times m0 */;
}
//const PxVec3 fricJ = -vPerp.getNormalized() * (fricResponse/impulseDivisor);
const PxVec3 fricJ = tDir * (fricResponse);
j = jImp * mMinToiNormal + fricJ;
}
else
{
j = jImp * mMinToiNormal;
}
verifyCCDPair(*this);
//If we have a negative impulse value, then we need to apply it. If not, the bodies are separating (no impulse to apply).
if(jImp < 0.0f)
{
mAppliedForce = -jImp;
//Adjust velocities
if((atom0 != NULL && atom0->mCCD->mPassDone) ||
(atom1 != NULL && atom1->mCCD->mPassDone))
{
mPenetrationPostStep = 0.0f;
}
else
{
if (atom0)
{
//atom0->mAcceleration.linear = atom0->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setLinearVelocity(atom0->getLinearVelocity() + j * invMass0);
atom0->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom0->mAcceleration.angular = atom0->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setAngularVelocity(atom0->getAngularVelocity() + invInertia0 * localPoint0.cross(j));
atom0->constrainAngularVelocity();
#endif
}
if (atom1)
{
//atom1->mAcceleration.linear = atom1->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setLinearVelocity(atom1->getLinearVelocity() - j * invMass1);
atom1->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom1->mAcceleration.angular = atom1->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setAngularVelocity(atom1->getAngularVelocity() - invInertia1 * localPoint1.cross(j));
atom1->constrainAngularVelocity();
#endif
}
}
}
}
//Update poses
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.0f);
atom0->mCCD->mUpdateCount++;
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(minToi);
atom1->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.0f);
atom1->mCCD->mUpdateCount++;
}
//If we had a penetration post-step (i.e. an initial overlap), step forwards slightly after collision response
if(mPenetrationPostStep > 0.0f)
{
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom0->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom1->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
}
//Mark passes as done
if (atom0)
{
atom0->mCCD->mPassDone = true;
atom0->mCCD->mHasAnyPassDone = true;
}
if (atom1)
{
atom1->mCCD->mPassDone = true;
atom1->mCCD->mHasAnyPassDone = true;
}
return true;
//return false;
}
else
{
printCCDDebug("advToi: clean sweep", atom0, mG0);
}
return false;
}
namespace
{
struct IslandCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const { return a.mIslandId < b.mIslandId; }
};
struct IslandPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const { return a->mIslandId < b->mIslandId; }
};
struct ToiCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const
{
return (a.mMinToi < b.mMinToi) ||
((a.mMinToi == b.mMinToi) && (a.mBa1 != NULL && b.mBa1 == NULL));
}
};
struct ToiPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const
{
return (a->mMinToi < b->mMinToi) ||
((a->mMinToi == b->mMinToi) && (a->mBa1 != NULL && b->mBa1 == NULL));
}
};
// --------------------------------------------------------------
/**
\brief Class to perform a set of sweep estimate tasks
*/
class PxsCCDSweepTask : public Cm::Task
{
PxsCCDPair** mPairs;
PxU32 mNumPairs;
PxReal mCCDThreshold;
public:
PxsCCDSweepTask(PxU64 contextID, PxsCCDPair** pairs, PxU32 nPairs, PxReal ccdThreshold) :
Cm::Task(contextID), mPairs(pairs), mNumPairs(nPairs), mCCDThreshold(ccdThreshold)
{
}
virtual void runInternal()
{
for (PxU32 j = 0; j < mNumPairs; j++)
{
PxsCCDPair& pair = *mPairs[j];
pair.sweepEstimateToi(mCCDThreshold);
pair.mEstimatePass = 0;
}
}
virtual const char *getName() const
{
return "PxsContext.CCDSweep";
}
private:
PxsCCDSweepTask& operator=(const PxsCCDSweepTask&);
};
#define ENABLE_RESWEEP 1
// --------------------------------------------------------------
/**
\brief Class to advance a set of islands
*/
class PxsCCDAdvanceTask : public Cm::Task
{
PxsCCDPair** mCCDPairs;
PxU32 mNumPairs;
PxsContext* mContext;
PxsCCDContext* mCCDContext;
PxReal mDt;
PxU32 mCCDPass;
const PxsCCDBodyArray& mCCDBodies;
PxU32 mFirstThreadIsland;
PxU32 mIslandsPerThread;
PxU32 mTotalIslandCount;
PxU32 mFirstIslandPair; // pairs are sorted by island
PxsCCDBody** mIslandBodies;
PxU16* mNumIslandBodies;
PxI32* mSweepTotalHits;
bool mClipTrajectory;
bool mDisableResweep;
PxsCCDAdvanceTask& operator=(const PxsCCDAdvanceTask&);
public:
PxsCCDAdvanceTask(PxsCCDPair** pairs, PxU32 nPairs, const PxsCCDBodyArray& ccdBodies,
PxsContext* context, PxsCCDContext* ccdContext, PxReal dt, PxU32 ccdPass,
PxU32 firstIslandPair, PxU32 firstThreadIsland, PxU32 islandsPerThread, PxU32 totalIslands,
PxsCCDBody** islandBodies, PxU16* numIslandBodies, bool clipTrajectory, bool disableResweep,
PxI32* sweepTotalHits)
: Cm::Task(context->getContextId()), mCCDPairs(pairs), mNumPairs(nPairs), mContext(context), mCCDContext(ccdContext), mDt(dt),
mCCDPass(ccdPass), mCCDBodies(ccdBodies), mFirstThreadIsland(firstThreadIsland),
mIslandsPerThread(islandsPerThread), mTotalIslandCount(totalIslands), mFirstIslandPair(firstIslandPair),
mIslandBodies(islandBodies), mNumIslandBodies(numIslandBodies), mSweepTotalHits(sweepTotalHits),
mClipTrajectory(clipTrajectory), mDisableResweep(disableResweep)
{
PX_ASSERT(mFirstIslandPair < mNumPairs);
}
virtual void runInternal()
{
PxI32 sweepTotalHits = 0;
PxcNpThreadContext* threadContext = mContext->getNpThreadContext();
PxReal ccdThreshold = mCCDContext->getCCDThreshold();
// --------------------------------------------------------------------------------------
// loop over island labels assigned to this thread
PxU32 islandStart = mFirstIslandPair;
PxU32 lastIsland = PxMin(mFirstThreadIsland + mIslandsPerThread, mTotalIslandCount);
for (PxU32 iIsland = mFirstThreadIsland; iIsland < lastIsland; iIsland++)
{
if (islandStart >= mNumPairs)
// this is possible when for instance there are two islands with 0 pairs in the second
// since islands are initially segmented using bodies, not pairs, it can happen
break;
// --------------------------------------------------------------------------------------
// sort all pairs within current island by toi
PxU32 islandEnd = islandStart+1;
PX_ASSERT(mCCDPairs[islandStart]->mIslandId == iIsland);
while (islandEnd < mNumPairs && mCCDPairs[islandEnd]->mIslandId == iIsland) // find first index past the current island id
islandEnd++;
if (islandEnd > islandStart+1)
PxSort(mCCDPairs+islandStart, islandEnd-islandStart, ToiPtrCompare());
PX_ASSERT(islandEnd <= mNumPairs);
// --------------------------------------------------------------------------------------
// advance all affected pairs within each island to min toi
// for each pair (A,B) in toi order, find any later-toi pairs that collide against A or B
// and resweep against changed trajectories of either A or B (excluding statics and kinematics)
PxReal islandMinToi = PX_MAX_REAL;
PxU32 estimatePass = 1;
PxReal dt = mDt;
for (PxU32 iFront = islandStart; iFront < islandEnd; iFront++)
{
PxsCCDPair& pair = *mCCDPairs[iFront];
verifyCCDPair(pair);
//If we have reached a pair with a TOI after 1.0, we can terminate this island
if(pair.mMinToi > 1.0f)
break;
bool needSweep0 = (pair.mBa0 && pair.mBa0->mCCD->mPassDone == false);
bool needSweep1 = (pair.mBa1 && pair.mBa1->mCCD->mPassDone == false);
//If both bodies have been updated (or one has been updated and the other is static), we can skip to the next pair
if(!(needSweep0 || needSweep1))
continue;
{
//If the pair was an estimate, we must perform an accurate sweep now
if(pair.mToiType == PxsCCDPair::eEstimate)
{
pair.sweepFindToi(*threadContext, dt, mCCDPass, ccdThreshold);
//Test to see if the pair is still the earliest pair.
if((iFront + 1) < islandEnd && mCCDPairs[iFront+1]->mMinToi < pair.mMinToi)
{
//If there is an earlier pair, we push this pair into its correct place in the list and return to the start
//of this update loop
PxsCCDPair* tmp = &pair;
PxU32 index = iFront;
while((index + 1) < islandEnd && mCCDPairs[index+1]->mMinToi < pair.mMinToi)
{
mCCDPairs[index] = mCCDPairs[index+1];
++index;
}
mCCDPairs[index] = tmp;
--iFront;
continue;
}
}
if (pair.mMinToi > 1.0f)
break;
//We now have the earliest contact pair for this island and one/both of the bodies have not been updated. We now perform
//contact modification to find out if the user still wants to respond to the collision
if(pair.mMinToi <= islandMinToi &&
pair.mIsModifiable &&
mCCDContext->getCCDContactModifyCallback())
{
PX_ALIGN(16, PxU8 dataBuffer[sizeof(PxModifiableContact) + sizeof(PxContactPatch)]);
PxContactPatch* patch = reinterpret_cast<PxContactPatch*>(dataBuffer);
PxModifiableContact* point = reinterpret_cast<PxModifiableContact*>(patch + 1);
patch->mMassModification.linear0 = 1.f;
patch->mMassModification.linear1 = 1.f;
patch->mMassModification.angular0 = 1.f;
patch->mMassModification.angular1 = 1.f;
patch->normal = pair.mMinToiNormal;
patch->dynamicFriction = pair.mDynamicFriction;
patch->staticFriction = pair.mStaticFriction;
patch->materialIndex0 = pair.mMaterialIndex0;
patch->materialIndex1 = pair.mMaterialIndex1;
patch->startContactIndex = 0;
patch->nbContacts = 1;
patch->materialFlags = 0;
patch->internalFlags = 0; //44 //Can be a U16
point->contact = pair.mMinToiPoint;
point->normal = pair.mMinToiNormal;
//KS - todo - reintroduce face indices!!!!
//point.internalFaceIndex0 = PXC_CONTACT_NO_FACE_INDEX;
//point.internalFaceIndex1 = pair.mFaceIndex;
point->materialIndex0 = pair.mMaterialIndex0;
point->materialIndex1 = pair.mMaterialIndex1;
point->dynamicFriction = pair.mDynamicFriction;
point->staticFriction = pair.mStaticFriction;
point->restitution = pair.mRestitution;
point->separation = 0.0f;
point->maxImpulse = PX_MAX_REAL;
point->materialFlags = 0;
point->targetVelocity = PxVec3(0.0f);
mCCDContext->runCCDModifiableContact(point, 1, pair.mCCDShape0->mShapeCore, pair.mCCDShape1->mShapeCore,
pair.mCCDShape0->mRigidCore, pair.mCCDShape1->mRigidCore, pair.mBa0, pair.mBa1);
if ((patch->internalFlags & PxContactPatch::eHAS_MAX_IMPULSE))
pair.mMaxImpulse = point->maxImpulse;
pair.mDynamicFriction = point->dynamicFriction;
pair.mStaticFriction = point->staticFriction;
pair.mRestitution = point->restitution;
pair.mMinToiPoint = point->contact;
pair.mMinToiNormal = point->normal;
}
}
// pair.mIsEarliestToiHit is used for contact notification.
// only mark as such if this is the first impact for both atoms of this pair (the impacts are sorted)
// and there was an actual impact for this pair
bool atom0FirstSweep = (pair.mBa0 && pair.mBa0->mCCD->mPassDone == false) || pair.mBa0 == NULL;
bool atom1FirstSweep = (pair.mBa1 && pair.mBa1->mCCD->mPassDone == false) || pair.mBa1 == NULL;
if (pair.mMinToi <= 1.0f && atom0FirstSweep && atom1FirstSweep)
pair.mIsEarliestToiHit = true;
// sweepAdvanceToToi sets mCCD->mPassDone flags on both atoms, doesn't advance atoms with flag already set
// can advance one atom if the other already has the flag set
bool advanced = pair.sweepAdvanceToToi( dt, mClipTrajectory);
if(pair.mMinToi < 0.0f)
pair.mMinToi = 0.0f;
verifyCCDPair(pair);
if (advanced && pair.mMinToi <= 1.0f)
{
sweepTotalHits++;
PxU32 islandStartIndex = iIsland == 0 ? 0 : PxU32(mNumIslandBodies[iIsland - 1]);
PxU32 islandEndIndex = mNumIslandBodies[iIsland];
if(pair.mMinToi > 0.0f)
{
for(PxU32 a = islandStartIndex; a < islandEndIndex; ++a)
{
if(!mIslandBodies[a]->mPassDone)
{
//If the body has not updated, we advance it to the current time-step that the island has reached.
PxsRigidBody* atom = mIslandBodies[a]->mBody;
atom->advancePrevPoseToToi(pair.mMinToi);
atom->mCCD->mTimeLeft = PxMax(atom->mCCD->mTimeLeft * (1.0f - pair.mMinToi), CCD_MIN_TIME_LEFT);
atom->mCCD->mUpdateCount++;
}
}
//Adjust remaining dt for the island
dt -= dt * pair.mMinToi;
const PxReal recipOneMinusToi = 1.f/(1.f - pair.mMinToi);
for(PxU32 k = iFront+1; k < islandEnd; ++k)
{
PxsCCDPair& pair1 = *mCCDPairs[k];
pair1.mMinToi = (pair1.mMinToi - pair.mMinToi)*recipOneMinusToi;
}
}
//If we disabled response, we don't need to resweep at all
if(!mDisableResweep && !(pair.mCm->getWorkUnit().flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE) && pair.mMaxImpulse != 0.0f)
{
void* a0 = pair.mBa0 == NULL ? NULL : reinterpret_cast<void*>(pair.mBa0);
void* a1 = pair.mBa1 == NULL ? NULL : reinterpret_cast<void*>(pair.mBa1);
for(PxU32 k = iFront+1; k < islandEnd; ++k)
{
PxsCCDPair& pair1 = *mCCDPairs[k];
void* b0 = pair1.mBa0 == NULL ? reinterpret_cast<void*>(pair1.mCCDShape0) : reinterpret_cast<void*>(pair1.mBa0);
void* b1 = pair1.mBa1 == NULL ? reinterpret_cast<void*>(pair1.mCCDShape1) : reinterpret_cast<void*>(pair1.mBa1);
bool containsStatic = pair1.mBa0 == NULL || pair1.mBa1 == NULL;
PX_ASSERT(b0 != NULL && b1 != NULL);
if ((!containsStatic) &&
((b0 == a0 && b1 != a1) || (b1 == a0 && b0 != a1) ||
(b0 == a1 && b1 != a0) || (b1 == a1 && b0 != a0))
)
{
if(estimatePass != pair1.mEstimatePass)
{
pair1.mEstimatePass = estimatePass;
// resweep pair1 since either b0 or b1 trajectory has changed
PxReal oldToi = pair1.mMinToi;
verifyCCDPair(pair1);
PxReal toi1 = pair1.sweepEstimateToi(ccdThreshold);
PX_ASSERT(pair1.mBa0); // this is because mMinToiNormal is the impact point here
if (toi1 < oldToi)
{
// if toi decreased, resort the array backwards
PxU32 kk = k;
PX_ASSERT(kk > 0);
while (kk-1 > iFront && mCCDPairs[kk-1]->mMinToi > toi1)
{
PxsCCDPair* temp = mCCDPairs[kk-1];
mCCDPairs[kk-1] = mCCDPairs[kk];
mCCDPairs[kk] = temp;
kk--;
}
}
else if (toi1 > oldToi)
{
// if toi increased, resort the array forwards
PxU32 kk = k;
PX_ASSERT(kk > 0);
PxU32 stepped = 0;
while (kk+1 < islandEnd && mCCDPairs[kk+1]->mMinToi < toi1)
{
stepped = 1;
PxsCCDPair* temp = mCCDPairs[kk+1];
mCCDPairs[kk+1] = mCCDPairs[kk];
mCCDPairs[kk] = temp;
kk++;
}
k -= stepped;
}
}
}
}
}
estimatePass++;
} // if pair.minToi <= 1.0f
} // for iFront
islandStart = islandEnd;
} // for (PxU32 iIsland = mFirstThreadIsland; iIsland < lastIsland; iIsland++)
PxAtomicAdd(mSweepTotalHits, sweepTotalHits);
mContext->putNpThreadContext(threadContext);
}
virtual const char *getName() const
{
return "PxsContext.CCDAdvance";
}
};
}
// --------------------------------------------------------------
// CCD main function
// Overall structure:
/*
for nPasses (passes are now handled in void Sc::Scene::updateCCDMultiPass)
update CCD broadphase, generate a list of CMs
foreach CM
create CCDPairs, CCDBodies from CM
add shapes, overlappingShapes to CCDBodies
foreach CCDBody
assign island labels per body
uses overlappingShapes
foreach CCDPair
assign island label to pair
sort all pairs by islandId
foreach CCDPair
sweep/find toi
compute normal:
foreach island
sort within island by toi
foreach pair within island
advanceToToi
from curPairInIsland to lastPairInIsland
resweep if needed
*/
// --------------------------------------------------------------
void PxsCCDContext::updateCCDBegin()
{
openCCDLog();
miCCDPass = 0;
mSweepTotalHits = 0;
}
// --------------------------------------------------------------
void PxsCCDContext::updateCCDEnd()
{
if (miCCDPass == mCCDMaxPasses - 1 || mSweepTotalHits == 0)
{
// --------------------------------------------------------------------------------------
// At last CCD pass we need to reset mBody pointers back to NULL
// so that the next frame we know which ones need to be newly paired with PxsCCDBody objects
// also free the CCDBody memory blocks
mMutex.lock();
for (PxU32 j = 0, n = mCCDBodies.size(); j < n; j++)
{
if (mCCDBodies[j].mBody->mCCD && mCCDBodies[j].mBody->mCCD->mHasAnyPassDone)
{
//Record this body in the list of bodies that were updated
mUpdatedCCDBodies.pushBack(mCCDBodies[j].mBody);
}
mCCDBodies[j].mBody->mCCD = NULL;
mCCDBodies[j].mBody->getCore().isFastMoving = false; //Clear the "isFastMoving" bool
}
mMutex.unlock();
mCCDBodies.clear_NoDelete();
}
mCCDShapes.clear_NoDelete();
mMap.clear();
miCCDPass++;
}
// --------------------------------------------------------------
void PxsCCDContext::verifyCCDBegin()
{
#if 0
// validate that all bodies have a NULL mCCD pointer
if (miCCDPass == 0)
{
PxBitMap::Iterator it(mActiveContactManager);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContactManagerPool.findByIndexFast(index);
PxsRigidBody* b0 = cm->mBodyShape0->getBodyAtom(), *b1 = cm->mBodyShape1->getBodyAtom();
PX_ASSERT(b0 == NULL || b0->mCCD == NULL);
PX_ASSERT(b1 == NULL || b1->mCCD == NULL);
}
}
#endif
}
void PxsCCDContext::resetContactManagers()
{
PxBitMap::Iterator it(mContext->mContactManagersWithCCDTouch);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContext->mContactManagerPool.findByIndexFast(index);
cm->clearCCDContactInfo();
}
mContext->mContactManagersWithCCDTouch.clear();
}
// --------------------------------------------------------------
// PT: version that early exits & doesn't read all the data
static PX_FORCE_INLINE bool pairNeedsCCD(const PxsContactManager* cm)
{
// skip disabled pairs
if(!cm->getCCD())
return false;
const PxcNpWorkUnit& workUnit = cm->getWorkUnit();
// skip articulation vs articulation ccd
//Actually. This is fundamentally wrong also :(. We only want to skip links in the same articulation - not all articulations!!!
{
const bool isJoint0 = (workUnit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) == PxcNpWorkUnitFlag::eARTICULATION_BODY0;
if(isJoint0)
{
const bool isJoint1 = (workUnit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) == PxcNpWorkUnitFlag::eARTICULATION_BODY1;
if(isJoint1)
return false;
}
}
{
const bool isFastMoving0 = static_cast<const PxsBodyCore*>(workUnit.rigidCore0)->isFastMoving != 0;
if(isFastMoving0)
return true;
const bool isFastMoving1 = (workUnit.flags & (PxcNpWorkUnitFlag::eARTICULATION_BODY1 | PxcNpWorkUnitFlag::eDYNAMIC_BODY1)) ? static_cast<const PxsBodyCore*>(workUnit.rigidCore1)->isFastMoving != 0: false;
return isFastMoving1;
}
}
static PxsCCDShape* processShape(
PxVec3& tr, PxReal& threshold, PxsCCDShape* ccdShape,
const PxsRigidCore* const rc, const PxsShapeCore* const sc, const PxsRigidBody* const ba,
const PxsContactManager* const cm, IG::IslandSim& islandSim, PxsCCDShapeArray& mCCDShapes, PxHashMap<PxsRigidShapePair, PxsCCDShape*>& mMap, bool flag)
{
if(ccdShape == NULL)
{
//If we hadn't already created ccdShape, create one
ccdShape = &mCCDShapes.pushBack();
ccdShape->mRigidCore = rc;
ccdShape->mShapeCore = sc;
ccdShape->mGeometry = &sc->mGeometry.getGeometry();
mMap.insert(PxsRigidShapePair(rc, sc), ccdShape);
PxTransform32 tm;
getAbsPose(tm, ccdShape, ba);
PxTransform32 oldTm;
if(ba)
getLastCCDAbsPose(oldTm, ccdShape, ba);
else
oldTm = tm;
tr = tm.p - oldTm.p;
PxVec3p origin, extents;
//Compute the shape's bounds and CCD threshold
threshold = computeBoundsWithCCDThreshold(origin, extents, sc->mGeometry.getGeometry(), tm);
//Set up the CCD shape
ccdShape->mCenter = origin - tr;
ccdShape->mExtents = extents;
ccdShape->mFastMovingThreshold = threshold;
ccdShape->mPrevTransform = oldTm;
ccdShape->mCurrentTransform = tm;
ccdShape->mUpdateCount = 0;
ccdShape->mNodeIndex = flag ? islandSim.getNodeIndex2(cm->getWorkUnit().mEdgeIndex)
: islandSim.getNodeIndex1(cm->getWorkUnit().mEdgeIndex);
}
else
{
//We had already created the shape, so extract the threshold and translation components
threshold = ccdShape->mFastMovingThreshold;
tr = ccdShape->mCurrentTransform.p - ccdShape->mPrevTransform.p;
}
return ccdShape;
}
void PxsCCDContext::updateCCD(PxReal dt, PxBaseTask* continuation, IG::IslandSim& islandSim, bool disableResweep, PxI32 numFastMovingShapes)
{
//Flag to run a slightly less-accurate version of CCD that will ensure that objects don't tunnel through the static world but is not as reliable for dynamic-dynamic collisions
mDisableCCDResweep = disableResweep;
mThresholdStream.clear(); // clear force threshold report stream
mContext->clearManagerTouchEvents();
if (miCCDPass == 0)
{
resetContactManagers();
}
// If we're not in the first pass and the previous pass had no sweeps or the BP didn't generate any fast-moving shapes, we can skip CCD entirely
if ((miCCDPass > 0 && mSweepTotalHits == 0) || (numFastMovingShapes == 0))
{
mSweepTotalHits = 0;
updateCCDEnd();
return;
}
mSweepTotalHits = 0;
PX_ASSERT(continuation);
PX_ASSERT(continuation->getReference() > 0);
//printf("CCD 1\n");
mCCDThreadContext = mContext->getNpThreadContext();
mCCDThreadContext->mDt = dt; // doesn't get set anywhere else since it's only used for CCD now
verifyCCDBegin();
// --------------------------------------------------------------------------------------
// From a list of active CMs, build a temporary array of PxsCCDPair objects (allocated in blocks)
// this is done to gather scattered data from memory and also to reduce PxsRidigBody permanent memory footprint
// we have to do it every pass since new CMs can become fast moving after each pass (and sometimes cease to be)
mCCDPairs.clear_NoDelete();
mCCDPtrPairs.forceSize_Unsafe(0);
mUpdatedCCDBodies.forceSize_Unsafe(0);
mCCDOverlaps.clear_NoDelete();
PxU32 nbKinematicStaticCollisions = 0;
bool needsSweep = false;
{
PX_PROFILE_ZONE("Sim.ccdPair", mContext->mContextID);
PxBitMap::Iterator it(mContext->mActiveContactManagersWithCCD);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContext->mContactManagerPool.findByIndexFast(index);
if(!pairNeedsCCD(cm))
continue;
const PxcNpWorkUnit& unit = cm->getWorkUnit();
const PxsRigidCore* rc0 = unit.rigidCore0;
const PxsRigidCore* rc1 = unit.rigidCore1;
{
const PxsShapeCore* sc0 = unit.shapeCore0;
const PxsShapeCore* sc1 = unit.shapeCore1;
PxsRigidBody* ba0 = cm->mRigidBody0;
PxsRigidBody* ba1 = cm->mRigidBody1;
//Look up the body/shape pair in our CCDShape map
const PxPair<const PxsRigidShapePair, PxsCCDShape*>* ccdShapePair0 = mMap.find(PxsRigidShapePair(rc0, sc0));
const PxPair<const PxsRigidShapePair, PxsCCDShape*>* ccdShapePair1 = mMap.find(PxsRigidShapePair(rc1, sc1));
//If the CCD shapes exist, extract them from the map
PxsCCDShape* ccdShape0 = ccdShapePair0 ? ccdShapePair0->second : NULL;
PxsCCDShape* ccdShape1 = ccdShapePair1 ? ccdShapePair1->second : NULL;
PxReal threshold0 = 0.0f;
PxReal threshold1 = 0.0f;
PxVec3 trA(0.0f);
PxVec3 trB(0.0f);
ccdShape0 = processShape(trA, threshold0, ccdShape0, rc0, sc0, ba0, cm, islandSim, mCCDShapes, mMap, false);
ccdShape1 = processShape(trB, threshold1, ccdShape1, rc1, sc1, ba1, cm, islandSim, mCCDShapes, mMap, true);
{
//Initialize the CCD bodies
PxsRigidBody* atoms[2] = {ba0, ba1};
for (int k = 0; k < 2; k++)
{
PxsRigidBody* b = atoms[k];
//If there isn't a body (i.e. it's a static), no need to create a CCD body
if (!b)
continue;
if (b->mCCD == NULL)
{
// this rigid body has no CCD body created for it yet. Create and initialize one.
PxsCCDBody& newB = mCCDBodies.pushBack();
b->mCCD = &newB;
b->mCCD->mIndex = PxTo16(mCCDBodies.size()-1);
b->mCCD->mBody = b;
b->mCCD->mTimeLeft = 1.0f;
b->mCCD->mOverlappingObjects = NULL;
b->mCCD->mUpdateCount = 0;
b->mCCD->mHasAnyPassDone = false;
b->mCCD->mNbInteractionsThisPass = 0;
}
b->mCCD->mPassDone = 0;
b->mCCD->mNbInteractionsThisPass++;
}
if(ba0 && ba1)
{
//If both bodies exist (i.e. this is dynamic-dynamic collision), we create an
//overlap between the 2 bodies used for island detection.
if(!(ba0->isKinematic() || ba1->isKinematic()))
{
if(!ba0->mCCD->overlaps(ba1->mCCD))
{
PxsCCDOverlap* overlapA = &mCCDOverlaps.pushBack();
PxsCCDOverlap* overlapB = &mCCDOverlaps.pushBack();
overlapA->mBody = ba1->mCCD;
overlapB->mBody = ba0->mCCD;
ba0->mCCD->addOverlap(overlapA);
ba1->mCCD->addOverlap(overlapB);
}
}
}
}
//We now create the CCD pair. These are used in the CCD sweep and update phases
if (ba0->isKinematic() && (ba1 == NULL || ba1->isKinematic()))
nbKinematicStaticCollisions++;
{
PxsCCDPair& p = mCCDPairs.pushBack();
p.mBa0 = ba0;
p.mBa1 = ba1;
p.mCCDShape0 = ccdShape0;
p.mCCDShape1 = ccdShape1;
p.mHasFriction = rc0->hasCCDFriction() || rc1->hasCCDFriction();
p.mMinToi = PX_MAX_REAL;
p.mG0 = cm->mNpUnit.shapeCore0->mGeometry.getType();
p.mG1 = cm->mNpUnit.shapeCore1->mGeometry.getType();
p.mCm = cm;
p.mIslandId = 0xFFFFffff;
p.mIsEarliestToiHit = false;
p.mFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
p.mIsModifiable = cm->isChangeable() != 0;
p.mAppliedForce = 0.0f;
p.mMaxImpulse = PxMin((ba0->mCore->mFlags & PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE) ? ba0->mCore->maxContactImpulse : PX_MAX_F32,
(ba1 && ba1->mCore->mFlags & PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE) ? ba1->mCore->maxContactImpulse : PX_MAX_F32);
#if PX_ENABLE_SIM_STATS
mContext->mSimStats.mNbCCDPairs[PxMin(p.mG0, p.mG1)][PxMax(p.mG0, p.mG1)] ++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//Calculate the sum of the thresholds and work out if we need to perform a sweep.
const PxReal thresh = PxMin(threshold0 + threshold1, mCCDThreshold);
//If no shape pairs in the entire scene are fast-moving, we can bypass the entire of the CCD.
needsSweep = needsSweep || (trA - trB).magnitudeSquared() >= (thresh * thresh);
}
}
}
//There are no fast-moving pairs in this scene, so we can terminate right now without proceeding any further
if(!needsSweep)
{
updateCCDEnd();
mContext->putNpThreadContext(mCCDThreadContext);
return;
}
}
//Create the pair pointer buffer. This is a flattened array of pointers to pairs. It is used to sort the pairs
//into islands and is also used to prioritize the pairs into their TOIs
{
const PxU32 size = mCCDPairs.size();
mCCDPtrPairs.reserve(size);
for(PxU32 a = 0; a < size; ++a)
{
mCCDPtrPairs.pushBack(&mCCDPairs[a]);
}
mThresholdStream.reserve(PxNextPowerOfTwo(size));
for (PxU32 a = 0; a < mCCDBodies.size(); ++a)
{
mCCDBodies[a].mPreSolverVelocity.linear = mCCDBodies[a].mBody->getLinearVelocity();
mCCDBodies[a].mPreSolverVelocity.angular = mCCDBodies[a].mBody->getAngularVelocity();
}
}
PxU32 ccdBodyCount = mCCDBodies.size();
// --------------------------------------------------------------------------------------
// assign island labels
const PxU16 noLabelYet = 0xFFFF;
//Temporary array allocations. Ideally, we should use the scratch pad for there
PxArray<PxU32> islandLabels;
islandLabels.resize(ccdBodyCount);
PxArray<const PxsCCDBody*> stack;
stack.reserve(ccdBodyCount);
stack.forceSize_Unsafe(ccdBodyCount);
//Initialize all islands labels (for each body) to be unitialized
mIslandSizes.forceSize_Unsafe(0);
mIslandSizes.reserve(ccdBodyCount + 1);
mIslandSizes.forceSize_Unsafe(ccdBodyCount + 1);
for (PxU32 j = 0; j < ccdBodyCount; j++)
islandLabels[j] = noLabelYet;
PxU32 islandCount = 0;
PxU32 stackSize = 0;
const PxsCCDBody* top = NULL;
for (PxU32 j = 0; j < ccdBodyCount; j++)
{
//If the body has already been labelled or if it is kinematic, continue
//Also, if the body has no interactions this pass, continue. In single-pass CCD, only bodies with interactions would be part of the CCD. However,
//with multi-pass CCD, we keep all bodies that interacted in previous passes. If the body now has no interactions, we skip it to ensure that island grouping doesn't fail in
//later stages by assigning an island ID to a body with no interactions
if (islandLabels[j] != noLabelYet || mCCDBodies[j].mBody->isKinematic() || mCCDBodies[j].mNbInteractionsThisPass == 0)
continue;
top = &mCCDBodies[j];
//Otherwise push it back into the queue and proceed
islandLabels[j] = islandCount;
stack[stackSize++] = top;
// assign new label to unlabeled atom
// assign the same label to all connected nodes using stack traversal
PxU16 islandSize = 0;
while (stackSize > 0)
{
--stackSize;
const PxsCCDBody* ccdb = top;
top = stack[PxMax(1u, stackSize)-1];
PxsCCDOverlap* overlaps = ccdb->mOverlappingObjects;
while(overlaps)
{
if (islandLabels[overlaps->mBody->mIndex] == noLabelYet) // non-static & unlabeled?
{
islandLabels[overlaps->mBody->mIndex] = islandCount;
stack[stackSize++] = overlaps->mBody; // push adjacent node to the top of the stack
top = overlaps->mBody;
islandSize++;
}
overlaps = overlaps->mNext;
}
}
//Record island size
mIslandSizes[islandCount] = PxU16(islandSize + 1);
islandCount++;
}
PxU32 kinematicIslandId = islandCount;
islandCount += nbKinematicStaticCollisions;
for (PxU32 i = kinematicIslandId; i < islandCount; ++i)
mIslandSizes[i] = 1;
// --------------------------------------------------------------------------------------
// label pairs with island ids
// (need an extra loop since we don't maintain a mapping from atom to all of it's pairs)
mCCDIslandHistogram.clear(); // number of pairs per island
mCCDIslandHistogram.resize(islandCount);
PxU32 totalActivePairs = 0;
for (PxU32 j = 0, n = mCCDPtrPairs.size(); j < n; j++)
{
const PxU32 staticLabel = 0xFFFFffff;
PxsCCDPair& p = *mCCDPtrPairs[j];
PxU32 id0 = p.mBa0 && !p.mBa0->isKinematic()? islandLabels[p.mBa0->mCCD->getIndex()] : staticLabel;
PxU32 id1 = p.mBa1 && !p.mBa1->isKinematic()? islandLabels[p.mBa1->mCCD->getIndex()] : staticLabel;
PxU32 islandId = PxMin(id0, id1);
if (islandId == staticLabel)
islandId = kinematicIslandId++;
p.mIslandId = islandId;
mCCDIslandHistogram[p.mIslandId] ++;
PX_ASSERT(p.mIslandId != staticLabel);
totalActivePairs++;
}
PxU16 count = 0;
for(PxU16 a = 0; a < islandCount+1; ++a)
{
PxU16 islandSize = mIslandSizes[a];
mIslandSizes[a] = count;
count += islandSize;
}
mIslandBodies.forceSize_Unsafe(0);
mIslandBodies.reserve(ccdBodyCount);
mIslandBodies.forceSize_Unsafe(ccdBodyCount);
for(PxU32 a = 0; a < mCCDBodies.size(); ++a)
{
const PxU32 island = islandLabels[mCCDBodies[a].mIndex];
if (island != 0xFFFF)
{
PxU16 writeIndex = mIslandSizes[island];
mIslandSizes[island] = PxU16(writeIndex + 1);
mIslandBodies[writeIndex] = &mCCDBodies[a];
}
}
// --------------------------------------------------------------------------------------
// setup tasks
mPostCCDDepenetrateTask.setContinuation(continuation);
mPostCCDAdvanceTask.setContinuation(&mPostCCDDepenetrateTask);
mPostCCDSweepTask.setContinuation(&mPostCCDAdvanceTask);
// --------------------------------------------------------------------------------------
// sort all pairs by islands
PxSort(mCCDPtrPairs.begin(), mCCDPtrPairs.size(), IslandPtrCompare());
// --------------------------------------------------------------------------------------
// sweep all CCD pairs
const PxU32 nPairs = mCCDPtrPairs.size();
const PxU32 numThreads = PxMax(1u, mContext->mTaskManager->getCpuDispatcher()->getWorkerCount()); PX_ASSERT(numThreads > 0);
mCCDPairsPerBatch = PxMax<PxU32>((nPairs)/numThreads, 1);
for (PxU32 batchBegin = 0; batchBegin < nPairs; batchBegin += mCCDPairsPerBatch)
{
void* ptr = mContext->mTaskPool.allocate(sizeof(PxsCCDSweepTask));
PX_ASSERT_WITH_MESSAGE(ptr, "Failed to allocate PxsCCDSweepTask");
const PxU32 batchEnd = PxMin(nPairs, batchBegin + mCCDPairsPerBatch);
PX_ASSERT(batchEnd >= batchBegin);
PxsCCDSweepTask* task = PX_PLACEMENT_NEW(ptr, PxsCCDSweepTask)(mContext->getContextId(), mCCDPtrPairs.begin() + batchBegin, batchEnd - batchBegin,
mCCDThreshold);
task->setContinuation(*mContext->mTaskManager, &mPostCCDSweepTask);
task->removeReference();
}
mPostCCDSweepTask.removeReference();
mPostCCDAdvanceTask.removeReference();
mPostCCDDepenetrateTask.removeReference();
}
void PxsCCDContext::postCCDSweep(PxBaseTask* continuation)
{
// --------------------------------------------------------------------------------------
// batch up the islands and send them over to worker threads
PxU32 firstIslandPair = 0;
PxU32 islandCount = mCCDIslandHistogram.size();
for (PxU32 firstIslandInBatch = 0; firstIslandInBatch < islandCount;)
{
PxU32 pairSum = 0;
PxU32 lastIslandInBatch = firstIslandInBatch+1;
PxU32 j;
// add up the numbers in the histogram until we reach target pairsPerBatch
for (j = firstIslandInBatch; j < islandCount; j++)
{
pairSum += mCCDIslandHistogram[j];
if (pairSum > mCCDPairsPerBatch)
{
lastIslandInBatch = j+1;
break;
}
}
if (j == islandCount) // j is islandCount if not enough pairs were left to fill up to pairsPerBatch
{
if (pairSum == 0)
break; // we are done and there are no islands in this batch
lastIslandInBatch = islandCount;
}
void* ptr = mContext->mTaskPool.allocate(sizeof(PxsCCDAdvanceTask));
PX_ASSERT_WITH_MESSAGE(ptr , "Failed to allocate PxsCCDSweepTask");
bool clipTrajectory = (miCCDPass == mCCDMaxPasses-1);
PxsCCDAdvanceTask* task = PX_PLACEMENT_NEW(ptr, PxsCCDAdvanceTask) (
mCCDPtrPairs.begin(), mCCDPtrPairs.size(), mCCDBodies, mContext, this, mCCDThreadContext->mDt, miCCDPass,
firstIslandPair, firstIslandInBatch, lastIslandInBatch-firstIslandInBatch, islandCount,
mIslandBodies.begin(), mIslandSizes.begin(), clipTrajectory, mDisableCCDResweep,
&mSweepTotalHits);
firstIslandInBatch = lastIslandInBatch;
firstIslandPair += pairSum;
task->setContinuation(*mContext->mTaskManager, continuation);
task->removeReference();
} // for iIsland
}
static PX_FORCE_INLINE bool shouldCreateContactReports(const PxsRigidCore* rigidCore)
{
return static_cast<const PxsBodyCore*>(rigidCore)->contactReportThreshold != PXV_CONTACT_REPORT_DISABLED;
}
void PxsCCDContext::postCCDAdvance(PxBaseTask* /*continuation*/)
{
// --------------------------------------------------------------------------------------
// contact notifications: update touch status (multi-threading this section would probably slow it down but might be worth a try)
PxU32 countLost = 0, countFound = 0, countRetouch = 0;
PxU32 islandCount = mCCDIslandHistogram.size();
PxU32 index = 0;
for (PxU32 island = 0; island < islandCount; ++island)
{
PxU32 islandEnd = mCCDIslandHistogram[island] + index;
for(PxU32 j = index; j < islandEnd; ++j)
{
PxsCCDPair& p = *mCCDPtrPairs[j];
//The CCD pairs are ordered by TOI. If we reach a TOI > 1, we can terminate
if(p.mMinToi > 1.f)
break;
//If this was the earliest touch for the pair of bodies, we can notify the user about it. If not, it's a future collision that we haven't stepped to yet
if (p.mIsEarliestToiHit)
{
//Flag that we had a CCD contact
p.mCm->setHadCCDContact();
//Test/set the changed touch map
PxU16 oldTouch = p.mCm->getTouchStatus();
if (!oldTouch)
{
mContext->mContactManagerTouchEvent.growAndSet(p.mCm->getIndex());
p.mCm->mNpUnit.statusFlags = PxU16((p.mCm->mNpUnit.statusFlags & (~PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH)) | PxcNpWorkUnitStatusFlag::eHAS_TOUCH);
//Also need to write it in the CmOutput structure!!!!!
////The achieve this, we need to unregister the CM from the Nphase, then re-register it with the status set. This is the only way to force a push to the GPU
Sc::ShapeInteraction* interaction = p.mCm->getShapeInteraction();
mNphaseContext.unregisterContactManager(p.mCm);
mNphaseContext.registerContactManager(p.mCm, interaction, 1, 0);
countFound++;
}
else
{
mContext->mContactManagerTouchEvent.growAndSet(p.mCm->getIndex());
p.mCm->raiseCCDRetouch();
countRetouch++;
}
//Do we want to create reports?
const bool createReports =
p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eOUTPUT_CONTACTS
|| (p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD
&& ((p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) && shouldCreateContactReports(p.mCm->mNpUnit.rigidCore0))
|| (p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) && shouldCreateContactReports(p.mCm->mNpUnit.rigidCore1))));
if(createReports)
{
mContext->mContactManagersWithCCDTouch.growAndSet(p.mCm->getIndex());
const PxU32 numContacts = 1;
PxsMaterialInfo matInfo;
PxContactBuffer& buffer = mCCDThreadContext->mContactBuffer;
PxContactPoint& cp = buffer.contacts[0];
cp.point = p.mMinToiPoint;
cp.normal = -p.mMinToiNormal; //KS - discrete contact gen produces contacts pointing in the opposite direction to CCD sweeps
cp.internalFaceIndex1 = p.mFaceIndex;
cp.separation = 0.0f;
cp.restitution = p.mRestitution;
cp.dynamicFriction = p.mDynamicFriction;
cp.staticFriction = p.mStaticFriction;
cp.targetVel = PxVec3(0.0f);
cp.maxImpulse = PX_MAX_REAL;
matInfo.mMaterialIndex0 = p.mMaterialIndex0;
matInfo.mMaterialIndex1 = p.mMaterialIndex1;
//Write contact stream for the contact. This will allocate memory for the contacts and forces
PxReal* contactForces;
//PxU8* contactStream;
PxU8* contactPatches;
PxU8* contactPoints;
PxU16 contactStreamSize;
PxU16 contactCount;
PxU8 nbPatches;
PxsCCDContactHeader* ccdHeader = reinterpret_cast<PxsCCDContactHeader*>(p.mCm->mNpUnit.ccdContacts);
if (writeCompressedContact(buffer.contacts, numContacts, mCCDThreadContext, contactCount, contactPatches,
contactPoints, contactStreamSize, contactForces, numContacts*sizeof(PxReal), mCCDThreadContext->mMaterialManager,
((p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT) != 0), true, &matInfo, nbPatches, sizeof(PxsCCDContactHeader),NULL, NULL,
false, NULL, NULL, NULL, p.mFaceIndex != PXC_CONTACT_NO_FACE_INDEX))
{
PxsCCDContactHeader* newCCDHeader = reinterpret_cast<PxsCCDContactHeader*>(contactPatches);
newCCDHeader->contactStreamSize = PxTo16(contactStreamSize);
newCCDHeader->isFromPreviousPass = 0;
p.mCm->mNpUnit.ccdContacts = contactPatches; // put the latest stream at the head of the linked list since it needs to get accessed every CCD pass
// to prepare the reports
if (!ccdHeader)
newCCDHeader->nextStream = NULL;
else
{
newCCDHeader->nextStream = ccdHeader;
ccdHeader->isFromPreviousPass = 1;
}
//And write the force and contact count
PX_ASSERT(contactForces != NULL);
contactForces[0] = p.mAppliedForce;
}
else if (!ccdHeader)
{
p.mCm->mNpUnit.ccdContacts = NULL;
// we do not set the status flag on failure because the pair might have written
// a contact stream sucessfully during discrete collision this frame.
}
else
ccdHeader->isFromPreviousPass = 1;
//If the touch event already existed, the solver would have already configured the threshold stream
if((p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eARTICULATION_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY1)) == 0 && p.mAppliedForce)
{
#if 1
ThresholdStreamElement elt;
elt.normalForce = p.mAppliedForce;
elt.accumulatedForce = 0.0f;
elt.threshold = PxMin<float>(p.mBa0 == NULL ? PX_MAX_REAL : p.mBa0->mCore->contactReportThreshold, p.mBa1 == NULL ? PX_MAX_REAL :
p.mBa1->mCore->contactReportThreshold);
elt.nodeIndexA = p.mCCDShape0->mNodeIndex;
elt.nodeIndexB =p.mCCDShape1->mNodeIndex;
PxOrder(elt.nodeIndexA,elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA.index() < elt.nodeIndexB.index());
mThresholdStream.pushBack(elt);
#endif
}
}
}
}
index = islandEnd;
}
mContext->mCMTouchEventCount[PXS_LOST_TOUCH_COUNT] += countLost;
mContext->mCMTouchEventCount[PXS_NEW_TOUCH_COUNT] += countFound;
mContext->mCMTouchEventCount[PXS_CCD_RETOUCH_COUNT] += countRetouch;
}
void PxsCCDContext::postCCDDepenetrate(PxBaseTask* /*continuation*/)
{
// --------------------------------------------------------------------------------------
// reset mOverlappingShapes array for all bodies
// we do it each pass because this set can change due to movement as well as new objects
// becoming fast moving due to intra-frame impacts
for (PxU32 j = 0; j < mCCDBodies.size(); j ++)
{
mCCDBodies[j].mOverlappingObjects = NULL;
mCCDBodies[j].mNbInteractionsThisPass = 0;
}
mCCDOverlaps.clear_NoDelete();
updateCCDEnd();
mContext->putNpThreadContext(mCCDThreadContext);
flushCCDLog();
}
Cm::SpatialVector PxsRigidBody::getPreSolverVelocities() const
{
if (mCCD)
return mCCD->mPreSolverVelocity;
return Cm::SpatialVector(PxVec3(0.0f), PxVec3(0.0f));
}
/*PxTransform PxsRigidBody::getAdvancedTransform(PxReal toi) const
{
//If it is kinematic, just return identity. We don't fully support kinematics yet
if (isKinematic())
return PxTransform(PxIdentity);
//Otherwise we interpolate the pose between the current and previous pose and return that pose
PxVec3 newLastP = mLastTransform.p*(1.0f-toi) + mCore->body2World.p*toi; // advance mLastTransform position to toi
PxQuat newLastQ = slerp(toi, getLastCCDTransform().q, mCore->body2World.q); // advance mLastTransform rotation to toi
return PxTransform(newLastP, newLastQ);
}*/
void PxsRigidBody::advancePrevPoseToToi(PxReal toi)
{
//If this is kinematic, just return
if (isKinematic())
return;
//update latest pose
const PxVec3 newLastP = mLastTransform.p*(1.0f-toi) + mCore->body2World.p*toi; // advance mLastTransform position to toi
mLastTransform.p = newLastP;
#if CCD_ROTATION_LOCKING
mCore->body2World.q = getLastCCDTransform().q;
#else
// slerp from last transform to current transform with ratio of toi
const PxQuat newLastQ = PxSlerp(toi, getLastCCDTransform().q, mCore->body2World.q); // advance mLastTransform rotation to toi
mLastTransform.q = newLastQ;
#endif
}
void PxsRigidBody::advanceToToi(PxReal toi, PxReal dt, bool clip)
{
if (isKinematic())
return;
if (clip)
{
//If clip is true, we set the previous and current pose to be the same. This basically makes the object appear stationary in the CCD
mCore->body2World.p = getLastCCDTransform().p;
#if !CCD_ROTATION_LOCKING
mCore->body2World.q = getLastCCDTransform().q;
#endif
}
else
{
// advance new CCD target after impact to remaining toi using post-impact velocities
mCore->body2World.p = getLastCCDTransform().p + getLinearVelocity() * dt * (1.0f - toi);
#if !CCD_ROTATION_LOCKING
const PxVec3 angularDelta = getAngularVelocity() * dt * (1.0f - toi);
const PxReal deltaMag = angularDelta.magnitude();
const PxVec3 deltaAng = deltaMag > 1e-20f ? angularDelta / deltaMag : PxVec3(1.0f, 0.0f, 0.0f);
const PxQuat angularQuat(deltaMag, deltaAng);
mCore->body2World.q = getLastCCDTransform().q * angularQuat;
#endif
PX_ASSERT(mCore->body2World.isSane());
}
// rescale total time left to elapse this frame
mCCD->mTimeLeft = PxMax(mCCD->mTimeLeft * (1.0f - toi), CCD_MIN_TIME_LEFT);
}
void PxsCCDContext::runCCDModifiableContact(PxModifiableContact* PX_RESTRICT contacts, PxU32 contactCount, const PxsShapeCore* PX_RESTRICT shapeCore0,
const PxsShapeCore* PX_RESTRICT shapeCore1, const PxsRigidCore* PX_RESTRICT rigidCore0, const PxsRigidCore* PX_RESTRICT rigidCore1,
const PxsRigidBody* PX_RESTRICT rigid0, const PxsRigidBody* PX_RESTRICT rigid1)
{
if(!mCCDContactModifyCallback)
return;
class PxcContactSet: public PxContactSet
{
public:
PxcContactSet(PxU32 count, PxModifiableContact* contacts_)
{
mContacts = contacts_;
mCount = count;
}
};
{
PxContactModifyPair p;
p.shape[0] = gPxvOffsetTable.convertPxsShape2Px(shapeCore0);
p.shape[1] = gPxvOffsetTable.convertPxsShape2Px(shapeCore1);
p.actor[0] = rigid0 != NULL ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(rigidCore0)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(rigidCore0);
p.actor[1] = rigid1 != NULL ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(rigidCore1)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(rigidCore1);
getShapeAbsPose(p.transform[0], shapeCore0, rigidCore0, rigid0);
getShapeAbsPose(p.transform[1], shapeCore1, rigidCore1, rigid1);
static_cast<PxcContactSet&>(p.contacts) =
PxcContactSet(contactCount, contacts);
mCCDContactModifyCallback->onCCDContactModify(&p, 1);
}
}
| 75,072 | C++ | 34.064456 | 232 | 0.69119 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsIslandSim.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 "PxsIslandSim.h"
#include "foundation/PxSort.h"
#include "foundation/PxUtilities.h"
#include "common/PxProfileZone.h"
#include "DyFeatherstoneArticulation.h"
#define IG_SANITY_CHECKS 0
using namespace physx;
using namespace IG;
IslandSim::IslandSim(PxArray<PartitionEdge*>* firstPartitionEdges, Cm::BlockArray<PxNodeIndex>& edgeNodeIndices, PxArray<PartitionEdge*>* destroyedPartitionEdges, PxU64 contextID) :
mNodes ("IslandSim::mNodes"),
mActiveNodeIndex ("IslandSim::mActiveNodeIndex"),
mIslands ("IslandSim::mIslands"),
mIslandStaticTouchCount ("IslandSim.activeStaticTouchCount"),
mActiveKinematicNodes ("IslandSim::mActiveKinematicNodes"),
mHopCounts ("IslandSim::mHopCounts"),
mFastRoute ("IslandSim::mFastRoute"),
mIslandIds ("IslandSim::mIslandIds"),
mActiveIslands ("IslandSim::mActiveIslands"),
mLastMapIndex (0),
mActivatingNodes ("IslandSim::mActivatingNodes"),
mDestroyedEdges ("IslandSim::mDestroyedEdges"),
mTempIslandIds ("IslandSim::mTempIslandIds"),
mVisitedNodes ("IslandSim::mVisitedNodes"),
mFirstPartitionEdges (firstPartitionEdges),
mEdgeNodeIndices (edgeNodeIndices),
mDestroyedPartitionEdges(destroyedPartitionEdges),
mContextId (contextID)
{
mNpIndexPtr = NULL;
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
mInitialActiveNodeCount[i] = 0;
mActiveEdgeCount[i] = 0;
}
}
#if PX_ENABLE_ASSERTS
template <typename Thing>
static bool contains(PxArray<Thing>& arr, const Thing& thing)
{
for(PxU32 a = 0; a < arr.size(); ++a)
{
if(thing == arr[a])
return true;
}
return false;
}
#endif
/*void IslandSim::resize(const PxU32 nbNodes, const PxU32 nbContactManagers, const PxU32 nbConstraints)
{
PxU32 totalEdges = nbContactManagers + nbConstraints;
mNodes.reserve(nbNodes);
mIslandIds.reserve(nbNodes);
mEdges.reserve(totalEdges);
mActiveContactEdges.resize(totalEdges);
mEdgeInstances.reserve(totalEdges*2);
}*/
void IslandSim::addNode(bool isActive, bool isKinematic, Node::NodeType type, PxNodeIndex nodeIndex)
{
// PT: the nodeIndex is assigned by the SimpleIslandManager one level higher.
const PxU32 handle = nodeIndex.index();
if(handle == mNodes.capacity())
{
const PxU32 newCapacity = PxMax(2*mNodes.capacity(), 256u);
mNodes.reserve(newCapacity);
mIslandIds.reserve(newCapacity);
mFastRoute.reserve(newCapacity);
mHopCounts.reserve(newCapacity);
mActiveNodeIndex.reserve(newCapacity);
}
const PxU32 newSize = PxMax(handle+1, mNodes.size());
mNodes.resize(newSize);
mIslandIds.resize(newSize);
mFastRoute.resize(newSize);
mHopCounts.resize(newSize);
mActiveNodeIndex.resize(newSize);
mActiveNodeIndex[handle] = PX_INVALID_NODE;
Node& node = mNodes[handle];
node.mType = PxTo8(type);
//Ensure that the node is not currently being used.
PX_ASSERT(node.isDeleted());
PxU8 flags = PxU16(isActive ? 0 : Node::eREADY_FOR_SLEEPING);
if(isKinematic)
flags |= Node::eKINEMATIC;
node.mFlags = flags;
mIslandIds[handle] = IG_INVALID_ISLAND;
mFastRoute[handle].setIndices(PX_INVALID_NODE);
mHopCounts[handle] = 0;
if(!isKinematic)
{
const IslandId islandHandle = mIslandHandles.getHandle();
if(islandHandle == mIslands.capacity())
{
const PxU32 newCapacity = PxMax(2*mIslands.capacity(), 256u);
mIslands.reserve(newCapacity);
mIslandAwake.resize(newCapacity);
mIslandStaticTouchCount.reserve(newCapacity);
}
mIslands.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandAwake.growAndReset(PxMax(islandHandle+1, mIslands.size()));
Island& island = mIslands[islandHandle];
island.mLastNode = island.mRootNode = nodeIndex;
island.mNodeCount[type] = 1;
mIslandIds[handle] = islandHandle;
mIslandStaticTouchCount[islandHandle] = 0;
}
if(isActive)
activateNode(nodeIndex);
}
void IslandSim::addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, isKinematic, Node::eRIGID_BODY_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mRigidBody = body;
}
void IslandSim::addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eARTICULATION_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLArticulation = llArtic;
}
#if PX_SUPPORT_GPU_PHYSX
void IslandSim::addSoftBody(Dy::SoftBody* llSoftBody, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eSOFTBODY_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLSoftBody = llSoftBody;
}
void IslandSim::addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eFEMCLOTH_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLFEMCloth = llFEMCloth;
}
void IslandSim::addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::ePARTICLESYSTEM_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLParticleSystem = llParticleSystem;
}
void IslandSim::addHairSystem(Dy::HairSystem* llHairSystem, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eHAIRSYSTEM_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLHairSystem = llHairSystem;
}
#endif
Sc::ArticulationSim* IslandSim::getArticulationSim(PxNodeIndex nodeIndex) const
{
void* userData = getLLArticulation(nodeIndex)->getUserData();
return reinterpret_cast<Sc::ArticulationSim*>(userData);
}
void IslandSim::connectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& source, PxNodeIndex /*destination*/)
{
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE);
instance.mNextEdge = source.mFirstEdgeIndex;
if(source.mFirstEdgeIndex != IG_INVALID_EDGE)
{
EdgeInstance& firstEdge = mEdgeInstances[source.mFirstEdgeIndex];
firstEdge.mPrevEdge = edgeIndex;
}
source.mFirstEdgeIndex = edgeIndex;
instance.mPrevEdge = IG_INVALID_EDGE;
}
void IslandSim::addConnection(PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Edge::EdgeType edgeType, EdgeIndex handle)
{
// PT: the EdgeIndex is assigned by the SimpleIslandManager one level higher.
PX_UNUSED(nodeHandle1);
PX_UNUSED(nodeHandle2);
if(handle >= mEdges.capacity())
{
PX_PROFILE_ZONE("ReserveIslandEdges", getContextId());
const PxU32 newSize = handle + 2048;
mEdges.reserve(newSize);
mActiveContactEdges.resize(mEdges.capacity());
}
mEdges.resize(PxMax(mEdges.size(), handle+1));
mActiveContactEdges.reset(handle);
Edge& edge = mEdges[handle];
if(edge.isPendingDestroyed())
{
//If it's in this state, then the edge has been tagged for destruction but actually is now not needed to be destroyed
edge.clearPendingDestroyed();
return;
}
if(edge.isInDirtyList())
{
PX_ASSERT(mEdgeNodeIndices[handle * 2].index() == nodeHandle1.index());
PX_ASSERT(mEdgeNodeIndices[handle * 2 + 1].index() == nodeHandle2.index());
PX_ASSERT(edge.mEdgeType == edgeType);
return;
}
PX_ASSERT(!edge.isInserted());
PX_ASSERT(edge.isDestroyed());
edge.clearDestroyed();
PX_ASSERT(edge.mNextIslandEdge == IG_INVALID_ISLAND);
PX_ASSERT(edge.mPrevIslandEdge == IG_INVALID_ISLAND);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle+1].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle].mPrevEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle+1].mPrevEdge == IG_INVALID_EDGE);
edge.mEdgeType = edgeType;
PX_ASSERT(handle*2 >= mEdgeInstances.size() || mEdgeInstances[handle*2].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2+1 >= mEdgeInstances.size() || mEdgeInstances[handle*2+1].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2 >= mEdgeInstances.size() || mEdgeInstances[handle*2].mPrevEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2+1 >= mEdgeInstances.size() || mEdgeInstances[handle*2+1].mPrevEdge == IG_INVALID_EDGE);
//Add the new handle
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edgeType], handle));
mDirtyEdges[edgeType].pushBack(handle);
edge.markInDirtyList();
}
edge.mEdgeState &= ~(Edge::eACTIVATING);
}
void IslandSim::addConnectionToGraph(EdgeIndex handle)
{
const EdgeInstanceIndex instanceHandle = 2*handle;
PX_ASSERT(instanceHandle < mEdgeInstances.capacity());
/*if(instanceHandle == mEdgeInstances.capacity())
{
mEdgeInstances.reserve(2*mEdgeInstances.capacity() + 2);
}*/
mEdgeInstances.resize(PxMax(instanceHandle+2, mEdgeInstances.size()));
Edge& edge = mEdges[handle];
// PT: TODO: int bools
bool activeEdge = false;
bool kinematicKinematicEdge = true;
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[instanceHandle];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[instanceHandle+1];
if(nodeIndex1.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex1.index()];
connectEdge(mEdgeInstances[instanceHandle], instanceHandle, node, nodeIndex2);
activeEdge = node.isActive() || node.isActivating();
kinematicKinematicEdge = node.isKinematic();
}
if(nodeIndex1.index() != nodeIndex2.index() && nodeIndex2.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex2.index()];
connectEdge(mEdgeInstances[instanceHandle + 1], instanceHandle + 1, node, nodeIndex1);
activeEdge = activeEdge || node.isActive() || node.isActivating();
kinematicKinematicEdge = kinematicKinematicEdge && node.isKinematic();
}
if(activeEdge && (!kinematicKinematicEdge || edge.getEdgeType() == IG::Edge::eCONTACT_MANAGER))
{
markEdgeActive(handle);
edge.activateEdge();
}
}
void IslandSim::removeConnectionFromGraph(EdgeIndex edgeIndex)
{
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * edgeIndex];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * edgeIndex+1];
if (nodeIndex1.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex1.index()];
if (nodeIndex2.index() == mFastRoute[nodeIndex1.index()].index())
mFastRoute[nodeIndex1.index()].setIndices(PX_INVALID_NODE);
if(!node.isDirty())
{
//mDirtyNodes.pushBack(nodeIndex1);
mDirtyMap.growAndSet(nodeIndex1.index());
node.markDirty();
}
}
if (nodeIndex2.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex2.index()];
if (nodeIndex1.index() == mFastRoute[nodeIndex2.index()].index())
mFastRoute[nodeIndex2.index()].setIndices(PX_INVALID_NODE);
if(!node.isDirty())
{
mDirtyMap.growAndSet(nodeIndex2.index());
node.markDirty();
}
}
}
void IslandSim::disconnectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& node)
{
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mNextEdge].mPrevEdge == edgeIndex);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mPrevEdge].mNextEdge == edgeIndex);
if(node.mFirstEdgeIndex == edgeIndex)
{
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE);
node.mFirstEdgeIndex = instance.mNextEdge;
}
else
{
EdgeInstance& prev = mEdgeInstances[instance.mPrevEdge];
PX_ASSERT(prev.mNextEdge == edgeIndex);
prev.mNextEdge = instance.mNextEdge;
}
if(instance.mNextEdge != IG_INVALID_EDGE)
{
EdgeInstance& next = mEdgeInstances[instance.mNextEdge];
PX_ASSERT(next.mPrevEdge == edgeIndex);
next.mPrevEdge = instance.mPrevEdge;
}
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mNextEdge].mPrevEdge == instance.mPrevEdge);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mPrevEdge].mNextEdge == instance.mNextEdge);
instance.mNextEdge = IG_INVALID_EDGE;
instance.mPrevEdge = IG_INVALID_EDGE;
}
void IslandSim::removeConnection(EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
if(!edge.isPendingDestroyed())// && edge.isInserted())
{
mDestroyedEdges.pushBack(edgeIndex);
/*if(!edge.isInserted())
edge.setReportOnlyDestroy();*/
}
edge.setPendingDestroyed();
}
void IslandSim::removeConnectionInternal(EdgeIndex edgeIndex)
{
PX_ASSERT(edgeIndex != IG_INVALID_EDGE);
const EdgeInstanceIndex edgeInstanceBase = edgeIndex*2;
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[edgeIndex * 2];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[edgeIndex * 2 + 1];
if (nodeIndex1.index() != PX_INVALID_NODE)
disconnectEdge(mEdgeInstances[edgeInstanceBase], edgeInstanceBase, mNodes[nodeIndex1.index()]);
if (nodeIndex2.index() != PX_INVALID_NODE && nodeIndex1.index() != nodeIndex2.index())
disconnectEdge(mEdgeInstances[edgeInstanceBase+1], edgeInstanceBase+1, mNodes[nodeIndex2.index()]);
}
/*void IslandSim::addContactManager(PxsContactManager*, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle)
{
addConnection(nodeHandle1, nodeHandle2, Edge::eCONTACT_MANAGER, handle);
}*/
void IslandSim::addConstraint(Dy::Constraint* /*constraint*/, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle)
{
addConnection(nodeHandle1, nodeHandle2, Edge::eCONSTRAINT, handle);
}
void IslandSim::activateNode(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex.index()];
if(!(node.isActive() || node.isActivating()))
{
//If the node is kinematic and already in the active node list, then we need to remove it
//from the active kinematic node list, then re-add it after the wake-up. It's a bit stupid
//but it means that we don't need another index
if(node.isKinematic() && mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//node.setActive();
//node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
//return;
const PxU32 activeRefCount = node.mActiveRefCount;
node.mActiveRefCount = 0;
node.clearActive();
markKinematicInactive(nodeIndex);
node.mActiveRefCount = activeRefCount;
}
node.setActivating(); //Tag it as activating
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActivatingNodes.size();
//Add to waking list
mActivatingNodes.pushBack(nodeIndex);
}
node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
node.clearDeactivating();
}
}
void IslandSim::deactivateNode(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex.index()];
//If the node is activating, clear its activating state and remove it from the activating list.
//If it wasn't already activating, then it's probably already in the active list
const bool wasActivating = node.isActivating();
if(wasActivating)
{
//Already activating, so remove it from the activating list
node.clearActivating();
PX_ASSERT(mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]].index() == nodeIndex.index());
const PxNodeIndex replaceIndex = mActivatingNodes[mActivatingNodes.size()-1];
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[nodeIndex.index()];
mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]] = replaceIndex;
mActivatingNodes.forceSize_Unsafe(mActivatingNodes.size()-1);
mActiveNodeIndex[nodeIndex.index()] = PX_INVALID_NODE;
if(node.isKinematic())
{
//If we were temporarily removed from the active kinematic list to be put in the waking kinematic list
//then add the node back in before deactivating the node. This is a bit counter-intuitive but the active
//kinematic list contains all active kinematics and all kinematics that are referenced by an active constraint
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(nodeIndex);
}
}
//Raise the "ready for sleeping" flag so that island gen can put this node to sleep
node.setIsReadyForSleeping();
}
}
void IslandSim::putNodeToSleep(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
deactivateNode(nodeIndex);
}
void IslandSim::activateNodeInternal(PxNodeIndex nodeIndex)
{
//This method should activate the node, then activate all the connections involving this node
Node& node = mNodes[nodeIndex.index()];
if(!node.isActive())
{
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
//Activate all the edges + nodes...
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeIndex idx = index/2;
Edge& edge = mEdges[idx]; //InstanceIndex/2 = edgeIndex
if(!edge.isActive())
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
index = mEdgeInstances[index].mNextEdge;
}
if(node.isKinematic())
markKinematicActive(nodeIndex);
else
markActive(nodeIndex);
node.setActive();
}
}
void IslandSim::deactivateNodeInternal(PxNodeIndex nodeIndex)
{
//We deactivate a node, we need to loop through all the edges and deactivate them *if* both bodies are asleep
Node& node = mNodes[nodeIndex.index()];
if(node.isActive())
{
if(node.isKinematic())
markKinematicInactive(nodeIndex);
else
markInactive(nodeIndex);
//Clear the active status flag
node.clearActive();
node.clearActivating();
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
if(outboundNode.index() == PX_INVALID_NODE ||
!mNodes[outboundNode.index()].isActive())
{
const EdgeIndex idx = index/2;
Edge& edge = mEdges[idx]; //InstanceIndex/2 = edgeIndex
//PX_ASSERT(edge.isActive()); //The edge must currently be inactive because the node was active
//Deactivate the edge if both nodes connected are inactive OR if one node is static/kinematic and the other is inactive...
PX_ASSERT(mEdgeNodeIndices[index & (~1)].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[index & (~1)].index()].isActive());
PX_ASSERT(mEdgeNodeIndices[index | 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[index | 1].index()].isActive());
if(edge.isActive())
{
edge.deactivateEdge();
mActiveEdgeCount[edge.mEdgeType]--;
removeEdgeFromActivatingList(idx);
mDeactivatingEdges[edge.mEdgeType].pushBack(idx);
}
}
index = instance.mNextEdge;
}
}
}
bool IslandSim::canFindRoot(PxNodeIndex startNode, PxNodeIndex targetNode, PxArray<PxNodeIndex>* visitedNodes)
{
if(visitedNodes)
visitedNodes->pushBack(startNode);
if(startNode.index() == targetNode.index())
return true;
PxBitMap visitedState;
visitedState.resizeAndClear(mNodes.size());
PxArray<PxNodeIndex> stack;
stack.pushBack(startNode);
visitedState.set(startNode.index());
do
{
const PxNodeIndex currentIndex = stack.popBack();
const Node& currentNode = mNodes[currentIndex.index()];
EdgeInstanceIndex currentEdge = currentNode.mFirstEdgeIndex;
while(currentEdge != IG_INVALID_EDGE)
{
const EdgeInstance& edge = mEdgeInstances[currentEdge];
const PxNodeIndex outboundNode = mEdgeNodeIndices[currentEdge ^ 1];
if(outboundNode.index() != PX_INVALID_NODE && !mNodes[outboundNode.index()].isKinematic() && !visitedState.test(outboundNode.index()))
{
if(outboundNode.index() == targetNode.index())
return true;
visitedState.set(outboundNode.index());
stack.pushBack(outboundNode);
if(visitedNodes)
visitedNodes->pushBack(outboundNode);
}
currentEdge = edge.mNextEdge;
}
}
while(stack.size());
return false;
}
void IslandSim::unwindRoute(PxU32 traversalIndex, PxNodeIndex lastNode, PxU32 hopCount, IslandId id)
{
//We have found either a witness *or* the root node with this traversal. In the event of finding the root node, hopCount will be 0. In the event of finding
//a witness, hopCount will be the hopCount that witness reported as being the distance to the root.
PxU32 currIndex = traversalIndex;
PxU32 hc = hopCount+1; //Add on 1 for the hop to the witness/root node.
do
{
TraversalState& state = mVisitedNodes[currIndex];
mHopCounts[state.mNodeIndex.index()] = hc++;
mIslandIds[state.mNodeIndex.index()] = id;
mFastRoute[state.mNodeIndex.index()] = lastNode;
currIndex = state.mPrevIndex;
lastNode = state.mNodeIndex;
}
while(currIndex != PX_INVALID_NODE);
}
void IslandSim::activateIsland(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(!mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex == IG_INVALID_ISLAND);
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
markIslandActive(islandId);
}
void IslandSim::deactivateIsland(IslandId islandId)
{
PX_ASSERT(mIslandAwake.test(islandId));
Island& island = mIslands[islandId];
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
const Node& node = mNodes[currentNode.index()];
//if(mActiveNodeIndex[currentNode.index()] < mInitialActiveNodeCount[node.mType])
mNodesToPutToSleep[node.mType].pushBack(currentNode); //If this node was previously active, then push it to the list of nodes to deactivate
deactivateNodeInternal(currentNode);
currentNode = node.mNextNode;
}
markIslandInactive(islandId);
}
void IslandSim::wakeIslands()
{
PX_PROFILE_ZONE("Basic.wakeIslands", getContextId());
//(1) Iterate over activating nodes and activate them
const PxU32 originalActiveIslands = mActiveIslands.size();
for (PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
for (PxU32 i = 0, count = mActivatedEdges[a].size(); i < count; ++i)
{
IG::Edge& edge = mEdges[mActivatedEdges[a][i]];
edge.mEdgeState &= (~Edge::eACTIVATING);
}
mActivatedEdges[a].forceSize_Unsafe(0);
}
/*mInitialActiveEdgeCount[0] = mActiveEdges[0].size();
mInitialActiveEdgeCount[1] = mActiveEdges[1].size();*/
for (PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
mInitialActiveNodeCount[a] = mActiveNodes[a].size();
}
for(PxU32 a = 0; a < mActivatingNodes.size(); ++a)
{
const PxNodeIndex wakeNode = mActivatingNodes[a];
const IslandId islandId = mIslandIds[wakeNode.index()];
Node& node = mNodes[wakeNode.index()];
node.clearActivating();
if(islandId != IG_INVALID_ISLAND)
{
if(!mIslandAwake.test(islandId))
markIslandActive(islandId);
mActiveNodeIndex[wakeNode.index()] = PX_INVALID_NODE; //Mark active node as invalid.
activateNodeInternal(wakeNode);
}
else
{
PX_ASSERT(node.isKinematic());
node.setActive();
PX_ASSERT(mActiveNodeIndex[wakeNode.index()] == a);
mActiveNodeIndex[wakeNode.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(wakeNode);
//Wake up the islands connected to this waking kinematic!
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& edgeInstance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
//Edge& edge = mEdges[index/2];
//if(edge.isConnected()) //Only wake up if the edge is not connected...
const PxNodeIndex nodeIndex = outboundNode;
if (nodeIndex.isStaticBody() || mIslandIds[nodeIndex.index()] == IG_INVALID_ISLAND)
{
//If the edge connects to a static body *or* it connects to a node which is not part of an island (i.e. a kinematic), then activate the edge
const EdgeIndex idx = index / 2;
Edge& edge = mEdges[idx];
if (!edge.isActive() && edge.getEdgeType() != IG::Edge::eCONSTRAINT)
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
}
else
{
const IslandId connectedIslandId = mIslandIds[nodeIndex.index()];
if(!mIslandAwake.test(connectedIslandId))
{
//Wake up that island
markIslandActive(connectedIslandId);
}
}
index = edgeInstance.mNextEdge;
}
}
}
mActivatingNodes.forceSize_Unsafe(0);
for(PxU32 a = originalActiveIslands; a < mActiveIslands.size(); ++a)
{
const Island& island = mIslands[mActiveIslands[a]];
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
}
}
void IslandSim::wakeIslands2()
{
const PxU32 originalActiveIslands = mActiveIslands.size();
for (PxU32 a = 0; a < mActivatingNodes.size(); ++a)
{
const PxNodeIndex wakeNode = mActivatingNodes[a];
const IslandId islandId = mIslandIds[wakeNode.index()];
Node& node = mNodes[wakeNode.index()];
node.clearActivating();
if (islandId != IG_INVALID_ISLAND)
{
if (!mIslandAwake.test(islandId))
markIslandActive(islandId);
mActiveNodeIndex[wakeNode.index()] = PX_INVALID_NODE; //Mark active node as invalid.
activateNodeInternal(wakeNode);
}
else
{
PX_ASSERT(node.isKinematic());
node.setActive();
PX_ASSERT(mActiveNodeIndex[wakeNode.index()] == a);
mActiveNodeIndex[wakeNode.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(wakeNode);
//Wake up the islands connected to this waking kinematic!
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while (index != IG_INVALID_EDGE)
{
const EdgeInstance& edgeInstance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
//Edge& edge = mEdges[index/2];
//if(edge.isConnected()) //Only wake up if the edge is not connected...
const PxNodeIndex nodeIndex = outboundNode;
if (nodeIndex.isStaticBody() || mIslandIds[nodeIndex.index()] == IG_INVALID_ISLAND)
{
//If the edge connects to a static body *or* it connects to a node which is not part of an island (i.e. a kinematic), then activate the edge
const EdgeIndex idx = index / 2;
Edge& edge = mEdges[idx];
if (!edge.isActive() && edge.getEdgeType() != IG::Edge::eCONSTRAINT)
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
}
else
{
IslandId connectedIslandId = mIslandIds[nodeIndex.index()];
if (!mIslandAwake.test(connectedIslandId))
{
//Wake up that island
markIslandActive(connectedIslandId);
}
}
index = edgeInstance.mNextEdge;
}
}
}
mActivatingNodes.forceSize_Unsafe(0);
for (PxU32 a = originalActiveIslands; a < mActiveIslands.size(); ++a)
{
const Island& island = mIslands[mActiveIslands[a]];
PxNodeIndex currentNode = island.mRootNode;
while (currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
}
}
void IslandSim::insertNewEdges()
{
PX_PROFILE_ZONE("Basic.insertNewEdges", getContextId());
mEdgeInstances.reserve(mEdges.capacity()*2);
for(PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for(PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
const EdgeIndex edgeIndex = mDirtyEdges[i][a];
Edge& edge = mEdges[edgeIndex];
if(!edge.isPendingDestroyed())
{
//PX_ASSERT(!edge.isInserted());
if(!edge.isInserted())
{
addConnectionToGraph(edgeIndex);
edge.setInserted();
}
}
}
}
}
void IslandSim::removeDestroyedEdges()
{
PX_PROFILE_ZONE("Basic.removeDestroyedEdges", getContextId());
for(PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
const EdgeIndex edgeIndex = mDestroyedEdges[a];
const Edge& edge = mEdges[edgeIndex];
if(edge.isPendingDestroyed())
{
if(!edge.isInDirtyList() && edge.isInserted())
{
PX_ASSERT(edge.isInserted());
removeConnectionInternal(edgeIndex);
removeConnectionFromGraph(edgeIndex);
//edge.clearInserted();
}
//edge.clearDestroyed();
}
}
}
void IslandSim::processNewEdges()
{
PX_PROFILE_ZONE("Basic.processNewEdges", getContextId());
//Stage 1: we process the list of new pairs. To do this, we need to first sort them based on a predicate...
insertNewEdges();
mHopCounts.resize(mNodes.size()); //Make sure we have enough space for hop counts for all nodes
mFastRoute.resize(mNodes.size());
for(PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for(PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
const EdgeIndex edgeIndex = mDirtyEdges[i][a];
const Edge& edge = mEdges[edgeIndex];
/*PX_ASSERT(edge.mState != Edge::eDESTROYED || ((edge.mNode1.index() == PX_INVALID_NODE || mNodes[edge.mNode1.index()].isKinematic() || mNodes[edge.mNode1.index()].isActive() == false) &&
(edge.mNode2.index() == PX_INVALID_NODE || mNodes[edge.mNode2.index()].isKinematic() || mNodes[edge.mNode2.index()].isActive() == false)));*/
//edge.clearInDirtyList();
//We do not process either destroyed or disconnected edges
if(/*edge.isConnected() && */!edge.isPendingDestroyed())
{
//Conditions:
//(1) Neither body is in an island (static/kinematics are never in islands) so we need to create a new island containing these bodies
// or just 1 body if the other is kinematic/static
//(2) Both bodies are already in the same island. Update root node hop count estimates for the bodies if a route through the new connection
// is shorter for either body
//(3) One body is already in an island and the other isn't, so we just add the new body to the existing island.
//(4) Both bodies are in different islands. In that case, we merge the islands
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * edgeIndex];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * edgeIndex+1];
const IslandId islandId1 = nodeIndex1.index() == PX_INVALID_NODE ? IG_INVALID_ISLAND : mIslandIds[nodeIndex1.index()];
const IslandId islandId2 = nodeIndex2.index() == PX_INVALID_NODE ? IG_INVALID_ISLAND : mIslandIds[nodeIndex2.index()];
//TODO - wake ups!!!!
//If one of the nodes is awake and the other is asleep, we need to wake 'em up
//When a node is activated, the island must also be activated...
const bool active1 = nodeIndex1.index() != PX_INVALID_NODE && mNodes[nodeIndex1.index()].isActive();
const bool active2 = nodeIndex2.index() != PX_INVALID_NODE && mNodes[nodeIndex2.index()].isActive();
IslandId islandId = IG_INVALID_ISLAND;
if(islandId1 == IG_INVALID_ISLAND && islandId2 == IG_INVALID_ISLAND)
{
//All nodes should be introduced in an island now unless they are static or kinematic. Therefore, if we get here, we have an edge
//between 2 kinematic nodes or a kinematic and static node. These should not influence island management so we should just ignore
//these edges.
}
else if(islandId1 == islandId2)
{
islandId = islandId1;
if(active1 || active2)
{
PX_ASSERT(mIslandAwake.test(islandId1)); //If we got here, where the 2 were already in an island, if 1 node is awake, the whole island must be awake
}
//Both bodies in the same island. Nothing major to do already but we should see if this creates a shorter path to root for either node
const PxU32 hopCount1 = mHopCounts[nodeIndex1.index()];
const PxU32 hopCount2 = mHopCounts[nodeIndex2.index()];
if((hopCount1+1) < hopCount2)
{
//It would be faster for node 2 to go through node 1
mHopCounts[nodeIndex2.index()] = hopCount1 + 1;
mFastRoute[nodeIndex2.index()] = nodeIndex1;
}
else if((hopCount2+1) < hopCount1)
{
//It would be faster for node 1 to go through node 2
mHopCounts[nodeIndex1.index()] = hopCount2 + 1;
mFastRoute[nodeIndex1.index()] = nodeIndex2;
}
//No need to activate/deactivate the island. Its state won't have changed
}
else if(islandId1 == IG_INVALID_ISLAND)
{
islandId = islandId2;
if (nodeIndex1.index() != PX_INVALID_NODE)
{
if (!mNodes[nodeIndex1.index()].isKinematic())
{
PX_ASSERT(islandId2 != IG_INVALID_ISLAND);
//We need to add node 1 to island2
PX_ASSERT(mNodes[nodeIndex1.index()].mNextNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
PX_ASSERT(mNodes[nodeIndex1.index()].mPrevNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
Island& island = mIslands[islandId2];
Node& lastNode = mNodes[island.mLastNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
Node& node = mNodes[nodeIndex1.index()];
lastNode.mNextNode = nodeIndex1;
node.mPrevNode = island.mLastNode;
island.mLastNode = nodeIndex1;
island.mNodeCount[node.mType]++;
mIslandIds[nodeIndex1.index()] = islandId2;
mHopCounts[nodeIndex1.index()] = mHopCounts[nodeIndex2.index()] + 1;
mFastRoute[nodeIndex1.index()] = nodeIndex2;
if(active1 || active2)
{
if(!mIslandAwake.test(islandId2))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId2);
}
if(!active1)
{
//Wake up this node...
activateNodeInternal(nodeIndex1);
}
}
}
else if(active1 && !active2)
{
//Active kinematic object -> wake island!
activateIsland(islandId2);
}
}
else
{
//A new touch with a static body...
Node& node = mNodes[nodeIndex2.index()];
node.mStaticTouchCount++; //Increment static touch counter on the body
//Island& island = mIslands[islandId2];
//island.mStaticTouchCount++; //Increment static touch counter on the island
mIslandStaticTouchCount[islandId2]++;
}
}
else if (islandId2 == IG_INVALID_ISLAND)
{
islandId = islandId1;
if (nodeIndex2.index() != PX_INVALID_NODE)
{
if (!mNodes[nodeIndex2.index()].isKinematic())
{
PX_ASSERT(islandId1 != PX_INVALID_NODE);
//We need to add node 1 to island2
PX_ASSERT(mNodes[nodeIndex2.index()].mNextNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
PX_ASSERT(mNodes[nodeIndex2.index()].mPrevNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
Island& island = mIslands[islandId1];
Node& lastNode = mNodes[island.mLastNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
Node& node = mNodes[nodeIndex2.index()];
lastNode.mNextNode = nodeIndex2;
node.mPrevNode = island.mLastNode;
island.mLastNode = nodeIndex2;
island.mNodeCount[node.mType]++;
mIslandIds[nodeIndex2.index()] = islandId1;
mHopCounts[nodeIndex2.index()] = mHopCounts[nodeIndex1.index()] + 1;
mFastRoute[nodeIndex2.index()] = nodeIndex1;
if(active1 || active2)
{
if(!mIslandAwake.test(islandId1))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId1);
}
if(!active1)
{
//Wake up this node...
activateNodeInternal(nodeIndex2);
}
}
}
else if(active2 && !active1)
{
//Active kinematic object -> wake island!
activateIsland(islandId1);
}
}
else
{
//New static touch
//A new touch with a static body...
Node& node = mNodes[nodeIndex1.index()];
node.mStaticTouchCount++; //Increment static touch counter on the body
//Island& island = mIslands[islandId1];
mIslandStaticTouchCount[islandId1]++;
//island.mStaticTouchCount++; //Increment static touch counter on the island
}
}
else
{
PX_ASSERT(islandId1 != islandId2);
PX_ASSERT(islandId1 != IG_INVALID_ISLAND && islandId2 != IG_INVALID_ISLAND);
if(active1 || active2)
{
//One of the 2 islands was awake, so need to wake the other one! We do this now, before we merge the islands, to ensure that all
//the bodies are activated
if(!mIslandAwake.test(islandId1))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId1);
}
if(!mIslandAwake.test(islandId2))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId2);
}
}
//OK. We need to merge these islands together...
islandId = mergeIslands(islandId1, islandId2, nodeIndex1, nodeIndex2);
}
if(islandId != IG_INVALID_ISLAND)
{
//Add new edge to existing island
Island& island = mIslands[islandId];
addEdgeToIsland(island, edgeIndex);
}
}
}
}
}
bool IslandSim::isPathTo(PxNodeIndex startNode, PxNodeIndex targetNode) const
{
const Node& node = mNodes[startNode.index()];
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[index];
if(/*mEdges[index/2].isConnected() &&*/ mEdgeNodeIndices[index^1].index() == targetNode.index())
return true;
index = instance.mNextEdge;
}
return false;
}
bool IslandSim::tryFastPath(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId)
{
PX_UNUSED(startNode);
PX_UNUSED(targetNode);
PxNodeIndex currentNode = startNode;
const PxU32 currentVisitedNodes = mVisitedNodes.size();
PxU32 depth = 0;
bool found = false;
do
{
//Get the fast path from this node...
if(mVisitedState.test(currentNode.index()))
{
found = mIslandIds[currentNode.index()] != IG_INVALID_ISLAND; //Already visited and not tagged with invalid island == a witness!
break;
}
if( currentNode.index() == targetNode.index())
{
found = true;
break;
}
mVisitedNodes.pushBack(TraversalState(currentNode, mVisitedNodes.size(), mVisitedNodes.size()-1, depth++));
PX_ASSERT(mFastRoute[currentNode.index()].index() == PX_INVALID_NODE || isPathTo(currentNode, mFastRoute[currentNode.index()]));
mIslandIds[currentNode.index()] = IG_INVALID_ISLAND;
mVisitedState.set(currentNode.index());
currentNode = mFastRoute[currentNode.index()];
}
while(currentNode.index() != PX_INVALID_NODE);
for(PxU32 a = currentVisitedNodes; a < mVisitedNodes.size(); ++a)
{
const TraversalState& state = mVisitedNodes[a];
mIslandIds[state.mNodeIndex.index()] = islandId;
}
if(!found)
{
for(PxU32 a = currentVisitedNodes; a < mVisitedNodes.size(); ++a)
{
const TraversalState& state = mVisitedNodes[a];
mVisitedState.reset(state.mNodeIndex.index());
}
mVisitedNodes.forceSize_Unsafe(currentVisitedNodes);
}
return found;
}
bool IslandSim::findRoute(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId)
{
//Firstly, traverse the fast path and tag up witnesses. TryFastPath can fail. In that case, no witnesses are left but this node is permitted to report
//that it is still part of the island. Whichever node lost its fast path will be tagged as dirty and will be responsible for recovering the fast path
//and tagging up the visited nodes
if(mFastRoute[startNode.index()].index() != PX_INVALID_NODE)
{
if(tryFastPath(startNode, targetNode, islandId))
return true;
//Try fast path can either be successful or not. If it was successful, then we had a valid fast path cached and all nodes on that fast path were tagged
//as witness nodes (visited and with a valid island ID). If the fast path was not successful, then no nodes were tagged as witnesses.
//Technically, we need to find a route to the root node but, as an optimization, we can simply return true from here with no witnesses added.
//Whichever node actually broke the "fast path" will also be on the list of dirty nodes and will be processed later.
//If that broken edge triggered an island separation, this node will be re-visited and added to that island, otherwise
//the path to the root node will be re-established. The end result is the same - the island state is computed - this just saves us some work.
//return true;
}
{
//If we got here, there was no fast path. Therefore, we need to fall back on searching for the root node. This is optimized by using "hop counts".
//These are per-node counts that indicate the expected number of hops from this node to the root node. These are lazily evaluated and updated
//as new edges are formed or when traversals occur to re-establish islands. As a result, they may be inaccurate but they still serve the purpose
//of guiding our search to minimize the chances of us doing an exhaustive search to find the root node.
mIslandIds[startNode.index()] = IG_INVALID_ISLAND;
TraversalState* startTraversal = &mVisitedNodes.pushBack(TraversalState(startNode, mVisitedNodes.size(), PX_INVALID_NODE, 0));
mVisitedState.set(startNode.index());
QueueElement element(startTraversal, mHopCounts[startNode.index()]);
mPriorityQueue.push(element);
do
{
const QueueElement currentQE = mPriorityQueue.pop();
const TraversalState& currentState = *currentQE.mState;
const Node& currentNode = mNodes[currentState.mNodeIndex.index()];
EdgeInstanceIndex edge = currentNode.mFirstEdgeIndex;
while(edge != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edge];
{
const PxNodeIndex nextIndex = mEdgeNodeIndices[edge ^ 1];
//Static or kinematic nodes don't connect islands.
if(nextIndex.index() != PX_INVALID_NODE && !mNodes[nextIndex.index()].isKinematic())
{
if(nextIndex.index() == targetNode.index())
{
unwindRoute(currentState.mCurrentIndex, nextIndex, 0, islandId);
return true;
}
if(mVisitedState.test(nextIndex.index()))
{
//We already visited this node. This means that it's either in the priority queue already or we
//visited in on a previous pass. If it was visited on a previous pass, then it already knows what island it's in.
//We now need to test the island id to find out if this node knows the root.
//If it has a valid root id, that id *is* our new root. We can guesstimate our hop count based on the node's properties
const IslandId visitedIslandId = mIslandIds[nextIndex.index()];
if(visitedIslandId != IG_INVALID_ISLAND)
{
//If we get here, we must have found a node that knows a route to our root node. It must not be a different island
//because that would caused me to have been visited already because totally separate islands trigger a full traversal on
//the orphaned side.
PX_ASSERT(visitedIslandId == islandId);
unwindRoute(currentState.mCurrentIndex, nextIndex, mHopCounts[nextIndex.index()], islandId);
return true;
}
}
else
{
//This node has not been visited yet, so we need to push it into the stack and continue traversing
TraversalState* state = &mVisitedNodes.pushBack(TraversalState(nextIndex, mVisitedNodes.size(), currentState.mCurrentIndex, currentState.mDepth+1));
QueueElement qe(state, mHopCounts[nextIndex.index()]);
mPriorityQueue.push(qe);
mVisitedState.set(nextIndex.index());
PX_ASSERT(mIslandIds[nextIndex.index()] == islandId);
mIslandIds[nextIndex.index()] = IG_INVALID_ISLAND; //Flag as invalid island until we know whether we can find root or an island id.
}
}
}
edge = instance.mNextEdge;
}
}
while(mPriorityQueue.size());
return false;
}
}
#define IG_LIMIT_DIRTY_NODES 0
void IslandSim::processLostEdges(PxArray<PxNodeIndex>& destroyedNodes, bool allowDeactivation, bool permitKinematicDeactivation, PxU32 dirtyNodeLimit)
{
PX_UNUSED(dirtyNodeLimit);
PX_PROFILE_ZONE("Basic.processLostEdges", getContextId());
//At this point, all nodes and edges are activated.
//Bit map for visited
mVisitedState.resizeAndClear(mNodes.size());
//Reserve space on priority queue for at least 1024 nodes. It will resize if more memory is required during traversal.
mPriorityQueue.reserve(1024);
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
mIslandSplitEdges[i].reserve(1024);
mVisitedNodes.reserve(mNodes.size()); //Make sure we have enough space for all nodes!
const PxU32 nbDestroyedEdges = mDestroyedEdges.size();
PX_UNUSED(nbDestroyedEdges);
{
PX_PROFILE_ZONE("Basic.removeEdgesFromIslands", getContextId());
for (PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
const EdgeIndex lostIndex = mDestroyedEdges[a];
Edge& lostEdge = mEdges[lostIndex];
if (lostEdge.isPendingDestroyed() && !lostEdge.isInDirtyList())
{
//Process this edge...
if (!lostEdge.isReportOnlyDestroy() && lostEdge.isInserted())
{
const PxU32 index1 = mEdgeNodeIndices[mDestroyedEdges[a] * 2].index();
const PxU32 index2 = mEdgeNodeIndices[mDestroyedEdges[a] * 2 + 1].index();
IslandId islandId = IG_INVALID_ISLAND;
if (index1 != PX_INVALID_NODE && index2 != PX_INVALID_NODE)
{
PX_ASSERT(mIslandIds[index1] == IG_INVALID_ISLAND || mIslandIds[index2] == IG_INVALID_ISLAND ||
mIslandIds[index1] == mIslandIds[index2]);
islandId = mIslandIds[index1] != IG_INVALID_ISLAND ? mIslandIds[index1] : mIslandIds[index2];
}
else if (index1 != PX_INVALID_NODE)
{
PX_ASSERT(index2 == PX_INVALID_NODE);
Node& node = mNodes[index1];
if (!node.isKinematic())
{
islandId = mIslandIds[index1];
node.mStaticTouchCount--;
//Island& island = mIslands[islandId];
mIslandStaticTouchCount[islandId]--;
//island.mStaticTouchCount--;
}
}
else if (index2 != PX_INVALID_NODE)
{
PX_ASSERT(index1 == PX_INVALID_NODE);
Node& node = mNodes[index2];
if (!node.isKinematic())
{
islandId = mIslandIds[index2];
node.mStaticTouchCount--;
//Island& island = mIslands[islandId];
mIslandStaticTouchCount[islandId]--;
//island.mStaticTouchCount--;
}
}
if (islandId != IG_INVALID_ISLAND)
{
//We need to remove this edge from the island
Island& island = mIslands[islandId];
removeEdgeFromIsland(island, lostIndex);
}
}
lostEdge.clearInserted();
}
}
}
if (allowDeactivation)
{
PX_PROFILE_ZONE("Basic.findPathsAndBreakIslands", getContextId());
//KS - process only this many dirty nodes, deferring future dirty nodes to subsequent frames.
//This means that it may take several frames for broken edges to trigger islands to completely break but this is better
//than triggering large performance spikes.
#if IG_LIMIT_DIRTY_NODES
PxBitMap::PxCircularIterator iter(mDirtyMap, mLastMapIndex);
const PxU32 MaxCount = dirtyNodeLimit;// +10000000;
PxU32 lastMapIndex = mLastMapIndex;
PxU32 count = 0;
#else
PxBitMap::Iterator iter(mDirtyMap);
#endif
PxU32 dirtyIdx;
#if IG_LIMIT_DIRTY_NODES
while ((dirtyIdx = iter.getNext()) != PxBitMap::PxCircularIterator::DONE
&& (count++ < MaxCount)
#else
while ((dirtyIdx = iter.getNext()) != PxBitMap::Iterator::DONE
#endif
)
{
#if IG_LIMIT_DIRTY_NODES
lastMapIndex = dirtyIdx + 1;
#endif
//Process dirty nodes. Figure out if we can make our way from the dirty node to the root.
mPriorityQueue.clear(); //Clear the queue used for traversal
mVisitedNodes.forceSize_Unsafe(0); //Clear the list of nodes in this island
const PxNodeIndex dirtyNodeIndex(dirtyIdx);
Node& dirtyNode = mNodes[dirtyNodeIndex.index()];
//Check whether this node has already been touched. If it has been touched this frame, then its island state is reliable
//and we can just unclear the dirty flag on the body. If we were already visited, then the state should have already been confirmed in a
//previous pass.
if (!dirtyNode.isKinematic() && !dirtyNode.isDeleted() && !mVisitedState.test(dirtyNodeIndex.index()))
{
//We haven't visited this node in our island repair passes yet, so we still need to process until we've hit a visited node or found
//our root node. Note that, as soon as we hit a visited node that has already been processed in a previous pass, we know that we can rely
//on its island information although the hop counts may not be optimal. It also indicates that this island was not broken immediately because
//otherwise, the entire new sub-island would already have been visited and this node would have already had its new island state assigned.
//Indicate that I've been visited
const IslandId islandId = mIslandIds[dirtyNodeIndex.index()];
const Island& findIsland = mIslands[islandId];
const PxNodeIndex searchNode = findIsland.mRootNode;//The node that we're searching for!
if (searchNode.index() != dirtyNodeIndex.index()) //If we are the root node, we don't need to do anything!
{
if (findRoute(dirtyNodeIndex, searchNode, islandId))
{
//We found the root node so let's let every visited node know that we found its root
//and we can also update our hop counts because we recorded how many hops it took to reach this
//node
//We already filled in the path to the root/witness with accurate hop counts. Now we just need to fill in the estimates
//for the remaining nodes and re-define their islandIds. We approximate their path to the root by just routing them through
//the route we already found.
//This loop works because mVisitedNodes are recorded in the order they were visited and we already filled in the critical path
//so the remainder of the paths will just fork from that path.
//Verify state (that we can see the root from this node)...
#if IG_SANITY_CHECKS
PX_ASSERT(canFindRoot(dirtyNodeIndex, searchNode, NULL)); //Verify that we found the connection
#endif
for (PxU32 b = 0; b < mVisitedNodes.size(); ++b)
{
TraversalState& state = mVisitedNodes[b];
if (mIslandIds[state.mNodeIndex.index()] == IG_INVALID_ISLAND)
{
mHopCounts[state.mNodeIndex.index()] = mHopCounts[mVisitedNodes[state.mPrevIndex].mNodeIndex.index()] + 1;
mFastRoute[state.mNodeIndex.index()] = mVisitedNodes[state.mPrevIndex].mNodeIndex;
mIslandIds[state.mNodeIndex.index()] = islandId;
}
}
}
else
{
//If I traversed and could not find the root node, then I have established a new island. In this island, I am the root node
//and I will point all my nodes towards me. Furthermore, I have established how many steps it took to reach all nodes in my island
//OK. We need to separate the islands. We have a list of nodes that are part of the new island (mVisitedNodes) and we know that the
//first node in that list is the root node.
//OK, we need to remove all these actors from their current island, then add them to the new island...
Island& oldIsland = mIslands[islandId];
//We can just unpick these nodes from the island because they do not contain the root node (if they did, then we wouldn't be
//removing this node from the island at all). The only challenge is if we need to remove the last node. In that case
//we need to re-establish the new last node in the island but perhaps the simplest way to do that would be to traverse
//the island to establish the last node again
#if IG_SANITY_CHECKS
PX_ASSERT(!canFindRoot(dirtyNodeIndex, searchNode, NULL));
#endif
PxU32 totalStaticTouchCount = 0;
PxU32 nodeCount[Node::eTYPE_COUNT];
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
nodeCount[t] = 0;
}
for (PxU32 t = 0; t < Edge::eEDGE_TYPE_COUNT; ++t)
{
mIslandSplitEdges[t].forceSize_Unsafe(0);
}
//NodeIndex lastIndex = oldIsland.mLastNode;
//nodeCount[node.mType] = 1;
for (PxU32 a = 0; a < mVisitedNodes.size(); ++a)
{
const PxNodeIndex index = mVisitedNodes[a].mNodeIndex;
Node& node = mNodes[index.index()];
if (node.mNextNode.index() != PX_INVALID_NODE)
mNodes[node.mNextNode.index()].mPrevNode = node.mPrevNode;
else
oldIsland.mLastNode = node.mPrevNode;
if (node.mPrevNode.index() != PX_INVALID_NODE)
mNodes[node.mPrevNode.index()].mNextNode = node.mNextNode;
nodeCount[node.mType]++;
node.mNextNode.setIndices(PX_INVALID_NODE);
node.mPrevNode.setIndices(PX_INVALID_NODE);
PX_ASSERT(mNodes[oldIsland.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
totalStaticTouchCount += node.mStaticTouchCount;
EdgeInstanceIndex idx = node.mFirstEdgeIndex;
while (idx != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[idx];
const EdgeIndex edgeIndex = idx / 2;
const Edge& edge = mEdges[edgeIndex];
//Only split the island if we're processing the first node or if the first node is infinte-mass
if (!(idx & 1) || (mEdgeNodeIndices[idx & (~1)].index() == PX_INVALID_NODE || mNodes[mEdgeNodeIndices[idx & (~1)].index()].isKinematic()))
{
//We will remove this edge from the island...
mIslandSplitEdges[edge.mEdgeType].pushBack(edgeIndex);
removeEdgeFromIsland(oldIsland, edgeIndex);
}
idx = instance.mNextEdge;
}
}
//oldIsland.mStaticTouchCount -= totalStaticTouchCount;
mIslandStaticTouchCount[islandId] -= totalStaticTouchCount;
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
PX_ASSERT(nodeCount[i] <= oldIsland.mNodeCount[i]);
oldIsland.mNodeCount[i] -= nodeCount[i];
}
//Now add all these nodes to the new island
//(1) Create the new island...
const IslandId newIslandHandle = mIslandHandles.getHandle();
/*if(newIslandHandle == mIslands.capacity())
{
mIslands.reserve(2*mIslands.capacity() + 1);
}*/
mIslands.resize(PxMax(newIslandHandle + 1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(newIslandHandle + 1, mIslandStaticTouchCount.size()));
Island& newIsland = mIslands[newIslandHandle];
if (mIslandAwake.test(islandId))
{
newIsland.mActiveIndex = mActiveIslands.size();
mActiveIslands.pushBack(newIslandHandle);
mIslandAwake.growAndSet(newIslandHandle); //Separated island, so it should be awake
}
else
{
mIslandAwake.growAndReset(newIslandHandle);
}
newIsland.mRootNode = dirtyNodeIndex;
mHopCounts[dirtyNodeIndex.index()] = 0;
mIslandIds[dirtyNodeIndex.index()] = newIslandHandle;
//newIsland.mTotalSize = mVisitedNodes.size();
mNodes[dirtyNodeIndex.index()].mPrevNode.setIndices(PX_INVALID_NODE); //First node so doesn't have a preceding node
mFastRoute[dirtyNodeIndex.index()].setIndices(PX_INVALID_NODE);
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
nodeCount[i] = 0;
nodeCount[dirtyNode.mType] = 1;
for (PxU32 a = 1; a < mVisitedNodes.size(); ++a)
{
const PxNodeIndex index = mVisitedNodes[a].mNodeIndex;
Node& thisNode = mNodes[index.index()];
const PxNodeIndex prevNodeIndex = mVisitedNodes[a - 1].mNodeIndex;
thisNode.mPrevNode = prevNodeIndex;
mNodes[prevNodeIndex.index()].mNextNode = index;
nodeCount[thisNode.mType]++;
mIslandIds[index.index()] = newIslandHandle;
mHopCounts[index.index()] = mVisitedNodes[a].mDepth; //How many hops to root
mFastRoute[index.index()] = mVisitedNodes[mVisitedNodes[a].mPrevIndex].mNodeIndex;
}
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
newIsland.mNodeCount[i] = nodeCount[i];
//Last node in the island
const PxNodeIndex lastIndex = mVisitedNodes[mVisitedNodes.size() - 1].mNodeIndex;
mNodes[lastIndex.index()].mNextNode.setIndices(PX_INVALID_NODE);
newIsland.mLastNode = lastIndex;
//newIsland.mStaticTouchCount = totalStaticTouchCount;
mIslandStaticTouchCount[newIslandHandle] = totalStaticTouchCount;
PX_ASSERT(mNodes[newIsland.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
for (PxU32 j = 0; j < IG::Edge::eEDGE_TYPE_COUNT; ++j)
{
PxArray<EdgeIndex>& splitEdges = mIslandSplitEdges[j];
const PxU32 splitEdgeSize = splitEdges.size();
if (splitEdgeSize)
{
splitEdges.pushBack(IG_INVALID_EDGE); //Push in a dummy invalid edge to complete the connectivity
mEdges[splitEdges[0]].mNextIslandEdge = splitEdges[1];
for (PxU32 a = 1; a < splitEdgeSize; ++a)
{
const EdgeIndex edgeIndex = splitEdges[a];
Edge& edge = mEdges[edgeIndex];
edge.mNextIslandEdge = splitEdges[a + 1];
edge.mPrevIslandEdge = splitEdges[a - 1];
}
newIsland.mFirstEdge[j] = splitEdges[0];
newIsland.mLastEdge[j] = splitEdges[splitEdgeSize - 1];
newIsland.mEdgeCount[j] = splitEdgeSize;
}
}
}
}
}
dirtyNode.clearDirty();
#if IG_LIMIT_DIRTY_NODES
mDirtyMap.reset(dirtyIdx);
#endif
}
#if IG_LIMIT_DIRTY_NODES
mLastMapIndex = lastMapIndex;
if (count < MaxCount)
mLastMapIndex = 0;
#else
mDirtyMap.clear();
#endif
//mDirtyNodes.forceSize_Unsafe(0);
}
{
PX_PROFILE_ZONE("Basic.clearDestroyedEdges", getContextId());
//Now process the lost edges...
for (PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
//Process these destroyed edges. Recompute island information. Update the islands and hop counters accordingly
const EdgeIndex index = mDestroyedEdges[a];
Edge& edge = mEdges[index];
if (edge.isPendingDestroyed())
{
//if(edge.mFirstPartitionEdge)
PartitionEdge* pEdge = mFirstPartitionEdges ? (*mFirstPartitionEdges)[index] : NULL;
if (pEdge)
{
mDestroyedPartitionEdges->pushBack(pEdge);
(*mFirstPartitionEdges)[index] = NULL; //Force first partition edge to NULL to ensure we don't have a clash
}
if (edge.isActive())
{
removeEdgeFromActivatingList(index); //TODO - can we remove this call? Can we handle this elsewhere, e.g. when destroying the nodes...
mActiveEdgeCount[edge.mEdgeType]--;
}
edge = Edge(); //Reset edge
mActiveContactEdges.growAndReset(index);
}
}
mDestroyedEdges.forceSize_Unsafe(0);
}
{
PX_PROFILE_ZONE("Basic.clearDestroyedNodes", getContextId());
for (PxU32 a = 0; a < destroyedNodes.size(); ++a)
{
const PxNodeIndex nodeIndex = destroyedNodes[a];
const IslandId islandId = mIslandIds[nodeIndex.index()];
Node& node = mNodes[nodeIndex.index()];
if (islandId != IG_INVALID_ISLAND)
{
Island& island = mIslands[islandId];
removeNodeFromIsland(island, nodeIndex);
mIslandIds[nodeIndex.index()] = IG_INVALID_ISLAND;
PxU32 nodeCountTotal = 0;
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
nodeCountTotal += island.mNodeCount[t];
}
if (nodeCountTotal == 0)
{
mIslandHandles.freeHandle(islandId);
if (island.mActiveIndex != IG_INVALID_ISLAND)
{
const IslandId replaceId = mActiveIslands[mActiveIslands.size() - 1];
Island& replaceIsland = mIslands[replaceId];
replaceIsland.mActiveIndex = island.mActiveIndex;
mActiveIslands[island.mActiveIndex] = replaceId;
mActiveIslands.forceSize_Unsafe(mActiveIslands.size() - 1);
island.mActiveIndex = IG_INVALID_ISLAND;
//island.mStaticTouchCount -= node.mStaticTouchCount; //Remove the static touch count from the island
mIslandStaticTouchCount[islandId] -= node.mStaticTouchCount;
}
mIslandAwake.reset(islandId);
island.mLastNode.setIndices(PX_INVALID_NODE);
island.mRootNode.setIndices(PX_INVALID_NODE);
island.mActiveIndex = IG_INVALID_ISLAND;
}
}
if (node.isKinematic())
{
if (mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//Remove from the active kinematics list...
markKinematicInactive(nodeIndex);
}
}
else
{
if (mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
markInactive(nodeIndex);
}
}
//node.reset();
node.mFlags |= Node::eDELETED;
}
}
//Now we need to produce the list of active edges and nodes!!!
//If we get here, we have a list of active islands. From this, we need to iterate over all active islands and establish if that island
//can, in fact, go to sleep. In order to become deactivated, all nodes in the island must be ready for sleeping...
if (allowDeactivation)
{
PX_PROFILE_ZONE("Basic.deactivation", getContextId());
for (PxU32 a = 0; a < mActiveIslands.size(); a++)
{
const IslandId islandId = mActiveIslands[a];
mIslandAwake.reset(islandId);
}
//Loop over the active kinematic nodes and tag all islands touched by active kinematics as awake
for (PxU32 a = mActiveKinematicNodes.size(); a > 0; --a)
{
const PxNodeIndex kinematicIndex = mActiveKinematicNodes[a - 1];
Node& kinematicNode = mNodes[kinematicIndex.index()];
if (kinematicNode.isReadyForSleeping())
{
if (permitKinematicDeactivation)
{
kinematicNode.clearActive();
markKinematicInactive(kinematicIndex);
}
}
else //if(!kinematicNode.isReadyForSleeping())
{
//KS - if kinematic is active, then wake up all islands the kinematic is touching
EdgeInstanceIndex edgeId = kinematicNode.mFirstEdgeIndex;
while (edgeId != IG_INVALID_EDGE)
{
EdgeInstance& instance = mEdgeInstances[edgeId];
//Edge& edge = mEdges[edgeId/2];
//Only wake up islands if a connection was present
//if(edge.isConnected())
{
PxNodeIndex outNode = mEdgeNodeIndices[edgeId ^ 1];
if (outNode.index() != PX_INVALID_NODE)
{
IslandId islandId = mIslandIds[outNode.index()];
if (islandId != IG_INVALID_ISLAND)
{
mIslandAwake.set(islandId);
PX_ASSERT(mIslands[islandId].mActiveIndex != IG_INVALID_ISLAND);
}
}
}
edgeId = instance.mNextEdge;
}
}
}
for (PxU32 a = mActiveIslands.size(); a > 0; --a)
{
const IslandId islandId = mActiveIslands[a - 1];
const Island& island = mIslands[islandId];
bool canDeactivate = !mIslandAwake.test(islandId);
mIslandAwake.set(islandId);
//If it was touched by an active kinematic in the above loop, we can't deactivate it.
//Therefore, no point in testing the nodes in the island. They must remain awake
if (canDeactivate)
{
PxNodeIndex nodeId = island.mRootNode;
while (nodeId.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeId.index()];
if (!node.isReadyForSleeping())
{
canDeactivate = false;
break;
}
nodeId = node.mNextNode;
}
if (canDeactivate)
{
//If all nodes in this island are ready for sleeping and there were no active
//kinematics interacting with the any bodies in the island, we can deactivate the island.
deactivateIsland(islandId);
}
}
}
}
{
PX_PROFILE_ZONE("Basic.resetDirtyEdges", getContextId());
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for (PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
Edge& edge = mEdges[mDirtyEdges[i][a]];
edge.clearInDirtyList();
}
mDirtyEdges[i].clear(); //All new edges processed
}
}
}
IslandId IslandSim::mergeIslands(IslandId island0, IslandId island1, PxNodeIndex node0, PxNodeIndex node1)
{
Island& is0 = mIslands[island0];
Island& is1 = mIslands[island1];
//We defer this process and do it later instead. That way, if we have some pathalogical
//case where multiple islands get merged repeatedly, we don't end up repeatedly remapping all the nodes in those islands
//to their new island. Instead, we just choose the largest island and remap the smaller island to that.
PxU32 totalSize0 = 0;
PxU32 totalSize1 = 0;
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
totalSize0 += is0.mNodeCount[i];
totalSize1 += is1.mNodeCount[i];
}
if(totalSize0 > totalSize1)
{
mergeIslandsInternal(is0, is1, island0, island1, node0, node1);
mIslandAwake.reset(island1);
mIslandHandles.freeHandle(island1);
mFastRoute[node1.index()] = node0;
return island0;
}
else
{
mergeIslandsInternal(is1, is0, island1, island0, node1, node0);
mIslandAwake.reset(island0);
mIslandHandles.freeHandle(island0);
mFastRoute[node0.index()] = node1;
return island1;
}
}
bool IslandSim::checkInternalConsistency() const
{
//Loop over islands, confirming that the island data is consistent...
//Really expensive. Turn off unless investigating some random issue...
#if 0
for (PxU32 a = 0; a < mIslands.size(); ++a)
{
const Island& island = mIslands[a];
PxU32 expectedNodeCount = 0;
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
expectedNodeCount += island.mNodeCount[t];
}
bool metLastNode = expectedNodeCount == 0;
PxNodeIndex nodeId = island.mRootNode;
while (nodeId.index() != PX_INVALID_NODE)
{
PX_ASSERT(mIslandIds[nodeId.index()] == a);
if (nodeId.index() == island.mLastNode.index())
{
metLastNode = true;
PX_ASSERT(mNodes[nodeId.index()].mNextNode.index() == PX_INVALID_NODE);
}
--expectedNodeCount;
nodeId = mNodes[nodeId.index()].mNextNode;
}
PX_ASSERT(expectedNodeCount == 0);
PX_ASSERT(metLastNode);
}
#endif
return true;
}
void IslandSim::mergeIslandsInternal(Island& island0, Island& island1, IslandId islandId0, IslandId islandId1, PxNodeIndex nodeIndex0, PxNodeIndex nodeIndex1)
{
#if PX_ENABLE_ASSERTS
PxU32 island0Size = 0;
PxU32 island1Size = 0;
for(PxU32 nodeType = 0; nodeType < Node::eTYPE_COUNT; ++nodeType)
{
island0Size += island0.mNodeCount[nodeType];
island1Size += island1.mNodeCount[nodeType];
}
#endif
PX_ASSERT(island0Size >= island1Size); //We only ever merge the smaller island to the larger island
//Stage 1 - we need to move all the nodes across to the new island ID (i.e. write all their new island indices, move them to the
//island and then also update their estimated hop counts to the root. As we don't want to do a full traversal at this point,
//instead, we estimate based on the route from the node to their previous root and then from that root to the new connection
//between the 2 islands. This is probably a very indirect route but it will be refined later.
//In this case, island1 is subsumed by island0
//It takes mHopCounts[nodeIndex1] to get from node1 to its old root. It takes mHopCounts[nodeIndex0] to get from nodeIndex0 to the new root
//and it takes 1 extra hop to go from node1 to node0. Therefore, a sub-optimal route can be planned going via the old root node that should take
//mHopCounts[nodeIndex0] + mHopCounts[nodeIndex1] + 1 + mHopCounts[nodeIndex] to travel from any arbitrary node (nodeIndex) in island1 to the root
//of island2.
const PxU32 extraPath = mHopCounts[nodeIndex0.index()] + mHopCounts[nodeIndex1.index()] + 1;
PxNodeIndex islandNode = island1.mRootNode;
while(islandNode.index() != PX_INVALID_NODE)
{
mHopCounts[islandNode.index()] += extraPath;
mIslandIds[islandNode.index()] = islandId0;
//mFastRoute[islandNode] = PX_INVALID_NODE;
Node& node = mNodes[islandNode.index()];
islandNode = node.mNextNode;
}
//Now fill in the hop count for node1, which is directly connected to node0.
mHopCounts[nodeIndex1.index()] = mHopCounts[nodeIndex0.index()] + 1;
Node& lastNode = mNodes[island0.mLastNode.index()];
Node& firstNode = mNodes[island1.mRootNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(firstNode.mPrevNode.index() == PX_INVALID_NODE);
PX_ASSERT(island1.mRootNode.index() != island0.mLastNode.index());
PX_ASSERT(mNodes[island0.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(mNodes[island1.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(mIslandIds[island0.mLastNode.index()] == islandId0);
lastNode.mNextNode = island1.mRootNode;
firstNode.mPrevNode = island0.mLastNode;
island0.mLastNode = island1.mLastNode;
//island0.mStaticTouchCount += island1.mStaticTouchCount;
mIslandStaticTouchCount[islandId0] += mIslandStaticTouchCount[islandId1];
//Merge the edge list for the islands...
for(PxU32 a = 0; a < IG::Edge::eEDGE_TYPE_COUNT; ++a)
{
if(island0.mLastEdge[a] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island0.mLastEdge[a]].mNextIslandEdge == IG_INVALID_EDGE);
mEdges[island0.mLastEdge[a]].mNextIslandEdge = island1.mFirstEdge[a];
}
else
{
PX_ASSERT(island0.mFirstEdge[a] == IG_INVALID_EDGE);
island0.mFirstEdge[a] = island1.mFirstEdge[a];
}
if(island1.mFirstEdge[a] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island1.mFirstEdge[a]].mPrevIslandEdge == IG_INVALID_EDGE);
mEdges[island1.mFirstEdge[a]].mPrevIslandEdge = island0.mLastEdge[a];
island0.mLastEdge[a] = island1.mLastEdge[a];
}
island0.mEdgeCount[a] += island1.mEdgeCount[a];
island1.mFirstEdge[a] = IG_INVALID_EDGE;
island1.mLastEdge[a] = IG_INVALID_EDGE;
island1.mEdgeCount[a] = 0;
}
for (PxU32 a = 0; a < IG::Node::eTYPE_COUNT; ++a)
{
island0.mNodeCount[a] += island1.mNodeCount[a];
island1.mNodeCount[a] = 0;
}
island1.mLastNode.setIndices(PX_INVALID_NODE);
island1.mRootNode.setIndices(PX_INVALID_NODE);
mIslandStaticTouchCount[islandId1] = 0;
//island1.mStaticTouchCount = 0;
//Remove from active island list
if(island1.mActiveIndex != IG_INVALID_ISLAND)
markIslandInactive(islandId1);
}
void IslandSim::removeEdgeFromActivatingList(EdgeIndex index)
{
Edge& edge = mEdges[index];
if (edge.mEdgeState & Edge::eACTIVATING)
{
for (PxU32 a = 0, count = mActivatedEdges[edge.mEdgeType].size(); a < count; a++)
{
if (mActivatedEdges[edge.mEdgeType][a] == index)
{
mActivatedEdges[edge.mEdgeType].replaceWithLast(a);
break;
}
}
edge.mEdgeState &= (~Edge::eACTIVATING);
}
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[index * 2];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[index * 2 + 1];
if (nodeIndex1.isValid() && nodeIndex2.isValid())
{
{
Node& node = mNodes[nodeIndex1.index()];
node.mActiveRefCount--;
}
{
Node& node = mNodes[nodeIndex2.index()];
node.mActiveRefCount--;
}
}
if(edge.mEdgeType == Edge::eCONTACT_MANAGER)
mActiveContactEdges.reset(index);
}
void IslandSim::setKinematic(PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
if(!node.isKinematic())
{
//Transition from dynamic to kinematic:
//(1) Remove this node from the island
//(2) Remove this node from the active node list
//(3) If active or referenced, add it to the active kinematic list
//(4) Tag the node as kinematic
//External code will re-filter interactions and lost touches will be reported
const IslandId islandId = mIslandIds[nodeIndex.index()];
PX_ASSERT(islandId != IG_INVALID_ISLAND);
Island& island = mIslands[islandId];
mIslandIds[nodeIndex.index()] = IG_INVALID_ISLAND;
removeNodeFromIsland(island, nodeIndex);
const bool isActive = node.isActive();
if (isActive)
{
//Remove from active list...
markInactive(nodeIndex);
}
else if (node.isActivating())
{
//Remove from activating list...
node.clearActivating();
PX_ASSERT(mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]].index() == nodeIndex.index());
const PxNodeIndex replaceIndex = mActivatingNodes[mActivatingNodes.size() - 1];
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[nodeIndex.index()];
mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]] = replaceIndex;
mActivatingNodes.forceSize_Unsafe(mActivatingNodes.size() - 1);
mActiveNodeIndex[nodeIndex.index()] = PX_INVALID_NODE;
}
node.setKinematicFlag();
node.clearActive();
if (/*isActive || */node.mActiveRefCount != 0)
{
//Add to active kinematic list...
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActivatingNodes.size();
mActivatingNodes.pushBack(nodeIndex);
node.setActivating();
}
{
//This node was potentially in an island with other bodies. We need to force an island recomputation in case the
//islands became broken due to losing this connection. Same rules as losing a contact, we just
//tag the nodes directly connected to the lost edge as "dirty" and force an island recomputation if
//it resulted in lost connections
EdgeInstanceIndex edgeId = node.mFirstEdgeIndex;
while(edgeId != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edgeId];
const EdgeInstanceIndex nextId = instance.mNextEdge;
const PxU32 idx = edgeId/2;
IG::Edge& edge = mEdges[edgeId/2];
removeEdgeFromIsland(island, idx);
removeConnectionInternal(idx);
removeConnectionFromGraph(idx);
edge.clearInserted();
if (edge.isActive())
{
removeEdgeFromActivatingList(idx);
edge.deactivateEdge();
mActiveEdgeCount[edge.mEdgeType]--;
mDeactivatingEdges[edge.mEdgeType].pushBack(idx);
}
if(!edge.isPendingDestroyed())
{
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edge.mEdgeType], idx));
mDirtyEdges[edge.mEdgeType].pushBack(idx);
edge.markInDirtyList();
}
}
else
{
edge.setReportOnlyDestroy();
}
edgeId = nextId;
}
}
PxU32 newNodeCount = 0;
for(PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
newNodeCount += island.mNodeCount[i];
if(newNodeCount == 0)
{
// If this island is empty after having removed the edges of the node we've just set to kinematic
// we invalidate all edges and set the island to inactive
for(PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
island.mFirstEdge[a] = island.mLastEdge[a] = IG_INVALID_EDGE;
island.mEdgeCount[a] = 0;
mIslandStaticTouchCount[islandId] = 0;
//island.mStaticTouchCount = 0;
}
if(island.mActiveIndex != IG_INVALID_ISLAND)
{
markIslandInactive(islandId);
}
mIslandAwake.reset(islandId);
mIslandHandles.freeHandle(islandId);
}
}
}
void IslandSim::setDynamic(PxNodeIndex nodeIndex)
{
//(1) Remove all edges involving this node from all islands they may be in
//(2) Mark all edges as "new" edges - let island gen re-process them!
//(3) Remove this node from the active kinematic list
//(4) Add this node to the active dynamic list (if it is active)
//(5) Mark node as dynamic
Node& node = mNodes[nodeIndex.index()];
if(node.isKinematic())
{
//EdgeInstanceIndex edgeIndex = node.mFirstEdgeIndex;
EdgeInstanceIndex edgeId = node.mFirstEdgeIndex;
while(edgeId != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edgeId];
const EdgeInstanceIndex nextId = instance.mNextEdge;
const PxNodeIndex otherNode = mEdgeNodeIndices[edgeId^1];
const PxU32 idx = edgeId/2;
IG::Edge& edge = mEdges[edgeId/2];
if(!otherNode.isStaticBody())
{
const IslandId islandId = mIslandIds[otherNode.index()];
if(islandId != IG_INVALID_ISLAND)
removeEdgeFromIsland(mIslands[islandId], idx);
}
removeConnectionInternal(idx);
removeConnectionFromGraph(idx);
edge.clearInserted();
if (edge.isActive())
{
edge.deactivateEdge();
removeEdgeFromActivatingList(idx);
mActiveEdgeCount[edge.mEdgeType]--;
}
if(!edge.isPendingDestroyed())
{
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edge.mEdgeType], idx));
mDirtyEdges[edge.mEdgeType].pushBack(idx);
edge.markInDirtyList();
}
}
else
{
edge.setReportOnlyDestroy();
}
edgeId = nextId;
}
if(!node.isActivating() && mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//Remove from active kinematic list, add to active dynamic list
PxU32 oldRefCount = node.mActiveRefCount;
node.mActiveRefCount = 0;
markKinematicInactive(nodeIndex);
node.mActiveRefCount = oldRefCount;
}
node.clearKinematicFlag();
//Create an island for this node. If there are any edges affecting this node, they will have been marked as
//"new" and will be processed next island update.
{
IslandId islandHandle = mIslandHandles.getHandle();
if(islandHandle == mIslands.capacity())
{
const PxU32 newCapacity = 2*mIslands.capacity()+1;
mIslands.reserve(newCapacity);
mIslandAwake.resize(newCapacity);
mIslandStaticTouchCount.resize(newCapacity);
}
mIslandAwake.reset(islandHandle);
mIslands.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(islandHandle + 1, mIslands.size()));
Island& island = mIslands[islandHandle];
island.mLastNode = island.mRootNode = nodeIndex;
PX_ASSERT(mNodes[nodeIndex.index()].mNextNode.index() == PX_INVALID_NODE);
island.mNodeCount[node.mType] = 1;
mIslandIds[nodeIndex.index()] = islandHandle;
mIslandStaticTouchCount[islandHandle] = 0;
if(node.isActive())
{
node.clearActive();
activateNode(nodeIndex);
}
}
}
}
| 79,924 | C++ | 33.420758 | 198 | 0.699052 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsRigidBody.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 PXS_RIGID_BODY_H
#define PXS_RIGID_BODY_H
#include "PxvDynamics.h"
#include "CmSpatialVector.h"
namespace physx
{
struct PxsCCDBody;
#define PX_INTERNAL_LOCK_FLAG_START 8
PX_ALIGN_PREFIX(16)
class PxsRigidBody
{
public:
enum PxsRigidBodyFlag
{
eFROZEN = 1 << 0, //This flag indicates that the stabilization is enabled and the body is
//"frozen". By "frozen", we mean that the body's transform is unchanged
//from the previous frame. This permits various optimizations.
eFREEZE_THIS_FRAME = 1 << 1,
eUNFREEZE_THIS_FRAME = 1 << 2,
eACTIVATE_THIS_FRAME = 1 << 3,
eDEACTIVATE_THIS_FRAME = 1 << 4,
// PT: this flag is now only used on the GPU. For the CPU the data is now stored directly in PxsBodyCore.
eDISABLE_GRAVITY_GPU = 1 << 5,
eSPECULATIVE_CCD = 1 << 6,
eENABLE_GYROSCOPIC = 1 << 7,
//KS - copied here for GPU simulation to avoid needing to pass another set of flags around.
eLOCK_LINEAR_X = 1 << (PX_INTERNAL_LOCK_FLAG_START),
eLOCK_LINEAR_Y = 1 << (PX_INTERNAL_LOCK_FLAG_START + 1),
eLOCK_LINEAR_Z = 1 << (PX_INTERNAL_LOCK_FLAG_START + 2),
eLOCK_ANGULAR_X = 1 << (PX_INTERNAL_LOCK_FLAG_START + 3),
eLOCK_ANGULAR_Y = 1 << (PX_INTERNAL_LOCK_FLAG_START + 4),
eLOCK_ANGULAR_Z = 1 << (PX_INTERNAL_LOCK_FLAG_START + 5),
eRETAIN_ACCELERATION = 1 << 14,
eFIRST_BODY_COPY_GPU = 1 << 15 // Flag to raise to indicate that the body is DMA'd to the GPU for the first time
};
PX_FORCE_INLINE PxsRigidBody(PxsBodyCore* core, PxReal freeze_count) :
// PT: TODO: unify naming conventions
mLastTransform (core->body2World),
mInternalFlags (0),
solverIterationCounts (core->solverIterationCounts),
mCCD (NULL),
mCore (core),
sleepLinVelAcc (PxVec3(0.0f)),
freezeCount (freeze_count),
sleepAngVelAcc (PxVec3(0.0f)),
accelScale (1.0f)
{}
PX_FORCE_INLINE ~PxsRigidBody() {}
PX_FORCE_INLINE const PxTransform& getPose() const { PX_ASSERT(mCore->body2World.isSane()); return mCore->body2World; }
PX_FORCE_INLINE const PxVec3& getLinearVelocity() const { PX_ASSERT(mCore->linearVelocity.isFinite()); return mCore->linearVelocity; }
PX_FORCE_INLINE const PxVec3& getAngularVelocity() const { PX_ASSERT(mCore->angularVelocity.isFinite()); return mCore->angularVelocity; }
PX_FORCE_INLINE void setVelocity(const PxVec3& linear,
const PxVec3& angular) { PX_ASSERT(linear.isFinite()); PX_ASSERT(angular.isFinite());
mCore->linearVelocity = linear;
mCore->angularVelocity = angular; }
PX_FORCE_INLINE void setLinearVelocity(const PxVec3& linear) { PX_ASSERT(linear.isFinite()); mCore->linearVelocity = linear; }
PX_FORCE_INLINE void setAngularVelocity(const PxVec3& angular) { PX_ASSERT(angular.isFinite()); mCore->angularVelocity = angular; }
PX_FORCE_INLINE void constrainLinearVelocity();
PX_FORCE_INLINE void constrainAngularVelocity();
PX_FORCE_INLINE PxU32 getIterationCounts() { return mCore->solverIterationCounts; }
PX_FORCE_INLINE PxReal getReportThreshold() const { return mCore->contactReportThreshold; }
PX_FORCE_INLINE const PxTransform& getLastCCDTransform() const { return mLastTransform; }
PX_FORCE_INLINE void saveLastCCDTransform() { mLastTransform = mCore->body2World; }
PX_FORCE_INLINE bool isKinematic() const { return mCore->inverseMass == 0.0f; }
PX_FORCE_INLINE void setPose(const PxTransform& pose) { mCore->body2World = pose; }
PX_FORCE_INLINE void setPosition(const PxVec3& position) { mCore->body2World.p = position; }
PX_FORCE_INLINE PxReal getInvMass() const { return mCore->inverseMass; }
PX_FORCE_INLINE PxVec3 getInvInertia() const { return mCore->inverseInertia; }
PX_FORCE_INLINE PxReal getMass() const { return 1.0f/mCore->inverseMass; }
PX_FORCE_INLINE PxVec3 getInertia() const { return PxVec3(1.0f/mCore->inverseInertia.x,
1.0f/mCore->inverseInertia.y,
1.0f/mCore->inverseInertia.z); }
PX_FORCE_INLINE PxsBodyCore& getCore() { return *mCore; }
PX_FORCE_INLINE const PxsBodyCore& getCore() const { return *mCore; }
PX_FORCE_INLINE PxU32 isActivateThisFrame() const { return PxU32(mInternalFlags & eACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isDeactivateThisFrame() const { return PxU32(mInternalFlags & eDEACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isFreezeThisFrame() const { return PxU32(mInternalFlags & eFREEZE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isUnfreezeThisFrame() const { return PxU32(mInternalFlags & eUNFREEZE_THIS_FRAME); }
PX_FORCE_INLINE void clearFreezeFlag() { mInternalFlags &= ~eFREEZE_THIS_FRAME; }
PX_FORCE_INLINE void clearUnfreezeFlag() { mInternalFlags &= ~eUNFREEZE_THIS_FRAME; }
PX_FORCE_INLINE void clearAllFrameFlags() { mInternalFlags &= ~(eFREEZE_THIS_FRAME | eUNFREEZE_THIS_FRAME | eACTIVATE_THIS_FRAME | eDEACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE void resetSleepFilter() { sleepAngVelAcc = sleepLinVelAcc = PxVec3(0.0f); }
// PT: implemented in PxsCCD.cpp:
void advanceToToi(PxReal toi, PxReal dt, bool clip);
void advancePrevPoseToToi(PxReal toi);
// PxTransform getAdvancedTransform(PxReal toi) const;
Cm::SpatialVector getPreSolverVelocities() const;
PxTransform mLastTransform; //28 (28)
PxU16 mInternalFlags; //30 (30)
PxU16 solverIterationCounts; //32 (32)
PxsCCDBody* mCCD; //36 (40) // only valid during CCD
PxsBodyCore* mCore; //40 (48)
#if !PX_P64_FAMILY
PxU32 alignmentPad[2]; //48 (48)
#endif
PxVec3 sleepLinVelAcc; //60 (60)
PxReal freezeCount; //64 (64)
PxVec3 sleepAngVelAcc; //76 (76)
PxReal accelScale; //80 (80)
}
PX_ALIGN_SUFFIX(16);
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxsRigidBody) & 0x0f));
void PxsRigidBody::constrainLinearVelocity()
{
const PxU32 lockFlags = mCore->lockFlags;
if(lockFlags)
{
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
mCore->linearVelocity.x = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
mCore->linearVelocity.y = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
mCore->linearVelocity.z = 0.0f;
}
}
void PxsRigidBody::constrainAngularVelocity()
{
const PxU32 lockFlags = mCore->lockFlags;
if(lockFlags)
{
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
mCore->angularVelocity.x = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
mCore->angularVelocity.y = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
mCore->angularVelocity.z = 0.0f;
}
}
}
#endif
| 8,645 | C | 45.483871 | 166 | 0.686871 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsCCD.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxGeometry.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxUserAllocated.h"
#include "GuCCDSweepConvexMesh.h"
#ifndef PXS_CCD_H
#define PXS_CCD_H
#define CCD_DEBUG_PRINTS 0
#define CCD_POST_DEPENETRATE_DIST 0.001f
#define CCD_ROTATION_LOCKING 0
#define CCD_MIN_TIME_LEFT 0.01f
#define DEBUG_RENDER_CCD 0
#if CCD_DEBUG_PRINTS
namespace physx {
extern void printCCDDebug(const char* msg, const PxsRigidBody* atom0, PxGeometryType::Enum g0, bool printPtr = true);
extern void printShape(PxsRigidBody* atom0, PxGeometryType::Enum g0, const char* annotation, PxReal dt, PxU32 pass, bool printPtr = true);
}
#define PRINTCCDSHAPE(x) printShape x
#define PRINTCCDDEBUG(x) printCCDDebug x
#else
#define PRINTCCDSHAPE(x)
#define PRINTCCDDEBUG(x)
#endif
namespace physx
{
float computeCCDThreshold(const PxGeometry& geometry);
// ------------------------------------------------------------------------------------------------------------
// a fraction of objects will be CCD active so this is dynamic, not a member of PsxRigidBody
// CCD code builds a temporary array of PxsCCDPair objects (allocated in blocks)
// this is done to gather scattered data from memory and also to reduce PxsRidigBody permanent memory footprint
// we have to do it every pass since new CMs can become fast moving after each pass (and sometimes cease to be)
//
struct PxsCCDBody;
class PxsRigidBody;
struct PxsShapeCore;
struct PxsRigidCore;
class PxsContactManager;
class PxsContext;
class PxCCDContactModifyCallback;
class PxcNpThreadContext;
class PxvNphaseImplementationContext;
namespace Dy
{
class ThresholdStream;
}
/**
\brief structure to represent interactions between a given body and another body.
*/
struct PxsCCDOverlap
{
//The body the interaction relates to
PxsCCDBody* mBody;
//The next interaction in the list
PxsCCDOverlap* mNext;
};
/**
\brief Temporary CCD representation for a shape.
Stores data about a shape that may be frequently used in CCD. It also stores update counters per-shape that can be compared with the body's update
counter to determine if the shape needs its transforms re-calculated. This avoids us needing to store a list of shapes in a CCD body.
*/
struct PxsCCDShape : public Gu::CCDShape
{
const PxsShapeCore* mShapeCore; //Shape core (can be shared)
const PxsRigidCore* mRigidCore; //Rigid body core
PxNodeIndex mNodeIndex;
};
/**
\brief Structure to represent a body in the CCD system.
*/
struct PxsCCDBody
{
Cm::SpatialVector mPreSolverVelocity;
PxU16 mIndex; //The CCD body's index
bool mPassDone; //Whether it has been processed in the current CCD pass
bool mHasAnyPassDone; //Whether this body was influenced by any passes
PxReal mTimeLeft; //CCD time left to elapse (normalized in range 0-1)
PxsRigidBody* mBody; //The rigid body
PxsCCDOverlap* mOverlappingObjects; //A list of overlapping bodies for island update
PxU32 mUpdateCount; //How many times this body has eben updated in the CCD. This is correlated with CCD shapes' update counts.
PxU32 mNbInteractionsThisPass; //How many interactions this pass
/**
\brief Returns the CCD body's index.
\return The CCD body's index.
*/
PX_FORCE_INLINE PxU32 getIndex() const { return mIndex; }
/**
\brief Tests whether this body has already registered an overlap with a given body.
\param[in] body The body to test against.
\return Whether this body has already registered an overlap with a given body.
*/
bool overlaps(PxsCCDBody* body) const
{
PxsCCDOverlap* overlaps = mOverlappingObjects;
while(overlaps)
{
if(overlaps->mBody == body)
return true;
overlaps = overlaps->mNext;
}
return false;
}
/**
\brief Registers an overlap with a given body
\param[in] overlap The CCD overlap to register.
*/
void addOverlap(PxsCCDOverlap* overlap)
{
overlap->mNext = mOverlappingObjects;
mOverlappingObjects = overlap;
}
};
/**
\brief a container class used in the CCD that minimizes frequency of hitting the allocator.
This class stores a set of blocks of memory. It is effectively an array that resizes more efficiently because it doesn't need to
reallocate an entire buffer and copy data.
*/
template<typename T, int BLOCK_SIZE>
struct PxsCCDBlockArray
{
/**
\brief A block of data
*/
struct Block : PxUserAllocated { T items[BLOCK_SIZE]; };
/**
\brief A header for a block of data.
*/
struct BlockInfo
{
Block* block;
PxU32 count; // number of elements in this block
BlockInfo(Block* aBlock, PxU32 aCount) : block(aBlock), count(aCount) {}
};
/*
\brief An array of block headers
*/
PxArray<BlockInfo> blocks;
/**
\brief The current block.
*/
PxU32 currentBlock;
/**
\brief Constructor
*/
PxsCCDBlockArray() : currentBlock(0)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
}
/**
\brief Destructor
*/
~PxsCCDBlockArray()
{
for (PxU32 i = 0; i < blocks.size(); i++)
{
PX_DELETE(blocks[i].block);
}
currentBlock = 0;
}
/**
\brief Clears this block array.
\note This clear function also deletes all additional blocks
*/
void clear()
{
for (PxU32 i = 0; i < blocks.size(); i++)
{
PX_DELETE(blocks[i].block);
}
blocks.clear();
blocks.pushBack(BlockInfo(PX_NEW(Block), 0)); // at least one block is expected to always be present in the array
currentBlock = 0;
}
/**
\brief Clears this block array but does not release the memory.
*/
void clear_NoDelete()
{
currentBlock = 0;
blocks[0].count = 0;
}
/**
\brief Push a new element onto the back of the block array
\return The new element
*/
T& pushBack()
{
PxU32 numBlocks = blocks.size();
if (blocks[currentBlock].count == BLOCK_SIZE)
{
if((currentBlock + 1) == numBlocks)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
numBlocks ++;
}
currentBlock++;
blocks[currentBlock].count = 0;
}
const PxU32 count = blocks[currentBlock].count ++;
return blocks[currentBlock].block->items[count];
}
/**
\brief Pushes a new element onto the back of this array, intitializing it to match the data
\param data The data to initialize the new element to
\return The new element
*/
T& pushBack(T& data)
{
PxU32 numBlocks = blocks.size();
if (blocks[currentBlock].count == BLOCK_SIZE)
{
if((currentBlock + 1) == numBlocks)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
numBlocks ++;
}
currentBlock++;
blocks[currentBlock].count = 0;
}
const PxU32 count = blocks[currentBlock].count ++;
blocks[currentBlock].block->items[count] = data;
return blocks[currentBlock].block->items[count];
}
/**
\brief Pops the last element from the list.
*/
void popBack()
{
PX_ASSERT(blocks[currentBlock].count > 0);
if (blocks[currentBlock].count > 1)
blocks[currentBlock].count --;
else
{
PX_DELETE(blocks[currentBlock].block);
blocks.popBack();
currentBlock--;
}
}
/**
\brief Returns the current size of the array.
\return The current size of the array.
*/
PxU32 size() const
{
return (currentBlock)*BLOCK_SIZE + blocks[currentBlock].count;
}
/**
\brief Returns the element at a given index in the array
\param[in] index The index of the element in the array
\return The element at a given index in the array.
*/
T& operator[] (PxU32 index) const
{
PX_ASSERT(index/BLOCK_SIZE < blocks.size());
PX_ASSERT(index%BLOCK_SIZE < blocks[index/BLOCK_SIZE].count);
return blocks[index/BLOCK_SIZE].block->items[index%BLOCK_SIZE];
}
};
/**
\brief A structure to represent a potential CCD interaction between a pair of shapes
*/
struct PxsCCDPair
{
/**
\brief Defines whether this is an estimated TOI or an accurate TOI.
We store pairs in a priority queue based on the TOIs. We use cheap estimates to cull away work and lazily evaluate TOIs. This means that an element in the
priority queue may either be an estimate or a precise result.
*/
enum E_TOIType
{
eEstimate,
ePrecise
};
PxsRigidBody* mBa0; // Body A. Can be NULL for statics
PxsRigidBody* mBa1; // Body B. Can be NULL for statics
PxsCCDShape* mCCDShape0; // Shape A
PxsCCDShape* mCCDShape1; // Shape B
PxVec3 mMinToiNormal; // The contact normal. Only valid for precise results. On the surface of body/shape A
PxReal mMinToi; // Min TOI. Valid for both precise and estimated results but estimates may be too early (i.e. conservative).
PxReal mPenetrationPostStep; // Valid only for precise sweeps. Only used for initial intersections (i.e. at TOI = 0).
PxVec3 mMinToiPoint; // The contact point. Only valid for precise sweep results.
PxReal mPenetration; // The penetration. Only valid for precise sweep results.
PxsContactManager* mCm; // The contact manager.
PxU32 mIslandId; // The index of the island this pair is in
PxGeometryType::Enum mG0, mG1; // The geometry types for shapes 0 and 1
bool mIsEarliestToiHit; // Indicates this was the earliest hit for one of the bodies in the pair
bool mIsModifiable; // Indicates whether this contact is modifiable
PxU32 mFaceIndex; // The face index. Only valid for precise sweeps involving meshes or heightfields.
PxU16 mMaterialIndex0; // The material index for shape 0
PxU16 mMaterialIndex1; // The material index for shape 1
PxReal mDynamicFriction; // The dynamic friction coefficient
PxReal mStaticFriction; // The static friction coefficient
PxReal mRestitution; // The restitution coefficient
PxU32 mEstimatePass; // The current estimation pass. Used after a sweep hit was found to determine if the pair needs re-estimating.
PxReal mAppliedForce; // The applied force for this pair. Only valid if the pair has been responded to.
PxReal mMaxImpulse; // The maximum impulse to be applied
E_TOIType mToiType; // The TOI type (estimate, precise).
bool mHasFriction; // Whether we want to simulate CCD friction for this pair
/**
\brief Perform a precise sweep for this pair
\param[in] threadContext The per-thread context
\param[in] dt The time-step
\param[in] pass The current CCD pass
\return The normalized TOI. <=1.0 indicates a hit. Otherwise PX_MAX_REAL.
*/
PxReal sweepFindToi(PxcNpThreadContext& threadContext, PxReal dt, PxU32 pass, PxReal ccdThreshold);
/**
\brief Performs a sweep estimation for this pair
\return The normalized TOI. <= 1.0 indicates a potential hit, otherwise PX_MAX_REAL.
*/
PxReal sweepEstimateToi(PxReal ccdThreshold);
/**
\brief Advances this pair to the TOI
\param[in] dt The time-step
\param[in] clipTrajectoryToToi Indicates whether we clip the body's trajectory to the end pose. Only done in the final pass
\return Whether the advance was successful. An advance will be unsuccessful if body bodies were already updated.
*/
bool sweepAdvanceToToi(PxReal dt, bool clipTrajectoryToToi);
/**
\brief Updates the transforms of the shapes involved in this pair.
*/
void updateShapes();
};
/**
\brief Block array of CCD bodies
*/
typedef PxsCCDBlockArray<PxsCCDBody, 128> PxsCCDBodyArray;
/**
\brief Block array of CCD pairs
*/
typedef PxsCCDBlockArray<PxsCCDPair, 128> PxsCCDPairArray;
/**
\brief Block array of CCD overlaps
*/
typedef PxsCCDBlockArray<PxsCCDOverlap, 128> PxsCCDOverlapArray;
/**
\brief Block array of CCD shapes
*/
typedef PxsCCDBlockArray<PxsCCDShape, 128> PxsCCDShapeArray;
/**
\brief Pair structure to be able to look-up a rigid body-shape pair in a map
*/
typedef PxPair<const PxsRigidCore*, const PxsShapeCore*> PxsRigidShapePair;
/**
\brief CCD context object.
*/
class PxsCCDContext : public PxUserAllocated
{
public:
/**
\brief Constructor for PxsCCDContext
\param[in] context The PxsContext that is associated with this PxsCCDContext.
*/
PxsCCDContext(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext, PxReal ccdThreshold);
/**
\brief Destructor for PxsCCDContext
*/
~PxsCCDContext();
/**
\brief Returns the CCD contact modification callback
\return The CCD contact modification callback
*/
PX_FORCE_INLINE PxCCDContactModifyCallback* getCCDContactModifyCallback() const { return mCCDContactModifyCallback; }
/**
\brief Sets the CCD contact modification callback
\param[in] c The CCD contact modification callback
*/
PX_FORCE_INLINE void setCCDContactModifyCallback(PxCCDContactModifyCallback* c) { mCCDContactModifyCallback = c; }
/**
\brief Returns the maximum number of CCD passes
\return The maximum number of CCD passes
*/
PX_FORCE_INLINE PxU32 getCCDMaxPasses() const { return mCCDMaxPasses; }
/**
\brief Sets the maximum number of CCD passes
\param[in] ccdMaxPasses The maximum number of CCD passes
*/
PX_FORCE_INLINE void setCCDMaxPasses(PxU32 ccdMaxPasses) { mCCDMaxPasses = ccdMaxPasses; }
/**
\brief Returns the current CCD pass
\return The current CCD pass
*/
PX_FORCE_INLINE PxU32 getCurrentCCDPass() const { return miCCDPass; }
/**
\brief Returns The number of swept hits reported
\return The number of swept hits reported
*/
PX_FORCE_INLINE PxI32 getNumSweepHits() const { return mSweepTotalHits; }
/**
\brief Returns The number of updated bodies
\return The number of updated bodies in this CCD pass
*/
PX_FORCE_INLINE PxU32 getNumUpdatedBodies() const { return mUpdatedCCDBodies.size(); }
/**
\brief Returns The update bodies array
\return The updated bodies array from this CCD pass
*/
PX_FORCE_INLINE PxsRigidBody*const* getUpdatedBodies() const { return mUpdatedCCDBodies.begin(); }
/**
\brief Returns Clears the updated bodies array
*/
PX_FORCE_INLINE void clearUpdatedBodies() { mUpdatedCCDBodies.forceSize_Unsafe(0); }
PX_FORCE_INLINE PxReal getCCDThreshold() const { return mCCDThreshold; }
PX_FORCE_INLINE void setCCDThreshold(PxReal t) { mCCDThreshold = t; }
/**
\brief Runs the CCD contact modification.
\param[in] contacts The list of modifiable contacts
\param[in] contactCount The number of contacts
\param[in] shapeCore0 The first shape core
\param[in] shapeCore1 The second shape core
\param[in] rigidCore0 The first rigid core
\param[in] rigidCore1 The second rigid core
\param[in] rigid0 The first rigid body
\param[in] rigid1 The second rigid body
*/
void runCCDModifiableContact(PxModifiableContact* PX_RESTRICT contacts, PxU32 contactCount, const PxsShapeCore* PX_RESTRICT shapeCore0,
const PxsShapeCore* PX_RESTRICT shapeCore1, const PxsRigidCore* PX_RESTRICT rigidCore0, const PxsRigidCore* PX_RESTRICT rigidCore1,
const PxsRigidBody* PX_RESTRICT rigid0, const PxsRigidBody* PX_RESTRICT rigid1);
/**
\brief Performs a single CCD update
This occurs after broad phase and is responsible for creating islands, finding the TOI of collisions, filtering contacts, issuing modification callbacks and responding to
collisions. At the end of this phase all bodies will have stepper to their first TOI if they were involved in a CCD collision this frame.
\param[in] dt The timestep to simulate
\param[in] continuation The continuation task
\param[in] islandSim The island manager
\param[in] disableResweep If this is true, we perform a reduced-fidelity CCD approach
*/
void updateCCD(PxReal dt, PxBaseTask* continuation, IG::IslandSim& islandSim, bool disableResweep, PxI32 numFastMovingShapes);
/**
\brief Signals the beginning of a CCD multi-pass update
*/
void updateCCDBegin();
/**
\brief Resets the CCD contact state in any contact managers that previously had a reported CCD touch. This must be called if CCD update is bypassed for a frame
*/
void resetContactManagers();
private:
/**
\brief Verifies the consistency of the CCD context at the beginning
*/
void verifyCCDBegin();
/**
\brief Cleans up after the CCD update has completed
*/
void updateCCDEnd();
/**
\brief Spawns the update island tasks after the initial sweep estimates have been performed
\param[in] continuation The continuation task
*/
void postCCDSweep(PxBaseTask* continuation);
/**
\brief Creates contact buffers for CCD contacts. These will be sent to the user in the contact notification.
\param[in] continuation The continuation task
*/
void postCCDAdvance(PxBaseTask* continuation);
/**
\brief The final phase of the CCD task chain. Cleans up after the parallel update/postCCDAdvance stages.
\param[in] continuation The continuation task
*/
void postCCDDepenetrate(PxBaseTask* continuation);
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDSweep> PostCCDSweepTask;
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDAdvance> PostCCDAdvanceTask;
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDDepenetrate> PostCCDDepenetrateTask;
PostCCDSweepTask mPostCCDSweepTask;
PostCCDAdvanceTask mPostCCDAdvanceTask;
PostCCDDepenetrateTask mPostCCDDepenetrateTask;
PxCCDContactModifyCallback* mCCDContactModifyCallback;
// CCD global data
bool mDisableCCDResweep;
PxU32 miCCDPass;
PxI32 mSweepTotalHits;
// a fraction of objects will be CCD active so PxsCCDBody is dynamic, not a member of PxsRigidBody
PxsCCDBodyArray mCCDBodies;
PxsCCDOverlapArray mCCDOverlaps;
PxsCCDShapeArray mCCDShapes;
PxArray<PxsCCDBody*> mIslandBodies;
PxArray<PxU16> mIslandSizes;
PxArray<PxsRigidBody*> mUpdatedCCDBodies;
PxHashMap<PxsRigidShapePair, PxsCCDShape*> mMap;
// temporary array updated during CCD update
//Array<PxsCCDPair> mCCDPairs;
PxsCCDPairArray mCCDPairs;
PxArray<PxsCCDPair*> mCCDPtrPairs;
// number of pairs per island
PxArray<PxU32> mCCDIslandHistogram;
// thread context valid during CCD update
PxcNpThreadContext* mCCDThreadContext;
// number of pairs to process per thread
PxU32 mCCDPairsPerBatch;
PxU32 mCCDMaxPasses;
PxsContext* mContext;
Dy::ThresholdStream& mThresholdStream;
PxvNphaseImplementationContext& mNphaseContext;
PxMutex mMutex;
PxReal mCCDThreshold;
private:
PX_NOCOPY(PxsCCDContext)
};
}
#endif
| 19,923 | C | 32.826825 | 172 | 0.730613 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContactManagerState.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 PXS_CONTACT_MANAGER_STATE_H
#define PXS_CONTACT_MANAGER_STATE_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
struct PxsShapeCore;
/**
There is an implicit 1:1 mapping between PxgContactManagerInput and PxsContactManagerOutput. The structures are split because PxgNpContactManagerInput contains constant
data that is produced by the CPU code and PxgNpContactManagerOutput contains per-frame contact information produced by the NP.
There is also a 1:1 mapping between the PxgNpContactManager and PxsContactManager. This mapping is handled within the PxgNPhaseCore.
The previous contact states are implicitly cached in PxsContactManager and will be propagated to the solver. Friction correlation is also done implicitly using cached
information in PxsContactManager.
The NP will produce a list of pairs that found/lost patches for the solver along with updating the PxgNpContactManagerOutput for all pairs.
*/
struct PxsContactManagerStatusFlag
{
enum Enum
{
eHAS_NO_TOUCH = (1 << 0),
eHAS_TOUCH = (1 << 1),
//eHAS_SOLVER_CONSTRAINTS = (1 << 2),
eREQUEST_CONSTRAINTS = (1 << 3),
eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the
// contact report callback if requested.
eDIRTY_MANAGER = (1 << 5),
eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH, // The touch status is known (if narrowphase never ran for a pair then no flag will be set)
eSTATIC_OR_KINEMATIC = (1 << 6)
};
};
struct PX_ALIGN_PREFIX(16) PxsContactManagerOutput
{
PxU8* contactPatches; //Start index/ptr for contact patches
PxU8* contactPoints; //Start index/ptr for contact points
PxReal* contactForces; //Start index/ptr for contact forces
PxU8 allflagsStart; //padding for compatibility with existing code
PxU8 nbPatches; //Num patches
PxU8 statusFlag; //Status flag (has touch etc.)
PxU8 prevPatches; //Previous number of patches
PxU16 nbContacts; //Num contacts
PxU16 flags; //Not really part of outputs, but we have 4 bytes of padding, so why not?
PX_FORCE_INLINE PxU32* getInternalFaceIndice()
{
return reinterpret_cast<PxU32*>(contactForces + nbContacts);
}
}
PX_ALIGN_SUFFIX(16);
struct PX_ALIGN_PREFIX(4) PxsContactManagerOutputCounts
{
PxU8 nbPatches; //Num patches
PxU8 prevPatches; //Previous number of patches
PxU8 statusFlag; //Status flag;
PxU8 unused; //Unused
} PX_ALIGN_SUFFIX(4);
struct PX_ALIGN_PREFIX(8) PxsTorsionalFrictionData
{
PxReal mTorsionalPatchRadius;
PxReal mMinTorsionalRadius;
PxsTorsionalFrictionData() {}
PxsTorsionalFrictionData(const PxReal patchRadius, const PxReal minPatchRadius) :
mTorsionalPatchRadius(patchRadius), mMinTorsionalRadius(minPatchRadius) {}
} PX_ALIGN_SUFFIX(8);
}
#endif //PXG_CONTACT_MANAGER_H
| 4,761 | C | 43.092592 | 169 | 0.744802 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsIslandSim.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 PXS_ISLAND_SIM_H
#define PXS_ISLAND_SIM_H
#include "foundation/PxAssert.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxArray.h"
#include "CmPriorityQueue.h"
#include "CmBlockArray.h"
#include "PxNodeIndex.h"
namespace physx
{
namespace Dy
{
struct Constraint;
class FeatherstoneArticulation;
#if PX_SUPPORT_GPU_PHYSX
class SoftBody;
class FEMCloth;
class ParticleSystem;
class HairSystem;
#endif
}
// PT: TODO: fw declaring an Sc class here is not good
namespace Sc
{
class ArticulationSim;
}
class PxsContactManager;
class PxsRigidBody;
struct PartitionEdge;
namespace IG
{
//This index is
#define IG_INVALID_ISLAND 0xFFFFFFFFu
#define IG_INVALID_EDGE 0xFFFFFFFFu
#define IG_INVALID_LINK 0xFFu
typedef PxU32 IslandId;
typedef PxU32 EdgeIndex;
typedef PxU32 EdgeInstanceIndex;
class IslandSim;
struct Edge
{
//Edge instances can be implicitly calculated based on this edge index, which is an offset into the array of edges.
//From that, the child edge index is simply the
//The constraint or contact referenced by this edge
enum EdgeType
{
eCONTACT_MANAGER,
eCONSTRAINT,
eSOFT_BODY_CONTACT,
eFEM_CLOTH_CONTACT,
ePARTICLE_SYSTEM_CONTACT,
eHAIR_SYSTEM_CONTACT,
eEDGE_TYPE_COUNT
};
enum EdgeState
{
eINSERTED =1<<0,
ePENDING_DESTROYED =1<<1,
eACTIVE =1<<2,
eIN_DIRTY_LIST =1<<3,
eDESTROYED =1<<4,
eREPORT_ONLY_DESTROY=1<<5,
eACTIVATING =1<<6
};
//NodeIndex mNode1, mNode2;
EdgeType mEdgeType;
PxU16 mEdgeState;
EdgeIndex mNextIslandEdge, mPrevIslandEdge;
PX_FORCE_INLINE void setInserted() { mEdgeState |= (eINSERTED); }
PX_FORCE_INLINE void clearInserted() { mEdgeState &= (~eINSERTED); }
PX_FORCE_INLINE void clearDestroyed() { mEdgeState &=(~eDESTROYED);}
PX_FORCE_INLINE void setPendingDestroyed() { mEdgeState |= ePENDING_DESTROYED; }
PX_FORCE_INLINE void clearPendingDestroyed() { mEdgeState &= (~ePENDING_DESTROYED); }
PX_FORCE_INLINE void activateEdge() { mEdgeState |= eACTIVE; }
PX_FORCE_INLINE void deactivateEdge() { mEdgeState &= (~eACTIVE); }
PX_FORCE_INLINE void markInDirtyList() { mEdgeState |= (eIN_DIRTY_LIST); }
PX_FORCE_INLINE void clearInDirtyList() { mEdgeState &= (~eIN_DIRTY_LIST); }
PX_FORCE_INLINE void setReportOnlyDestroy() { mEdgeState |= (eREPORT_ONLY_DESTROY); }
PX_FORCE_INLINE void clearReportOnlyDestroy() { mEdgeState &= (~eREPORT_ONLY_DESTROY); }
public:
Edge() : mEdgeType(Edge::eCONTACT_MANAGER), mEdgeState(eDESTROYED),
mNextIslandEdge(IG_INVALID_EDGE), mPrevIslandEdge(IG_INVALID_EDGE)
{
}
PX_FORCE_INLINE bool isInserted() const { return !!(mEdgeState & eINSERTED);}
PX_FORCE_INLINE bool isDestroyed() const { return !!(mEdgeState & eDESTROYED); }
PX_FORCE_INLINE bool isPendingDestroyed() const { return !!(mEdgeState & ePENDING_DESTROYED); }
PX_FORCE_INLINE bool isActive() const { return !!(mEdgeState & eACTIVE); }
PX_FORCE_INLINE bool isInDirtyList() const { return !!(mEdgeState & eIN_DIRTY_LIST); }
PX_FORCE_INLINE EdgeType getEdgeType() const { return mEdgeType; }
//PX_FORCE_INLINE const NodeIndex getIndex1() const { return mNode1; }
//PX_FORCE_INLINE const NodeIndex getIndex2() const { return mNode2; }
PX_FORCE_INLINE bool isReportOnlyDestroy() { return !!(mEdgeState & eREPORT_ONLY_DESTROY); }
};
struct EdgeInstance
{
EdgeInstanceIndex mNextEdge, mPrevEdge; //The next edge instance in this node's list of edge instances
EdgeInstance() : mNextEdge(IG_INVALID_EDGE), mPrevEdge(IG_INVALID_EDGE)
{
}
};
template<typename Handle>
class HandleManager
{
PxArray<Handle> mFreeHandles;
Handle mCurrentHandle;
public:
HandleManager() : mFreeHandles("FreeHandles"), mCurrentHandle(0)
{
}
~HandleManager(){}
Handle getHandle()
{
if(mFreeHandles.size())
{
Handle handle = mFreeHandles.popBack();
PX_ASSERT(isValidHandle(handle));
return handle;
}
return mCurrentHandle++;
}
bool isNotFreeHandle(Handle handle) const
{
for(PxU32 a = 0; a < mFreeHandles.size(); ++a)
{
if(mFreeHandles[a] == handle)
return false;
}
return true;
}
void freeHandle(Handle handle)
{
PX_ASSERT(isValidHandle(handle));
PX_ASSERT(isNotFreeHandle(handle));
if(handle == mCurrentHandle)
mCurrentHandle--;
else
mFreeHandles.pushBack(handle);
}
bool isValidHandle(Handle handle) const
{
return handle < mCurrentHandle;
}
PX_FORCE_INLINE PxU32 getTotalHandles() const { return mCurrentHandle; }
};
class Node
{
public:
enum NodeType
{
eRIGID_BODY_TYPE,
eARTICULATION_TYPE,
eSOFTBODY_TYPE,
eFEMCLOTH_TYPE,
ePARTICLESYSTEM_TYPE,
eHAIRSYSTEM_TYPE,
eTYPE_COUNT
};
enum State
{
eREADY_FOR_SLEEPING = 1u << 0, //! Ready to go to sleep
eACTIVE = 1u << 1, //! Active
eKINEMATIC = 1u << 2, //! Kinematic
eDELETED = 1u << 3, //! Is pending deletion
eDIRTY = 1u << 4, //! Is dirty (i.e. lost a connection)
eACTIVATING = 1u << 5, //! Is in the activating list
eDEACTIVATING = 1u << 6 //! It is being forced to deactivate this frame
};
EdgeInstanceIndex mFirstEdgeIndex;
PxU8 mFlags;
PxU8 mType;
PxU16 mStaticTouchCount;
//PxU32 mActiveNodeIndex; //! Look-up for this node in the active nodes list, activating list or deactivating list...
PxNodeIndex mNextNode, mPrevNode;
//A counter for the number of active references to this body. Whenever an edge is activated, this is incremented.
//Whenver an edge is deactivated, this is decremented. This is used for kinematic bodies to determine if they need
//to be in the active kinematics list
PxU32 mActiveRefCount;
//A node can correspond with either a rigid body or an articulation or softBody
union
{
PxsRigidBody* mRigidBody;
Dy::FeatherstoneArticulation* mLLArticulation;
#if PX_SUPPORT_GPU_PHYSX
Dy::SoftBody* mLLSoftBody;
Dy::FEMCloth* mLLFEMCloth;
Dy::ParticleSystem* mLLParticleSystem;
Dy::HairSystem* mLLHairSystem;
#endif
};
PX_FORCE_INLINE Node() : mFirstEdgeIndex(IG_INVALID_EDGE), mFlags(eDELETED), mType(eRIGID_BODY_TYPE),
mStaticTouchCount(0), mActiveRefCount(0), mRigidBody(NULL)
{
}
PX_FORCE_INLINE ~Node() {}
PX_FORCE_INLINE void reset()
{
mFirstEdgeIndex = IG_INVALID_EDGE;
mFlags = eDELETED;
mRigidBody = NULL;
mActiveRefCount = 0;
mStaticTouchCount = 0;
}
PX_FORCE_INLINE void setRigidBody(PxsRigidBody* body) { mRigidBody = body; }
PX_FORCE_INLINE PxsRigidBody* getRigidBody() const { return mRigidBody; }
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getArticulation() const { return mLLArticulation; }
#if PX_SUPPORT_GPU_PHYSX
PX_FORCE_INLINE Dy::SoftBody* getSoftBody() const { return mLLSoftBody; }
PX_FORCE_INLINE Dy::FEMCloth* getFEMCloth() const { return mLLFEMCloth; }
PX_FORCE_INLINE Dy::HairSystem* getHairSystem() const { return mLLHairSystem; }
#endif
PX_FORCE_INLINE void setActive() { mFlags |= eACTIVE; }
PX_FORCE_INLINE void clearActive() { mFlags &= ~eACTIVE; }
PX_FORCE_INLINE void setActivating() { mFlags |= eACTIVATING; }
PX_FORCE_INLINE void clearActivating() { mFlags &= ~eACTIVATING; }
PX_FORCE_INLINE void setDeactivating() { mFlags |= eDEACTIVATING; }
PX_FORCE_INLINE void clearDeactivating() { mFlags &= (~eDEACTIVATING); }
//Activates a body/node.
PX_FORCE_INLINE void setIsReadyForSleeping() { mFlags |= eREADY_FOR_SLEEPING; }
PX_FORCE_INLINE void clearIsReadyForSleeping() { mFlags &= (~eREADY_FOR_SLEEPING); }
PX_FORCE_INLINE void setIsDeleted() { mFlags |= eDELETED; }
PX_FORCE_INLINE void setKinematicFlag() { PX_ASSERT(!isKinematic()); mFlags |= eKINEMATIC; }
PX_FORCE_INLINE void clearKinematicFlag() { PX_ASSERT(isKinematic()); mFlags &= (~eKINEMATIC); }
PX_FORCE_INLINE void markDirty() { mFlags |= eDIRTY; }
PX_FORCE_INLINE void clearDirty() { mFlags &= (~eDIRTY); }
public:
PX_FORCE_INLINE bool isActive() const { return !!(mFlags & eACTIVE); }
PX_FORCE_INLINE bool isActiveOrActivating() const { return !!(mFlags & (eACTIVE | eACTIVATING)); }
PX_FORCE_INLINE bool isActivating() const { return !!(mFlags & eACTIVATING); }
PX_FORCE_INLINE bool isDeactivating() const { return !!(mFlags & eDEACTIVATING); }
PX_FORCE_INLINE bool isKinematic() const { return !!(mFlags & eKINEMATIC); }
PX_FORCE_INLINE bool isDeleted() const { return !!(mFlags & eDELETED); }
PX_FORCE_INLINE bool isDirty() const { return !!(mFlags & eDIRTY); }
PX_FORCE_INLINE bool isReadyForSleeping() const { return !!(mFlags & eREADY_FOR_SLEEPING); }
PX_FORCE_INLINE NodeType getNodeType() const { return NodeType(mType); }
friend class SimpleIslandManager;
};
struct Island
{
PxNodeIndex mRootNode;
PxNodeIndex mLastNode;
PxU32 mNodeCount[Node::eTYPE_COUNT];
PxU32 mActiveIndex;
EdgeIndex mFirstEdge[Edge::eEDGE_TYPE_COUNT], mLastEdge[Edge::eEDGE_TYPE_COUNT];
PxU32 mEdgeCount[Edge::eEDGE_TYPE_COUNT];
Island() : mActiveIndex(IG_INVALID_ISLAND)
{
for(PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
mFirstEdge[a] = IG_INVALID_EDGE;
mLastEdge[a] = IG_INVALID_EDGE;
mEdgeCount[a] = 0;
}
for(PxU32 a = 0; a < Node::eTYPE_COUNT; ++a)
{
mNodeCount[a] = 0;
}
}
};
struct TraversalState
{
PxNodeIndex mNodeIndex;
PxU32 mCurrentIndex;
PxU32 mPrevIndex;
PxU32 mDepth;
TraversalState()
{
}
TraversalState(PxNodeIndex nodeIndex, PxU32 currentIndex, PxU32 prevIndex, PxU32 depth) :
mNodeIndex(nodeIndex), mCurrentIndex(currentIndex), mPrevIndex(prevIndex), mDepth(depth)
{
}
};
struct QueueElement
{
TraversalState* mState;
PxU32 mHopCount;
QueueElement()
{
}
QueueElement(TraversalState* state, PxU32 hopCount) : mState(state), mHopCount(hopCount)
{
}
};
struct NodeComparator
{
NodeComparator()
{
}
bool operator() (const QueueElement& node0, const QueueElement& node1) const
{
return node0.mHopCount < node1.mHopCount;
}
private:
NodeComparator& operator = (const NodeComparator&);
};
class IslandSim
{
PX_NOCOPY(IslandSim)
HandleManager<IslandId> mIslandHandles; //! Handle manager for islands
PxArray<Node> mNodes; //! The nodes used in the constraint graph
PxArray<PxU32> mActiveNodeIndex; //! The active node index for each node
Cm::BlockArray<Edge> mEdges;
Cm::BlockArray<EdgeInstance> mEdgeInstances; //! Edges used to connect nodes in the constraint graph
PxArray<Island> mIslands; //! The array of islands
PxArray<PxU32> mIslandStaticTouchCount; //! Array of static touch counts per-island
PxArray<PxNodeIndex> mActiveNodes[Node::eTYPE_COUNT]; //! An array of active nodes
PxArray<PxNodeIndex> mActiveKinematicNodes; //! An array of active or referenced kinematic nodes
PxArray<EdgeIndex> mActivatedEdges[Edge::eEDGE_TYPE_COUNT]; //! An array of active edges
PxU32 mActiveEdgeCount[Edge::eEDGE_TYPE_COUNT];
PxArray<PxU32> mHopCounts; //! The observed number of "hops" from a given node to its root node. May be inaccurate but used to accelerate searches.
PxArray<PxNodeIndex> mFastRoute; //! The observed last route from a given node to the root node. We try the fast route (unless its broken) before trying others.
PxArray<IslandId> mIslandIds; //! The array of per-node island ids
PxBitMap mIslandAwake; //! Indicates whether an island is awake or not
PxBitMap mActiveContactEdges;
//An array of active islands
PxArray<IslandId> mActiveIslands;
PxU32 mInitialActiveNodeCount[Edge::eEDGE_TYPE_COUNT];
PxArray<PxNodeIndex> mNodesToPutToSleep[Node::eTYPE_COUNT];
//Input to this frame's island management (changed nodes/edges)
//Input list of changes observed this frame. If there no changes, no work to be done.
PxArray<EdgeIndex> mDirtyEdges[Edge::eEDGE_TYPE_COUNT];
//Dirty nodes. These nodes lost at least one connection so we need to recompute islands from these nodes
//PxArray<NodeIndex> mDirtyNodes;
PxBitMap mDirtyMap;
PxU32 mLastMapIndex;
//An array of nodes to activate
PxArray<PxNodeIndex> mActivatingNodes;
PxArray<EdgeIndex> mDestroyedEdges;
PxArray<IslandId> mTempIslandIds;
//Temporary, transient data used for traversals. TODO - move to PxsSimpleIslandManager. Or if we keep it here, we can
//process multiple island simulations in parallel
Cm::PriorityQueue<QueueElement, NodeComparator> mPriorityQueue; //! Priority queue used for graph traversal
PxArray<TraversalState> mVisitedNodes; //! The list of nodes visited in the current traversal
PxBitMap mVisitedState; //! Indicates whether a node has been visited
PxArray<EdgeIndex> mIslandSplitEdges[Edge::eEDGE_TYPE_COUNT];
PxArray<EdgeIndex> mDeactivatingEdges[Edge::eEDGE_TYPE_COUNT];
PxArray<PartitionEdge*>* mFirstPartitionEdges;
Cm::BlockArray<PxNodeIndex>& mEdgeNodeIndices;
PxArray<physx::PartitionEdge*>* mDestroyedPartitionEdges;
PxU32* mNpIndexPtr;
const PxU64 mContextId;
public:
IslandSim(PxArray<PartitionEdge*>* firstPartitionEdges, Cm::BlockArray<PxNodeIndex>& edgeNodeIndices, PxArray<PartitionEdge*>* destroyedPartitionEdges, PxU64 contextID);
~IslandSim() {}
//void resize(const PxU32 nbNodes, const PxU32 nbContactManagers, const PxU32 nbConstraints);
void addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive, PxNodeIndex nodeIndex);
void addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive, PxNodeIndex nodeIndex);
#if PX_SUPPORT_GPU_PHYSX
void addSoftBody(Dy::SoftBody* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addFEMCloth(Dy::FEMCloth* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addParticleSystem(Dy::ParticleSystem* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addHairSystem(Dy::HairSystem* llHairSystem, bool isActive, PxNodeIndex nodeIndex);
#endif
//void addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle);
void addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle);
void activateNode(PxNodeIndex index);
void deactivateNode(PxNodeIndex index);
void putNodeToSleep(PxNodeIndex index);
void removeConnection(EdgeIndex edgeIndex);
PX_FORCE_INLINE PxU32 getNbNodes() const { return mNodes.size(); }
PX_FORCE_INLINE PxU32 getNbActiveNodes(Node::NodeType type) const { return mActiveNodes[type].size(); }
PX_FORCE_INLINE const PxNodeIndex* getActiveNodes(Node::NodeType type) const { return mActiveNodes[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActiveKinematics() const { return mActiveKinematicNodes.size(); }
PX_FORCE_INLINE const PxNodeIndex* getActiveKinematics() const { return mActiveKinematicNodes.begin(); }
PX_FORCE_INLINE PxU32 getNbNodesToActivate(Node::NodeType type) const { return mActiveNodes[type].size() - mInitialActiveNodeCount[type]; }
PX_FORCE_INLINE const PxNodeIndex* getNodesToActivate(Node::NodeType type) const { return mActiveNodes[type].begin() + mInitialActiveNodeCount[type]; }
PX_FORCE_INLINE PxU32 getNbNodesToDeactivate(Node::NodeType type) const { return mNodesToPutToSleep[type].size(); }
PX_FORCE_INLINE const PxNodeIndex* getNodesToDeactivate(Node::NodeType type) const { return mNodesToPutToSleep[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActivatedEdges(Edge::EdgeType type) const { return mActivatedEdges[type].size(); }
PX_FORCE_INLINE const EdgeIndex* getActivatedEdges(Edge::EdgeType type) const { return mActivatedEdges[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActiveEdges(Edge::EdgeType type) const { return mActiveEdgeCount[type]; }
PX_FORCE_INLINE PartitionEdge* getFirstPartitionEdge(IG::EdgeIndex edgeIndex) const { return (*mFirstPartitionEdges)[edgeIndex]; }
PX_FORCE_INLINE void setFirstPartitionEdge(IG::EdgeIndex edgeIndex, PartitionEdge* partitionEdge) { (*mFirstPartitionEdges)[edgeIndex] = partitionEdge; }
//PX_FORCE_INLINE const EdgeIndex* getActiveEdges(Edge::EdgeType type) const { return mActiveEdges[type].begin(); }
PX_FORCE_INLINE PxsRigidBody* getRigidBody(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eRIGID_BODY_TYPE);
return node.mRigidBody;
}
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getLLArticulation(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eARTICULATION_TYPE);
return node.mLLArticulation;
}
// PT: this one is questionable here
Sc::ArticulationSim* getArticulationSim(PxNodeIndex nodeIndex) const;
#if PX_SUPPORT_GPU_PHYSX
PX_FORCE_INLINE Dy::SoftBody* getLLSoftBody(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eSOFTBODY_TYPE);
return node.mLLSoftBody;
}
PX_FORCE_INLINE Dy::FEMCloth* getLLFEMCloth(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eFEMCLOTH_TYPE);
return node.mLLFEMCloth;
}
PX_FORCE_INLINE Dy::HairSystem* getLLHairSystem(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eHAIRSYSTEM_TYPE);
return node.mLLHairSystem;
}
#endif
PX_FORCE_INLINE void clearDeactivations()
{
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
mNodesToPutToSleep[i].forceSize_Unsafe(0);
mDeactivatingEdges[i].forceSize_Unsafe(0);
}
}
PX_FORCE_INLINE const Island& getIsland(IG::IslandId islandIndex) const { return mIslands[islandIndex]; }
PX_FORCE_INLINE PxU32 getNbActiveIslands() const { return mActiveIslands.size(); }
PX_FORCE_INLINE const IslandId* getActiveIslands() const { return mActiveIslands.begin(); }
PX_FORCE_INLINE PxU32 getNbDeactivatingEdges(const IG::Edge::EdgeType edgeType) const { return mDeactivatingEdges[edgeType].size(); }
PX_FORCE_INLINE const EdgeIndex* getDeactivatingEdges(const IG::Edge::EdgeType edgeType) const { return mDeactivatingEdges[edgeType].begin(); }
PX_FORCE_INLINE PxU32 getNbDestroyedEdges() const { return mDestroyedEdges.size(); }
PX_FORCE_INLINE const EdgeIndex* getDestroyedEdges() const { return mDestroyedEdges.begin(); }
PX_FORCE_INLINE PxU32 getNbDestroyedPartitionEdges() const { return mDestroyedPartitionEdges->size(); }
PX_FORCE_INLINE const PartitionEdge*const * getDestroyedPartitionEdges() const { return mDestroyedPartitionEdges->begin(); }
PX_FORCE_INLINE PartitionEdge** getDestroyedPartitionEdges() { return mDestroyedPartitionEdges->begin(); }
PX_FORCE_INLINE PxU32 getNbDirtyEdges(IG::Edge::EdgeType type) const { return mDirtyEdges[type].size(); }
PX_FORCE_INLINE const EdgeIndex* getDirtyEdges(IG::Edge::EdgeType type) const { return mDirtyEdges[type].begin(); }
PX_FORCE_INLINE const Edge& getEdge(const EdgeIndex edgeIndex) const { return mEdges[edgeIndex]; }
PX_FORCE_INLINE Edge& getEdge(const EdgeIndex edgeIndex) { return mEdges[edgeIndex]; }
PX_FORCE_INLINE const Node& getNode(const PxNodeIndex& nodeIndex) const { return mNodes[nodeIndex.index()]; }
PX_FORCE_INLINE const Island& getIsland(const PxNodeIndex& nodeIndex) const { PX_ASSERT(mIslandIds[nodeIndex.index()] != IG_INVALID_ISLAND); return mIslands[mIslandIds[nodeIndex.index()]]; }
PX_FORCE_INLINE PxU32 getIslandStaticTouchCount(const PxNodeIndex& nodeIndex) const { PX_ASSERT(mIslandIds[nodeIndex.index()] != IG_INVALID_ISLAND); return mIslandStaticTouchCount[mIslandIds[nodeIndex.index()]]; }
PX_FORCE_INLINE const PxBitMap& getActiveContactManagerBitmap() const { return mActiveContactEdges; }
PX_FORCE_INLINE PxU32 getActiveNodeIndex(const PxNodeIndex& nodeIndex) const { PxU32 activeNodeIndex = mActiveNodeIndex[nodeIndex.index()]; return activeNodeIndex;}
PX_FORCE_INLINE const PxU32* getActiveNodeIndex() const { return mActiveNodeIndex.begin(); }
PX_FORCE_INLINE PxU32 getNbActiveNodeIndex() const { return mActiveNodeIndex.size(); }
void setKinematic(PxNodeIndex nodeIndex);
void setDynamic(PxNodeIndex nodeIndex);
PX_FORCE_INLINE PxNodeIndex getNodeIndex1(IG::EdgeIndex index) const { return mEdgeNodeIndices[2 * index]; }
PX_FORCE_INLINE PxNodeIndex getNodeIndex2(IG::EdgeIndex index) const { return mEdgeNodeIndices[2 * index + 1]; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextId; }
PxU32 getNbIslands() const { return mIslandStaticTouchCount.size(); }
const PxU32* getIslandStaticTouchCount() const { return mIslandStaticTouchCount.begin(); }
const PxU32* getIslandIds() const { return mIslandIds.begin(); }
bool checkInternalConsistency() const;
PX_INLINE void activateNode_ForGPUSolver(PxNodeIndex index)
{
IG::Node& node = mNodes[index.index()];
node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
node.clearDeactivating();
}
PX_INLINE void deactivateNode_ForGPUSolver(PxNodeIndex index)
{
IG::Node& node = mNodes[index.index()];
node.setIsReadyForSleeping();
}
// PT: these ones are strange, used to store an unrelated ptr from the outside, and only for GPU
// Why do we store that here? What happens on the CPU ?
PX_FORCE_INLINE void setEdgeNodeIndexPtr(PxU32* ptr) { mNpIndexPtr = ptr; }
PX_FORCE_INLINE PxU32* getEdgeNodeIndexPtr() const { return mNpIndexPtr; }
private:
void insertNewEdges();
void removeDestroyedEdges();
void wakeIslands();
void wakeIslands2();
void processNewEdges();
void processLostEdges(PxArray<PxNodeIndex>& destroyedNodes, bool allowDeactivation, bool permitKinematicDeactivation, PxU32 dirtyNodeLimit);
void removeConnectionInternal(EdgeIndex edgeIndex);
void addConnection(PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Edge::EdgeType edgeType, EdgeIndex handle);
void addConnectionToGraph(EdgeIndex index);
void removeConnectionFromGraph(EdgeIndex edgeIndex);
void connectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& source, PxNodeIndex destination);
void disconnectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& node);
//Merges 2 islands together. The returned id is the id of the merged island
IslandId mergeIslands(IslandId island0, IslandId island1, PxNodeIndex node0, PxNodeIndex node1);
void mergeIslandsInternal(Island& island0, Island& island1, IslandId islandId0, IslandId islandId1, PxNodeIndex node0, PxNodeIndex node1);
void unwindRoute(PxU32 traversalIndex, PxNodeIndex lastNode, PxU32 hopCount, IslandId id);
void activateIsland(IslandId island);
void deactivateIsland(IslandId island);
bool canFindRoot(PxNodeIndex startNode, PxNodeIndex targetNode, PxArray<PxNodeIndex>* visitedNodes);
bool tryFastPath(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId);
bool findRoute(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId);
bool isPathTo(PxNodeIndex startNode, PxNodeIndex targetNode) const;
void addNode(bool isActive, bool isKinematic, Node::NodeType type, PxNodeIndex nodeIndex);
void activateNodeInternal(PxNodeIndex index);
void deactivateNodeInternal(PxNodeIndex index);
/* PX_FORCE_INLINE void notifyReadyForSleeping(const PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
//PX_ASSERT(node.isActive());
node.setIsReadyForSleeping();
}
PX_FORCE_INLINE void notifyNotReadyForSleeping(const PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.isActive() || node.isActivating());
node.clearIsReadyForSleeping();
}*/
PX_FORCE_INLINE void markIslandActive(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(!mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex == IG_INVALID_ISLAND);
mIslandAwake.set(islandId);
island.mActiveIndex = mActiveIslands.size();
mActiveIslands.pushBack(islandId);
}
PX_FORCE_INLINE void markIslandInactive(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex != IG_INVALID_ISLAND);
PX_ASSERT(mActiveIslands[island.mActiveIndex] == islandId);
IslandId replaceId = mActiveIslands[mActiveIslands.size()-1];
PX_ASSERT(mIslandAwake.test(replaceId));
Island& replaceIsland = mIslands[replaceId];
replaceIsland.mActiveIndex = island.mActiveIndex;
mActiveIslands[island.mActiveIndex] = replaceId;
mActiveIslands.forceSize_Unsafe(mActiveIslands.size()-1);
island.mActiveIndex = IG_INVALID_ISLAND;
mIslandAwake.reset(islandId);
}
PX_FORCE_INLINE void markKinematicActive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(node.isKinematic());
if(node.mActiveRefCount == 0 && mActiveNodeIndex[index.index()] == PX_INVALID_NODE)
{
//PX_ASSERT(mActiveNodeIndex[index.index()] == PX_INVALID_NODE);
//node.mActiveNodeIndex = mActiveKinematicNodes.size();
mActiveNodeIndex[index.index()] = mActiveKinematicNodes.size();
PxNodeIndex nodeIndex;
nodeIndex = index;
mActiveKinematicNodes.pushBack(nodeIndex);
}
}
PX_FORCE_INLINE void markKinematicInactive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PX_ASSERT(mActiveKinematicNodes[mActiveNodeIndex[index.index()]].index() == index.index());
if(node.mActiveRefCount == 0)
{
//Only remove from active kinematic list if it has no active contacts referencing it *and* it is asleep
if(mActiveNodeIndex[index.index()] != PX_INVALID_NODE)
{
//Need to verify active node index because there is an edge case where a node could be woken, then put to
//sleep in the same frame. This would mean that it would not have an active index at this stage.
PxNodeIndex replaceIndex = mActiveKinematicNodes.back();
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == mActiveKinematicNodes.size()-1);
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[index.index()];
mActiveKinematicNodes[mActiveNodeIndex[index.index()]] = replaceIndex;
mActiveKinematicNodes.forceSize_Unsafe(mActiveKinematicNodes.size()-1);
mActiveNodeIndex[index.index()] = PX_INVALID_NODE;
}
}
}
PX_FORCE_INLINE void markActive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] == PX_INVALID_NODE);
mActiveNodeIndex[index.index()] = mActiveNodes[node.mType].size();
PxNodeIndex nodeIndex;
nodeIndex = index;
mActiveNodes[node.mType].pushBack(nodeIndex);
}
PX_FORCE_INLINE void markInactive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PxArray<PxNodeIndex>& activeNodes = mActiveNodes[node.mType];
PX_ASSERT(activeNodes[mActiveNodeIndex[index.index()]].index() == index.index());
const PxU32 initialActiveNodeCount = mInitialActiveNodeCount[node.mType];
if(mActiveNodeIndex[index.index()] < initialActiveNodeCount)
{
//It's in the initial active node set. We retain a list of active nodes, where the existing active nodes
//are at the beginning of the array and the newly activated nodes are at the end of the array...
//The solution is to move the node to the end of the initial active node list in this case
PxU32 activeNodeIndex = mActiveNodeIndex[index.index()];
PxNodeIndex replaceIndex = activeNodes[initialActiveNodeCount-1];
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == initialActiveNodeCount-1);
mActiveNodeIndex[index.index()] = mActiveNodeIndex[replaceIndex.index()];
mActiveNodeIndex[replaceIndex.index()] = activeNodeIndex;
activeNodes[activeNodeIndex] = replaceIndex;
activeNodes[mActiveNodeIndex[index.index()]] = index;
mInitialActiveNodeCount[node.mType]--;
}
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PX_ASSERT(activeNodes[mActiveNodeIndex[index.index()]].index() == index.index());
PxNodeIndex replaceIndex = activeNodes.back();
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == activeNodes.size()-1);
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[index.index()];
activeNodes[mActiveNodeIndex[index.index()]] = replaceIndex;
activeNodes.forceSize_Unsafe(activeNodes.size()-1);
mActiveNodeIndex[index.index()] = PX_INVALID_NODE;
}
PX_FORCE_INLINE void markEdgeActive(EdgeIndex index)
{
Edge& edge = mEdges[index];
PX_ASSERT((edge.mEdgeState & Edge::eACTIVATING) == 0);
edge.mEdgeState |= Edge::eACTIVATING;
mActivatedEdges[edge.mEdgeType].pushBack(index);
mActiveEdgeCount[edge.mEdgeType]++;
//Set the active bit...
if(edge.mEdgeType == Edge::eCONTACT_MANAGER)
mActiveContactEdges.set(index);
PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * index];
PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * index + 1];
if (nodeIndex1.index() != PX_INVALID_NODE && nodeIndex2.index() != PX_INVALID_NODE)
{
PX_ASSERT((!mNodes[nodeIndex1.index()].isKinematic()) || (!mNodes[nodeIndex2.index()].isKinematic()) || edge.getEdgeType() == IG::Edge::eCONTACT_MANAGER);
{
Node& node = mNodes[nodeIndex1.index()];
if(node.mActiveRefCount == 0 && node.isKinematic() && !(node.isActive() || node.isActivating()))
{
//Add to active kinematic list
markKinematicActive(nodeIndex1);
}
node.mActiveRefCount++;
}
{
Node& node = mNodes[nodeIndex2.index()];
if(node.mActiveRefCount == 0 && node.isKinematic() && !(node.isActive() || node.isActivating()))
{
//Add to active kinematic list
markKinematicActive(nodeIndex2);
}
node.mActiveRefCount++;
}
}
}
void removeEdgeFromActivatingList(EdgeIndex index);
PX_FORCE_INLINE void removeEdgeFromIsland(Island& island, EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
if(edge.mNextIslandEdge != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[edge.mNextIslandEdge].mPrevIslandEdge == edgeIndex);
mEdges[edge.mNextIslandEdge].mPrevIslandEdge = edge.mPrevIslandEdge;
}
else
{
PX_ASSERT(island.mLastEdge[edge.mEdgeType] == edgeIndex);
island.mLastEdge[edge.mEdgeType] = edge.mPrevIslandEdge;
}
if(edge.mPrevIslandEdge != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[edge.mPrevIslandEdge].mNextIslandEdge == edgeIndex);
mEdges[edge.mPrevIslandEdge].mNextIslandEdge = edge.mNextIslandEdge;
}
else
{
PX_ASSERT(island.mFirstEdge[edge.mEdgeType] == edgeIndex);
island.mFirstEdge[edge.mEdgeType] = edge.mNextIslandEdge;
}
island.mEdgeCount[edge.mEdgeType]--;
edge.mNextIslandEdge = edge.mPrevIslandEdge = IG_INVALID_EDGE;
}
PX_FORCE_INLINE void addEdgeToIsland(Island& island, EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
PX_ASSERT(edge.mNextIslandEdge == IG_INVALID_EDGE && edge.mPrevIslandEdge == IG_INVALID_EDGE);
if(island.mLastEdge[edge.mEdgeType] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island.mLastEdge[edge.mEdgeType]].mNextIslandEdge == IG_INVALID_EDGE);
mEdges[island.mLastEdge[edge.mEdgeType]].mNextIslandEdge = edgeIndex;
}
else
{
PX_ASSERT(island.mFirstEdge[edge.mEdgeType] == IG_INVALID_EDGE);
island.mFirstEdge[edge.mEdgeType] = edgeIndex;
}
edge.mPrevIslandEdge = island.mLastEdge[edge.mEdgeType];
island.mLastEdge[edge.mEdgeType] = edgeIndex;
island.mEdgeCount[edge.mEdgeType]++;
}
PX_FORCE_INLINE void removeNodeFromIsland(Island& island, PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
if(node.mNextNode.isValid())
{
PX_ASSERT(mNodes[node.mNextNode.index()].mPrevNode.index() == nodeIndex.index());
mNodes[node.mNextNode.index()].mPrevNode = node.mPrevNode;
}
else
{
PX_ASSERT(island.mLastNode.index() == nodeIndex.index());
island.mLastNode = node.mPrevNode;
}
if(node.mPrevNode.isValid())
{
PX_ASSERT(mNodes[node.mPrevNode.index()].mNextNode.index() == nodeIndex.index());
mNodes[node.mPrevNode.index()].mNextNode = node.mNextNode;
}
else
{
PX_ASSERT(island.mRootNode.index() == nodeIndex.index());
island.mRootNode = node.mNextNode;
}
island.mNodeCount[node.mType]--;
node.mNextNode = PxNodeIndex(); node.mPrevNode = PxNodeIndex();
}
//void setEdgeConnectedInternal(EdgeIndex edgeIndex);
//void setEdgeDisconnectedInternal(EdgeIndex edgeIndex);
friend class SimpleIslandManager;
friend class ThirdPassTask;
};
}
struct PartitionIndexData
{
PxU16 mPartitionIndex; //! The current partition this edge is in. Used to find the edge efficiently. PxU8 is probably too small (256 partitions max) but PxU16 should be more than enough
PxU8 mPatchIndex; //! The patch index for this partition edge. There may be multiple entries for a given edge if there are multiple patches.
PxU8 mCType; //! The type of constraint this is
PxU32 mPartitionEntryIndex; //! index of partition edges for this partition
};
struct PartitionNodeData
{
PxNodeIndex mNodeIndex0;
PxNodeIndex mNodeIndex1;
PxU32 mNextIndex0;
PxU32 mNextIndex1;
};
#define INVALID_PARTITION_INDEX 0xFFFF
struct PartitionEdge
{
IG::EdgeIndex mEdgeIndex; //! The edge index into the island manager. Used to identify the contact manager/constraint
PxNodeIndex mNode0; //! The node index for node 0. Can be obtained from the edge index alternatively
PxNodeIndex mNode1; //! The node idnex for node 1. Can be obtained from the edge index alternatively
bool mInfiniteMass0; //! Whether body 0 is kinematic
bool mArticulation0; //! Whether body 0 is an articulation link
bool mInfiniteMass1; //! Whether body 1 is kinematic
bool mArticulation1; //! Whether body 1 is an articulation link
PartitionEdge* mNextPatch; //! for the contact manager has more than 1 patch, we have next patch's edge and previous patch's edge to connect to this edge
PxU32 mUniqueIndex; //! a unique ID for this edge
//KS - This constructor explicitly does not set mUniqueIndex. It is filled in by the pool allocator and this constructor
//is called afterwards. We do not want to stomp the uniqueIndex value
PartitionEdge() : mEdgeIndex(IG_INVALID_EDGE), mInfiniteMass0(false), mArticulation0(false),
mInfiniteMass1(false), mArticulation1(false), mNextPatch(NULL)//, mUniqueIndex(IG_INVALID_EDGE)
{
}
};
}
#endif
| 36,023 | C | 35.684318 | 214 | 0.739278 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsSimulationController.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 PXS_SIMULATION_CONTROLLER_H
#define PXS_SIMULATION_CONTROLLER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxPinnedArray.h"
#include "foundation/PxUserAllocated.h"
#include "PxScene.h"
#include "PxParticleSystem.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFLIPParticleSystem.h"
#include "PxMPMParticleSystem.h"
// if these assert fail adjust the type here and in the forward declaration of the #else section just below
PX_COMPILE_TIME_ASSERT(sizeof(physx::PxMPMParticleDataFlag::Enum) == sizeof(physx::PxU32));
PX_COMPILE_TIME_ASSERT(sizeof(physx::PxSparseGridDataFlag::Enum) == sizeof(physx::PxU32));
#else
namespace PxMPMParticleDataFlag { enum Enum : physx::PxU32; }
namespace PxSparseGridDataFlag { enum Enum : physx::PxU32; }
#endif
#include "PxParticleSolverType.h"
namespace physx
{
namespace Dy
{
class Context;
struct Constraint;
class FeatherstoneArticulation;
struct ArticulationJointCore;
class ParticleSystemCore;
class ParticleSystem;
#if PX_SUPPORT_GPU_PHYSX
class SoftBody;
class FEMCloth;
class HairSystem;
#endif
}
namespace Bp
{
class BoundsArray;
class BroadPhase;
class AABBManagerBase;
}
namespace IG
{
class SimpleIslandManager;
class IslandSim;
}
namespace Sc
{
class BodySim;
}
class PxNodeIndex;
class PxsTransformCache;
class PxvNphaseImplementationContext;
class PxBaseTask;
class PxsContext;
struct PxsShapeSim;
class PxsRigidBody;
class PxsKernelWranglerManager;
class PxsHeapMemoryAllocatorManager;
class PxgParticleSystemCore;
struct PxConeLimitedConstraint;
struct PxsShapeCore;
class PxPhysXGpu;
struct PxgSolverConstraintManagerConstants;
class PxsSimulationControllerCallback : public PxUserAllocated
{
public:
virtual void updateScBodyAndShapeSim(PxBaseTask* continuation) = 0;
virtual PxU32 getNbCcdBodies() = 0;
virtual ~PxsSimulationControllerCallback() {}
};
class PxsSimulationController : public PxUserAllocated
{
public:
PxsSimulationController(PxsSimulationControllerCallback* callback, PxIntBool gpu) : mCallback(callback), mGPU(gpu) {}
virtual ~PxsSimulationController(){}
virtual void addJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/, IG::IslandSim& /*islandSim*/, PxArray<PxU32>& /*jointIndices*/,
PxPinnedArray<PxgSolverConstraintManagerConstants>& /*managerIter*/, PxU32 /*uniqueId*/){}
virtual void removeJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/, PxArray<PxU32>& /*jointIndices*/, IG::IslandSim& /*islandSim*/){}
virtual void addShape(PxsShapeSim* /*shapeSim*/, const PxU32 /*index*/){}
virtual void reinsertShape(PxsShapeSim* /*shapeSim*/, const PxU32 /*index*/) {}
virtual void updateShape(PxsShapeSim& /*shapeSim*/, const PxNodeIndex& /*index*/) {}
virtual void removeShape(const PxU32 /*index*/){}
virtual void addDynamic(PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*nodeIndex*/){}
virtual void addDynamics(PxsRigidBody** /*rigidBody*/, const PxU32* /*nodeIndex*/, PxU32 /*nbBodies*/) {}
virtual void addArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseDeferredArticulationIds() {}
#if PX_SUPPORT_GPU_PHYSX
virtual void addSoftBody(Dy::SoftBody* /*softBody*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseSoftBody(Dy::SoftBody* /*softBody*/) {}
virtual void releaseDeferredSoftBodyIds() {}
virtual void activateSoftbody(Dy::SoftBody*) {}
virtual void deactivateSoftbody(Dy::SoftBody*) {}
virtual void activateSoftbodySelfCollision(Dy::SoftBody*) {}
virtual void deactivateSoftbodySelfCollision(Dy::SoftBody*) {}
virtual void setSoftBodyWakeCounter(Dy::SoftBody*) {}
virtual void addParticleFilter(Dy::SoftBody* /*softBodySystem*/, Dy::ParticleSystem* /*particleSystem*/,
PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/) {}
virtual void removeParticleFilter(Dy::SoftBody* /*softBodySystem*/,
const Dy::ParticleSystem* /*particleSystem*/, PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/) {}
virtual PxU32 addParticleAttachment(Dy::SoftBody* /*softBodySystem*/, const Dy::ParticleSystem* /*particleSystem*/,
PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/, const PxVec4& /*barycentrics*/, const bool /*isActive*/) { return 0; }
virtual void removeParticleAttachment(Dy::SoftBody* /*softBody*/, PxU32 /*handle*/) {}
virtual void addRigidFilter(Dy::SoftBody* /*softBodySystem*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/) {}
virtual void removeRigidFilter(Dy::SoftBody* /*softBodySystem*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/) {}
virtual PxU32 addRigidAttachment(Dy::SoftBody* /*softBodySystem*/, const PxNodeIndex& /*softBodyNodeIndex*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/, const PxVec3& /*actorSpacePose*/,
PxConeLimitedConstraint* /*constraint*/, const bool /*isActive*/) { return 0; }
virtual void removeRigidAttachment(Dy::SoftBody* /*softBody*/, PxU32 /*handle*/) {}
virtual void addTetRigidFilter(Dy::SoftBody* /*softBodySystem*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetId*/) {}
virtual PxU32 addTetRigidAttachment(Dy::SoftBody* /*softBodySystem*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetIdx*/,
const PxVec4& /*barycentrics*/, const PxVec3& /*actorSpacePose*/, PxConeLimitedConstraint* /*constraint*/,
const bool /*isActive*/) { return 0; }
virtual void removeTetRigidFilter(Dy::SoftBody* /*softBody*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetId*/) {}
virtual void addSoftBodyFilter(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/,
PxU32 /*tetIdx1*/) {}
virtual void removeSoftBodyFilter(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/,
PxU32 /*tetId1*/) {}
virtual void addSoftBodyFilters(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32* /*tetIndices0*/, PxU32* /*tetIndices1*/,
PxU32 /*tetIndicesSize*/) {}
virtual void removeSoftBodyFilters(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32* /*tetIndices0*/, PxU32* /*tetIndices1*/,
PxU32 /*tetIndicesSize*/) {}
virtual PxU32 addSoftBodyAttachment(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/, PxU32 /*tetIdx1*/,
const PxVec4& /*tetBarycentric0*/, const PxVec4& /*tetBarycentric1*/,
PxConeLimitedConstraint* /*constraint*/, PxReal /*constraintOffset*/, const bool /*isActive*/) { return 0; }
virtual void removeSoftBodyAttachment(Dy::SoftBody* /*softBody0*/, PxU32 /*handle*/) {}
virtual void addClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/, PxU32 /*tetIdx*/) {}
virtual void removeClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/, PxU32 /*tetIdx*/) {}
virtual void addVertClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*vertIdx*/, PxU32 /*tetIdx*/) {}
virtual void removeVertClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*vertIdx*/, PxU32 /*tetIdx*/) {}
virtual PxU32 addClothAttachment(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/,
const PxVec4& /*triBarycentric*/, PxU32 /*tetIdx*/, const PxVec4& /*tetBarycentric*/,
PxConeLimitedConstraint* /*constraint*/, PxReal /*constraintOffset*/,
const bool /*isActive*/) { return 0; }
virtual void removeClothAttachment(Dy::SoftBody* /*softBody*/,PxU32 /*handle*/) {}
virtual void addFEMCloth(Dy::FEMCloth* /*femCloth*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseFEMCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void releaseDeferredFEMClothIds() {}
virtual void activateCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void deactivateCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void setClothWakeCounter(Dy::FEMCloth*) {}
virtual void addRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertId*/) {}
virtual void removeRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertId*/) {}
virtual PxU32 addRigidAttachment(Dy::FEMCloth* /*cloth*/, const PxNodeIndex& /*clothNodeIndex*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/, const PxVec3& /*actorSpacePose*/,
PxConeLimitedConstraint* /*constraint*/, const bool /*isActive*/) { return 0; }
virtual void removeRigidAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addTriRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/) {}
virtual void removeTriRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/) {}
virtual PxU32 addTriRigidAttachment(Dy::FEMCloth* /*cloth*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/, const PxVec4& /*barycentrics*/,
const PxVec3& /*actorSpacePose*/, PxConeLimitedConstraint* /*constraint*/,
const bool /*isActive*/) { return 0; }
virtual void removeTriRigidAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addClothFilter(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/) {}
virtual void removeClothFilter(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/) {}
virtual PxU32 addTriClothAttachment(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/,
const PxVec4& /*triBarycentric0*/, const PxVec4& /*triBarycentric1*/, const bool /*addToActive*/) { return 0; }
virtual void removeTriClothAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addParticleSystem(Dy::ParticleSystem* /*particleSystem*/, const PxNodeIndex& /*nodeIndex*/, PxParticleSolverType::Enum /*type*/) {}
virtual void releaseParticleSystem(Dy::ParticleSystem* /*particleSystem*/, PxParticleSolverType::Enum /*type*/) {}
virtual void releaseDeferredParticleSystemIds() {}
virtual void addHairSystem(Dy::HairSystem* /*hairSystem*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseHairSystem(Dy::HairSystem* /*hairSystem*/) {}
virtual void releaseDeferredHairSystemIds() {}
virtual void activateHairSystem(Dy::HairSystem*) {}
virtual void deactivateHairSystem(Dy::HairSystem*) {}
virtual void setHairSystemWakeCounter(Dy::HairSystem*) {}
#endif
virtual void flush() {}
virtual void updateDynamic(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/){}
virtual void updateBodies(PxsRigidBody** /*rigidBodies*/, PxU32* /*nodeIndices*/, const PxU32 /*nbBodies*/) {}
// virtual void updateBody(PxsRigidBody* /*rigidBody*/, const PxU32 /*nodeIndex*/) {}
virtual void updateBodies(PxBaseTask* /*continuation*/){}
virtual void updateShapes(PxBaseTask* /*continuation*/) {}
virtual void preIntegrateAndUpdateBound(PxBaseTask* /*continuation*/, const PxVec3 /*gravity*/, const PxReal /*dt*/){}
virtual void updateParticleSystemsAndSoftBodies(){}
virtual void sortContacts(){}
virtual void update(PxBitMapPinned& /*changedHandleMap*/){}
virtual void updateArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationJoint(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
// virtual void updateArticulationTendon(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationExtAccel(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationAfterIntegration(PxsContext* /*llContext*/, Bp::AABBManagerBase* /*aabbManager*/,
PxArray<Sc::BodySim*>& /*ccdBodies*/, PxBaseTask* /*continuation*/, IG::IslandSim& /*islandSim*/, float /*dt*/) {}
virtual void mergeChangedAABBMgHandle() {}
virtual void gpuDmabackData(PxsTransformCache& /*cache*/, Bp::BoundsArray& /*boundArray*/, PxBitMapPinned& /*changedAABBMgrHandles*/, bool /*enableDirectGPUAPI*/){}
virtual void updateScBodyAndShapeSim(PxsTransformCache& cache, Bp::BoundsArray& boundArray, PxBaseTask* continuation) = 0;
virtual PxU32* getActiveBodies() { return NULL; }
virtual PxU32* getDeactiveBodies() { return NULL; }
virtual void** getRigidBodies() { return NULL; }
virtual PxU32 getNbBodies() { return 0; }
virtual PxU32* getUnfrozenShapes() { return NULL; }
virtual PxU32* getFrozenShapes() { return NULL; }
virtual PxsShapeSim** getShapeSims() { return NULL; }
virtual PxU32 getNbFrozenShapes() { return 0; }
virtual PxU32 getNbUnfrozenShapes() { return 0; }
virtual PxU32 getNbShapes() { return 0; }
virtual void clear() { }
virtual void setBounds(Bp::BoundsArray* /*boundArray*/){}
virtual void reserve(const PxU32 /*nbBodies*/) {}
virtual PxU32 getArticulationRemapIndex(const PxU32 /*nodeIndex*/) { return PX_INVALID_U32;}
//virtual void setParticleSystemManager(PxgParticleSystemCore* psCore) = 0;
virtual void copyArticulationData(void* /*jointData*/, void* /*index*/, PxArticulationGpuDataType::Enum /*dataType*/, const PxU32 /*nbUpdatedArticulations*/, CUevent /*copyEvent*/) {}
virtual void applyArticulationData(void* /*data*/, void* /*index*/, PxArticulationGpuDataType::Enum /*dataType*/, const PxU32 /*nbUpdatedArticulations*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
virtual void updateArticulationsKinematic(CUevent /*signalEvent*/) {}
//KS - the methods below here should probably be wrapped in if PX_SUPPORT_GPU_PHYSX
// PT: isn't the whole class only needed for GPU anyway?
virtual void copySoftBodyData(void** /*data*/, void* /*dataSizes*/, void* /*softBodyIndices*/, PxSoftBodyGpuDataFlag::Enum /*flag*/, const PxU32 /*nbCopySoftBodies*/, const PxU32 /*maxSize*/, CUevent /*copyEvent*/) {}
virtual void applySoftBodyData(void** /*data*/, void* /*dataSizes*/, void* /*softBodyIndices*/, PxSoftBodyGpuDataFlag::Enum /*flag*/, const PxU32 /*nbUpdatedSoftBodies*/, const PxU32 /*maxSize*/, CUevent /*applyEvent*/, CUevent /*signalEvent*/) {}
virtual void copyContactData(Dy::Context* /*dyContext*/, void* /*data*/, const PxU32 /*maxContactPairs*/, void* /*numContactPairs*/, CUevent /*copyEvent*/) {}
virtual void copyBodyData(PxGpuBodyData* /*data*/, PxGpuActorPair* /*index*/, const PxU32 /*nbCopyActors*/, CUevent /*copyEvent*/){}
virtual void applyActorData(void* /*data*/, PxGpuActorPair* /*index*/, PxActorCacheFlag::Enum /*flag*/, const PxU32 /*nbUpdatedActors*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
virtual void evaluateSDFDistances(const PxU32* /*sdfShapeIds*/, const PxU32 /*nbShapes*/, const PxVec4* /*samplePointsConcatenated*/,
const PxU32* /*samplePointCountPerShape*/, const PxU32 /*maxPointCount*/, PxVec4* /*localGradientAndSDFConcatenated*/, CUevent /*event*/) {}
virtual PxU32 getInternalShapeIndex(const PxsShapeCore& /*shapeCore*/) { return PX_INVALID_U32; }
virtual void syncParticleData() {}
virtual void updateBoundsAndShapes(Bp::AABBManagerBase& /*aabbManager*/, bool /*useDirectApi*/){}
virtual void computeDenseJacobians(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/){}
virtual void computeGeneralizedMassMatrices(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/){}
virtual void computeGeneralizedGravityForces(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, const PxVec3& /*gravity*/, CUevent /*computeEvent*/){}
virtual void computeCoriolisAndCentrifugalForces(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/) {}
virtual void applyParticleBufferData(const PxU32* /*indices*/, const PxGpuParticleBufferIndexPair* /*indexPairs*/, const PxParticleBufferFlags* /*flags*/, PxU32 /*nbUpdatedBuffers*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
#if PX_SUPPORT_GPU_PHYSX
virtual PxU32 getNbDeactivatedFEMCloth() const { return 0; }
virtual PxU32 getNbActivatedFEMCloth() const { return 0; }
virtual Dy::FEMCloth** getDeactivatedFEMCloths() const { return NULL; }
virtual Dy::FEMCloth** getActivatedFEMCloths() const { return NULL; }
virtual PxU32 getNbDeactivatedSoftbodies() const { return 0; }
virtual PxU32 getNbActivatedSoftbodies() const { return 0; }
virtual const PxReal* getSoftBodyWakeCounters() const { return NULL; }
virtual const PxReal* getHairSystemWakeCounters() const { return NULL; }
virtual Dy::SoftBody** getDeactivatedSoftbodies() const { return NULL; }
virtual Dy::SoftBody** getActivatedSoftbodies() const { return NULL; }
virtual bool hasFEMCloth() const { return false; }
virtual bool hasSoftBodies() const { return false; }
virtual PxU32 getNbDeactivatedHairSystems() const { return 0; }
virtual PxU32 getNbActivatedHairSystems() const { return 0; }
virtual Dy::HairSystem** getDeactivatedHairSystems() const { return NULL; }
virtual Dy::HairSystem** getActivatedHairSystems() const { return NULL; }
virtual bool hasHairSystems() const { return false; }
#endif
virtual void* getMPMDataPointer(const Dy::ParticleSystem& /*psLL*/, PxMPMParticleDataFlag::Enum /*flags*/) { return NULL; }
virtual void* getSparseGridDataPointer(const Dy::ParticleSystem& /*psLL*/, PxSparseGridDataFlag::Enum /*flags*/, PxParticleSolverType::Enum /*type*/) { return NULL; }
protected:
PxsSimulationControllerCallback* mCallback;
public:
const PxIntBool mGPU; // PT: true for GPU version, used to quickly skip calls for CPU version
};
}
#endif
| 19,873 | C | 53.900552 | 249 | 0.729583 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsHeapMemoryAllocator.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 PXS_HEAP_MEMORY_ALLOCATOR_H
#define PXS_HEAP_MEMORY_ALLOCATOR_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
struct PxsHeapStats
{
enum Enum
{
eOTHER = 0,
eBROADPHASE,
eNARROWPHASE,
eSOLVER,
eARTICULATION,
eSIMULATION,
eSIMULATION_ARTICULATION,
eSIMULATION_PARTICLES,
eSIMULATION_SOFTBODY,
eSIMULATION_FEMCLOTH,
eSIMULATION_HAIRSYSTEM,
eSHARED_PARTICLES,
eSHARED_SOFTBODY,
eSHARED_FEMCLOTH,
eSHARED_HAIRSYSTEM,
eHEAPSTATS_COUNT
};
PxU64 stats[eHEAPSTATS_COUNT];
PxsHeapStats()
{
for (PxU32 i = 0; i < eHEAPSTATS_COUNT; i++)
{
stats[i] = 0;
}
}
};
// PT: TODO: consider dropping this class
class PxsHeapMemoryAllocator : public PxVirtualAllocatorCallback, public PxUserAllocated
{
public:
virtual ~PxsHeapMemoryAllocator(){}
// PxVirtualAllocatorCallback
//virtual void* allocate(const size_t size, const int group, const char* file, const int line) = 0;
//virtual void deallocate(void* ptr) = 0;
//~PxVirtualAllocatorCallback
};
class PxsHeapMemoryAllocatorManager : public PxUserAllocated
{
public:
virtual ~PxsHeapMemoryAllocatorManager() {}
virtual PxU64 getDeviceMemorySize() const = 0;
virtual PxsHeapStats getDeviceHeapStats() const = 0;
PxsHeapMemoryAllocator* mMappedMemoryAllocators;
};
}
#endif
| 3,077 | C | 31.4 | 101 | 0.747806 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsNphaseImplementationContext.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 PXS_NPHASE_IMPLEMENTATION_CONTEXT_H
#define PXS_NPHASE_IMPLEMENTATION_CONTEXT_H
#include "PxvNphaseImplementationContext.h"
#include "PxsContactManagerState.h"
#include "PxcNpCache.h"
#include "foundation/PxPinnedArray.h"
class PxsCMDiscreteUpdateTask;
namespace physx
{
struct PxsContactManagers : PxsContactManagerBase
{
PxArray<PxsContactManagerOutput> mOutputContactManagers;
PxArray<PxsContactManager*> mContactManagerMapping;
PxArray<Gu::Cache> mCaches;
PxPinnedArray<Sc::ShapeInteraction*> mShapeInteractions;
PxFloatArrayPinned mRestDistances;
PxPinnedArray<PxsTorsionalFrictionData> mTorsionalProperties;
PxsContactManagers(const PxU32 bucketId, PxVirtualAllocatorCallback* callback) : PxsContactManagerBase(bucketId),
mOutputContactManagers ("mOutputContactManagers"),
mContactManagerMapping ("mContactManagerMapping"),
mCaches ("mCaches"),
mShapeInteractions (PxVirtualAllocator(callback)),
mRestDistances (callback),
mTorsionalProperties (callback)
{
}
void clear()
{
mOutputContactManagers.forceSize_Unsafe(0);
mContactManagerMapping.forceSize_Unsafe(0);
mCaches.forceSize_Unsafe(0);
mShapeInteractions.forceSize_Unsafe(0);
mRestDistances.forceSize_Unsafe(0);
mTorsionalProperties.forceSize_Unsafe(0);
}
private:
PX_NOCOPY(PxsContactManagers)
};
class PxsNphaseImplementationContext : public PxvNphaseImplementationContextUsableAsFallback
{
public:
PxsNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* callback, PxU32 index, bool gpu) :
PxvNphaseImplementationContextUsableAsFallback (context),
mNarrowPhasePairs (index, callback),
mNewNarrowPhasePairs (index, callback),
mModifyCallback (NULL),
mIslandSim (islandSim),
mGPU (gpu)
{}
// PxvNphaseImplementationContext
virtual void destroy() PX_OVERRIDE;
virtual void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation,
PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShape) PX_OVERRIDE;
virtual void postBroadPhaseUpdateContactManager(PxBaseTask*) PX_OVERRIDE {}
virtual void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchUpdateContactManager() PX_OVERRIDE {}
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 numPatches) PX_OVERRIDE;
// virtual void registerContactManagers(PxsContactManager** cm, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId);
virtual void unregisterContactManager(PxsContactManager* cm) PX_OVERRIDE;
virtual void refreshContactManager(PxsContactManager* cm) PX_OVERRIDE;
virtual void registerShape(const PxNodeIndex& /*nodeIndex*/, const PxsShapeCore& /*shapeCore*/, const PxU32 /*transformCacheID*/, PxActor* /*actor*/, const bool /*isFemCloth*/) PX_OVERRIDE {}
virtual void unregisterShape(const PxsShapeCore& /*shapeCore*/, const PxU32 /*transformCacheID*/, const bool /*isFemCloth*/) PX_OVERRIDE {}
virtual void registerAggregate(const PxU32 /*transformCacheID*/) PX_OVERRIDE {}
virtual void registerMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void updateShapeMaterial(const PxsShapeCore&) PX_OVERRIDE {}
virtual void startNarrowPhaseTasks() PX_OVERRIDE {}
virtual void appendContactManagers() PX_OVERRIDE;
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 npIndex) PX_OVERRIDE;
virtual PxsContactManagerOutputIterator getContactManagerOutputs() PX_OVERRIDE;
virtual void setContactModifyCallback(PxContactModifyCallback* callback) PX_OVERRIDE { mModifyCallback = callback; }
virtual void acquireContext() PX_OVERRIDE {}
virtual void releaseContext() PX_OVERRIDE {}
virtual void preallocateNewBuffers(PxU32 /*nbNewPairs*/, PxU32 /*maxIndex*/) PX_OVERRIDE { /*TODO - implement if it's useful to do so*/}
virtual void lock() PX_OVERRIDE { mContactManagerMutex.lock(); }
virtual void unlock() PX_OVERRIDE { mContactManagerMutex.unlock(); }
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() PX_OVERRIDE { return mCmFoundLostOutputCounts.begin(); }
virtual PxsContactManager** getFoundPatchManagers() PX_OVERRIDE { return mCmFoundLost.begin(); }
virtual PxU32 getNbFoundPatchManagers() PX_OVERRIDE { return mCmFoundLost.size(); }
virtual PxsContactManagerOutput* getGPUContactManagerOutputBase() PX_OVERRIDE { return NULL; }
virtual PxReal* getGPURestDistances() PX_OVERRIDE { return NULL; }
virtual Sc::ShapeInteraction** getGPUShapeInteractions() PX_OVERRIDE { return NULL; }
virtual PxsTorsionalFrictionData* getGPUTorsionalData() PX_OVERRIDE { return NULL; }
//~PxvNphaseImplementationContext
// PxvNphaseImplementationFallback
virtual void processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation) PX_OVERRIDE;
virtual void processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation) PX_OVERRIDE;
virtual void unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void appendContactManagersFallback(PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void removeContactManagersFallback(PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual Sc::ShapeInteraction** getShapeInteractions() PX_OVERRIDE { return mNarrowPhasePairs.mShapeInteractions.begin(); }
virtual PxReal* getRestDistances() PX_OVERRIDE { return mNarrowPhasePairs.mRestDistances.begin(); }
virtual PxsTorsionalFrictionData* getTorsionalData() PX_OVERRIDE { return mNarrowPhasePairs.mTorsionalProperties.begin(); }
//~PxvNphaseImplementationFallback
PxArray<PxU32> mRemovedContactManagers;
PxsContactManagers mNarrowPhasePairs;
PxsContactManagers mNewNarrowPhasePairs;
PxContactModifyCallback* mModifyCallback;
IG::IslandSim* mIslandSim;
PxMutex mContactManagerMutex;
PxArray<PxsCMDiscreteUpdateTask*> mCmTasks;
PxArray<PxsContactManagerOutputCounts> mCmFoundLostOutputCounts;
PxArray<PxsContactManager*> mCmFoundLost;
const bool mGPU;
private:
void unregisterContactManagerInternal(PxU32 npIndex, PxsContactManagers& managers, PxsContactManagerOutput* cmOutputs);
PX_FORCE_INLINE void unregisterAndForceSize(PxsContactManagers& cms, PxU32 index)
{
unregisterContactManagerInternal(index, cms, cms.mOutputContactManagers.begin());
cms.mOutputContactManagers.forceSize_Unsafe(cms.mOutputContactManagers.size()-1);
}
void appendNewLostPairs();
PX_NOCOPY(PxsNphaseImplementationContext)
};
}
#endif
| 10,239 | C | 49.945273 | 198 | 0.762867 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsIslandManagerTypes.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 PXS_ISLAND_MANAGER_TYPES_H
#define PXS_ISLAND_MANAGER_TYPES_H
namespace physx
{
class PxsContactManager;
namespace Dy
{
struct Constraint;
}
typedef PxU32 NodeType;
typedef PxU32 EdgeType;
typedef PxU32 IslandType;
#define INVALID_NODE 0xffffffff
#define INVALID_EDGE 0xffffffff
#define INVALID_ISLAND 0xffffffff
class PxsIslandIndices
{
public:
PxsIslandIndices() {}
~PxsIslandIndices() {}
NodeType bodies;
NodeType articulations;
EdgeType contactManagers;
EdgeType constraints;
};
typedef PxU64 PxsNodeType;
/**
\brief Each contact manager or constraint references two separate bodies, where
a body can be a dynamic rigid body, a kinematic rigid body, an articulation or a static.
The struct PxsIndexedInteraction describes the bodies that make up the pair.
*/
struct PxsIndexedInteraction
{
/**
\brief An enumerated list of all possible body types.
A body type is stored for each body in the pair.
*/
enum Enum
{
eBODY = 0,
eKINEMATIC = 1,
eARTICULATION = 2,
eWORLD = 3
};
/**
\brief An index describing how to access body0
\note If body0 is a dynamic (eBODY) rigid body then solverBody0 is an index into PxsIslandObjects::bodies.
\note If body0 is a kinematic (eKINEMATIC) rigid body then solverBody0 is an index into PxsIslandManager::getActiveKinematics.
\note If body0 is a static (eWORLD) then solverBody0 is PX_MAX_U32 or PX_MAX_U64, depending on the platform being 32- or 64-bit.
\note If body0 is an articulation then the articulation is found directly from Dy::getArticulation(articulation0)
\note If body0 is an soft body then the soft body is found directly from Dy::getSoftBody(softBody0)
*/
union
{
PxsNodeType solverBody0;
PxsNodeType articulation0;
};
/**
\brief An index describing how to access body1
\note If body1 is a dynamic (eBODY) rigid body then solverBody1 is an index into PxsIslandObjects::bodies.
\note If body1 is a kinematic (eKINEMATIC) rigid body then solverBody1 is an index into PxsIslandManager::getActiveKinematics.
\note If body1 is a static (eWORLD) then solverBody1 is PX_MAX_U32 or PX_MAX_U64, depending on the platform being 32- or 64-bit.
\note If body1 is an articulation then the articulation is found directly from Dy::getArticulation(articulation1)
\note If body0 is an soft body then the soft body is found directly from Dy::getSoftBody(softBody1)
*/
union
{
PxsNodeType solverBody1;
PxsNodeType articulation1;
};
/**
\brief The type (eBODY, eKINEMATIC etc) of body0
*/
PxU8 indexType0;
/**
\brief The type (eBODY, eKINEMATIC etc) of body1
*/
PxU8 indexType1;
PxU8 pad[2];
};
/**
@see PxsIslandObjects, PxsIndexedInteraction
*/
struct PxsIndexedContactManager : public PxsIndexedInteraction
{
/**
\brief The contact manager corresponds to the value set in PxsIslandManager::setEdgeRigidCM
*/
PxsContactManager* contactManager;
PxsIndexedContactManager(PxsContactManager* cm) : contactManager(cm) {}
};
#if !PX_X64
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxsIndexedContactManager) & 0x0f));
#endif
/**
@see PxsIslandObjects, PxsIndexedInteraction
*/
struct PxsIndexedConstraint : public PxsIndexedInteraction
{
/**
\brief The constraint corresponds to the value set in PxsIslandManager::setEdgeConstraint
*/
Dy::Constraint* constraint;
PxsIndexedConstraint(Dy::Constraint* c) : constraint(c) {}
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxsIndexedConstraint) & 0x0f));
#endif
} //namespace physx
#endif
| 5,169 | C | 30.333333 | 129 | 0.762623 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsMaterialCombiner.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 PXS_MATERIAL_COMBINER_H
#define PXS_MATERIAL_COMBINER_H
#include "PxsMaterialCore.h"
namespace physx
{
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal combineScalars(PxReal a, PxReal b, PxI32 combineMode)
{
switch (combineMode)
{
case PxCombineMode::eAVERAGE:
return 0.5f * (a + b);
case PxCombineMode::eMIN:
return PxMin(a,b);
case PxCombineMode::eMULTIPLY:
return a * b;
case PxCombineMode::eMAX:
return PxMax(a,b);
default:
return PxReal(0);
}
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal PxsCombineRestitution(const PxsMaterialData& mat0, const PxsMaterialData& mat1)
{
return combineScalars(mat0.restitution, mat1.restitution, ((mat0.flags | mat1.flags) & PxMaterialFlag::eCOMPLIANT_CONTACT) ?
PxCombineMode::eMIN : PxMax(mat0.getRestitutionCombineMode(), mat1.getRestitutionCombineMode()));
}
//ML:: move this function to header file to avoid LHS in Xbox
//PT: also called by CUDA code now
PX_CUDA_CALLABLE PX_FORCE_INLINE void PxsCombineIsotropicFriction(const PxsMaterialData& mat0, const PxsMaterialData& mat1, PxReal& dynamicFriction, PxReal& staticFriction, PxU32& flags)
{
const PxU32 combineFlags = (mat0.flags | mat1.flags); //& (PxMaterialFlag::eDISABLE_STRONG_FRICTION|PxMaterialFlag::eDISABLE_FRICTION); //eventually set DisStrongFric flag, lower all others.
if (!(combineFlags & PxMaterialFlag::eDISABLE_FRICTION))
{
const PxI32 fictionCombineMode = PxMax(mat0.getFrictionCombineMode(), mat1.getFrictionCombineMode());
PxReal dynFriction = 0.0f;
PxReal staFriction = 0.0f;
switch (fictionCombineMode)
{
case PxCombineMode::eAVERAGE:
dynFriction = 0.5f * (mat0.dynamicFriction + mat1.dynamicFriction);
staFriction = 0.5f * (mat0.staticFriction + mat1.staticFriction);
break;
case PxCombineMode::eMIN:
dynFriction = PxMin(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMin(mat0.staticFriction, mat1.staticFriction);
break;
case PxCombineMode::eMULTIPLY:
dynFriction = (mat0.dynamicFriction * mat1.dynamicFriction);
staFriction = (mat0.staticFriction * mat1.staticFriction);
break;
case PxCombineMode::eMAX:
dynFriction = PxMax(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMax(mat0.staticFriction, mat1.staticFriction);
break;
}
//isotropic case
const PxReal fDynFriction = PxMax(dynFriction, 0.0f);
// PT: TODO: the two branches aren't actually doing the same thing:
// - one is ">", the other is ">="
// - one uses a clamped dynFriction, the other not
#ifdef __CUDACC__
const PxReal fStaFriction = (staFriction - fDynFriction) > 0 ? staFriction : dynFriction;
#else
const PxReal fStaFriction = physx::intrinsics::fsel(staFriction - fDynFriction, staFriction, fDynFriction);
#endif
dynamicFriction = fDynFriction;
staticFriction = fStaFriction;
flags = combineFlags;
}
else
{
flags = combineFlags | PxMaterialFlag::eDISABLE_STRONG_FRICTION;
dynamicFriction = 0.0f;
staticFriction = 0.0f;
}
}
}
#endif
| 4,746 | C | 39.922413 | 192 | 0.741256 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsTransformCache.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 PXS_TRANSFORM_CACHE_H
#define PXS_TRANSFORM_CACHE_H
#include "CmIDPool.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxPinnedArray.h"
#define PX_DEFAULT_CACHE_SIZE 512
namespace physx
{
struct PxsTransformFlag
{
enum Flags
{
eFROZEN = (1 << 0)
};
};
struct PX_ALIGN_PREFIX(16) PxsCachedTransform
{
PxTransform transform;
PxU32 flags;
PX_FORCE_INLINE PxU32 isFrozen() const { return flags & PxsTransformFlag::eFROZEN; }
}
PX_ALIGN_SUFFIX(16);
class PxsTransformCache : public PxUserAllocated
{
typedef PxU32 RefCountType;
public:
PxsTransformCache(PxVirtualAllocatorCallback& allocatorCallback) : mTransformCache(PxVirtualAllocator(&allocatorCallback)), mHasAnythingChanged(true)
{
/*mTransformCache.reserve(PX_DEFAULT_CACHE_SIZE);
mTransformCache.forceSize_Unsafe(PX_DEFAULT_CACHE_SIZE);*/
mUsedSize = 0;
}
void initEntry(PxU32 index)
{
PxU32 oldCapacity = mTransformCache.capacity();
if (index >= oldCapacity)
{
PxU32 newCapacity = PxNextPowerOfTwo(index);
mTransformCache.reserve(newCapacity);
mTransformCache.forceSize_Unsafe(newCapacity);
}
mUsedSize = PxMax(mUsedSize, index + 1u);
}
PX_FORCE_INLINE void setTransformCache(const PxTransform& transform, const PxU32 flags, const PxU32 index)
{
mTransformCache[index].transform = transform;
mTransformCache[index].flags = flags;
mHasAnythingChanged = true;
}
PX_FORCE_INLINE const PxsCachedTransform& getTransformCache(const PxU32 index) const
{
return mTransformCache[index];
}
PX_FORCE_INLINE PxsCachedTransform& getTransformCache(const PxU32 index)
{
return mTransformCache[index];
}
PX_FORCE_INLINE void shiftTransforms(const PxVec3& shift)
{
for (PxU32 i = 0; i < mTransformCache.capacity(); i++)
{
mTransformCache[i].transform.p += shift;
}
mHasAnythingChanged = true;
}
PX_FORCE_INLINE PxU32 getTotalSize() const
{
return mUsedSize;
}
PX_FORCE_INLINE const PxsCachedTransform* getTransforms() const
{
return mTransformCache.begin();
}
PX_FORCE_INLINE PxsCachedTransform* getTransforms()
{
return mTransformCache.begin();
}
PX_FORCE_INLINE PxPinnedArray<PxsCachedTransform>* getCachedTransformArray()
{
return &mTransformCache;
}
PX_FORCE_INLINE void resetChangedState() { mHasAnythingChanged = false; }
PX_FORCE_INLINE void setChangedState() { mHasAnythingChanged = true; }
PX_FORCE_INLINE bool hasChanged() const { return mHasAnythingChanged; }
private:
PxPinnedArray<PxsCachedTransform> mTransformCache;
PxU32 mUsedSize;
bool mHasAnythingChanged;
};
}
#endif
| 4,428 | C | 30.411347 | 151 | 0.74458 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsSimpleIslandManager.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 PXS_SIMPLE_ISLAND_GEN_H
#define PXS_SIMPLE_ISLAND_GEN_H
#include "foundation/PxUserAllocated.h"
#include "PxsIslandSim.h"
#include "CmTask.h"
namespace physx
{
// PT: TODO: fw declaring an Sc class here is not good
namespace Sc
{
class Interaction;
}
namespace IG
{
class SimpleIslandManager;
class ThirdPassTask : public Cm::Task
{
SimpleIslandManager& mIslandManager;
IslandSim& mIslandSim;
public:
ThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager, IslandSim& islandSim);
virtual void runInternal();
virtual const char* getName() const
{
return "ThirdPassIslandGenTask";
}
private:
PX_NOCOPY(ThirdPassTask)
};
class PostThirdPassTask : public Cm::Task
{
SimpleIslandManager& mIslandManager;
public:
PostThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager);
virtual void runInternal();
virtual const char* getName() const
{
return "PostThirdPassTask";
}
private:
PX_NOCOPY(PostThirdPassTask)
};
class SimpleIslandManager : public PxUserAllocated
{
HandleManager<PxU32> mNodeHandles; //! Handle manager for nodes
HandleManager<EdgeIndex> mEdgeHandles; //! Handle manager for edges
//An array of destroyed nodes
PxArray<PxNodeIndex> mDestroyedNodes;
Cm::BlockArray<Sc::Interaction*> mInteractions;
//Edges destroyed this frame
PxArray<EdgeIndex> mDestroyedEdges;
PxArray<PartitionEdge*> mFirstPartitionEdges;
PxArray<PartitionEdge*> mDestroyedPartitionEdges;
//KS - stores node indices for a given edge. Node index 0 is at 2* edgeId and NodeIndex1 is at 2*edgeId + 1
//can also be used for edgeInstance indexing so there's no need to figure out outboundNode ID either!
Cm::BlockArray<PxNodeIndex> mEdgeNodeIndices;
Cm::BlockArray<void*> mConstraintOrCm; //! Pointers to either the constraint or Cm for this pair
PxBitMap mConnectedMap;
IslandSim mIslandManager;
IslandSim mSpeculativeIslandManager;
ThirdPassTask mSpeculativeThirdPassTask;
ThirdPassTask mAccurateThirdPassTask;
PostThirdPassTask mPostThirdPassTask;
PxU32 mMaxDirtyNodesPerFrame;
PxU64 mContextID;
public:
SimpleIslandManager(bool useEnhancedDeterminism, PxU64 contextID);
~SimpleIslandManager();
PxNodeIndex addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive);
void removeNode(const PxNodeIndex index);
PxNodeIndex addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive);
#if PX_SUPPORT_GPU_PHYSX
PxNodeIndex addSoftBody(Dy::SoftBody* llSoftBody, bool isActive);
PxNodeIndex addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive);
PxNodeIndex addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive);
PxNodeIndex addHairSystem(Dy::HairSystem* llHairSystem, bool isActive);
#endif
EdgeIndex addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction,
Edge::EdgeType edgeType);
EdgeIndex addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction);
bool isConnected(EdgeIndex edgeIndex) const { return !!mConnectedMap.test(edgeIndex); }
PX_FORCE_INLINE PxNodeIndex getEdgeIndex(EdgeInstanceIndex edgeIndex) const { return mEdgeNodeIndices[edgeIndex]; }
void activateNode(PxNodeIndex index);
void deactivateNode(PxNodeIndex index);
void putNodeToSleep(PxNodeIndex index);
void removeConnection(EdgeIndex edgeIndex);
void firstPassIslandGen();
void additionalSpeculativeActivation();
void secondPassIslandGen();
void thirdPassIslandGen(PxBaseTask* continuation);
PX_INLINE void clearDestroyedEdges()
{
mDestroyedPartitionEdges.forceSize_Unsafe(0);
}
void setEdgeConnected(EdgeIndex edgeIndex, Edge::EdgeType edgeType);
void setEdgeDisconnected(EdgeIndex edgeIndex);
bool getIsEdgeConnected(EdgeIndex edgeIndex);
void setEdgeRigidCM(const EdgeIndex edgeIndex, PxsContactManager* cm);
void clearEdgeRigidCM(const EdgeIndex edgeIndex);
void setKinematic(PxNodeIndex nodeIndex);
void setDynamic(PxNodeIndex nodeIndex);
const IslandSim& getSpeculativeIslandSim() const { return mSpeculativeIslandManager; }
const IslandSim& getAccurateIslandSim() const { return mIslandManager; }
IslandSim& getAccurateIslandSim() { return mIslandManager; }
IslandSim& getSpeculativeIslandSim() { return mSpeculativeIslandManager; }
PX_FORCE_INLINE PxU32 getNbEdgeHandles() const { return mEdgeHandles.getTotalHandles(); }
PX_FORCE_INLINE PxU32 getNbNodeHandles() const { return mNodeHandles.getTotalHandles(); }
void deactivateEdge(const EdgeIndex edge);
PX_FORCE_INLINE PxsContactManager* getContactManager(IG::EdgeIndex edgeId) const { return reinterpret_cast<PxsContactManager*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE PxsContactManager* getContactManagerUnsafe(IG::EdgeIndex edgeId) const { return reinterpret_cast<PxsContactManager*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Dy::Constraint* getConstraint(IG::EdgeIndex edgeId) const { return reinterpret_cast<Dy::Constraint*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Dy::Constraint* getConstraintUnsafe(IG::EdgeIndex edgeId) const { return reinterpret_cast<Dy::Constraint*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Sc::Interaction* getInteraction(IG::EdgeIndex edgeId) const { return mInteractions[edgeId]; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
bool checkInternalConsistency();
private:
friend class ThirdPassTask;
friend class PostThirdPassTask;
bool validateDeactivations() const;
PX_NOCOPY(SimpleIslandManager)
};
}
}
#endif
| 7,239 | C | 32.99061 | 161 | 0.790026 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContactManager.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 PXS_CONTACT_MANAGER_H
#define PXS_CONTACT_MANAGER_H
#include "PxvConfig.h"
#include "PxcNpWorkUnit.h"
namespace physx
{
class PxsContext;
class PxsRigidBody;
namespace Dy
{
class DynamicsContext;
}
namespace Sc
{
class ShapeInteraction;
}
/**
\brief Additional header structure for CCD contact data stream.
*/
struct PxsCCDContactHeader
{
/**
\brief Stream for next collision. The same pair can collide multiple times during multiple CCD passes.
*/
PxsCCDContactHeader* nextStream; //4 //8
/**
\brief Size (in bytes) of the CCD contact stream (not including force buffer)
*/
PxU16 contactStreamSize; //6 //10
/**
\brief Defines whether the stream is from a previous pass.
It could happen that the stream can not get allocated because we run out of memory. In that case the current event should not use the stream
from an event of the previous pass.
*/
PxU16 isFromPreviousPass; //8 //12
PxU8 pad[12 - sizeof(PxsCCDContactHeader*)]; //16
};
PX_COMPILE_TIME_ASSERT((sizeof(PxsCCDContactHeader) & 0xF) == 0);
class PxsContactManager
{
public:
PxsContactManager(PxsContext* context, PxU32 index);
~PxsContactManager();
PX_FORCE_INLINE void setDisableStrongFriction(PxU32 d) { (!d) ? mNpUnit.flags &= ~PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION
: mNpUnit.flags |= PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION; }
PX_FORCE_INLINE PxReal getRestDistance() const { return mNpUnit.restDistance; }
PX_FORCE_INLINE void setRestDistance(PxReal v) { mNpUnit.restDistance = v; }
PX_FORCE_INLINE PxU8 getDominance0() const { return mNpUnit.dominance0; }
PX_FORCE_INLINE void setDominance0(PxU8 v) { mNpUnit.dominance0 = v; }
PX_FORCE_INLINE PxU8 getDominance1() const { return mNpUnit.dominance1; }
PX_FORCE_INLINE void setDominance1(PxU8 v) { mNpUnit.dominance1 = v; }
PX_FORCE_INLINE PxU16 getTouchStatus() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH); }
PX_FORCE_INLINE PxU16 touchStatusKnown() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eTOUCH_KNOWN); }
PX_FORCE_INLINE PxI32 getTouchIdx() const { return (mNpUnit.statusFlags& PxcNpWorkUnitStatusFlag::eHAS_TOUCH) ? 1 : (mNpUnit.statusFlags& PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH ? -1 : 0); }
PX_FORCE_INLINE PxU32 getIndex() const { return mNpUnit.index; }
PX_FORCE_INLINE PxU16 getHasCCDRetouch() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH); }
PX_FORCE_INLINE void clearCCDRetouch() { mNpUnit.statusFlags &= ~PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH; }
PX_FORCE_INLINE void raiseCCDRetouch() { mNpUnit.statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH; }
// flags stuff - needs to be refactored
PX_FORCE_INLINE PxIntBool isChangeable() const { return PxIntBool(mFlags & PXS_CM_CHANGEABLE); }
PX_FORCE_INLINE PxIntBool getCCD() const { return PxIntBool((mFlags & PXS_CM_CCD_LINEAR) && (mNpUnit.flags & PxcNpWorkUnitFlag::eDETECT_CCD_CONTACTS)); }
PX_FORCE_INLINE PxIntBool getHadCCDContact() const { return PxIntBool(mFlags & PXS_CM_CCD_CONTACT); }
PX_FORCE_INLINE void setHadCCDContact() { mFlags |= PXS_CM_CCD_CONTACT; }
void setCCD(bool enable);
PX_FORCE_INLINE void clearCCDContactInfo() { mFlags &= ~PXS_CM_CCD_CONTACT; mNpUnit.ccdContacts = NULL; }
PX_FORCE_INLINE PxcNpWorkUnit& getWorkUnit() { return mNpUnit; }
PX_FORCE_INLINE const PxcNpWorkUnit& getWorkUnit() const { return mNpUnit; }
PX_FORCE_INLINE Sc::ShapeInteraction* getShapeInteraction() const { return mShapeInteraction; }
// Setup solver-constraints
PX_FORCE_INLINE void resetCachedState()
{
// happens when the body transform or shape relative transform changes.
mNpUnit.clearCachedState();
}
private:
//KS - moving this up - we want to get at flags
PxsRigidBody* mRigidBody0; //4 //8
PxsRigidBody* mRigidBody1; //8 //16
PxU32 mFlags; //20 //36
Sc::ShapeInteraction* mShapeInteraction; //16 //32
friend class PxsContext;
// everything required for narrow phase to run
PxcNpWorkUnit mNpUnit;
enum
{
PXS_CM_CHANGEABLE = (1<<0),
PXS_CM_CCD_LINEAR = (1<<1),
PXS_CM_CCD_CONTACT = (1 << 2)
};
friend class Dy::DynamicsContext;
friend struct PxsCCDPair;
friend class PxsCCDContext;
friend class Sc::ShapeInteraction;
};
}
#endif
| 6,276 | C | 40.569536 | 197 | 0.715105 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxvNphaseImplementationContext.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 PXV_NPHASE_IMPLEMENTATION_CONTEXT_H
#define PXV_NPHASE_IMPLEMENTATION_CONTEXT_H
#include "PxSceneDesc.h"
#include "PxsContactManagerState.h"
#include "foundation/PxArray.h"
#include "PxsNphaseCommon.h"
// PT: TODO: forward decl don't work easily with templates, to revisit
#include "PxsMaterialCore.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "PxsPBDMaterialCore.h"
namespace physx
{
namespace IG
{
class IslandSim;
typedef PxU32 EdgeIndex;
}
namespace Cm
{
class FanoutTask;
}
namespace Sc
{
class ShapeInteraction;
}
class PxNodeIndex;
class PxBaseTask;
class PxsContext;
struct PxsShapeCore;
class PxsContactManager;
struct PxsContactManagerOutput;
struct PxsTorsionalFrictionData;
class PxsContactManagerOutputIterator
{
PxU32 mOffsets[1<<PxsContactManagerBase::MaxBucketBits];
PxsContactManagerOutput* mOutputs;
public:
PxsContactManagerOutputIterator() : mOutputs(NULL)
{
}
PxsContactManagerOutputIterator(PxU32* offsets, PxU32 nbOffsets, PxsContactManagerOutput* outputs) : mOutputs(outputs)
{
PX_ASSERT(nbOffsets <= (1<<PxsContactManagerBase::MaxBucketBits));
for(PxU32 a = 0; a < nbOffsets; ++a)
{
mOffsets[a] = offsets[a];
}
}
PX_FORCE_INLINE PxsContactManagerOutput& getContactManager(PxU32 id)
{
PX_ASSERT((id & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) == 0);
PxU32 bucketId = PxsContactManagerBase::computeBucketIndexFromId(id);
PxU32 cmOutId = PxsContactManagerBase::computeIndexFromId(id);
return mOutputs[mOffsets[bucketId] + cmOutId];
}
PxU32 getIndex(PxU32 id)
{
PX_ASSERT((id & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) == 0);
PxU32 bucketId = PxsContactManagerBase::computeBucketIndexFromId(id);
PxU32 cmOutId = PxsContactManagerBase::computeIndexFromId(id);
return mOffsets[bucketId] + cmOutId;
}
};
class PxvNphaseImplementationContext
{
private:
PX_NOCOPY(PxvNphaseImplementationContext)
public:
PxvNphaseImplementationContext(PxsContext& context): mContext(context) {}
virtual ~PxvNphaseImplementationContext() {}
virtual void destroy() = 0;
virtual void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation, PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShapeTask) = 0;
virtual void postBroadPhaseUpdateContactManager(PxBaseTask* continuation) = 0;
virtual void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation) = 0;
virtual void fetchUpdateContactManager() = 0;
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* interaction, PxI32 touching, PxU32 patchCount) = 0;
// virtual void registerContactManagers(PxsContactManager** cm, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId) = 0;
virtual void unregisterContactManager(PxsContactManager* cm) = 0;
virtual void refreshContactManager(PxsContactManager* cm) = 0;
virtual void registerShape(const PxNodeIndex& nodeIndex, const PxsShapeCore& shapeCore, const PxU32 transformCacheID, PxActor* actor, const bool isFemCloth = false) = 0;
virtual void unregisterShape(const PxsShapeCore& shapeCore, const PxU32 transformCacheID, const bool isFemCloth = false) = 0;
virtual void registerAggregate(const PxU32 transformCacheID) = 0;
virtual void registerMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void updateShapeMaterial(const PxsShapeCore& shapeCore) = 0;
virtual void startNarrowPhaseTasks() = 0;
virtual void appendContactManagers() = 0;
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 index) = 0;
virtual PxsContactManagerOutputIterator getContactManagerOutputs() = 0;
virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0;
virtual void acquireContext() = 0;
virtual void releaseContext() = 0;
virtual void preallocateNewBuffers(PxU32 nbNewPairs, PxU32 maxIndex) = 0;
virtual void lock() = 0;
virtual void unlock() = 0;
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() = 0;
virtual PxsContactManager** getFoundPatchManagers() = 0;
virtual PxU32 getNbFoundPatchManagers() = 0;
//GPU-specific buffers. Return null for CPU narrow phase
virtual PxsContactManagerOutput* getGPUContactManagerOutputBase() = 0;
virtual PxReal* getGPURestDistances() = 0;
virtual Sc::ShapeInteraction** getGPUShapeInteractions() = 0;
virtual PxsTorsionalFrictionData* getGPUTorsionalData() = 0;
protected:
PxsContext& mContext;
};
class PxvNphaseImplementationFallback
{
private:
PX_NOCOPY(PxvNphaseImplementationFallback)
public:
PxvNphaseImplementationFallback() {}
virtual ~PxvNphaseImplementationFallback() {}
virtual void processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation) = 0;
virtual void processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?! Should be "registerContactManagerFallback"...
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 numPatches) = 0;
virtual void unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) = 0;
virtual void refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 npId) = 0;
virtual void appendContactManagersFallback(PxsContactManagerOutput* outputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0;
virtual void removeContactManagersFallback(PxsContactManagerOutput* cmOutputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual void lock() = 0;
virtual void unlock() = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() = 0;
virtual PxsContactManager** getFoundPatchManagers() = 0;
virtual PxU32 getNbFoundPatchManagers() = 0;
virtual Sc::ShapeInteraction** getShapeInteractions() = 0;
virtual PxReal* getRestDistances() = 0;
virtual PxsTorsionalFrictionData* getTorsionalData() = 0;
};
class PxvNphaseImplementationContextUsableAsFallback: public PxvNphaseImplementationContext, public PxvNphaseImplementationFallback
{
private:
PX_NOCOPY(PxvNphaseImplementationContextUsableAsFallback)
public:
PxvNphaseImplementationContextUsableAsFallback(PxsContext& context) : PxvNphaseImplementationContext(context) {}
virtual ~PxvNphaseImplementationContextUsableAsFallback() {}
};
PxvNphaseImplementationContextUsableAsFallback* createNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* allocator, bool gpuDynamics);
}
#endif
| 10,453 | C | 40.816 | 189 | 0.773271 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContext.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 PXS_CONTEXT_H
#define PXS_CONTEXT_H
#include "foundation/PxPinnedArray.h"
#include "PxVisualizationParameter.h"
#include "PxSceneDesc.h"
#include "common/PxRenderOutput.h"
#include "CmPool.h"
#include "PxvNphaseImplementationContext.h"
#include "PxvSimStats.h"
#include "PxsContactManager.h"
#include "PxcNpBatch.h"
#include "PxcConstraintBlockStream.h"
#include "PxcNpCacheStreamPair.h"
#include "PxcNpMemBlockPool.h"
#include "CmUtils.h"
#include "CmTask.h"
#include "PxContactModifyCallback.h"
#include "PxsTransformCache.h"
#include "GuPersistentContactManifold.h"
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
class PxCudaContextManager;
}
#endif
namespace physx
{
class PxsRigidBody;
struct PxcConstraintBlock;
class PxsMaterialManager;
class PxsCCDContext;
struct PxsContactManagerOutput;
struct PxvContactManagerTouchEvent;
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
typedef PxU32 EdgeIndex;
}
enum PxsTouchEventCount
{
PXS_LOST_TOUCH_COUNT,
PXS_NEW_TOUCH_COUNT,
PXS_CCD_RETOUCH_COUNT, // pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// (but they could have lost touch in between)
PXS_TOUCH_EVENT_COUNT
};
class PxsContext : public PxUserAllocated, public PxcNpContext
{
PX_NOCOPY(PxsContext)
public:
PxsContext( const PxSceneDesc& desc, PxTaskManager*, Cm::FlushPool&, PxCudaContextManager*, PxU32 poolSlabSize, PxU64 contextID);
~PxsContext();
void createTransformCache(PxVirtualAllocatorCallback& allocatorCallback);
PxsContactManager* createContactManager(PxsContactManager* contactManager, bool useCCD);
void createCache(Gu::Cache& cache, PxGeometryType::Enum geomType0, PxGeometryType::Enum geomType1);
void destroyCache(Gu::Cache& cache);
void destroyContactManager(PxsContactManager* cm);
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
// Collision properties
PX_FORCE_INLINE PxContactModifyCallback* getContactModifyCallback() const { return mContactModifyCallback; }
PX_FORCE_INLINE void setContactModifyCallback(PxContactModifyCallback* c) { mContactModifyCallback = c; mNpImplementationContext->setContactModifyCallback(c);}
// resource-related
void setScratchBlock(void* addr, PxU32 size);
PX_FORCE_INLINE void setContactDistance(const PxFloatArrayPinned* contactDistances) { mContactDistances = contactDistances; }
// Task-related
void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation,
PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShapeTask);
void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation);
void fetchUpdateContactManager();
void swapStreams();
void resetThreadContexts();
// Manager status change
bool getManagerTouchEventCount(int* newTouch, int* lostTouch, int* ccdTouch) const;
bool fillManagerTouchEvents(
PxvContactManagerTouchEvent* newTouch, PxI32& newTouchCount,
PxvContactManagerTouchEvent* lostTouch, PxI32& lostTouchCount,
PxvContactManagerTouchEvent* ccdTouch, PxI32& ccdTouchCount);
void beginUpdate();
// PX_ENABLE_SIM_STATS
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE const PxvSimStats& getSimStats() const { return mSimStats; }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() const { return mTaskPool; }
PX_FORCE_INLINE PxRenderBuffer& getRenderBuffer() { return mRenderBuffer; }
PX_FORCE_INLINE PxReal getRenderScale() const { return mVisualizationParams[PxVisualizationParameter::eSCALE]; }
PX_FORCE_INLINE PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const
{
PX_ASSERT(param < PxVisualizationParameter::eNUM_VALUES);
return mVisualizationParams[param];
}
PX_FORCE_INLINE void setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value)
{
PX_ASSERT(param < PxVisualizationParameter::eNUM_VALUES);
PX_ASSERT(value >= 0.0f);
mVisualizationParams[param] = value;
}
PX_FORCE_INLINE void setVisualizationCullingBox(const PxBounds3& box) { mVisualizationCullingBox = box; }
PX_FORCE_INLINE const PxBounds3& getVisualizationCullingBox() const { return mVisualizationCullingBox; }
PX_FORCE_INLINE bool getPCM() const { return mPCM; }
PX_FORCE_INLINE bool getContactCacheFlag() const { return mContactCache; }
PX_FORCE_INLINE bool getCreateAveragePoint() const { return mCreateAveragePoint; }
// general stuff
void shiftOrigin(const PxVec3& shift);
PX_FORCE_INLINE void setPCM(bool enabled) { mPCM = enabled; }
PX_FORCE_INLINE void setContactCache(bool enabled) { mContactCache = enabled; }
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
PX_FORCE_INLINE PxsTransformCache& getTransformCache() { return *mTransformCache; }
PX_FORCE_INLINE const PxReal* getContactDistances() const { return mContactDistances->begin(); }
PX_FORCE_INLINE PxvNphaseImplementationContext* getNphaseImplementationContext() const { return mNpImplementationContext; }
PX_FORCE_INLINE void setNphaseImplementationContext(PxvNphaseImplementationContext* ctx) { mNpImplementationContext = ctx; }
PX_FORCE_INLINE PxvNphaseImplementationContext* getNphaseFallbackImplementationContext() const { return mNpFallbackImplementationContext; }
PX_FORCE_INLINE void setNphaseFallbackImplementationContext(PxvNphaseImplementationContext* ctx) { mNpFallbackImplementationContext = ctx; }
PxU32 getTotalCompressedContactSize() const { return mTotalCompressedCacheSize; }
PxU32 getMaxPatchCount() const { return mMaxPatches; }
PX_FORCE_INLINE PxcNpThreadContext* getNpThreadContext()
{
// We may want to conditional compile to exclude this on single threaded implementations
// if it is determined to be a performance hit.
return mNpThreadContextPool.get();
}
PX_FORCE_INLINE void putNpThreadContext(PxcNpThreadContext* threadContext)
{ mNpThreadContextPool.put(threadContext); }
PX_FORCE_INLINE PxMutex& getLock() { return mLock; }
PX_FORCE_INLINE PxTaskManager& getTaskManager()
{
PX_ASSERT(mTaskManager);
return *mTaskManager;
}
PX_FORCE_INLINE PxCudaContextManager* getCudaContextManager()
{
return mCudaContextManager;
}
PX_FORCE_INLINE void clearManagerTouchEvents();
PX_FORCE_INLINE Cm::PoolList<PxsContactManager, PxsContext>& getContactManagerPool()
{
return this->mContactManagerPool;
}
PX_FORCE_INLINE void setActiveContactManager(const PxsContactManager* manager, PxIntBool useCCD)
{
/*const PxU32 index = manager->getIndex();
if(index >= mActiveContactManager.size())
{
const PxU32 newSize = (2 * index + 256)&~255;
mActiveContactManager.resize(newSize);
}
mActiveContactManager.set(index);*/
//Record any pairs that have CCD enabled!
if(useCCD)
{
const PxU32 index = manager->getIndex();
if(index >= mActiveContactManagersWithCCD.size())
{
const PxU32 newSize = (2 * index + 256)&~255;
mActiveContactManagersWithCCD.resize(newSize);
}
mActiveContactManagersWithCCD.set(index);
}
}
private:
void mergeCMDiscreteUpdateResults(PxBaseTask* continuation);
PxU32 mIndex;
// Threading
PxcThreadCoherentCache<PxcNpThreadContext, PxcNpContext>
mNpThreadContextPool;
// Contact managers
Cm::PoolList<PxsContactManager, PxsContext> mContactManagerPool;
PxPool<Gu::LargePersistentContactManifold> mManifoldPool;
PxPool<Gu::SpherePersistentContactManifold> mSphereManifoldPool;
// PxBitMap mActiveContactManager;
PxBitMap mActiveContactManagersWithCCD; //KS - adding to filter any pairs that had a touch
PxBitMap mContactManagersWithCCDTouch; //KS - adding to filter any pairs that had a touch
PxBitMap mContactManagerTouchEvent;
//Cm::BitMap mContactManagerPatchChangeEvent;
PxU32 mCMTouchEventCount[PXS_TOUCH_EVENT_COUNT];
PxMutex mLock;
PxContactModifyCallback* mContactModifyCallback;
// narrowphase platform-dependent implementations support
PxvNphaseImplementationContext* mNpImplementationContext;
PxvNphaseImplementationContext* mNpFallbackImplementationContext;
// debug rendering (CS TODO: MS would like to have these wrapped into a class)
PxReal mVisualizationParams[PxVisualizationParameter::eNUM_VALUES];
PxBounds3 mVisualizationCullingBox;
PxTaskManager* mTaskManager;
Cm::FlushPool& mTaskPool;
PxCudaContextManager* mCudaContextManager;
// PxU32 mTouchesLost;
// PxU32 mTouchesFound;
// PX_ENABLE_SIM_STATS
PxvSimStats mSimStats;
bool mPCM;
bool mContactCache;
bool mCreateAveragePoint;
PxsTransformCache* mTransformCache;
const PxFloatArrayPinned* mContactDistances;
PxU32 mMaxPatches;
PxU32 mTotalCompressedCacheSize;
const PxU64 mContextID;
friend class PxsCCDContext;
friend class PxsNphaseImplementationContext;
friend class PxgNphaseImplementationContext; //FDTODO ideally it shouldn't be here..
};
PX_FORCE_INLINE void PxsContext::clearManagerTouchEvents()
{
mContactManagerTouchEvent.clear();
for(PxU32 i = 0; i < PXS_TOUCH_EVENT_COUNT; ++i)
{
mCMTouchEventCount[i] = 0;
}
}
}
#endif
| 11,660 | C | 36.616129 | 166 | 0.725386 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/src/px_globals.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 "PxvGlobals.h"
#include "PxsContext.h"
#include "PxcContactMethodImpl.h"
#include "GuContactMethodImpl.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
static physx::PxPhysXGpu* gPxPhysXGpu = NULL;
#endif
namespace physx
{
PxvOffsetTable gPxvOffsetTable;
void PxvInit(const PxvOffsetTable& offsetTable)
{
#if PX_SUPPORT_GPU_PHYSX
gPxPhysXGpu = NULL;
#endif
gPxvOffsetTable = offsetTable;
}
void PxvTerm()
{
#if PX_SUPPORT_GPU_PHYSX
PX_RELEASE(gPxPhysXGpu);
#endif
}
}
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
//forward declare stuff from PxPhysXGpuModuleLoader.cpp
void PxLoadPhysxGPUModule(const char* appGUID);
void PxUnloadPhysxGPUModule();
typedef physx::PxPhysXGpu* (PxCreatePhysXGpu_FUNC)();
extern PxCreatePhysXGpu_FUNC* g_PxCreatePhysXGpu_Func;
PxPhysXGpu* PxvGetPhysXGpu(bool createIfNeeded)
{
if (!gPxPhysXGpu && createIfNeeded)
{
#ifdef PX_PHYSX_GPU_STATIC
gPxPhysXGpu = PxCreatePhysXGpu();
#else
PxLoadPhysxGPUModule(NULL);
if (g_PxCreatePhysXGpu_Func)
{
gPxPhysXGpu = g_PxCreatePhysXGpu_Func();
}
#endif
}
return gPxPhysXGpu;
}
// PT: added for the standalone GPU BP but we may want to revisit this
void PxvReleasePhysXGpu(PxPhysXGpu* gpu)
{
PX_ASSERT(gpu==gPxPhysXGpu);
PxUnloadPhysxGPUModule();
PX_RELEASE(gpu);
gPxPhysXGpu = NULL;
}
}
#endif
#include "common/PxMetaData.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsMaterialCore.h"
namespace physx
{
template<> void PxsMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxCombineMode::Enum, PxU32)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxMaterialFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, PxsMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, staticFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, restitution, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterialFlags, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, fricCombineMode, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, restCombineMode, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMSoftBodyMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMSoftBodyMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, dampingScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, materialModel, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformLowLimitRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformHighLimitRatio, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxFEMSoftBodyMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMClothMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMClothMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, thickness, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxFEMClothMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsPBDMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsPBDMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU32, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, vorticityConfinement, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, surfaceTension, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cohesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, lift, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, drag, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cflCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleFrictionScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleAdhesionScale, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxPBDMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFLIPMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFLIPMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, surfaceTension, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxFLIPMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsMPMMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsMPMMaterialCore)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxIntBool, PxU32)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxIntBool, isPlastic, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, youngsModulus, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, poissonsRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, hardening, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalStretch, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, tensileDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, compressiveDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, attractiveForceResidual, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxMPMMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
}
| 10,403 | C++ | 41.814815 | 118 | 0.783908 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvGeometry.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 PXV_GEOMETRY_H
#define PXV_GEOMETRY_H
#include "foundation/PxTransform.h"
#include "PxvConfig.h"
/*!
\file
Geometry interface
*/
/************************************************************************/
/* Shapes */
/************************************************************************/
#include "GuGeometryChecks.h"
#include "CmUtils.h"
namespace physx
{
//
// Summary of our material approach:
//
// On the API level, materials are accessed via pointer. Internally we store indices into the material table.
// The material table is stored in the SDK and the materials are shared among scenes. To make this threadsafe,
// we have the following approach:
//
// - Every scene has a copy of the SDK master material table
// - At the beginning of a simulation step, the scene material table gets synced to the master material table.
// - While the simulation is running, the scene table does not get touched.
// - Each shape stores the indices of its material(s). When the simulation is not running and a user requests the
// materials of the shape, the indices are used to fetch the material from the master material table. When the
// the simulation is running then the same indices are used internally to fetch the materials from the scene
// material table.
// - This whole scheme only works as long as the position of a material in the material table does not change
// when other materials get deleted/inserted. The data structure of the material table makes sure that is the case.
//
struct MaterialIndicesStruct
{
// PX_SERIALIZATION
MaterialIndicesStruct(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
MaterialIndicesStruct()
: indices(NULL)
, numIndices(0)
, pad(PX_PADDING_16)
{
}
~MaterialIndicesStruct()
{
}
void allocate(PxU16 size)
{
indices = PX_ALLOCATE(PxU16, size, "MaterialIndicesStruct::allocate");
numIndices = size;
}
void deallocate()
{
PX_FREE(indices);
numIndices = 0;
}
PxU16* indices; // the remap table for material index
PxU16 numIndices; // the size of the remap table
PxU16 pad; // pad for serialization
PxU32 gpuRemapId; // PT: using padding bytes on x64
};
struct PxConvexMeshGeometryLL: public PxConvexMeshGeometry
{
bool gpuCompatible; // PT: TODO: remove?
};
struct PxTriangleMeshGeometryLL: public PxTriangleMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxParticleSystemGeometryLL : public PxParticleSystemGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxTetrahedronMeshGeometryLL : public PxTetrahedronMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHeightFieldGeometryLL : public PxHeightFieldGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHairSystemGeometryLL : public PxHairSystemGeometry
{
PxU32 gpuRemapId;
};
template <> struct PxcGeometryTraits<PxParticleSystemGeometryLL> { enum { TypeID = PxGeometryType::ePARTICLESYSTEM}; };
template <> struct PxcGeometryTraits<PxConvexMeshGeometryLL> { enum { TypeID = PxGeometryType::eCONVEXMESH }; };
template <> struct PxcGeometryTraits<PxTriangleMeshGeometryLL> { enum { TypeID = PxGeometryType::eTRIANGLEMESH }; };
template <> struct PxcGeometryTraits<PxTetrahedronMeshGeometryLL> { enum { TypeID = PxGeometryType::eTETRAHEDRONMESH }; };
template <> struct PxcGeometryTraits<PxHeightFieldGeometryLL> { enum { TypeID = PxGeometryType::eHEIGHTFIELD }; };
template <> struct PxcGeometryTraits<PxHairSystemGeometryLL> { enum { TypeID = PxGeometryType::eHAIRSYSTEM }; };
class InvalidGeometry : public PxGeometry
{
public:
PX_CUDA_CALLABLE PX_FORCE_INLINE InvalidGeometry() : PxGeometry(PxGeometryType::eINVALID) {}
};
class GeometryUnion
{
public:
// PX_SERIALIZATION
GeometryUnion(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion() { reinterpret_cast<InvalidGeometry&>(mGeometry) = InvalidGeometry(); }
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion(const PxGeometry& g) { set(g); }
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxGeometry& getGeometry() const { return reinterpret_cast<const PxGeometry&>(mGeometry); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometryType::Enum getType() const { return reinterpret_cast<const PxGeometry&>(mGeometry).getType(); }
PX_CUDA_CALLABLE void set(const PxGeometry& g);
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE Geom& get()
{
checkType<Geom>(getGeometry());
return reinterpret_cast<Geom&>(mGeometry);
}
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE const Geom& get() const
{
checkType<Geom>(getGeometry());
return reinterpret_cast<const Geom&>(mGeometry);
}
private:
union {
void* alignment; // PT: Makes sure the class is at least aligned to pointer size. See DE6803.
PxU8 box[sizeof(PxBoxGeometry)];
PxU8 sphere[sizeof(PxSphereGeometry)];
PxU8 capsule[sizeof(PxCapsuleGeometry)];
PxU8 plane[sizeof(PxPlaneGeometry)];
PxU8 convex[sizeof(PxConvexMeshGeometryLL)];
PxU8 particleSystem[sizeof(PxParticleSystemGeometryLL)];
PxU8 mesh[sizeof(PxTriangleMeshGeometryLL)];
PxU8 tetMesh[sizeof(PxTetrahedronMeshGeometryLL)];
PxU8 heightfield[sizeof(PxHeightFieldGeometryLL)];
PxU8 hairsystem[sizeof(PxHairSystemGeometryLL)];
PxU8 custom[sizeof(PxCustomGeometry)];
PxU8 invalid[sizeof(InvalidGeometry)];
} mGeometry;
};
struct PxShapeCoreFlag
{
enum Enum
{
eOWNS_MATERIAL_IDX_MEMORY = (1<<0), // PT: for de-serialization to avoid deallocating material index list. Moved there from Sc::ShapeCore (since one byte was free).
eIS_EXCLUSIVE = (1<<1), // PT: shape's exclusive flag
eIDT_TRANSFORM = (1<<2), // PT: true if PxsShapeCore::transform is identity
eSOFT_BODY_SHAPE = (1<<3), // True if this shape is a soft body shape
eCLOTH_SHAPE = (1<<4) // True if this shape is a cloth shape
};
};
typedef PxFlags<PxShapeCoreFlag::Enum,PxU8> PxShapeCoreFlags;
PX_FLAGS_OPERATORS(PxShapeCoreFlag::Enum,PxU8)
struct PxsShapeCore
{
PxsShapeCore()
{
setDensityForFluid(800.0f);
}
// PX_SERIALIZATION
PxsShapeCore(const PxEMPTY) : mShapeCoreFlags(PxEmpty), mGeometry(PxEmpty) {}
//~PX_SERIALIZATION
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
protected:
#endif
PX_ALIGN_PREFIX(16)
PxTransform mTransform PX_ALIGN_SUFFIX(16); // PT: Offset 0
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
public:
#endif
PX_FORCE_INLINE const PxTransform& getTransform() const
{
return mTransform;
}
PX_FORCE_INLINE void setTransform(const PxTransform& t)
{
mTransform = t;
if(t.p.isZero() && t.q.isIdentity())
mShapeCoreFlags.raise(PxShapeCoreFlag::eIDT_TRANSFORM);
else
mShapeCoreFlags.clear(PxShapeCoreFlag::eIDT_TRANSFORM);
}
PxReal mContactOffset; // PT: Offset 28
PxU8 mShapeFlags; // PT: Offset 32 !< API shape flags // PT: TODO: use PxShapeFlags here. Needs to move flags to separate file.
PxShapeCoreFlags mShapeCoreFlags; // PT: Offset 33
PxU16 mMaterialIndex; // PT: Offset 34
PxReal mRestOffset; // PT: Offset 36 - same as the API property of the same name - PT: moved from Sc::ShapeCore to fill padding bytes
GeometryUnion mGeometry; // PT: Offset 40
PxReal mTorsionalRadius; // PT: Offset 104 - PT: moved from Sc::ShapeCore to fill padding bytes
PxReal mMinTorsionalPatchRadius; // PT: Offset 108 - PT: moved from Sc::ShapeCore to fill padding bytes
PX_FORCE_INLINE float getDensityForFluid() const
{
return mGeometry.getGeometry().mTypePadding;
}
PX_FORCE_INLINE void setDensityForFluid(float density)
{
const_cast<PxGeometry&>(mGeometry.getGeometry()).mTypePadding = density;
}
};
PX_COMPILE_TIME_ASSERT( sizeof(GeometryUnion) <= 64); // PT: if you break this one I will not be happy
PX_COMPILE_TIME_ASSERT( (sizeof(PxsShapeCore)&0xf) == 0);
}
#endif
| 9,715 | C | 35.253731 | 167 | 0.732373 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsFEMSoftBodyMaterialCore.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 PXS_FEM_MATERIAL_CORE_H
#define PXS_FEM_MATERIAL_CORE_H
#include "PxFEMSoftBodyMaterial.h"
#include "PxsMaterialShared.h"
namespace physx
{
PX_FORCE_INLINE PX_CUDA_CALLABLE PxU16 toUniformU16(PxReal f)
{
f = PxClamp(f, 0.0f, 1.0f);
return PxU16(f * 65535.0f);
}
PX_FORCE_INLINE PX_CUDA_CALLABLE PxReal toUniformReal(PxU16 v)
{
return PxReal(v) * (1.0f / 65535.0f);
}
PX_ALIGN_PREFIX(16) struct PxsFEMSoftBodyMaterialData
{
PxReal youngs; //4
PxReal poissons; //8
PxReal dynamicFriction; //12
PxReal damping; //16
PxU16 dampingScale; //20, known to be in the range of 0...1. Mapped to integer range 0...65535
PxU16 materialModel; //22
PxReal deformThreshold; //24
PxReal deformLowLimitRatio; //28
PxReal deformHighLimitRatio; //32
PX_CUDA_CALLABLE PxsFEMSoftBodyMaterialData() :
youngs (1.e+6f),
poissons (0.45f),
dynamicFriction (0.0f),
damping (0.0f),
//dampingScale (0),
materialModel (PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL),
deformThreshold (PX_MAX_F32),
deformLowLimitRatio (1.0f),
deformHighLimitRatio(1.0f)
{}
PxsFEMSoftBodyMaterialData(const PxEMPTY) {}
}PX_ALIGN_SUFFIX(16);
typedef MaterialCoreT<PxsFEMSoftBodyMaterialData, PxFEMSoftBodyMaterial> PxsFEMSoftBodyMaterialCore;
} //namespace phyxs
#endif
| 3,047 | C | 35.722891 | 101 | 0.737118 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialManager.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 PXS_MATERIAL_MANAGER_H
#define PXS_MATERIAL_MANAGER_H
#include "PxsMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "foundation/PxAlignedMalloc.h"
namespace physx
{
struct PxsMaterialInfo
{
PxU16 mMaterialIndex0;
PxU16 mMaterialIndex1;
};
template<class MaterialCore>
class PxsMaterialManagerT
{
public:
PxsMaterialManagerT()
{
const PxU32 matCount = 128;
materials = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*matCount, PX_FL));
maxMaterials = matCount;
for(PxU32 i=0; i<matCount; ++i)
{
materials[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
}
~PxsMaterialManagerT()
{
physx::PxAlignedAllocator<16>().deallocate(materials);
}
void setMaterial(MaterialCore* mat)
{
const PxU16 materialIndex = mat->mMaterialIndex;
resize(PxU32(materialIndex) + 1);
materials[materialIndex] = *mat;
}
void updateMaterial(MaterialCore* mat)
{
materials[mat->mMaterialIndex] =*mat;
}
void removeMaterial(MaterialCore* mat)
{
mat->mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
PX_FORCE_INLINE MaterialCore* getMaterial(const PxU32 index)const
{
PX_ASSERT(index < maxMaterials);
return &materials[index];
}
PxU32 getMaxSize()const
{
return maxMaterials;
}
void resize(PxU32 minValueForMax)
{
if(maxMaterials>=minValueForMax)
return;
const PxU32 numMaterials = maxMaterials;
maxMaterials = (minValueForMax+31)&~31;
MaterialCore* mat = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*maxMaterials, PX_FL));
for(PxU32 i=0; i<numMaterials; ++i)
mat[i] = materials[i];
for(PxU32 i = numMaterials; i < maxMaterials; ++i)
mat[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
physx::PxAlignedAllocator<16>().deallocate(materials);
materials = mat;
}
MaterialCore* materials;//make sure materials's start address is 16 bytes align
PxU32 maxMaterials;
PxU32 mPad;
#if !PX_P64_FAMILY
PxU32 mPad2;
#endif
};
//This class is used for forward declaration
class PxsMaterialManager : public PxsMaterialManagerT<PxsMaterialCore>
{
};
class PxsFEMMaterialManager : public PxsMaterialManagerT<PxsFEMSoftBodyMaterialCore>
{
};
class PxsFEMClothMaterialManager : public PxsMaterialManagerT<PxsFEMClothMaterialCore>
{
};
class PxsPBDMaterialManager : public PxsMaterialManagerT<PxsPBDMaterialCore>
{
};
class PxsFLIPMaterialManager : public PxsMaterialManagerT<PxsFLIPMaterialCore>
{
};
class PxsMPMMaterialManager : public PxsMaterialManagerT<PxsMPMMaterialCore>
{
};
template<class MaterialCore>
class PxsMaterialManagerIterator
{
public:
PxsMaterialManagerIterator(PxsMaterialManagerT<MaterialCore>& manager) : mManager(manager), mIndex(0)
{
}
bool getNextMaterial(MaterialCore*& materialCore)
{
const PxU32 maxSize = mManager.getMaxSize();
PxU32 index = mIndex;
while(index < maxSize && mManager.getMaterial(index)->mMaterialIndex == MATERIAL_INVALID_HANDLE)
index++;
materialCore = NULL;
if(index < maxSize)
materialCore = mManager.getMaterial(index++);
mIndex = index;
return materialCore!=NULL;
}
private:
PxsMaterialManagerIterator& operator=(const PxsMaterialManagerIterator&);
PxsMaterialManagerT<MaterialCore>& mManager;
PxU32 mIndex;
};
}
#endif
| 5,236 | C | 28.094444 | 140 | 0.744079 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvDynamics.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 PXV_DYNAMICS_H
#define PXV_DYNAMICS_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxIntrinsics.h"
#include "PxRigidDynamic.h"
namespace physx
{
/*!
\file
Dynamics interface.
*/
struct PxsRigidCore
{
PxsRigidCore() : mFlags(0), solverIterationCounts(0) {}
PxsRigidCore(const PxEMPTY) : mFlags(PxEmpty) {}
PX_ALIGN_PREFIX(16)
PxTransform body2World PX_ALIGN_SUFFIX(16);
PxRigidBodyFlags mFlags; // API body flags
PxU16 solverIterationCounts; // vel iters are in low word and pos iters in high word.
PX_FORCE_INLINE PxU32 isKinematic() const { return mFlags & PxRigidBodyFlag::eKINEMATIC; }
PX_FORCE_INLINE PxU32 hasCCD() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD; }
PX_FORCE_INLINE PxU32 hasCCDFriction() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD_FRICTION; }
PX_FORCE_INLINE PxU32 hasIdtBody2Actor() const { return mFlags & PxRigidBodyFlag::eRESERVED; }
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsRigidCore) == 32);
#define PXV_CONTACT_REPORT_DISABLED PX_MAX_F32
struct PxsBodyCore : public PxsRigidCore
{
PxsBodyCore() : PxsRigidCore() { fixedBaseLink = PxU8(0); }
PxsBodyCore(const PxEMPTY) : PxsRigidCore(PxEmpty) {}
PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return body2Actor; }
PX_FORCE_INLINE void setBody2Actor(const PxTransform& t)
{
if(t.p.isZero() && t.q.isIdentity())
mFlags.raise(PxRigidBodyFlag::eRESERVED);
else
mFlags.clear(PxRigidBodyFlag::eRESERVED);
body2Actor = t;
}
protected:
PxTransform body2Actor;
public:
PxReal ccdAdvanceCoefficient; //64
PxVec3 linearVelocity;
PxReal maxPenBias;
PxVec3 angularVelocity;
PxReal contactReportThreshold; //96
PxReal maxAngularVelocitySq;
PxReal maxLinearVelocitySq;
PxReal linearDamping;
PxReal angularDamping; //112
PxVec3 inverseInertia;
PxReal inverseMass; //128
PxReal maxContactImpulse;
PxReal sleepThreshold;
union
{
PxReal freezeThreshold;
PxReal cfmScale;
};
PxReal wakeCounter; //144 this is authoritative wakeCounter
PxReal solverWakeCounter; //this is calculated by the solver when it performs sleepCheck. It is committed to wakeCounter in ScAfterIntegrationTask if the body is still awake.
PxU32 numCountedInteractions;
PxReal offsetSlop; //Slop value used to snap contact line of action back in-line with the COM
PxU8 isFastMoving; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxU8 disableGravity; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxRigidDynamicLockFlags lockFlags; //This is u8.
PxU8 fixedBaseLink; //160 This indicates whether the articulation link has PxArticulationFlag::eFIX_BASE. All fits into 16 byte alignment
// PT: moved from Sc::BodyCore ctor - we don't want to duplicate all this in immediate mode
PX_FORCE_INLINE void init( const PxTransform& bodyPose,
const PxVec3& inverseInertia_, PxReal inverseMass_,
PxReal wakeCounter_, PxReal scaleSpeed,
PxReal linearDamping_, PxReal angularDamping_,
PxReal maxLinearVelocitySq_, PxReal maxAngularVelocitySq_,
PxActorType::Enum type)
{
PX_ASSERT(bodyPose.p.isFinite());
PX_ASSERT(bodyPose.q.isFinite());
// PT: TODO: unify naming convention
// From PxsRigidCore
body2World = bodyPose;
mFlags = PxRigidBodyFlags();
solverIterationCounts = (1 << 8) | 4;
setBody2Actor(PxTransform(PxIdentity));
ccdAdvanceCoefficient = 0.15f;
linearVelocity = PxVec3(0.0f);
maxPenBias = -1e32f;//-PX_MAX_F32;
angularVelocity = PxVec3(0.0f);
contactReportThreshold = PXV_CONTACT_REPORT_DISABLED;
maxAngularVelocitySq = maxAngularVelocitySq_;
maxLinearVelocitySq = maxLinearVelocitySq_;
linearDamping = linearDamping_;
angularDamping = angularDamping_;
inverseInertia = inverseInertia_;
inverseMass = inverseMass_;
maxContactImpulse = 1e32f;// PX_MAX_F32;
sleepThreshold = 5e-5f * scaleSpeed * scaleSpeed;
if(type == PxActorType::eARTICULATION_LINK)
cfmScale = 0.025f;
else
freezeThreshold = 2.5e-5f * scaleSpeed * scaleSpeed;
wakeCounter = wakeCounter_;
offsetSlop = 0.f;
// PT: this one is not initialized?
//solverWakeCounter
// PT: these are initialized in BodySim ctor
//numCountedInteractions;
//numBodyInteractions;
isFastMoving = false;
disableGravity = false;
lockFlags = PxRigidDynamicLockFlags(0);
}
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsBodyCore) == 160);
}
#endif
| 6,401 | C | 36.00578 | 180 | 0.732698 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMPMMaterialCore.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 PXS_MPM_MATERIAL_CORE_H
#define PXS_MPM_MATERIAL_CORE_H
#include "PxParticleGpu.h"
#include "PxsMaterialShared.h"
#include "PxMPMMaterial.h"
namespace physx
{
struct PxsMPMMaterialData : public PxsParticleMaterialData
{
PxsMPMMaterialData() {} // PT: TODO: ctor leaves things uninitialized, is that by design?
PxsMPMMaterialData(const PxEMPTY) {}
PxIntBool isPlastic; //24
PxReal youngsModulus; //28
PxReal poissonsRatio; //32
PxReal hardening; //snow //36
PxReal criticalCompression; //snow //40
PxReal criticalStretch; //snow //44
//Only used when damage tracking is activated in the cutting flags
PxReal tensileDamageSensitivity; //48
PxReal compressiveDamageSensitivity; //52
PxReal attractiveForceResidual; //56
PxReal sandFrictionAngle; //sand //60
PxReal yieldStress; //von Mises //64
PxMPMMaterialModel::Enum materialModel; //68
PxMPMCuttingFlags cuttingFlags; //72
PxReal density; //76;
PxReal stretchAndShearDamping; //80;
PxReal rotationalDamping; //84;
};
typedef MaterialCoreT<PxsMPMMaterialData, PxMPMMaterial> PxsMPMMaterialCore;
} //namespace phyxs
#endif
| 2,888 | C | 38.575342 | 94 | 0.74723 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialCore.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 PXS_MATERIAL_CORE_H
#define PXS_MATERIAL_CORE_H
#include "PxMaterial.h"
#include "foundation/PxUtilities.h"
#include "PxsMaterialShared.h"
namespace physx
{
struct PxsMaterialData
{
PxReal dynamicFriction; //4
PxReal staticFriction; //8
PxReal restitution; //12
PxReal damping; //16
PxMaterialFlags flags; //18
PxU8 fricCombineMode; //19 PxCombineMode::Enum
PxU8 restCombineMode; //20 PxCombineMode::Enum
PxsMaterialData() :
dynamicFriction (0.0f),
staticFriction (0.0f),
restitution (0.0f),
damping (0.0f),
flags (PxMaterialFlag::eIMPROVED_PATCH_FRICTION),
fricCombineMode (PxCombineMode::eAVERAGE),
restCombineMode (PxCombineMode::eAVERAGE)
{}
PxsMaterialData(const PxEMPTY) {}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getFrictionCombineMode() const { return PxCombineMode::Enum(fricCombineMode); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getRestitutionCombineMode() const { return PxCombineMode::Enum(restCombineMode); }
PX_FORCE_INLINE void setFrictionCombineMode(PxCombineMode::Enum combineMode) { fricCombineMode = PxTo8(combineMode); }
PX_FORCE_INLINE void setRestitutionCombineMode(PxCombineMode::Enum combineMode) { restCombineMode = PxTo8(combineMode); }
};
typedef MaterialCoreT<PxsMaterialData, PxMaterial> PxsMaterialCore;
} //namespace phyxs
#endif
| 3,091 | C | 42.549295 | 137 | 0.757037 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvSimStats.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 PXV_SIM_STATS_H
#define PXV_SIM_STATS_H
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#include "geometry/PxGeometry.h"
namespace physx
{
/*!
\file
Context handling
*/
/************************************************************************/
/* Context handling, types */
/************************************************************************/
/*!
Description: contains statistics for the simulation.
*/
struct PxvSimStats
{
PxvSimStats() { clearAll(); }
void clearAll() { PxMemZero(this, sizeof(PxvSimStats)); } // set counters to zero
PX_FORCE_INLINE void incCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbCCDPairs[g0][g1]++;
}
PX_FORCE_INLINE void decCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbCCDPairs[g0][g1]);
mNbCCDPairs[g0][g1]--;
}
PX_FORCE_INLINE void incModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbModifiedContactPairs[g0][g1]++;
}
PX_FORCE_INLINE void decModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbModifiedContactPairs[g0][g1]);
mNbModifiedContactPairs[g0][g1]--;
}
// PT: those guys are now persistent and shouldn't be cleared each frame
PxU32 mNbDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbCCDPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbDiscreteContactPairsTotal; // PT: sum of mNbDiscreteContactPairs, i.e. number of pairs reaching narrow phase
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
PxU32 mNbActiveConstraints;
PxU32 mNbActiveDynamicBodies;
PxU32 mNbActiveKinematicBodies;
PxU32 mNbAxisSolverConstraints;
PxU32 mTotalCompressedContactSize;
PxU32 mTotalConstraintSize;
PxU32 mPeakConstraintBlockAllocations;
PxU32 mNbNewPairs;
PxU32 mNbLostPairs;
PxU32 mNbNewTouches;
PxU32 mNbLostTouches;
PxU32 mNbPartitions;
};
}
#endif
| 4,082 | C | 35.455357 | 119 | 0.727095 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvManager.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 PXV_MANAGER_H
#define PXV_MANAGER_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxvConfig.h"
#include "PxvGeometry.h"
namespace physx
{
/*!
\file
Manager interface
*/
/************************************************************************/
/* Managers */
/************************************************************************/
class PxsContactManager;
struct PxsRigidCore;
struct PxsShapeCore;
class PxsRigidBody;
/*!
Type of PXD_MANAGER_CCD_MODE property
*/
enum PxvContactManagerCCDMode
{
PXD_MANAGER_CCD_NONE,
PXD_MANAGER_CCD_LINEAR
};
/*!
Manager descriptor
*/
struct PxvManagerDescRigidRigid
{
/*!
Manager user data
\sa PXD_MANAGER_USER_DATA
*/
//void* userData;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE0
*/
PxU8 dominance0;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE1
*/
PxU8 dominance1;
/*!
PxsRigidBodies
*/
PxsRigidBody* rigidBody0;
PxsRigidBody* rigidBody1;
/*!
Shape Core structures
*/
const PxsShapeCore* shapeCore0;
const PxsShapeCore* shapeCore1;
/*!
Body Core structures
*/
PxsRigidCore* rigidCore0;
PxsRigidCore* rigidCore1;
/*!
Enable contact information reporting.
*/
int reportContactInfo;
/*!
Enable contact impulse threshold reporting.
*/
int hasForceThreshold;
/*!
Enable generated contacts to be changeable
*/
int contactChangeable;
/*!
Disable strong friction
*/
//int disableStrongFriction;
/*!
Contact resolution rest distance.
*/
PxReal restDistance;
/*!
Disable contact response
*/
int disableResponse;
/*!
Disable discrete contact generation
*/
int disableDiscreteContact;
/*!
Disable CCD contact generation
*/
int disableCCDContact;
/*!
Is connected to an articulation (1 - first body, 2 - second body)
*/
int hasArticulations;
/*!
is connected to a dynamic (1 - first body, 2 - second body)
*/
int hasDynamics;
/*!
Is the pair touching? Use when re-creating the manager with prior knowledge about touch status.
positive: pair is touching
0: touch state unknown (this is a new pair)
negative: pair is not touching
Default is 0
*/
int hasTouch;
/*!
Identifies whether body 1 is kinematic. We can treat kinematics as statics and embed velocity into constraint
because kinematic bodies' velocities will not change
*/
bool body1Kinematic;
/*
Index entries into the transform cache for shape 0
*/
PxU32 transformCache0;
/*
Index entries into the transform cache for shape 1
*/
PxU32 transformCache1;
PxvManagerDescRigidRigid()
{
PxMemSet(this, 0, sizeof(PxvManagerDescRigidRigid));
dominance0 = 1u;
dominance1 = 1u;
}
};
/*!
Report struct for contact manager touch reports
*/
struct PxvContactManagerTouchEvent
{
void* userData;
// PT: only useful to search for places where we get/set this specific user data
PX_FORCE_INLINE void setCMTouchEventUserData(void* ud) { userData = ud; }
PX_FORCE_INLINE void* getCMTouchEventUserData() const { return userData; }
};
}
#endif
| 5,101 | C | 22.730232 | 110 | 0.709273 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpMemBlockPool.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxMath.h"
#include "PxcNpMemBlockPool.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxInlineArray.h"
#include "PxcScratchAllocator.h"
using namespace physx;
PxcNpMemBlockPool::PxcNpMemBlockPool(PxcScratchAllocator& allocator) :
mConstraints("PxcNpMemBlockPool::mConstraints"),
mExceptionalConstraints("PxcNpMemBlockPool::mExceptionalConstraints"),
mNpCacheActiveStream(0),
mFrictionActiveStream(0),
mCCDCacheActiveStream(0),
mContactIndex(0),
mAllocatedBlocks(0),
mMaxBlocks(0),
mUsedBlocks(0),
mMaxUsedBlocks(0),
mScratchBlockAddr(0),
mNbScratchBlocks(0),
mScratchAllocator(allocator),
mPeakConstraintAllocations(0),
mConstraintAllocations(0)
{
}
void PxcNpMemBlockPool::init(PxU32 initialBlockCount, PxU32 maxBlocks)
{
mMaxBlocks = maxBlocks;
mInitialBlocks = initialBlockCount;
PxU32 reserve = PxMax<PxU32>(initialBlockCount, 64);
mConstraints.reserve(reserve);
mExceptionalConstraints.reserve(16);
mFriction[0].reserve(reserve);
mFriction[1].reserve(reserve);
mNpCache[0].reserve(reserve);
mNpCache[1].reserve(reserve);
mUnused.reserve(reserve);
setBlockCount(initialBlockCount);
}
PxU32 PxcNpMemBlockPool::getUsedBlockCount() const
{
return mUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getMaxUsedBlockCount() const
{
return mMaxUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getPeakConstraintBlockCount() const
{
return mPeakConstraintAllocations;
}
void PxcNpMemBlockPool::setBlockCount(PxU32 blockCount)
{
PxMutex::ScopedLock lock(mLock);
PxU32 current = getUsedBlockCount();
for(PxU32 i=current;i<blockCount;i++)
{
mUnused.pushBack(reinterpret_cast<PxcNpMemBlock *>(PX_ALLOC(PxcNpMemBlock::SIZE, "PxcNpMemBlock")));
mAllocatedBlocks++;
}
}
void PxcNpMemBlockPool::releaseUnusedBlocks()
{
PxMutex::ScopedLock lock(mLock);
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
mAllocatedBlocks--;
}
}
PxcNpMemBlockPool::~PxcNpMemBlockPool()
{
// swapping twice guarantees all blocks are released from the stream pairs
swapFrictionStreams();
swapFrictionStreams();
swapNpCacheStreams();
swapNpCacheStreams();
releaseConstraintMemory();
releaseContacts();
releaseContacts();
PX_ASSERT(mUsedBlocks == 0);
flushUnused();
}
void PxcNpMemBlockPool::acquireConstraintMemory()
{
PxU32 size;
void* addr = mScratchAllocator.allocAll(size);
size = size&~(PxcNpMemBlock::SIZE-1);
PX_ASSERT(mScratchBlocks.size()==0);
mScratchBlockAddr = reinterpret_cast<PxcNpMemBlock*>(addr);
mNbScratchBlocks = size/PxcNpMemBlock::SIZE;
mScratchBlocks.resize(mNbScratchBlocks);
for(PxU32 i=0;i<mNbScratchBlocks;i++)
mScratchBlocks[i] = mScratchBlockAddr+i;
}
void PxcNpMemBlockPool::releaseConstraintMemory()
{
PxMutex::ScopedLock lock(mLock);
mPeakConstraintAllocations = mConstraintAllocations = 0;
while(mConstraints.size())
{
PxcNpMemBlock* block = mConstraints.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
for(PxU32 i=0;i<mExceptionalConstraints.size();i++)
PX_FREE(mExceptionalConstraints[i]);
mExceptionalConstraints.clear();
PX_ASSERT(mScratchBlocks.size()==mNbScratchBlocks); // check we released them all
mScratchBlocks.clear();
if(mScratchBlockAddr)
{
mScratchAllocator.free(mScratchBlockAddr);
mScratchBlockAddr = 0;
mNbScratchBlocks = 0;
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount, PxU32* peakAllocationCount, bool isScratchAllocation)
{
PxMutex::ScopedLock lock(mLock);
if(allocationCount && peakAllocationCount)
{
*peakAllocationCount = PxMax(*allocationCount + 1, *peakAllocationCount);
(*allocationCount)++;
}
// this is a bit of hack - the logic would be better placed in acquireConstraintBlock, but then we'd have to grab the mutex
// once there to check the scratch block array and once here if we fail - or, we'd need a larger refactor to separate out
// locking and acquisition.
if(isScratchAllocation && mScratchBlocks.size()>0)
{
PxcNpMemBlock* block = mScratchBlocks.popBack();
trackingArray.pushBack(block);
return block;
}
if(mUnused.size())
{
PxcNpMemBlock* block = mUnused.popBack();
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
return block;
}
if(mAllocatedBlocks == mMaxBlocks)
{
#if PX_CHECKED
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Reached maximum number of allocated blocks so 16k block allocation will fail!");
#endif
return NULL;
}
#if PX_CHECKED
if(mInitialBlocks)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Number of required 16k memory blocks has exceeded the initial number of blocks. Allocator is being called. Consider increasing the number of pre-allocated 16k blocks.");
}
#endif
// increment here so that if we hit the limit in separate threads we won't overallocated
mAllocatedBlocks++;
PxcNpMemBlock* block = reinterpret_cast<PxcNpMemBlock*>(PX_ALLOC(sizeof(PxcNpMemBlock), "PxcNpMemBlock"));
if(block)
{
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
}
else
mAllocatedBlocks--;
return block;
}
PxU8* PxcNpMemBlockPool::acquireExceptionalConstraintMemory(PxU32 size)
{
PxU8* memory = reinterpret_cast<PxU8*>(PX_ALLOC(size, "PxcNpExceptionalMemory"));
if(memory)
{
PxMutex::ScopedLock lock(mLock);
mExceptionalConstraints.pushBack(memory);
}
return memory;
}
void PxcNpMemBlockPool::release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mUsedBlocks >= deadArray.size());
mUsedBlocks -= deadArray.size();
if(allocationCount)
{
*allocationCount -= deadArray.size();
}
while(deadArray.size())
{
PxcNpMemBlock* block = deadArray.popBack();
for(PxU32 a = 0; a < mUnused.size(); ++a)
{
PX_ASSERT(mUnused[a] != block);
}
mUnused.pushBack(block);
}
}
void PxcNpMemBlockPool::flushUnused()
{
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock()
{
// we track the scratch blocks in the constraint block array, because the code in acquireMultipleConstraintBlocks
// assumes that acquired blocks are listed there.
return acquire(mConstraints);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock(PxcNpMemBlockArray& memBlocks)
{
return acquire(memBlocks, &mConstraintAllocations, &mPeakConstraintAllocations, true);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireContactBlock()
{
return acquire(mContacts[mContactIndex], NULL, NULL, true);
}
void PxcNpMemBlockPool::releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks)
{
PxMutex::ScopedLock lock(mLock);
while(memBlocks.size())
{
PxcNpMemBlock* block = memBlocks.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
}
void PxcNpMemBlockPool::releaseContacts()
{
//releaseConstraintBlocks(mContacts);
release(mContacts[1-mContactIndex]);
mContactIndex = 1-mContactIndex;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireFrictionBlock()
{
return acquire(mFriction[mFrictionActiveStream]);
}
void PxcNpMemBlockPool::swapFrictionStreams()
{
release(mFriction[1-mFrictionActiveStream]);
mFrictionActiveStream = 1-mFrictionActiveStream;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireNpCacheBlock()
{
return acquire(mNpCache[mNpCacheActiveStream]);
}
void PxcNpMemBlockPool::swapNpCacheStreams()
{
release(mNpCache[1-mNpCacheActiveStream]);
mNpCacheActiveStream = 1-mNpCacheActiveStream;
}
| 9,542 | C++ | 26.501441 | 173 | 0.763991 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactCache.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 "PxcContactCache.h"
#include "PxsContactManager.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCache.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
//#define ENABLE_CONTACT_CACHE_STATS
#ifdef ENABLE_CONTACT_CACHE_STATS
static PxU32 gNbCalls;
static PxU32 gNbHits;
#endif
void PxcClearContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls = 0;
gNbHits = 0;
#endif
}
void PxcDisplayContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
pxPrintf("%d|%d (%f)\n", gNbHits, gNbCalls, gNbCalls ? float(gNbHits)/float(gNbCalls) : 0.0f);
#endif
}
namespace physx
{
const bool g_CanUseContactCache[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
false, //PxcContactSphereSphere
false, //PxcContactSpherePlane
true, //PxcContactSphereCapsule
false, //PxcContactSphereBox
true, //PxcContactSphereConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactSphereMesh
true, //PxcContactSphereHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePLANE
{
false, //-
false, //PxcInvalidContactPair
true, //PxcContactPlaneCapsule
true, //PxcContactPlaneBox
true, //PxcContactPlaneConvex
false, //ParticleSystem
true, //SoftBody
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCAPSULE
{
false, //-
false, //-
true, //PxcContactCapsuleCapsule
true, //PxcContactCapsuleBox
true, //PxcContactCapsuleConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactCapsuleMesh
true, //PxcContactCapsuleHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eBOX
{
false, //-
false, //-
false, //-
true, //PxcContactBoxBox
true, //PxcContactBoxConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactBoxMesh
true, //PxcContactBoxHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCONVEXMESH
{
false, //-
false, //-
false, //-
false, //-
true, //PxcContactConvexConvex
false, //-
true, //-
true, //PxcContactConvexMesh2
true, //PxcContactConvexHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePARTICLESYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTETRAHEDRONMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTRIANGLEMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHEIGHTFIELD
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHAIRSYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
//PxGeometryType::eCUSTOM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_CanUseContactCache) / sizeof(g_CanUseContactCache[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
static PX_FORCE_INLINE void updateContact( PxContactPoint& dst, const PxcLocalContactsCache& contactsData,
const PxMat34& world0, const PxMat34& world1,
const PxVec3& point, const PxVec3& normal, float separation)
{
const PxVec3 tmp0 = contactsData.mTransform0.transformInv(point);
const PxVec3 worldpt0 = world0.transform(tmp0);
const PxVec3 tmp1 = contactsData.mTransform1.transformInv(point);
const PxVec3 worldpt1 = world1.transform(tmp1);
const PxVec3 motion = worldpt0 - worldpt1;
dst.normal = normal;
dst.point = (worldpt0 + worldpt1)*0.5f;
//dst.point = point;
dst.separation = separation + motion.dot(normal);
}
static PX_FORCE_INLINE void prefetchData128(PxU8* PX_RESTRICT ptr, PxU32 size)
{
// PT: always prefetch the cache line containing our address (which unfortunately won't be aligned to 128 most of the time)
PxPrefetchLine(ptr, 0);
// PT: compute start offset of our data within its cache line
const PxU32 startOffset = PxU32(size_t(ptr)&127);
// PT: prefetch next cache line if needed
if(startOffset+size>128)
PxPrefetchLine(ptr+128, 0);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, const PxVec3& v)
{
*reinterpret_cast<PxVec3*>(bytes) = v;
return bytes + sizeof(PxVec3);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxReal v)
{
*reinterpret_cast<PxReal*>(bytes) = v;
return bytes + sizeof(PxReal);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxU32 v)
{
*reinterpret_cast<PxU32*>(bytes) = v;
return bytes + sizeof(PxU32);
}
//PxU32 gContactCache_NbCalls = 0;
//PxU32 gContactCache_NbHits = 0;
static PX_FORCE_INLINE PxReal maxComponentDeltaPos(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.p.x - t1.p.x);
delta = PxMax(delta, PxAbs(t0.p.y - t1.p.y));
delta = PxMax(delta, PxAbs(t0.p.z - t1.p.z));
return delta;
}
static PX_FORCE_INLINE PxReal maxComponentDeltaRot(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.q.x - t1.q.x);
delta = PxMax(delta, PxAbs(t0.q.y - t1.q.y));
delta = PxMax(delta, PxAbs(t0.q.z - t1.q.z));
delta = PxMax(delta, PxAbs(t0.q.w - t1.q.w));
return delta;
}
bool physx::PxcCacheLocalContacts( PxcNpThreadContext& context, Cache& pairContactCache,
const PxTransform32& tm0, const PxTransform32& tm1,
const PxcContactMethod conMethod,
const PxGeometry& shape0, const PxGeometry& shape1)
{
const NarrowPhaseParams& params = context.mNarrowPhaseParams;
// gContactCache_NbCalls++;
if(pairContactCache.mCachedData)
prefetchData128(pairContactCache.mCachedData, pairContactCache.mCachedSize);
PxContactBuffer& contactBuffer = context.mContactBuffer;
contactBuffer.reset();
PxcLocalContactsCache contactsData;
PxU32 nbCachedBytes;
const PxU8* cachedBytes = PxcNpCacheRead2(pairContactCache, contactsData, nbCachedBytes);
pairContactCache.mCachedData = NULL;
pairContactCache.mCachedSize = 0;
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls++;
#endif
const PxU32 payloadSize = (sizeof(PxcLocalContactsCache)+3)&~3;
if(cachedBytes)
{
// PT: we used to store the relative TM but it's better to save memory and recompute it
const PxTransform t0to1 = tm1.transformInv(tm0);
const PxTransform relTM = contactsData.mTransform1.transformInv(contactsData.mTransform0);
const PxReal epsilon = 0.01f;
if( maxComponentDeltaPos(t0to1, relTM)<epsilon*params.mToleranceLength
&& maxComponentDeltaRot(t0to1, relTM)<epsilon)
{
// gContactCache_NbHits++;
const PxU32 nbContacts = contactsData.mNbCachedContacts;
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbCachedBytes);
prefetchData128(ls, (payloadSize + 4 + nbCachedBytes + 0xF)&~0xF);
contactBuffer.count = nbContacts;
if(nbContacts)
{
PxContactPoint* PX_RESTRICT dst = contactBuffer.contacts;
const Matrix34FromTransform world1(tm1);
const Matrix34FromTransform world0(tm0);
const bool sameNormal = contactsData.mSameNormal;
const PxU8* contacts = reinterpret_cast<const PxU8*>(cachedBytes);
const PxVec3* normal0 = NULL;
for(PxU32 i=0;i<nbContacts;i++)
{
if(i!=nbContacts-1)
PxPrefetchLine(contacts, 128);
const PxVec3* cachedNormal;
if(!i || !sameNormal)
{
cachedNormal = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
normal0 = cachedNormal;
}
else
{
cachedNormal = normal0;
}
const PxVec3* cachedPoint = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
const PxReal* cachedPD = reinterpret_cast<const PxReal*>(contacts); contacts += sizeof(PxReal);
updateContact(*dst, contactsData, world0, world1, *cachedPoint, *cachedNormal, *cachedPD);
if(contactsData.mUseFaceIndices)
{
const PxU32* cachedIndex1 = reinterpret_cast<const PxU32*>(contacts); contacts += sizeof(PxU32);
dst->internalFaceIndex1 = *cachedIndex1;
}
else
{
dst->internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX;
}
dst++;
}
}
if(ls)
PxcNpCacheWriteFinalize(ls, contactsData, nbCachedBytes, cachedBytes);
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbHits++;
#endif
return true;
}
else
{
// PT: if we reach this point we cached the contacts but we couldn't use them next frame
// => waste of time and memory
}
}
conMethod(shape0, shape1, tm0, tm1, params, pairContactCache, context.mContactBuffer, &context.mRenderOutput);
//if(contactBuffer.count)
{
contactsData.mTransform0 = tm0;
contactsData.mTransform1 = tm1;
PxU32 nbBytes = 0;
const PxU8* bytes = NULL;
const PxU32 count = contactBuffer.count;
if(count)
{
const bool useFaceIndices = contactBuffer.contacts[0].internalFaceIndex1!=PXC_CONTACT_NO_FACE_INDEX;
contactsData.mNbCachedContacts = PxTo16(count);
contactsData.mUseFaceIndices = useFaceIndices;
const PxContactPoint* PX_RESTRICT srcContacts = contactBuffer.contacts;
// PT: this loop should not be here. We should output the contacts directly compressed, as we used to.
bool sameNormal = true;
{
const PxVec3 normal0 = srcContacts->normal;
for(PxU32 i=1;i<count;i++)
{
if(srcContacts[i].normal!=normal0)
{
sameNormal = false;
break;
}
}
}
contactsData.mSameNormal = sameNormal;
if(!sameNormal)
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = count * sizeOfItem;
}
else
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = sizeof(PxVec3) + count * sizeOfItem;
}
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes);
if(ls)
{
*reinterpret_cast<PxcLocalContactsCache*>(ls) = contactsData;
*reinterpret_cast<PxU32*>(ls+payloadSize) = nbBytes;
bytes = ls+payloadSize+sizeof(PxU32);
PxU8* dest = const_cast<PxU8*>(bytes);
for(PxU32 i=0;i<count;i++)
{
if(!i || !sameNormal)
dest = outputToCache(dest, srcContacts[i].normal);
dest = outputToCache(dest, srcContacts[i].point);
dest = outputToCache(dest, srcContacts[i].separation);
if(useFaceIndices)
{
dest = outputToCache(dest, srcContacts[i].internalFaceIndex1);
}
}
PX_ASSERT(size_t(dest) - size_t(bytes)==nbBytes);
}
else
{
contactsData.mNbCachedContacts = 0;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, 0, bytes);
}
}
else
{
contactsData.mNbCachedContacts = 0;
contactsData.mUseFaceIndices = false;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes, bytes);
}
}
return false;
}
| 14,360 | C++ | 28.671488 | 124 | 0.700139 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcMaterialMethodImpl.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 "PxcMaterialMethodImpl.h"
#include "PxvGeometry.h"
#include "PxcNpThreadContext.h"
#include "PxsMaterialManager.h"
#include "GuTriangleMesh.h"
#include "GuHeightField.h"
using namespace physx;
using namespace Gu;
// PT: moved these functions to same file for improving code locality and easily reusing code (calling smaller functions from larger ones, see below)
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialShape(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex = shape->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
PX_ASSERT(index==0 || index==1);
for(PxU32 i=0; i<count; i++)
(&materialInfo[i].mMaterialIndex0)[index] = materialIndex;
}
static void PxcGetMaterialShapeShape(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex0 = shape0->mMaterialIndex;
const PxU16 materialIndex1 = shape1->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
for(PxU32 i=0; i<count; i++)
{
materialInfo[i].mMaterialIndex0 = materialIndex0;
materialInfo[i].mMaterialIndex1 = materialIndex1;
}
}
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE const PxU16* getMaterialIndicesLL(const PxTriangleMeshGeometry& meshGeom)
{
return static_cast<const Gu::TriangleMesh*>(meshGeom.triangleMesh)->getMaterials();
}
static void PxcGetMaterialMesh(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxTriangleMeshGeometryLL& shapeMesh = shape->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxTriangleMeshGeometryLL& shapeMesh = shape1->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
// PT: TODO: check this, it reads shape0 and labels it shapeMesh1? It's otherwise the same code as PxcGetMaterialShapeMesh ?
const PxTriangleMeshGeometryLL& shapeMesh1 = shape0->mGeometry.get<const PxTriangleMeshGeometryLL>();
if (shapeMesh1.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh1);
const PxU16* indices = shapeMesh1.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for (PxU32 i = 0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
//contact.featureIndex1 = shapeMesh.materials.indices[localMaterialIndex];
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static PxU32 GetMaterialIndex(const Gu::HeightFieldData* hfData, PxU32 triangleIndex)
{
const PxU32 sampleIndex = triangleIndex >> 1;
const bool isFirstTriangle = (triangleIndex & 0x1) == 0;
//get sample
const PxHeightFieldSample* hf = &hfData->samples[sampleIndex];
return isFirstTriangle ? hf->materialIndex0 : hf->materialIndex1;
}
static void PxcGetMaterialHeightField(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxHeightFieldGeometryLL& hfGeom = shape->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if (hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialSoftBody(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 1);
PX_UNUSED(index);
PxcGetMaterialShape(shape, index, context, materialInfo);
}
static void PxcGetMaterialShapeSoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
static void PxcGetMaterialSoftBodySoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
///////////////////////////////////////////////////////////////////////////////
namespace physx
{
PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[] =
{
PxcGetMaterialShape, //PxGeometryType::eSPHERE
PxcGetMaterialShape, //PxGeometryType::ePLANE
PxcGetMaterialShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShape, //PxGeometryType::eBOX
PxcGetMaterialShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShape, //PxGeometryType::eCUSTOM
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetSingleMaterialMethodTable) / sizeof(g_GetSingleMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcGetMaterialShapeShape, //PxGeometryType::eSPHERE
PxcGetMaterialShapeShape, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetMaterialMethodTable) / sizeof(g_GetMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 19,532 | C++ | 42.310421 | 180 | 0.746314 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactMethodImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxGeometry.h"
#include "PxcContactMethodImpl.h"
using namespace physx;
#define ARGS shape0, shape1, transform0, transform1, params, cache, contactBuffer, renderOutput
static bool PxcInvalidContactPair (GU_CONTACT_METHOD_ARGS_UNUSED) { return false; }
// PT: IMPORTANT: do NOT remove the indirection! Using the Gu functions directly in the table produces massive perf problems.
static bool PxcContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return contactSphereSphere(ARGS); }
static bool PxcContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return contactSphereCapsule(ARGS); }
static bool PxcContactSphereBox (GU_CONTACT_METHOD_ARGS) { return contactSphereBox(ARGS); }
static bool PxcContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return contactSpherePlane(ARGS); }
static bool PxcContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return contactSphereMesh(ARGS); }
static bool PxcContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return contactSphereHeightfield(ARGS); }
static bool PxcContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return contactPlaneBox(ARGS); }
static bool PxcContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return contactPlaneCapsule(ARGS); }
static bool PxcContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return contactPlaneConvex(ARGS); }
static bool PxcContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return contactCapsuleCapsule(ARGS); }
static bool PxcContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return contactCapsuleBox(ARGS); }
static bool PxcContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return contactCapsuleMesh(ARGS); }
static bool PxcContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return contactCapsuleHeightfield(ARGS); }
static bool PxcContactBoxBox (GU_CONTACT_METHOD_ARGS) { return contactBoxBox(ARGS); }
static bool PxcContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return contactBoxConvex(ARGS); }
static bool PxcContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return contactBoxMesh(ARGS); }
static bool PxcContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return contactBoxHeightfield(ARGS); }
static bool PxcContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return contactConvexConvex(ARGS); }
static bool PxcContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return contactConvexMesh(ARGS); }
static bool PxcContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return contactConvexHeightfield(ARGS); }
static bool PxcContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return contactGeometryCustomGeometry(ARGS); }
static bool PxcPCMContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereSphere(ARGS); }
static bool PxcPCMContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return pcmContactSpherePlane(ARGS); }
static bool PxcPCMContactSphereBox (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereBox(ARGS); }
static bool PxcPCMContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereCapsule(ARGS); }
static bool PxcPCMContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereConvex(ARGS); }
static bool PxcPCMContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereMesh(ARGS); }
static bool PxcPCMContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereHeightField(ARGS); }
static bool PxcPCMContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneCapsule(ARGS); }
static bool PxcPCMContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneBox(ARGS); }
static bool PxcPCMContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneConvex(ARGS); }
static bool PxcPCMContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleCapsule(ARGS); }
static bool PxcPCMContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleBox(ARGS); }
static bool PxcPCMContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleConvex(ARGS); }
static bool PxcPCMContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleMesh(ARGS); }
static bool PxcPCMContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleHeightField(ARGS); }
static bool PxcPCMContactBoxBox (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxBox(ARGS); }
static bool PxcPCMContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxConvex(ARGS); }
static bool PxcPCMContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxMesh(ARGS); }
static bool PxcPCMContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxHeightField(ARGS); }
static bool PxcPCMContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexConvex(ARGS); }
static bool PxcPCMContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexMesh(ARGS); }
static bool PxcPCMContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexHeightField(ARGS); }
static bool PxcPCMContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return pcmContactGeometryCustomGeometry(ARGS); }
#undef ARGS
namespace physx
{
//Table of contact methods for different shape-type combinations
PxcContactMethod g_ContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcContactSphereSphere, //PxGeometryType::eSPHERE
PxcContactSpherePlane, //PxGeometryType::ePLANE
PxcContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcContactSphereBox, //PxGeometryType::eBOX
PxcContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcContactPlaneBox, //PxGeometryType::eBOX
PxcContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcContactCapsuleBox, //PxGeometryType::eBOX
PxcContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcContactBoxBox, //PxGeometryType::eBOX
PxcContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_ContactMethodTable) / sizeof(g_ContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcContactMethod g_PCMContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcPCMContactSphereSphere, //PxGeometryType::eSPHERE
PxcPCMContactSpherePlane, //PxGeometryType::ePLANE
PxcPCMContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactSphereBox, //PxGeometryType::eBOX
PxcPCMContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcPCMContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactPlaneBox, //PxGeometryType::eBOX
PxcPCMContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcPCMContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactCapsuleBox, //PxGeometryType::eBOX
PxcPCMContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcPCMContactBoxBox, //PxGeometryType::eBOX
PxcPCMContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcPCMContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_PCMContactMethodTable) / sizeof(g_PCMContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 21,192 | C++ | 48.05787 | 128 | 0.74514 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpThreadContext.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 "PxcConstraintBlockStream.h"
#include "PxcNpThreadContext.h"
using namespace physx;
PxcNpThreadContext::PxcNpThreadContext(PxcNpContext* params) :
mRenderOutput (params->mRenderBuffer),
mContactBlockStream (params->mNpMemBlockPool),
mNpCacheStreamPair (params->mNpMemBlockPool),
mNarrowPhaseParams (0.0f, params->mMeshContactMargin, params->mToleranceLength),
mBodySimPool ("BodySimPool"),
mPCM (false),
mContactCache (false),
mCreateAveragePoint (false),
#if PX_ENABLE_SIM_STATS
mCompressedCacheSize (0),
mNbDiscreteContactPairsWithCacheHits(0),
mNbDiscreteContactPairsWithContacts (0),
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mMaxPatches (0),
mTotalCompressedCacheSize (0),
mContactStreamPool (params->mContactStreamPool),
mPatchStreamPool (params->mPatchStreamPool),
mForceAndIndiceStreamPool (params->mForceAndIndiceStreamPool),
mMaterialManager (params->mMaterialManager),
mLocalNewTouchCount (0),
mLocalLostTouchCount (0)
{
#if PX_ENABLE_SIM_STATS
clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
PxcNpThreadContext::~PxcNpThreadContext()
{
}
#if PX_ENABLE_SIM_STATS
void PxcNpThreadContext::clearStats()
{
PxMemSet(mDiscreteContactPairs, 0, sizeof(mDiscreteContactPairs));
PxMemSet(mModifiedContactPairs, 0, sizeof(mModifiedContactPairs));
mCompressedCacheSize = 0;
mNbDiscreteContactPairsWithCacheHits = 0;
mNbDiscreteContactPairsWithContacts = 0;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
void PxcNpThreadContext::reset(PxU32 cmCount)
{
mContactBlockStream.reset();
mNpCacheStreamPair.reset();
mLocalChangeTouch.clear();
mLocalChangeTouch.resize(cmCount);
mLocalNewTouchCount = 0;
mLocalLostTouchCount = 0;
}
| 3,476 | C++ | 36.387096 | 85 | 0.767261 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpBatch.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxTriangleMesh.h"
#include "common/PxProfileZone.h"
#include "PxcNpBatch.h"
#include "PxcNpWorkUnit.h"
#include "PxcContactCache.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "CmTask.h"
#include "PxsMaterialManager.h"
#include "PxsTransformCache.h"
#include "PxsContactManagerState.h"
// PT: use this define to enable detailed analysis of the NP functions.
//#define LOCAL_PROFILE_ZONE(x, y) PX_PROFILE_ZONE(x, y)
#define LOCAL_PROFILE_ZONE(x, y)
using namespace physx;
using namespace Gu;
PX_COMPILE_TIME_ASSERT(sizeof(PxsCachedTransform)==sizeof(PxTransform32));
static void startContacts(PxsContactManagerOutput& output, PxcNpThreadContext& context)
{
context.mContactBuffer.reset();
output.contactForces = NULL;
output.contactPatches = NULL;
output.contactPoints = NULL;
output.nbContacts = 0;
output.nbPatches = 0;
output.statusFlag = 0;
}
static void flipContacts(PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT materialInfo)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
for(PxU32 i=0; i<buffer.count; ++i)
{
PxContactPoint& contactPoint = buffer.contacts[i];
contactPoint.normal = -contactPoint.normal;
PxSwap(materialInfo[i].mMaterialIndex0, materialInfo[i].mMaterialIndex1);
}
}
static PX_FORCE_INLINE void updateDiscreteContactStats(PxcNpThreadContext& context, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
#if PX_ENABLE_SIM_STATS
PX_ASSERT(type0<=type1);
context.mDiscreteContactPairs[type0][type1]++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(context);
PX_UNUSED(type0);
PX_UNUSED(type1);
#endif
}
static bool copyBuffers(PxsContactManagerOutput& cmOutput, Gu::Cache& cache, PxcNpThreadContext& context, const bool useContactCache, const bool isMeshType)
{
bool ret = false;
//Copy the contact stream from previous buffer to current buffer...
PxU32 oldSize = sizeof(PxContact) * cmOutput.nbContacts + sizeof(PxContactPatch)*cmOutput.nbPatches;
if(oldSize)
{
ret = true;
PxU8* oldPatches = cmOutput.contactPatches;
PxU8* oldContacts = cmOutput.contactPoints;
PxReal* oldForces = cmOutput.contactForces;
PxU32 forceSize = cmOutput.nbContacts * sizeof(PxReal);
if(isMeshType)
forceSize += cmOutput.nbContacts * sizeof(PxU32);
PxU8* PX_RESTRICT contactPatches = NULL;
PxU8* PX_RESTRICT contactPoints = NULL;
PxReal* forceBuffer = NULL;
bool isOverflown = false;
//ML: if we are using contactStreamPool, which means we are running the GPU codepath
if(context.mContactStreamPool)
{
const PxU32 patchSize = cmOutput.nbPatches * sizeof(PxContactPatch);
const PxU32 contactSize = cmOutput.nbContacts * sizeof(PxContact);
PxU32 index = PxU32(PxAtomicAdd(&context.mContactStreamPool->mSharedDataIndex, PxI32(contactSize)));
if(context.mContactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPoints = context.mContactStreamPool->mDataStream + context.mContactStreamPool->mDataStreamSize - index;
const PxU32 patchIndex = PxU32(PxAtomicAdd(&context.mPatchStreamPool->mSharedDataIndex, PxI32(patchSize)));
if(context.mPatchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPatches = context.mPatchStreamPool->mDataStream + context.mPatchStreamPool->mDataStreamSize - patchIndex;
if(forceSize)
{
index = PxU32(PxAtomicAdd(&context.mForceAndIndiceStreamPool->mSharedDataIndex, PxI32(forceSize)));
if(context.mForceAndIndiceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceBuffer = reinterpret_cast<PxReal*>(context.mForceAndIndiceStreamPool->mDataStream + context.mForceAndIndiceStreamPool->mDataStreamSize - index);
}
if(isOverflown)
{
contactPatches = NULL;
contactPoints = NULL;
forceBuffer = NULL;
cmOutput.nbContacts = cmOutput.nbPatches = 0;
}
else
{
PxMemCopy(contactPatches, oldPatches, patchSize);
PxMemCopy(contactPoints, oldContacts, contactSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
}
else
{
const PxU32 alignedOldSize = (oldSize + 0xf) & 0xfffffff0;
PxU8* data = context.mContactBlockStream.reserve(alignedOldSize + forceSize);
if(forceSize)
forceBuffer = reinterpret_cast<PxReal*>(data + alignedOldSize);
contactPatches = data;
contactPoints = data + cmOutput.nbPatches * sizeof(PxContactPatch);
PxMemCopy(data, oldPatches, oldSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
if(forceSize)
PxMemZero(forceBuffer, forceSize);
cmOutput.contactPatches= contactPatches;
cmOutput.contactPoints = contactPoints;
cmOutput.contactForces = forceBuffer;
}
if(cache.mCachedSize)
{
if(cache.isMultiManifold())
{
PX_ASSERT((cache.mCachedSize & 0xF) == 0);
PxU8* newData = context.mNpCacheStreamPair.reserve(cache.mCachedSize);
PX_ASSERT((reinterpret_cast<uintptr_t>(newData)& 0xF) == 0);
PxMemCopy(newData, & cache.getMultipleManifold(), cache.mCachedSize);
cache.setMultiManifold(newData);
}
else if(useContactCache)
{
//Copy cache information as well...
const PxU8* cachedData = cache.mCachedData;
PxU8* newData = context.mNpCacheStreamPair.reserve(PxU32(cache.mCachedSize + 0xf) & 0xfff0);
PxMemCopy(newData, cachedData, cache.mCachedSize);
cache.mCachedData = newData;
}
}
return ret;
}
//ML: isMeshType is used in the GPU codepath. If the collision pair is mesh/heightfield vs primitives, we need to allocate enough memory for the mForceAndIndiceStreamPool in the threadContext.
static bool finishContacts(const PxcNpWorkUnit& input, PxsContactManagerOutput& npOutput, PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT pMaterials, const bool isMeshType, PxU64 contextID)
{
PX_UNUSED(contextID);
LOCAL_PROFILE_ZONE("finishContacts", contextID);
PxContactBuffer& buffer = threadContext.mContactBuffer;
PX_ASSERT((npOutput.statusFlag & PxsContactManagerStatusFlag::eTOUCH_KNOWN) != PxsContactManagerStatusFlag::eTOUCH_KNOWN);
PxU8 statusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
if(buffer.count)
statusFlags |= PxsContactManagerStatusFlag::eHAS_TOUCH;
else
statusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.nbContacts = PxTo16(buffer.count);
if(!buffer.count)
{
npOutput.statusFlag = statusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
return true;
}
PX_ASSERT(buffer.count);
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
npOutput.statusFlag = statusFlags;
PxU32 contactForceByteSize = buffer.count * sizeof(PxReal);
//Regardless of the flags, we need to now record the compressed contact stream
PxU16 compressedContactSize;
const bool createReports =
input.flags & PxcNpWorkUnitFlag::eOUTPUT_CONTACTS
|| (input.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
if((!isMeshType && !createReports))
contactForceByteSize = 0;
bool res = (writeCompressedContact(buffer.contacts, buffer.count, &threadContext, npOutput.nbContacts, npOutput.contactPatches, npOutput.contactPoints, compressedContactSize,
reinterpret_cast<PxReal*&>(npOutput.contactForces), contactForceByteSize, threadContext.mMaterialManager, ((input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT) != 0),
false, pMaterials, npOutput.nbPatches, 0, NULL, NULL, threadContext.mCreateAveragePoint, threadContext.mContactStreamPool,
threadContext.mPatchStreamPool, threadContext.mForceAndIndiceStreamPool, isMeshType) != 0);
//handle buffer overflow
if(!npOutput.nbContacts)
{
PxU8 thisStatusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
thisStatusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.statusFlag = thisStatusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts--;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
return res;
}
template<bool useContactCacheT>
static PX_FORCE_INLINE bool checkContactsMustBeGenerated(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output,
const PxsCachedTransform* cachedTransform0, const PxsCachedTransform* cachedTransform1,
const bool flip, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
PX_ASSERT(cachedTransform0->transform.isSane() && cachedTransform1->transform.isSane());
//ML : if user doesn't raise the eDETECT_DISCRETE_CONTACT, we should not generate contacts
if(!(input.flags & PxcNpWorkUnitFlag::eDETECT_DISCRETE_CONTACT))
return false;
if(!(output.statusFlag & PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER) && !(input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT))
{
const PxU32 body0Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 body1Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 active0 = PxU32(body0Dynamic && !cachedTransform0->isFrozen());
const PxU32 active1 = PxU32(body1Dynamic && !cachedTransform1->isFrozen());
if(!(active0 || active1))
{
if(flip)
PxSwap(type0, type1);
const bool useContactCache = useContactCacheT ? context.mContactCache && g_CanUseContactCache[type0][type1] : false;
#if PX_ENABLE_SIM_STATS
if(output.nbContacts)
context.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
copyBuffers(output, cache, context, useContactCache, isMeshType);
return false;
}
}
output.statusFlag &= (~PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER);
const PxReal contactDist0 = context.mContactDistances[input.mTransformCache0];
const PxReal contactDist1 = context.mContactDistances[input.mTransformCache1];
//context.mNarrowPhaseParams.mContactDistance = shape0->contactOffset + shape1->contactOffset;
context.mNarrowPhaseParams.mContactDistance = contactDist0 + contactDist1;
return true;
}
template<bool useLegacyCodepath>
static PX_FORCE_INLINE void discreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
PxGeometryType::Enum type0 = static_cast<PxGeometryType::Enum>(input.geomType0);
PxGeometryType::Enum type1 = static_cast<PxGeometryType::Enum>(input.geomType1);
const bool flip = (type1<type0);
const PxsCachedTransform* cachedTransform0 = &context.mTransformCache->getTransformCache(input.mTransformCache0);
const PxsCachedTransform* cachedTransform1 = &context.mTransformCache->getTransformCache(input.mTransformCache1);
if(!checkContactsMustBeGenerated<useLegacyCodepath>(context, input, cache, output, cachedTransform0, cachedTransform1, flip, type0, type1))
return;
PxsShapeCore* shape0 = const_cast<PxsShapeCore*>(input.shapeCore0);
PxsShapeCore* shape1 = const_cast<PxsShapeCore*>(input.shapeCore1);
if(flip)
{
PxSwap(type0, type1);
PxSwap(shape0, shape1);
PxSwap(cachedTransform0, cachedTransform1);
}
PxsMaterialInfo materialInfo[PxContactBuffer::MAX_CONTACTS];
Gu::MultiplePersistentContactManifold& manifold = context.mTempManifold;
bool isMultiManifold = false;
if(!useLegacyCodepath)
{
if(cache.isMultiManifold())
{
//We are using a multi-manifold. This is cached in a reduced npCache...
isMultiManifold = true;
uintptr_t address = uintptr_t(&cache.getMultipleManifold());
manifold.fromBuffer(reinterpret_cast<PxU8*>(address));
cache.setMultiManifold(&manifold);
}
else if(cache.isManifold())
{
void* address = reinterpret_cast<void*>(&cache.getManifold());
PxPrefetch(address);
PxPrefetch(address, 128);
PxPrefetch(address, 256);
}
}
updateDiscreteContactStats(context, type0, type1);
startContacts(output, context);
const PxTransform32* tm0 = reinterpret_cast<const PxTransform32*>(cachedTransform0);
const PxTransform32* tm1 = reinterpret_cast<const PxTransform32*>(cachedTransform1);
PX_ASSERT(tm0->isSane() && tm1->isSane());
const PxGeometry& contactShape0 = shape0->mGeometry.getGeometry();
const PxGeometry& contactShape1 = shape1->mGeometry.getGeometry();
if(useLegacyCodepath)
{
// PT: many cache misses here...
PxPrefetchLine(shape1, 0); // PT: at least get rid of L2s for shape1
const PxcContactMethod conMethod = g_ContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
const bool useContactCache = context.mContactCache && g_CanUseContactCache[type0][type1];
if(useContactCache)
{
const bool status = PxcCacheLocalContacts(context, cache, *tm0, *tm1, conMethod, contactShape0, contactShape1);
#if PX_ENABLE_SIM_STATS
if(status)
context.mNbDiscreteContactPairsWithCacheHits++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(status);
#endif
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
const PxcContactMethod conMethod = g_PCMContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
if(context.mContactBuffer.count)
{
const PxcGetMaterialMethod materialMethod = g_GetMaterialMethodTable[type0][type1];
if(materialMethod)
{
LOCAL_PROFILE_ZONE("materialMethod", contextID);
materialMethod(shape0, shape1, context, materialInfo);
}
if(flip)
{
LOCAL_PROFILE_ZONE("flipContacts", contextID);
flipContacts(context, materialInfo);
}
}
if(!useLegacyCodepath)
{
if(isMultiManifold)
{
//Store the manifold back...
const PxU32 size = (sizeof(MultiPersistentManifoldHeader) +
manifold.mNumManifolds * sizeof(SingleManifoldHeader) +
manifold.mNumTotalContacts * sizeof(Gu::CachedMeshPersistentContact));
PxU8* buffer = context.mNpCacheStreamPair.reserve(size);
PX_ASSERT((reinterpret_cast<uintptr_t>(buffer)& 0xf) == 0);
manifold.toBuffer(buffer);
cache.setMultiManifold(buffer);
cache.mCachedSize = PxTo16(size);
}
}
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
finishContacts(input, output, context, materialInfo, isMeshType, contextID);
}
void physx::PxcDiscreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhase", contextID);
discreteNarrowPhase<true>(context, input, cache, output, contextID);
}
void physx::PxcDiscreteNarrowPhasePCM(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhasePCM", contextID);
discreteNarrowPhase<false>(context, input, cache, output, contextID);
}
| 17,311 | C++ | 35.91258 | 205 | 0.763214 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpContactPrepShared.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "PxcNpWorkUnit.h"
#include "PxvDynamics.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcNpContactPrepShared.h"
#include "foundation/PxAtomic.h"
#include "PxsContactManagerState.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxErrors.h"
using namespace physx;
using namespace aos;
static PX_FORCE_INLINE void copyContactPoint(PxContact* PX_RESTRICT point, const PxContactPoint* PX_RESTRICT cp)
{
// PT: TODO: consider moving "separation" right after "point" in both structures, to copy both at the same time.
// point->contact = cp->point;
const Vec4V contactV = V4LoadA(&cp->point.x); // PT: V4LoadA safe because 'point' is aligned.
V4StoreU(contactV, &point->contact.x);
point->separation = cp->separation;
}
void combineMaterials(const PxsMaterialManager* materialManager, PxU16 origMatIndex0, PxU16 origMatIndex1, PxReal& staticFriction, PxReal& dynamicFriction, PxReal& combinedRestitution, PxU32& materialFlags, PxReal& combinedDamping)
{
const PxsMaterialData& data0 = *materialManager->getMaterial(origMatIndex0);
const PxsMaterialData& data1 = *materialManager->getMaterial(origMatIndex1);
combinedRestitution = PxsCombineRestitution(data0, data1);
combinedDamping = PxMax(data0.damping, data1.damping);
PxsCombineIsotropicFriction(data0, data1, dynamicFriction, staticFriction, materialFlags);
}
struct StridePatch
{
PxU8 startIndex;
PxU8 endIndex;
PxU8 nextIndex;
PxU8 totalCount;
bool isRoot;
};
PxU32 physx::writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& outContactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize, PxsConstraintBlockManager* manager, PxcConstraintBlockStream* blockStream, bool insertAveragePoint,
PxcDataStreamPool* contactStreamPool, PxcDataStreamPool* patchStreamPool, PxcDataStreamPool* forceStreamPool, const bool isMeshType)
{
if(numContactPoints == 0)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
//Calculate the size of the contact buffer...
PX_ALLOCA(strPatches, StridePatch, numContactPoints);
StridePatch* stridePatches = &strPatches[0];
PxU32 numStrideHeaders = 1;
PxU32 totalUniquePatches = 1;
PxU32 totalContactPoints = numContactPoints;
PxU32 strideStart = 0;
bool root = true;
StridePatch* parentRootPatch = NULL;
{
const PxReal closeNormalThresh = PXC_SAME_NORMAL;
//Go through and tag how many patches we have...
PxVec3 normal = contactPoints[0].normal;
PxU16 mat0 = pMaterial[0].mMaterialIndex0;
PxU16 mat1 = pMaterial[0].mMaterialIndex1;
for(PxU32 a = 1; a < numContactPoints; ++a)
{
if(normal.dot(contactPoints[a].normal) < closeNormalThresh ||
pMaterial[a].mMaterialIndex0 != mat0 || pMaterial[a].mMaterialIndex1 != mat1)
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(a);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(a - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(a - strideStart);
root = true;
parentRootPatch = NULL;
for(PxU32 b = 1; b < numStrideHeaders; ++b)
{
StridePatch& thisPatch = stridePatches[b-1];
if(thisPatch.isRoot)
{
PxU32 ind = thisPatch.startIndex;
PxReal dp2 = contactPoints[a].normal.dot(contactPoints[ind].normal);
if(dp2 >= closeNormalThresh && pMaterial[a].mMaterialIndex0 == pMaterial[ind].mMaterialIndex0 &&
pMaterial[a].mMaterialIndex1 == pMaterial[ind].mMaterialIndex1)
{
PxU32 nextInd = b-1;
while(stridePatches[nextInd].nextIndex != 0xFF)
nextInd = stridePatches[nextInd].nextIndex;
stridePatches[nextInd].nextIndex = PxU8(numStrideHeaders);
root = false;
parentRootPatch = &stridePatches[b-1];
break;
}
}
}
normal = contactPoints[a].normal;
mat0 = pMaterial[a].mMaterialIndex0;
mat1 = pMaterial[a].mMaterialIndex1;
totalContactPoints = insertAveragePoint && (a - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
strideStart = a;
numStrideHeaders++;
if(root)
totalUniquePatches++;
}
}
totalContactPoints = insertAveragePoint &&(numContactPoints - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
contactForceByteSize = insertAveragePoint && contactForceByteSize != 0 ? contactForceByteSize + sizeof(PxF32) * (totalContactPoints - numContactPoints) : contactForceByteSize;
}
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(numContactPoints);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(numContactPoints - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(numContactPoints - strideStart);
}
numPatches = PxU8(totalUniquePatches);
//Calculate the number of patches/points required
const bool isModifiable = !forceNoResponse && hasModifiableContacts;
const PxU32 patchHeaderSize = sizeof(PxContactPatch) * (isModifiable ? totalContactPoints : totalUniquePatches) + additionalHeaderSize;
const PxU32 pointSize = totalContactPoints * (isModifiable ? sizeof(PxModifiableContact) : sizeof(PxContact));
PxU32 requiredContactSize = pointSize;
PxU32 requiredPatchSize = patchHeaderSize;
PxU32 totalRequiredSize;
PxU8* PX_RESTRICT contactData = NULL;
PxU8* PX_RESTRICT patchData = NULL;
PxReal* PX_RESTRICT forceData = NULL;
PxU32* PX_RESTRICT triangleIndice = NULL;
if(contactStreamPool && !isModifiable && additionalHeaderSize == 0) //If the contacts are modifiable, we **DON'T** allocate them in GPU pinned memory. This will be handled later when they're modified
{
bool isOverflown = false;
PxU32 contactIndex = PxU32(PxAtomicAdd(&contactStreamPool->mSharedDataIndex, PxI32(requiredContactSize)));
if (contactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactData = contactStreamPool->mDataStream + contactStreamPool->mDataStreamSize - contactIndex;
PxU32 patchIndex = PxU32(PxAtomicAdd(&patchStreamPool->mSharedDataIndex, PxI32(requiredPatchSize)));
if (patchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
patchData = patchStreamPool->mDataStream + patchStreamPool->mDataStreamSize - patchIndex;
if(contactForceByteSize)
{
contactForceByteSize = isMeshType ? contactForceByteSize * 2 : contactForceByteSize;
contactIndex = PxU32(PxAtomicAdd(&forceStreamPool->mSharedDataIndex, PxI32(contactForceByteSize)));
if (forceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceData = reinterpret_cast<PxReal*>(forceStreamPool->mDataStream + forceStreamPool->mDataStreamSize - contactIndex);
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
}
totalRequiredSize = requiredContactSize + requiredPatchSize;
if (isOverflown)
{
patchData = NULL;
contactData = NULL;
forceData = NULL;
triangleIndice = NULL;
}
}
else
{
PxU32 alignedRequiredSize = (requiredContactSize + requiredPatchSize + 0xf) & 0xfffffff0;
contactForceByteSize = (isMeshType ? contactForceByteSize * 2 : contactForceByteSize);
PxU32 totalSize = alignedRequiredSize + contactForceByteSize;
PxU8* data = manager ? blockStream->reserve(totalSize, *manager) : threadContext->mContactBlockStream.reserve(totalSize);
patchData = data;
contactData = patchData + requiredPatchSize;
if(contactForceByteSize)
{
forceData = reinterpret_cast<PxReal*>((data + alignedRequiredSize));
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
if(data)
{
PxMemZero(forceData, contactForceByteSize);
}
}
totalRequiredSize = alignedRequiredSize;
}
PxPrefetchLine(patchData);
PxPrefetchLine(contactData);
if(patchData == NULL)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
#if PX_ENABLE_SIM_STATS
if(threadContext)
{
threadContext->mCompressedCacheSize += totalRequiredSize;
threadContext->mTotalCompressedCacheSize += totalRequiredSize;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
compressedContactSize = PxTo16(totalRequiredSize);
//PxU32 startIndex = 0;
//Extract first material
PxU16 origMatIndex0 = pMaterial[0].mMaterialIndex0;
PxU16 origMatIndex1 = pMaterial[0].mMaterialIndex1;
PxReal staticFriction, dynamicFriction, combinedRestitution, combinedDamping;
PxU32 materialFlags;
combineMaterials(materialManager, origMatIndex0, origMatIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
PxU8* PX_RESTRICT dataPlusOffset = patchData + additionalHeaderSize;
PxContactPatch* PX_RESTRICT patches = reinterpret_cast<PxContactPatch*>(dataPlusOffset);
PxU32* PX_RESTRICT faceIndice = triangleIndice;
outContactPatches = patchData;
outContactPoints = contactData;
outContactForces = forceData;
struct Local
{
static PX_FORCE_INLINE void fillPatch(PxContactPatch* PX_RESTRICT patch, const StridePatch& rootPatch, const PxVec3& normal,
PxU32 currentIndex, PxReal staticFriction_, PxReal dynamicFriction_, PxReal combinedRestitution_, PxReal combinedDamping_,
PxU32 materialFlags_, PxU32 flags, PxU16 matIndex0, PxU16 matIndex1
)
{
patch->mMassModification.linear0 = 1.0f;
patch->mMassModification.linear1 = 1.0f;
patch->mMassModification.angular0 = 1.0f;
patch->mMassModification.angular1 = 1.0f;
PX_ASSERT(PxAbs(normal.magnitude() - 1) < 1e-3f);
patch->normal = normal;
patch->restitution = combinedRestitution_;
patch->dynamicFriction = dynamicFriction_;
patch->staticFriction = staticFriction_;
patch->damping = combinedDamping_;
patch->startContactIndex = PxTo8(currentIndex);
//KS - we could probably compress this further into the header but the complexity might not be worth it
patch->nbContacts = rootPatch.totalCount;
patch->materialFlags = PxU8(materialFlags_);
patch->internalFlags = PxU8(flags);
patch->materialIndex0 = matIndex0;
patch->materialIndex1 = matIndex1;
}
};
if(isModifiable)
{
PxU32 flags = PxU32(isModifiable ? PxContactPatch::eMODIFIABLE : 0) |
(forceNoResponse ? PxContactPatch::eFORCE_NO_RESPONSE : 0) |
(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxU32 currentIndex = 0;
PxModifiableContact* PX_RESTRICT point = reinterpret_cast<PxModifiableContact*>(contactData);
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
//const PxU32 endIndex = strideHeader[a];
const PxU32 totalCountThisPatch = rootPatch.totalCount;
if(insertAveragePoint && totalCountThisPatch > 1)
{
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = p.nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
patch->nbContacts++;
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point->normal = contactPoints[startIndex].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
point->normal = contactPoints[b].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = p.nextIndex;
}
}
}
}
else
{
PxU32 flags = PxU32(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxContact* PX_RESTRICT point = reinterpret_cast<PxContact*>(contactData);
PxU32 currentIndex = 0;
{
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
if(insertAveragePoint && (rootPatch.totalCount) > 1)
{
patch->nbContacts++;
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = stridePatches[index].nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = stridePatches[index].nextIndex;
}
}
}
}
}
writtenContactCount = PxTo16(totalContactPoints);
return totalRequiredSize;
}
| 18,676 | C++ | 33.91028 | 231 | 0.720979 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcMaterialMethodImpl.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 PXC_MATERIAL_METHOD_H
#define PXC_MATERIAL_METHOD_H
#include "geometry/PxGeometry.h"
namespace physx
{
struct PxsShapeCore;
struct PxsMaterialInfo;
class PxcNpThreadContext;
#define MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape0, \
const PxsShapeCore* shape1, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
#define SINGLE_MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape, \
const PxU32 index, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
/*!
Method prototype for fetch material routines
*/
typedef void (*PxcGetMaterialMethod) (MATERIAL_METHOD_ARGS);
typedef void (*PxcGetSingleMaterialMethod) (SINGLE_MATERIAL_METHOD_ARGS);
extern PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT];
extern PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[PxGeometryType::eGEOMETRY_COUNT];
}
#endif
| 2,609 | C | 37.382352 | 98 | 0.774243 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpWorkUnit.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 PXC_NP_WORK_UNIT_H
#define PXC_NP_WORK_UNIT_H
#include "PxcNpThreadContext.h"
#include "PxcMaterialMethodImpl.h"
#include "PxcNpCache.h"
namespace physx
{
struct PxsRigidCore;
struct PxsShapeCore;
struct PxcNpWorkUnitFlag
{
enum Enum
{
eOUTPUT_CONTACTS = 1 << 0,
eOUTPUT_CONSTRAINTS = 1 << 1,
eDISABLE_STRONG_FRICTION = 1 << 2,
eARTICULATION_BODY0 = 1 << 3,
eARTICULATION_BODY1 = 1 << 4,
eDYNAMIC_BODY0 = 1 << 5,
eDYNAMIC_BODY1 = 1 << 6,
eSOFT_BODY = 1 << 7,
eMODIFIABLE_CONTACT = 1 << 8,
eFORCE_THRESHOLD = 1 << 9,
eDETECT_DISCRETE_CONTACT = 1 << 10,
eHAS_KINEMATIC_ACTOR = 1 << 11,
eDISABLE_RESPONSE = 1 << 12,
eDETECT_CCD_CONTACTS = 1 << 13,
};
};
struct PxcNpWorkUnitStatusFlag
{
enum Enum
{
eHAS_NO_TOUCH = (1 << 0),
eHAS_TOUCH = (1 << 1),
//eHAS_SOLVER_CONSTRAINTS = (1 << 2),
eREQUEST_CONSTRAINTS = (1 << 3),
eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the
// contact report callback if requested.
eDIRTY_MANAGER = (1 << 5),
eREFRESHED_WITH_TOUCH = (1 << 6),
eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH // The touch status is known (if narrowphase never ran for a pair then no flag will be set)
};
};
// PT: TODO: fix the inconsistent namings (mXXX) in this class
struct PxcNpWorkUnit
{
const PxsRigidCore* rigidCore0; // INPUT //4 //8
const PxsRigidCore* rigidCore1; // INPUT //8 //16
const PxsShapeCore* shapeCore0; // INPUT //12 //24
const PxsShapeCore* shapeCore1; // INPUT //16 //32
PxU8* ccdContacts; // OUTPUT //20 //40
PxU8* frictionDataPtr; // INOUT //24 //48
PxU16 flags; // INPUT //26 //50
PxU8 frictionPatchCount; // INOUT //27 //51
PxU8 statusFlags; // OUTPUT (see PxcNpWorkUnitStatusFlag) //28 //52
PxU8 dominance0; // INPUT //29 //53
PxU8 dominance1; // INPUT //30 //54
PxU8 geomType0; // INPUT //31 //55
PxU8 geomType1; // INPUT //32 //56
PxU32 index; // INPUT //36 //60
PxReal restDistance; // INPUT //40 //64
PxU32 mTransformCache0; // //44 //68
PxU32 mTransformCache1; // //48 //72
PxU32 mEdgeIndex; //inout the island gen edge index //52 //76
PxU32 mNpIndex; //INPUT //56 //80
PxReal mTorsionalPatchRadius; //60 //84
PxReal mMinTorsionalPatchRadius; //64 //88
PxReal mOffsetSlop; //68 //92
PX_FORCE_INLINE void clearCachedState()
{
frictionDataPtr = NULL;
frictionPatchCount = 0;
ccdContacts = NULL;
}
};
//#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxcNpWorkUnit) & 0x0f));
//#endif
#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(sizeof(PxcNpWorkUnit)==128);
#endif
}
#endif
| 4,799 | C | 35.090225 | 153 | 0.656178 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpMemBlockPool.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 PXC_NP_MEM_BLOCK_POOL_H
#define PXC_NP_MEM_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
namespace physx
{
class PxcScratchAllocator;
struct PxcNpMemBlock
{
enum
{
SIZE = 16384
};
PxU8 data[SIZE];
};
typedef PxArray<PxcNpMemBlock*> PxcNpMemBlockArray;
class PxcNpMemBlockPool
{
PX_NOCOPY(PxcNpMemBlockPool)
public:
PxcNpMemBlockPool(PxcScratchAllocator& allocator);
~PxcNpMemBlockPool();
void init(PxU32 initial16KDataBlocks, PxU32 maxBlocks);
void flush();
void setBlockCount(PxU32 count);
PxU32 getUsedBlockCount() const;
PxU32 getMaxUsedBlockCount() const;
PxU32 getPeakConstraintBlockCount() const;
void releaseUnusedBlocks();
PxcNpMemBlock* acquireConstraintBlock();
PxcNpMemBlock* acquireConstraintBlock(PxcNpMemBlockArray& memBlocks);
PxcNpMemBlock* acquireContactBlock();
PxcNpMemBlock* acquireFrictionBlock();
PxcNpMemBlock* acquireNpCacheBlock();
PxU8* acquireExceptionalConstraintMemory(PxU32 size);
void acquireConstraintMemory();
void releaseConstraintMemory();
void releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks);
void releaseContacts();
void swapFrictionStreams();
void swapNpCacheStreams();
void flushUnused();
private:
PxMutex mLock;
PxcNpMemBlockArray mConstraints;
PxcNpMemBlockArray mContacts[2];
PxcNpMemBlockArray mFriction[2];
PxcNpMemBlockArray mNpCache[2];
PxcNpMemBlockArray mScratchBlocks;
PxArray<PxU8*> mExceptionalConstraints;
PxcNpMemBlockArray mUnused;
PxU32 mNpCacheActiveStream;
PxU32 mFrictionActiveStream;
PxU32 mCCDCacheActiveStream;
PxU32 mContactIndex;
PxU32 mAllocatedBlocks;
PxU32 mMaxBlocks;
PxU32 mInitialBlocks;
PxU32 mUsedBlocks;
PxU32 mMaxUsedBlocks;
PxcNpMemBlock* mScratchBlockAddr;
PxU32 mNbScratchBlocks;
PxcScratchAllocator& mScratchAllocator;
PxU32 mPeakConstraintAllocations;
PxU32 mConstraintAllocations;
PxcNpMemBlock* acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount = NULL, PxU32* peakAllocationCount = NULL, bool isScratchAllocation = false);
void release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount = NULL);
};
}
#endif
| 3,940 | C | 32.398305 | 159 | 0.770812 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpContactPrepShared.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 PXC_NP_CONTACT_PREP_SHARED_H
#define PXC_NP_CONTACT_PREP_SHARED_H
namespace physx
{
class PxcNpThreadContext;
struct PxsMaterialInfo;
class PxsMaterialManager;
class PxsConstraintBlockManager;
class PxcConstraintBlockStream;
struct PxsContactManagerOutput;
namespace Gu
{
struct ContactPoint;
}
static const PxReal PXC_SAME_NORMAL = 0.999f; //Around 6 degrees
PxU32 writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& contactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize = 0, PxsConstraintBlockManager* manager = NULL, PxcConstraintBlockStream* blockStream = NULL, bool insertAveragePoint = false,
PxcDataStreamPool* pool = NULL, PxcDataStreamPool* patchStreamPool = NULL, PxcDataStreamPool* forcePool = NULL, const bool isMeshType = false);
}
#endif
| 2,879 | C | 49.526315 | 168 | 0.783258 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcConstraintBlockStream.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 PXC_CONSTRAINT_BLOCK_POOL_H
#define PXC_CONSTRAINT_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
#include "PxcNpMemBlockPool.h"
namespace physx
{
class PxsConstraintBlockManager
{
public:
PxsConstraintBlockManager(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool)
{
}
PX_FORCE_INLINE void reset()
{
mBlockPool.releaseConstraintBlocks(mTrackingArray);
}
PxcNpMemBlockArray mTrackingArray;
PxcNpMemBlockPool& mBlockPool;
private:
PxsConstraintBlockManager& operator=(const PxsConstraintBlockManager&);
};
class PxcConstraintBlockStream
{
PX_NOCOPY(PxcConstraintBlockStream)
public:
PxcConstraintBlockStream(PxcNpMemBlockPool & blockPool) :
mBlockPool (blockPool),
mBlock (NULL),
mUsed (0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size, PxsConstraintBlockManager& manager)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireConstraintBlock(manager.mTrackingArray);
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
//Tracking peak allocations
PxU32 mPeakUsed;
};
class PxcContactBlockStream
{
PX_NOCOPY(PxcContactBlockStream)
public:
PxcContactBlockStream(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool),
mBlock(NULL),
mUsed(0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
PX_ASSERT(size <= PxcNpMemBlock::SIZE);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireContactBlock();
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
};
}
#endif
| 4,995 | C | 31.232258 | 84 | 0.682082 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpCache.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 PXC_NP_CACHE_H
#define PXC_NP_CACHE_H
#include "foundation/PxMemory.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxPool.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCacheStreamPair.h"
#include "GuContactMethodImpl.h"
namespace physx
{
template <typename T>
void PxcNpCacheWrite(PxcNpCacheStreamPair& streams,
Gu::Cache& cache,
const T& payload,
PxU32 bytes,
const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(ls==NULL || (reinterpret_cast<PxU8*>(-1))==ls)
{
if(ls==NULL)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
return;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
return;
}
}
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PxU8* PxcNpCacheWriteInitiate(PxcNpCacheStreamPair& streams, Gu::Cache& cache, const T& payload, PxU32 bytes)
{
PX_UNUSED(payload);
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(NULL==ls || reinterpret_cast<PxU8*>(-1)==ls)
{
if(NULL==ls)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
}
}
return ls;
}
template <typename T>
PX_FORCE_INLINE void PxcNpCacheWriteFinalize(PxU8* ls, const T& payload, PxU32 bytes, const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PX_FORCE_INLINE PxU8* PxcNpCacheRead(Gu::Cache& cache, T*& payload)
{
PxU8* ls = cache.mCachedData;
payload = reinterpret_cast<T*>(ls);
const PxU32 payloadSize = (sizeof(T)+3)&~3;
return reinterpret_cast<PxU8*>(ls+payloadSize+sizeof(PxU32));
}
template <typename T>
const PxU8* PxcNpCacheRead2(Gu::Cache& cache, T& payload, PxU32& bytes)
{
const PxU8* ls = cache.mCachedData;
if(ls==NULL)
{
bytes = 0;
return NULL;
}
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
payload = *reinterpret_cast<const T*>(ls);
bytes = *reinterpret_cast<const PxU32*>(ls+payloadSize);
PX_ASSERT(cache.mCachedSize == ((payloadSize + 4 + bytes+0xF)&~0xF));
return reinterpret_cast<const PxU8*>(ls+payloadSize+sizeof(PxU32));
}
}
#endif
| 5,161 | C | 32.738562 | 140 | 0.728347 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpThreadContext.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 PXC_NP_THREAD_CONTEXT_H
#define PXC_NP_THREAD_CONTEXT_H
#include "geometry/PxGeometry.h"
#include "geomutils/PxContactBuffer.h"
#include "common/PxRenderOutput.h"
#include "CmRenderBuffer.h"
#include "PxvConfig.h"
#include "CmScaling.h"
#include "PxcNpCacheStreamPair.h"
#include "PxcConstraintBlockStream.h"
#include "PxcThreadCoherentCache.h"
#include "PxcScratchAllocator.h"
#include "foundation/PxBitMap.h"
#include "../pcm/GuPersistentContactManifold.h"
#include "../contact/GuContactMethodImpl.h"
namespace physx
{
class PxsTransformCache;
class PxsMaterialManager;
namespace Sc
{
class BodySim;
}
/*!
Per-thread context used by contact generation routines.
*/
struct PxcDataStreamPool
{
PxU8* mDataStream;
PxI32 mSharedDataIndex;
PxU32 mDataStreamSize;
PxU32 mSharedDataIndexGPU;
bool isOverflown() const
{
//FD: my expectaton is that reading those variables is atomic, shared indices are non-decreasing,
//so we can only get a false overflow alert because of concurrency issues, which is not a big deal as it means
//it did overflow a bit later
return (mSharedDataIndex + mSharedDataIndexGPU) > mDataStreamSize;
}
};
struct PxcNpContext
{
private:
PX_NOCOPY(PxcNpContext)
public:
PxcNpContext() :
mNpMemBlockPool (mScratchAllocator),
mMeshContactMargin (0.0f),
mToleranceLength (0.0f),
mContactStreamPool (NULL),
mPatchStreamPool (NULL),
mForceAndIndiceStreamPool(NULL),
mMaterialManager (NULL)
{
}
PxcScratchAllocator mScratchAllocator;
PxcNpMemBlockPool mNpMemBlockPool;
PxReal mMeshContactMargin;
PxReal mToleranceLength;
Cm::RenderBuffer mRenderBuffer;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool;
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
PX_FORCE_INLINE PxReal getToleranceLength() const { return mToleranceLength; }
PX_FORCE_INLINE void setToleranceLength(PxReal x) { mToleranceLength = x; }
PX_FORCE_INLINE PxReal getMeshContactMargin() const { return mMeshContactMargin; }
PX_FORCE_INLINE void setMeshContactMargin(PxReal x) { mMeshContactMargin = x; }
PX_FORCE_INLINE PxcNpMemBlockPool& getNpMemBlockPool() { return mNpMemBlockPool; }
PX_FORCE_INLINE const PxcNpMemBlockPool& getNpMemBlockPool() const { return mNpMemBlockPool; }
PX_FORCE_INLINE void setMaterialManager(PxsMaterialManager* m){ mMaterialManager = m; }
PX_FORCE_INLINE PxsMaterialManager* getMaterialManager() const { return mMaterialManager; }
};
class PxcNpThreadContext : public PxcThreadCoherentCache<PxcNpThreadContext, PxcNpContext>::EntryBase
{
PX_NOCOPY(PxcNpThreadContext)
public:
PxcNpThreadContext(PxcNpContext* params);
~PxcNpThreadContext();
#if PX_ENABLE_SIM_STATS
void clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PX_FORCE_INLINE void addLocalNewTouchCount(PxU32 newTouchCMCount) { mLocalNewTouchCount += newTouchCMCount; }
PX_FORCE_INLINE void addLocalLostTouchCount(PxU32 lostTouchCMCount) { mLocalLostTouchCount += lostTouchCMCount; }
PX_FORCE_INLINE PxU32 getLocalNewTouchCount() const { return mLocalNewTouchCount; }
PX_FORCE_INLINE PxU32 getLocalLostTouchCount() const { return mLocalLostTouchCount; }
PX_FORCE_INLINE PxBitMap& getLocalChangeTouch() { return mLocalChangeTouch; }
void reset(PxU32 cmCount);
// debugging
PxRenderOutput mRenderOutput;
// dsequeira: Need to think about this block pool allocation a bit more. Ideally we'd be
// taking blocks from a single pool, except that we want to be able to selectively reclaim
// blocks if the user needs to defragment, depending on which artifacts they're willing
// to tolerate, such that the blocks we don't reclaim are contiguous.
#if PX_ENABLE_SIM_STATS
PxU32 mDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxcContactBlockStream mContactBlockStream; // constraint block pool
PxcNpCacheStreamPair mNpCacheStreamPair; // narrow phase pairwise data cache
// Everything below here is scratch state. Most of it can even overlap.
// temporary contact buffer
PxContactBuffer mContactBuffer;
PX_ALIGN(16, Gu::MultiplePersistentContactManifold mTempManifold);
Gu::NarrowPhaseParams mNarrowPhaseParams;
// DS: this stuff got moved here from the PxcNpPairContext. As Pierre says:
////////// PT: those members shouldn't be there in the end, it's not necessary
PxArray<Sc::BodySim*> mBodySimPool;
PxsTransformCache* mTransformCache;
const PxReal* mContactDistances;
bool mPCM;
bool mContactCache;
bool mCreateAveragePoint; // flag to enforce whether we create average points
#if PX_ENABLE_SIM_STATS
PxU32 mCompressedCacheSize;
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxReal mDt; // AP: still needed for ccd
PxU32 mCCDPass;
PxU32 mCCDFaceIndex;
PxU32 mMaxPatches;
//PxU32 mTotalContactCount;
PxU32 mTotalCompressedCacheSize;
//PxU32 mTotalPatchCount;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool; //this stream is used to store the force buffer and triangle index if we are performing mesh/heightfield contact gen
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
private:
// change touch handling.
PxBitMap mLocalChangeTouch;
PxU32 mLocalNewTouchCount;
PxU32 mLocalLostTouchCount;
};
}
#endif
| 7,962 | C | 38.034314 | 169 | 0.72846 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcScratchAllocator.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 PXC_SCRATCH_ALLOCATOR_H
#define PXC_SCRATCH_ALLOCATOR_H
#include "foundation/PxAssert.h"
#include "PxvConfig.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxcScratchAllocator : public PxUserAllocated
{
PX_NOCOPY(PxcScratchAllocator)
public:
PxcScratchAllocator() : mStack("PxcScratchAllocator"), mStart(NULL), mSize(0)
{
mStack.reserve(64);
mStack.pushBack(0);
}
void setBlock(void* addr, PxU32 size)
{
PX_ASSERT(!(size&15));
// if the stack is not empty then some scratch memory was not freed on the previous frame. That's
// likely indicative of a problem, because when the scratch block is too small the memory will have
// come from the heap
PX_ASSERT(mStack.size()==1);
mStack.popBack();
mStart = reinterpret_cast<PxU8*>(addr);
mSize = size;
mStack.pushBack(mStart + size);
}
void* allocAll(PxU32& size)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>0);
size = PxU32(mStack.back()-mStart);
if(size==0)
return NULL;
mStack.pushBack(mStart);
return mStart;
}
void* alloc(PxU32 requestedSize, bool fallBackToHeap = false)
{
requestedSize = (requestedSize+15)&~15;
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>=1);
PxU8* top = mStack.back();
if(top - mStart >= ptrdiff_t(requestedSize))
{
PxU8* addr = top - requestedSize;
mStack.pushBack(addr);
return addr;
}
if(!fallBackToHeap)
return NULL;
return PX_ALLOC(requestedSize, "Scratch Block Fallback");
}
void free(void* addr)
{
PX_ASSERT(addr!=NULL);
if(!isScratchAddr(addr))
{
PX_FREE(addr);
return;
}
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>1);
PxU32 i=mStack.size()-1;
while(mStack[i]<addr)
i--;
PX_ASSERT(mStack[i]==addr);
mStack.remove(i);
}
bool isScratchAddr(void* addr) const
{
PxU8* a = reinterpret_cast<PxU8*>(addr);
return a>= mStart && a<mStart+mSize;
}
private:
PxMutex mLock;
PxArray<PxU8*> mStack;
PxU8* mStart;
PxU32 mSize;
};
}
#endif
| 3,831 | C | 26.768116 | 101 | 0.719394 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcThreadCoherentCache.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 PXC_THREAD_COHERENT_CACHE_H
#define PXC_THREAD_COHERENT_CACHE_H
#include "foundation/PxMutex.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxSList.h"
namespace physx
{
class PxsContext;
/*!
Controls a pool of large objects which must be thread safe.
Tries to return the object most recently used by the thread(for better cache coherancy).
Assumes the object has a default contructor.
(Note the semantics are different to a pool because we dont want to construct/destroy each time
an object is requested, which may be expensive).
TODO: add thread coherancy.
*/
template<class T, class Params>
class PxcThreadCoherentCache : public PxAlignedAllocator<16, PxReflectionAllocator<T> >
{
typedef PxAlignedAllocator<16, PxReflectionAllocator<T> > Allocator;
PX_NOCOPY(PxcThreadCoherentCache)
public:
typedef PxSListEntry EntryBase;
PX_INLINE PxcThreadCoherentCache(Params* params, const Allocator& alloc = Allocator()) : Allocator(alloc), mParams(params)
{
}
PX_INLINE ~PxcThreadCoherentCache()
{
T* np = static_cast<T*>(root.pop());
while(np!=NULL)
{
np->~T();
Allocator::deallocate(np);
np = static_cast<T*>(root.pop());
}
}
PX_INLINE T* get()
{
T* rv = static_cast<T*>(root.pop());
if(rv==NULL)
{
rv = reinterpret_cast<T*>(Allocator::allocate(sizeof(T), PX_FL));
PX_PLACEMENT_NEW(rv, T(mParams));
}
return rv;
}
PX_INLINE void put(T* item)
{
root.push(*item);
}
private:
PxSList root;
Params* mParams;
template<class T2, class P2>
friend class PxcThreadCoherentCacheIterator;
};
/*!
Used to iterate over all objects controlled by the cache.
Note: The iterator flushes the cache(extracts all items on construction and adds them back on
destruction so we can iterate the list in a safe manner).
*/
template<class T, class Params>
class PxcThreadCoherentCacheIterator
{
public:
PxcThreadCoherentCacheIterator(PxcThreadCoherentCache<T, Params>& cache) : mCache(cache)
{
mNext = cache.root.flush();
mFirst = mNext;
}
~PxcThreadCoherentCacheIterator()
{
PxSListEntry* np = mFirst;
while(np != NULL)
{
PxSListEntry* npNext = np->next();
mCache.root.push(*np);
np = npNext;
}
}
PX_INLINE T* getNext()
{
if(mNext == NULL)
return NULL;
T* rv = static_cast<T*>(mNext);
mNext = mNext->next();
return rv;
}
private:
PxcThreadCoherentCacheIterator<T, Params>& operator=(const PxcThreadCoherentCacheIterator<T, Params>&);
PxcThreadCoherentCache<T, Params> &mCache;
PxSListEntry* mNext;
PxSListEntry* mFirst;
};
}
#endif
| 4,247 | C | 27.510067 | 123 | 0.73652 |
NVIDIA-Omniverse/PhysX/physx/include/PxSimulationEventCallback.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 PX_SIMULATION_EVENT_CALLBACK_H
#define PX_SIMULATION_EVENT_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxContact.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxActor;
class PxRigidActor;
class PxRigidBody;
class PxConstraint;
/**
\brief Extra data item types for contact pairs.
@see PxContactPairExtraDataItem.type
*/
struct PxContactPairExtraDataType
{
enum Enum
{
ePRE_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
ePOST_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
eCONTACT_EVENT_POSE, //!< see #PxContactPairPose
eCONTACT_PAIR_INDEX //!< see #PxContactPairIndex
};
};
/**
\brief Base class for items in the extra data stream of contact pairs
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairExtraDataItem() {}
/**
\brief The type of the extra data stream item
*/
PxU8 type;
};
/**
\brief Velocities of the contact pair rigid bodies
This struct is shared by multiple types of extra data items. The #type field allows to distinguish between them:
\li PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY: see #PxPairFlag::ePRE_SOLVER_VELOCITY
\li PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY: see #PxPairFlag::ePOST_SOLVER_VELOCITY
\note For static rigid bodies, the velocities will be set to zero.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairVelocity : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairVelocity() {}
/**
\brief The linear velocity of the rigid bodies
*/
PxVec3 linearVelocity[2];
/**
\brief The angular velocity of the rigid bodies
*/
PxVec3 angularVelocity[2];
};
/**
\brief World space actor poses of the contact pair rigid bodies
@see PxContactPairHeader.extraDataStream PxPairFlag::eCONTACT_EVENT_POSE
*/
struct PxContactPairPose : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairPose() {}
/**
\brief The world space pose of the rigid bodies
*/
PxTransform globalPose[2];
};
/**
\brief Marker for the beginning of a new item set in the extra data stream.
If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same
object multiple times. Also, different shapes of the same actor might gain and lose contact with an other
object over multiple passes. This marker allows to separate the extra data items for each collision case, as well as
distinguish the shape pair reports of different CCD passes.
Example:
Let us assume that an actor a0 with shapes s0_0 and s0_1 hits another actor a1 with shape s1.
First s0_0 will hit s1, then a0 will slightly rotate and s0_1 will hit s1 while s0_0 will lose contact with s1.
Furthermore, let us say that contact event pose information is requested as extra data.
The extra data stream will look like this:
PxContactPairIndexA | PxContactPairPoseA | PxContactPairIndexB | PxContactPairPoseB
The corresponding array of PxContactPair events (see #PxSimulationEventCallback.onContact()) will look like this:
PxContactPair(touch_found: s0_0, s1) | PxContactPair(touch_lost: s0_0, s1) | PxContactPair(touch_found: s0_1, s1)
The #index of PxContactPairIndexA will point to the first entry in the PxContactPair array, for PxContactPairIndexB,
#index will point to the third entry.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairIndex : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairIndex() {}
/**
\brief The next item set in the extra data stream refers to the contact pairs starting at #index in the reported PxContactPair array.
*/
PxU16 index;
};
/**
\brief A class to iterate over a contact pair extra data stream.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataIterator
{
/**
\brief Constructor
\param[in] stream Pointer to the start of the stream.
\param[in] size Size of the stream in bytes.
*/
PX_FORCE_INLINE PxContactPairExtraDataIterator(const PxU8* stream, PxU32 size)
: currPtr(stream), endPtr(stream + size), contactPairIndex(0)
{
clearDataPtrs();
}
/**
\brief Advances the iterator to next set of extra data items.
The contact pair extra data stream contains sets of items as requested by the corresponding #PxPairFlag flags
#PxPairFlag::ePRE_SOLVER_VELOCITY, #PxPairFlag::ePOST_SOLVER_VELOCITY, #PxPairFlag::eCONTACT_EVENT_POSE. A set can contain one
item of each plus the PxContactPairIndex item. This method parses the stream and points the iterator
member variables to the corresponding items of the current set, if they are available. If CCD is not enabled,
you should only get one set of items. If CCD with multiple passes is enabled, you might get more than one item
set.
\note Even though contact pair extra data is requested per shape pair, you will not get an item set per shape pair
but one per actor pair. If, for example, an actor has two shapes and both collide with another actor, then
there will only be one item set (since it applies to both shape pairs).
\return True if there was another set of extra data items in the stream, else false.
@see PxContactPairVelocity PxContactPairPose PxContactPairIndex
*/
PX_INLINE bool nextItemSet()
{
clearDataPtrs();
bool foundEntry = false;
bool endOfItemSet = false;
while ((currPtr < endPtr) && (!endOfItemSet))
{
const PxContactPairExtraDataItem* edItem = reinterpret_cast<const PxContactPairExtraDataItem*>(currPtr);
PxU8 type = edItem->type;
switch(type)
{
case PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY:
{
PX_ASSERT(!preSolverVelocity);
preSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY:
{
postSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_EVENT_POSE:
{
eventPose = static_cast<const PxContactPairPose*>(edItem);
currPtr += sizeof(PxContactPairPose);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_PAIR_INDEX:
{
if (!foundEntry)
{
contactPairIndex = static_cast<const PxContactPairIndex*>(edItem)->index;
currPtr += sizeof(PxContactPairIndex);
foundEntry = true;
}
else
endOfItemSet = true;
}
break;
default:
return foundEntry;
}
}
return foundEntry;
}
private:
/**
\brief Internal helper
*/
PX_FORCE_INLINE void clearDataPtrs()
{
preSolverVelocity = NULL;
postSolverVelocity = NULL;
eventPose = NULL;
}
public:
/**
\brief Current pointer in the stream.
*/
const PxU8* currPtr;
/**
\brief Pointer to the end of the stream.
*/
const PxU8* endPtr;
/**
\brief Pointer to the current pre solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* preSolverVelocity;
/**
\brief Pointer to the current post solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* postSolverVelocity;
/**
\brief Pointer to the current contact event pose item in the stream. NULL if there is none.
@see PxContactPairPose
*/
const PxContactPairPose* eventPose;
/**
\brief The contact pair index of the current item set in the stream.
@see PxContactPairIndex
*/
PxU32 contactPairIndex;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPairHeader
*/
struct PxContactPairHeaderFlag
{
enum Enum
{
eREMOVED_ACTOR_0 = (1<<0), //!< The actor with index 0 has been removed from the scene.
eREMOVED_ACTOR_1 = (1<<1) //!< The actor with index 1 has been removed from the scene.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairHeaderFlag.
@see PxContactPairHeaderFlag
*/
typedef PxFlags<PxContactPairHeaderFlag::Enum, PxU16> PxContactPairHeaderFlags;
PX_FLAGS_OPERATORS(PxContactPairHeaderFlag::Enum, PxU16)
/**
\brief An Instance of this class is passed to PxSimulationEventCallback.onContact().
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPairHeader
{
public:
PX_INLINE PxContactPairHeader() {}
/**
\brief The two actors of the notification shape pairs.
\note The actor pointers might reference deleted actors. This will be the case if PxPairFlag::eNOTIFY_TOUCH_LOST
or PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved actors
gets deleted or removed from the scene. Check the #flags member to see whether that is the case.
Do not dereference a pointer to a deleted actor. The pointer to a deleted actor is only provided
such that user data structures which might depend on the pointer value can be updated.
@see PxActor
*/
PxActor* actors[2];
/**
\brief Stream containing extra data as requested in the PxPairFlag flags of the simulation filter.
This pointer is only valid if any kind of extra data information has been requested for the contact report pair (see #PxPairFlag::ePOST_SOLVER_VELOCITY etc.),
else it will be NULL.
@see PxPairFlag
*/
const PxU8* extraDataStream;
/**
\brief Size of the extra data stream [bytes]
*/
PxU16 extraDataStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairHeaderFlag
*/
PxContactPairHeaderFlags flags;
/**
\brief pointer to the contact pairs
*/
const struct PxContactPair* pairs;
/**
\brief number of contact pairs
*/
PxU32 nbPairs;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPair
*/
struct PxContactPairFlag
{
enum Enum
{
/**
\brief The shape with index 0 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_0 = (1<<0),
/**
\brief The shape with index 1 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_1 = (1<<1),
/**
\brief First actor pair contact.
The provided shape pair marks the first contact between the two actors, no other shape pair has been touching prior to the current simulation frame.
\note: This info is only available if #PxPairFlag::eNOTIFY_TOUCH_FOUND has been declared for the pair.
*/
eACTOR_PAIR_HAS_FIRST_TOUCH = (1<<2),
/**
\brief All contact between the actor pair was lost.
All contact between the two actors has been lost, no shape pairs remain touching after the current simulation frame.
*/
eACTOR_PAIR_LOST_TOUCH = (1<<3),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The applied contact impulses are provided for every contact point.
This is the case if #PxPairFlag::eSOLVE_CONTACT has been set for the pair.
*/
eINTERNAL_HAS_IMPULSES = (1<<4),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The provided contact point information is flipped with regards to the shapes of the contact pair. This mainly concerns the order of the internal triangle indices.
*/
eINTERNAL_CONTACTS_ARE_FLIPPED = (1<<5)
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairFlag.
@see PxContactPairFlag
*/
typedef PxFlags<PxContactPairFlag::Enum, PxU16> PxContactPairFlags;
PX_FLAGS_OPERATORS(PxContactPairFlag::Enum, PxU16)
/**
\brief A contact point as used by contact notification
*/
struct PxContactPairPoint
{
/**
\brief The position of the contact point between the shapes, in world space.
*/
PxVec3 position;
/**
\brief The separation of the shapes at the contact point. A negative separation denotes a penetration.
*/
PxReal separation;
/**
\brief The normal of the contacting surfaces at the contact point. The normal direction points from the second shape to the first shape.
*/
PxVec3 normal;
/**
\brief The surface index of shape 0 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex0;
/**
\brief The impulse applied at the contact point, in world space. Divide by the simulation time step to get a force value.
*/
PxVec3 impulse;
/**
\brief The surface index of shape 1 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex1;
};
/**
\brief Contact report pair information.
Instances of this class are passed to PxSimulationEventCallback.onContact(). If contact reports have been requested for a pair of shapes (see #PxPairFlag),
then the corresponding contact information will be provided through this structure.
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPair
{
public:
PX_INLINE PxContactPair() {}
/**
\brief The two shapes that make up the pair.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved shapes
gets deleted. Check the #flags member to see whether that is the case. Do not dereference a pointer to a
deleted shape. The pointer to a deleted shape is only provided such that user data structures which might
depend on the pointer value can be updated.
@see PxShape
*/
PxShape* shapes[2];
/**
\brief Pointer to first patch header in contact stream containing contact patch data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPatches;
/**
\brief Pointer to first contact point in contact stream containing contact data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPoints;
/**
\brief Buffer containing applied impulse data.
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxReal* contactImpulses;
/**
\brief Size of the contact stream [bytes] including force buffer
*/
PxU32 requiredBufferSize;
/**
\brief Number of contact points stored in the contact stream
*/
PxU8 contactCount;
/**
\brief Number of contact patches stored in the contact stream
*/
PxU8 patchCount;
/**
\brief Size of the contact stream [bytes] not including force buffer
*/
PxU16 contactStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairFlag
*/
PxContactPairFlags flags;
/**
\brief Flags raised due to the contact.
The events field is a combination of:
<ul>
<li>PxPairFlag::eNOTIFY_TOUCH_FOUND,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_LOST,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_CCD,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST</li>
</ul>
See the documentation of #PxPairFlag for an explanation of each.
\note eNOTIFY_TOUCH_CCD can get raised even if the pair did not request this event. However, in such a case it will only get
raised in combination with one of the other flags to point out that the other event occured during a CCD pass.
@see PxPairFlag
*/
PxPairFlags events;
PxU32 internalData[2]; // For internal use only
/**
\brief Extracts the contact points from the stream and stores them in a convenient format.
\param[out] userBuffer Array of PxContactPairPoint structures to extract the contact points to. The number of contacts for a pair is defined by #contactCount
\param[in] bufferSize Number of PxContactPairPoint structures the provided buffer can store.
\return Number of contact points written to the buffer.
@see PxContactPairPoint
*/
PX_INLINE PxU32 extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const;
/**
\brief Helper method to clone the contact pair and copy the contact data stream into a user buffer.
The contact data stream is only accessible during the contact report callback. This helper function provides copy functionality
to buffer the contact stream information such that it can get accessed at a later stage.
\param[out] newPair The contact pair info will get copied to this instance. The contact data stream pointer of the copy will be redirected to the provided user buffer. Use NULL to skip the contact pair copy operation.
\param[out] bufferMemory Memory block to store the contact data stream to. At most #requiredBufferSize bytes will get written to the buffer.
*/
PX_INLINE void bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const;
PX_INLINE const PxU32* getInternalFaceIndices() const;
};
PX_INLINE PxU32 PxContactPair::extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const
{
PxU32 nbContacts = 0;
if(contactCount && bufferSize)
{
PxContactStreamIterator iter(contactPatches, contactPoints, getInternalFaceIndices(), patchCount, contactCount);
const PxReal* impulses = contactImpulses;
const PxU32 flippedContacts = (flags & PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED);
const PxU32 hasImpulses = (flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
iter.nextContact();
PxContactPairPoint& dst = userBuffer[nbContacts];
dst.position = iter.getContactPoint();
dst.separation = iter.getSeparation();
dst.normal = iter.getContactNormal();
if(!flippedContacts)
{
dst.internalFaceIndex0 = iter.getFaceIndex0();
dst.internalFaceIndex1 = iter.getFaceIndex1();
}
else
{
dst.internalFaceIndex0 = iter.getFaceIndex1();
dst.internalFaceIndex1 = iter.getFaceIndex0();
}
if(hasImpulses)
{
const PxReal impulse = impulses[nbContacts];
dst.impulse = dst.normal * impulse;
}
else
dst.impulse = PxVec3(0.0f);
++nbContacts;
if(nbContacts == bufferSize)
return nbContacts;
}
}
}
return nbContacts;
}
PX_INLINE void PxContactPair::bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const
{
PxU8* patches = bufferMemory;
PxU8* contacts = NULL;
if(patches)
{
contacts = bufferMemory + patchCount * sizeof(PxContactPatch);
PxMemCopy(patches, contactPatches, sizeof(PxContactPatch)*patchCount);
PxMemCopy(contacts, contactPoints, contactStreamSize - (sizeof(PxContactPatch)*patchCount));
}
if(contactImpulses)
{
PxMemCopy(bufferMemory + ((contactStreamSize + 15) & (~15)), contactImpulses, sizeof(PxReal) * contactCount);
}
if (newPair)
{
*newPair = *this;
newPair->contactPatches = patches;
newPair->contactPoints = contacts;
}
}
PX_INLINE const PxU32* PxContactPair::getInternalFaceIndices() const
{
return reinterpret_cast<const PxU32*>(contactImpulses + contactCount);
}
/**
\brief Collection of flags providing information on trigger report pairs.
@see PxTriggerPair
*/
struct PxTriggerPairFlag
{
enum Enum
{
eREMOVED_SHAPE_TRIGGER = (1<<0), //!< The trigger shape has been removed from the actor/scene.
eREMOVED_SHAPE_OTHER = (1<<1), //!< The shape causing the trigger event has been removed from the actor/scene.
eNEXT_FREE = (1<<2) //!< For internal use only.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxTriggerPairFlag.
@see PxTriggerPairFlag
*/
typedef PxFlags<PxTriggerPairFlag::Enum, PxU8> PxTriggerPairFlags;
PX_FLAGS_OPERATORS(PxTriggerPairFlag::Enum, PxU8)
/**
\brief Descriptor for a trigger pair.
An array of these structs gets passed to the PxSimulationEventCallback::onTrigger() report.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
events were requested for the pair and one of the involved shapes gets deleted. Check the #flags member to see
whether that is the case. Do not dereference a pointer to a deleted shape. The pointer to a deleted shape is
only provided such that user data structures which might depend on the pointer value can be updated.
@see PxSimulationEventCallback.onTrigger()
*/
struct PxTriggerPair
{
PX_INLINE PxTriggerPair() {}
PxShape* triggerShape; //!< The shape that has been marked as a trigger.
PxActor* triggerActor; //!< The actor to which triggerShape is attached
PxShape* otherShape; //!< The shape causing the trigger event. \deprecated (see #PxSimulationEventCallback::onTrigger()) If collision between trigger shapes is enabled, then this member might point to a trigger shape as well.
PxActor* otherActor; //!< The actor to which otherShape is attached
PxPairFlag::Enum status; //!< Type of trigger event (eNOTIFY_TOUCH_FOUND or eNOTIFY_TOUCH_LOST). eNOTIFY_TOUCH_PERSISTS events are not supported.
PxTriggerPairFlags flags; //!< Additional information on the pair (see #PxTriggerPairFlag)
};
/**
\brief Descriptor for a broken constraint.
An array of these structs gets passed to the PxSimulationEventCallback::onConstraintBreak() report.
@see PxConstraint PxSimulationEventCallback.onConstraintBreak()
*/
struct PxConstraintInfo
{
PX_INLINE PxConstraintInfo() {}
PX_INLINE PxConstraintInfo(PxConstraint* c, void* extRef, PxU32 t) : constraint(c), externalReference(extRef), type(t) {}
PxConstraint* constraint; //!< The broken constraint.
void* externalReference; //!< The external object which owns the constraint (see #PxConstraintConnector::getExternalReference())
PxU32 type; //!< Unique type ID of the external object. Allows to cast the provided external reference to the appropriate type
};
/**
\brief An interface class that the user can implement in order to receive simulation events.
With the exception of onAdvance(), the events get sent during the call to either #PxScene::fetchResults() or
#PxScene::flushSimulation() with sendPendingReports=true. onAdvance() gets called while the simulation
is running (that is between PxScene::simulate() or PxScene::advance() and PxScene::fetchResults()).
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
<b>Threading:</b> With the exception of onAdvance(), it is not necessary to make these callbacks thread safe as
they will only be called in the context of the user thread.
@see PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback()
*/
class PxSimulationEventCallback
{
public:
/**
\brief This is called when a breakable constraint breaks.
\note The user should not release the constraint shader inside this call!
\note No event will get reported if the constraint breaks but gets deleted while the time step is still being simulated.
\param[in] constraints - The constraints which have been broken.
\param[in] count - The number of constraints
@see PxConstraint PxConstraintDesc.linearBreakForce PxConstraintDesc.angularBreakForce
*/
virtual void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been woken up.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is awake, then A->putToSleep() gets called, then later A->wakeUp() gets called.
At the next simulate/fetchResults() step only an onWake() event will get triggered because that was the last transition.
\note If an actor gets newly added to a scene with properties such that it is awake and the sleep state does not get changed by
the user or simulation, then an onWake() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which just woke up.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onWake(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been put to sleep.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is asleep, then A->wakeUp() gets called, then later A->putToSleep() gets called.
At the next simulate/fetchResults() step only an onSleep() event will get triggered because that was the last transition (assuming the simulation
does not wake the actor up).
\note If an actor gets newly added to a scene with properties such that it is asleep and the sleep state does not get changed by
the user or simulation, then an onSleep() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which have just been put to sleep.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onSleep(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called when certain contact events occur.
The method will be called for a pair of actors if one of the colliding shape pairs requested contact notification.
You request which events are reported using the filter shader/callback mechanism (see #PxSimulationFilterShader,
#PxSimulationFilterCallback, #PxPairFlag).
Do not keep references to the passed objects, as they will be
invalid after this function returns.
\param[in] pairHeader Information on the two actors whose shapes triggered a contact report.
\param[in] pairs The contact pairs of two actors for which contact reports have been requested. See #PxContactPair.
\param[in] nbPairs The number of provided contact pairs.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxContactPair PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) = 0;
/**
\brief This is called with the current trigger pair events.
Shapes which have been marked as triggers using PxShapeFlag::eTRIGGER_SHAPE will send events
according to the pair flag specification in the filter shader (see #PxPairFlag, #PxSimulationFilterShader).
\note Trigger shapes will no longer send notification events for interactions with other trigger shapes.
\param[in] pairs - The trigger pair events.
\param[in] count - The number of trigger pair events.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxPairFlag PxSimulationFilterShader PxShapeFlag PxShape.setFlag()
*/
virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) = 0;
/**
\brief Provides early access to the new pose of moving rigid bodies.
When this call occurs, rigid bodies having the #PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
flag set, were moved by the simulation and their new poses can be accessed through the provided buffers.
\note The provided buffers are valid and can be read until the next call to #PxScene::simulate() or #PxScene::collide().
\note This callback gets triggered while the simulation is running. If the provided rigid body references are used to
read properties of the object, then the callback has to guarantee no other thread is writing to the same body at the same
time.
\note The code in this callback should be lightweight as it can block the simulation, that is, the
#PxScene::fetchResults() call.
\param[in] bodyBuffer The rigid bodies that moved and requested early pose reporting.
\param[in] poseBuffer The integrated rigid body poses of the bodies listed in bodyBuffer.
\param[in] count The number of entries in the provided buffers.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
*/
virtual void onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count) = 0;
virtual ~PxSimulationEventCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,876 | C | 32.930769 | 230 | 0.754502 |
NVIDIA-Omniverse/PhysX/physx/include/PxContactModifyCallback.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 PX_CONTACT_MODIFY_CALLBACK_H
#define PX_CONTACT_MODIFY_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxShape.h"
#include "PxContact.h"
#include "foundation/PxTransform.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
/**
\brief An array of contact points, as passed to contact modification.
The word 'set' in the name does not imply that duplicates are filtered in any
way. This initial set of contacts does potentially get reduced to a smaller
set before being passed to the solver.
You can use the accessors to read and write contact properties. The number of
contacts is immutable, other than being able to disable contacts using ignore().
@see PxContactModifyCallback, PxModifiableContact
*/
class PxContactSet
{
public:
/**
\brief Get the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\return Position to the requested point in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE const PxVec3& getPoint(PxU32 i) const { return mContacts[i].contact; }
/**
\brief Alter the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] p The new position in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE void setPoint(PxU32 i, const PxVec3& p) { mContacts[i].contact = p; }
/**
\brief Get the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The requested normal in world space
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE const PxVec3& getNormal(PxU32 i) const { return mContacts[i].normal; }
/**
\brief Alter the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] n The new normal in world space
\note Changing the normal can cause contact points to be ignored.
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE void setNormal(PxU32 i, const PxVec3& n)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].normal = n;
}
/**
\brief Get the separation distance of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The separation. Negative implies penetration.
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE PxReal getSeparation(PxU32 i) const { return mContacts[i].separation; }
/**
\brief Alter the separation of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new separation
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE void setSeparation(PxU32 i, PxReal s) { mContacts[i].separation = s; }
/**
\brief Get the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The target velocity in world frame
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE const PxVec3& getTargetVelocity(PxU32 i) const { return mContacts[i].targetVelocity; }
/**
\brief Alter the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] v The new velocity in world frame as seen from the second actor in the contact pair, i.e., the solver will try to achieve targetVel == (vel1 - vel2)
\note The sign of the velocity needs to be flipped depending on the order of the actors in the pair. There is no guarantee about the consistency of the order from frame to frame.
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE void setTargetVelocity(PxU32 i, const PxVec3& v)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_TARGET_VELOCITY;
mContacts[i].targetVelocity = v;
}
/**
\brief Get the face index with respect to the first shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the first shape
\note At the moment, the first shape is never a tri-mesh, therefore this function always returns PXC_CONTACT_NO_FACE_INDEX
@see PxModifiableContact.internalFaceIndex0
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex0(PxU32 i) const { PX_UNUSED(i); return PXC_CONTACT_NO_FACE_INDEX; }
/**
\brief Get the face index with respect to the second shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the second shape
@see PxModifiableContact.internalFaceIndex1
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex1(PxU32 i) const
{
PxContactPatch* patch = getPatch();
if (patch->internalFlags & PxContactPatch::eHAS_FACE_INDICES)
{
return reinterpret_cast<PxU32*>(mContacts + mCount)[mCount + i];
}
return PXC_CONTACT_NO_FACE_INDEX;
}
/**
\brief Get the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The maximum impulse
@see PxModifiableContact.maxImpulse
*/
PX_FORCE_INLINE PxReal getMaxImpulse(PxU32 i) const { return mContacts[i].maxImpulse; }
/**
\brief Alter the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new maximum impulse
\note Must be nonnegative. If set to zero, the contact point will be ignored
@see PxModifiableContact.maxImpulse, ignore()
*/
PX_FORCE_INLINE void setMaxImpulse(PxU32 i, PxReal s)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_MAX_IMPULSE;
mContacts[i].maxImpulse = s;
}
/**
\brief Get the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The restitution coefficient
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE PxReal getRestitution(PxU32 i) const { return mContacts[i].restitution; }
/**
\brief Alter the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] r The new restitution coefficient
\note Valid ranges [0,1]
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE void setRestitution(PxU32 i, PxReal r)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].restitution = r;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient (dimensionless)
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE PxReal getStaticFriction(PxU32 i) const { return mContacts[i].staticFriction; }
/**
\brief Alter the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient (dimensionless), range [0, inf]
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE void setStaticFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].staticFriction = f;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE PxReal getDynamicFriction(PxU32 i) const { return mContacts[i].dynamicFriction; }
/**
\brief Alter the static dynamic coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE void setDynamicFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].dynamicFriction = f;
}
/**
\brief Ignore the contact point.
\param[in] i Index of the point in the set
If a contact point is ignored then no force will get applied at this point. This can be used to disable collision in certain areas of a shape, for example.
*/
PX_FORCE_INLINE void ignore(PxU32 i) { setMaxImpulse(i, 0.0f); }
/**
\brief The number of contact points in the set.
*/
PX_FORCE_INLINE PxU32 size() const { return mCount; }
/**
\brief Returns the invMassScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear0;
}
/**
\brief Returns the invMassScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear1;
}
/**
\brief Returns the invInertiaScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular0;
}
/**
\brief Returns the invInertiaScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular1;
}
/**
\brief Sets the invMassScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invMassScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
protected:
PX_FORCE_INLINE PxContactPatch* getPatch() const
{
const size_t headerOffset = sizeof(PxContactPatch)*mCount;
return reinterpret_cast<PxContactPatch*>(reinterpret_cast<PxU8*>(mContacts) - headerOffset);
}
PxU32 mCount; //!< Number of contact points in the set
PxModifiableContact* mContacts; //!< The contact points of the set
};
/**
\brief An array of instances of this class is passed to PxContactModifyCallback::onContactModify().
@see PxContactModifyCallback
*/
class PxContactModifyPair
{
public:
/**
\brief The actors which make up the pair in contact.
Note that these are the actors as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxRigidActor* actor[2];
/**
\brief The shapes which make up the pair in contact.
Note that these are the shapes as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxShape* shape[2];
/**
\brief The shape to world transforms of the two shapes.
These are the transforms as the simulation engine sees them, and may have been modified by the application
since the simulation step started.
*/
PxTransform transform[2];
/**
\brief An array of contact points between these two shapes.
*/
PxContactSet contacts;
};
/**
\brief An interface class that the user can implement in order to modify contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
@see PxContactModifyPair
*/
virtual void onContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxContactModifyCallback(){}
};
/**
\brief An interface class that the user can implement in order to modify CCD contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxCCDContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
*/
virtual void onCCDContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxCCDContactModifyCallback(){}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 18,893 | C | 34.784091 | 179 | 0.747473 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysicsAPI.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 PX_PHYSICS_API_H
#define PX_PHYSICS_API_H
/** \addtogroup physics
@{
*/
/**
This is the main include header for the Physics SDK, for users who
want to use a single #include file.
Alternatively, one can instead directly #include a subset of the below files.
*/
// Foundation SDK
#include "foundation/Px.h"
#include "foundation/PxAlignedMalloc.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxArray.h"
#include "foundation/PxAssert.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxBitAndData.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxBroadcast.h"
#include "foundation/PxErrorCallback.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFlags.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxFoundationConfig.h"
#include "foundation/PxFPU.h"
#include "foundation/PxHash.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxInlineAllocator.h"
#include "foundation/PxInlineArray.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxIO.h"
#include "foundation/PxMat33.h"
#include "foundation/PxMat44.h"
#include "foundation/PxMath.h"
#include "foundation/PxMathIntrinsics.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxMemory.h"
#include "foundation/PxMutex.h"
#include "foundation/PxPhysicsVersion.h"
#include "foundation/PxPlane.h"
#include "foundation/PxPool.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxProfiler.h"
#include "foundation/PxQuat.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxSList.h"
#include "foundation/PxSocket.h"
#include "foundation/PxSort.h"
#include "foundation/PxStrideIterator.h"
#include "foundation/PxString.h"
#include "foundation/PxSync.h"
#include "foundation/PxTempAllocator.h"
#include "foundation/PxThread.h"
#include "foundation/PxTime.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUnionCast.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVec2.h"
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxVecQuat.h"
#include "foundation/PxVecTransform.h"
//Not physics specific utilities and common code
#include "common/PxCoreUtilityTypes.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxRenderBuffer.h"
#include "common/PxBase.h"
#include "common/PxTolerancesScale.h"
#include "common/PxTypeInfo.h"
#include "common/PxStringTable.h"
#include "common/PxSerializer.h"
#include "common/PxMetaData.h"
#include "common/PxMetaDataFlags.h"
#include "common/PxSerialFramework.h"
#include "common/PxInsertionCallback.h"
//Task Manager
#include "task/PxTask.h"
// Cuda Mananger
#if PX_SUPPORT_GPU_PHYSX
#include "gpu/PxGpu.h"
#endif
//Geometry Library
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxBVH.h"
#include "geometry/PxBVHBuildStrategy.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHelpers.h"
#include "geometry/PxGeometryQuery.h"
#include "geometry/PxHeightField.h"
#include "geometry/PxHeightFieldDesc.h"
#include "geometry/PxHeightFieldFlag.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxHeightFieldSample.h"
#include "geometry/PxMeshQuery.h"
#include "geometry/PxMeshScale.h"
#include "geometry/PxPlaneGeometry.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxTriangle.h"
#include "geometry/PxTriangleMesh.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "geometry/PxTetrahedron.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxTetrahedronMeshGeometry.h"
// PhysX Core SDK
#include "PxActor.h"
#include "PxAggregate.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "PxArticulationLink.h"
#include "PxClient.h"
#include "PxConeLimitedConstraint.h"
#include "PxConstraint.h"
#include "PxConstraintDesc.h"
#include "PxContact.h"
#include "PxContactModifyCallback.h"
#include "PxDeletionListener.h"
#include "PxFEMSoftBodyMaterial.h"
#include "PxFiltering.h"
#include "PxForceMode.h"
#include "PxLockedData.h"
#include "PxMaterial.h"
#include "PxParticleBuffer.h"
#include "PxParticleSystem.h"
#include "PxPBDParticleSystem.h"
#include "PxPBDMaterial.h"
#include "PxPhysics.h"
#include "PxPhysXConfig.h"
#include "PxQueryFiltering.h"
#include "PxQueryReport.h"
#include "PxRigidActor.h"
#include "PxRigidBody.h"
#include "PxRigidDynamic.h"
#include "PxRigidStatic.h"
#include "PxScene.h"
#include "PxSceneDesc.h"
#include "PxSceneLock.h"
#include "PxShape.h"
#include "PxSimulationEventCallback.h"
#include "PxSimulationStatistics.h"
#include "PxSoftBody.h"
#include "PxVisualizationParameter.h"
#include "PxPruningStructure.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#include "PxFEMClothMaterial.h"
#include "PxFLIPParticleSystem.h"
#include "PxFLIPMaterial.h"
#include "PxHairSystem.h"
#include "PxMPMMaterial.h"
#include "PxMPMParticleSystem.h"
#endif
//Character Controller
#include "characterkinematic/PxBoxController.h"
#include "characterkinematic/PxCapsuleController.h"
#include "characterkinematic/PxController.h"
#include "characterkinematic/PxControllerBehavior.h"
#include "characterkinematic/PxControllerManager.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "characterkinematic/PxExtended.h"
//Cooking (data preprocessing)
#include "cooking/Pxc.h"
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxCooking.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "cooking/PxBVH33MidphaseDesc.h"
#include "cooking/PxBVH34MidphaseDesc.h"
#include "cooking/PxMidphaseDesc.h"
//Extensions to the SDK
#include "extensions/PxDefaultStreams.h"
#include "extensions/PxExtensionsAPI.h"
//Serialization
#include "extensions/PxSerialization.h"
#include "extensions/PxBinaryConverter.h"
#include "extensions/PxRepXSerializer.h"
//Vehicle Simulation
#include "vehicle2/PxVehicleAPI.h"
#include "vehicle/PxVehicleComponents.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleSDK.h"
#include "vehicle/PxVehicleShaders.h"
#include "vehicle/PxVehicleTireFriction.h"
#include "vehicle/PxVehicleUpdate.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUtilControl.h"
#include "vehicle/PxVehicleUtilSetup.h"
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleDriveNW.h"
//Connecting the SDK to Visual Debugger
#include "pvd/PxPvdSceneClient.h"
#include "pvd/PxPvd.h"
#include "pvd/PxPvdTransport.h"
/** @} */
#endif
| 8,680 | C | 33.312253 | 77 | 0.792742 |
NVIDIA-Omniverse/PhysX/physx/include/PxNodeIndex.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 PX_NODEINDEX_H
#define PX_NODEINDEX_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#define PX_INVALID_NODE 0xFFFFFFFFu
/**
\brief PxNodeIndex
Node index is the unique index for each actor referenced by the island gen. It contains details like
if the actor is an articulation or rigid body. If it is an articulation, the node index also contains
the link index of the rigid body within the articulation. Also, it contains information to detect whether
the rigid body is static body or not
*/
class PxNodeIndex
{
protected:
PxU64 ind;
public:
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id, PxU32 articLinkId) : ind((PxU64(id) << 32) | (articLinkId << 1) | 1)
{
}
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id = PX_INVALID_NODE) : ind((PxU64(id) << 32))
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 index() const { return PxU32(ind >> 32); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 articulationLinkId() const { return PxU32((ind >> 1) & 0x7FFFFFFF); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isArticulation() const { return PxU32(ind & 1); }
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isStaticBody() const { return PxU32(ind >> 32) == PX_INVALID_NODE; }
PX_CUDA_CALLABLE bool isValid() const { return PxU32(ind >> 32) != PX_INVALID_NODE; }
PX_CUDA_CALLABLE void setIndices(PxU32 index, PxU32 articLinkId) { ind = ((PxU64(index) << 32) | (articLinkId << 1) | 1); }
PX_CUDA_CALLABLE void setIndices(PxU32 index) { ind = ((PxU64(index) << 32)); }
PX_CUDA_CALLABLE bool operator < (const PxNodeIndex& other) const { return ind < other.ind; }
PX_CUDA_CALLABLE bool operator <= (const PxNodeIndex& other) const { return ind <= other.ind; }
PX_CUDA_CALLABLE bool operator == (const PxNodeIndex& other) const { return ind == other.ind; }
PX_CUDA_CALLABLE PxU64 getInd() const { return ind; }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,668 | C | 39.766666 | 134 | 0.73337 |
NVIDIA-Omniverse/PhysX/physx/include/PxQueryFiltering.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 PX_QUERY_FILTERING_H
#define PX_QUERY_FILTERING_H
/** \addtogroup scenequery
@{
*/
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxQueryReport.h"
#include "PxClient.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxRigidActor;
struct PxQueryHit;
/**
\brief Filtering flags for scene queries.
@see PxQueryFilterData.flags
*/
struct PxQueryFlag
{
enum Enum
{
eSTATIC = (1<<0), //!< Traverse static shapes
eDYNAMIC = (1<<1), //!< Traverse dynamic shapes
ePREFILTER = (1<<2), //!< Run the pre-intersection-test filter (see #PxQueryFilterCallback::preFilter())
ePOSTFILTER = (1<<3), //!< Run the post-intersection-test filter (see #PxQueryFilterCallback::postFilter())
eANY_HIT = (1<<4), //!< Abort traversal as soon as any hit is found and return it via callback.block.
//!< Helps query performance. Both eTOUCH and eBLOCK hitTypes are considered hits with this flag.
eNO_BLOCK = (1<<5), //!< All hits are reported as touching. Overrides eBLOCK returned from user filters with eTOUCH.
//!< This is also an optimization hint that may improve query performance.
eBATCH_QUERY_LEGACY_BEHAVIOUR = (1<<6), //!< Run with legacy batch query filter behavior. Raising this flag ensures that
//!< the hardcoded filter equation is neglected. This guarantees that any provided PxQueryFilterCallback
//!< will be utilised, as specified by the ePREFILTER and ePOSTFILTER flags.
eDISABLE_HARDCODED_FILTER = (1<<6), //!< Same as eBATCH_QUERY_LEGACY_BEHAVIOUR, more explicit name making it clearer that this can also be used
//!< with regular/non-batched queries if needed.
eRESERVED = (1<<15) //!< Reserved for internal use
};
};
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eSTATIC==(1<<0));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eDYNAMIC==(1<<1));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR==PxQueryFlag::eDISABLE_HARDCODED_FILTER);
/**
\brief Flags typedef for the set of bits defined in PxQueryFlag.
*/
typedef PxFlags<PxQueryFlag::Enum,PxU16> PxQueryFlags;
PX_FLAGS_OPERATORS(PxQueryFlag::Enum,PxU16)
/**
\brief Classification of scene query hits (intersections).
- eNONE: Returning this hit type means that the hit should not be reported.
- eBLOCK: For all raycast, sweep and overlap queries the nearest eBLOCK type hit will always be returned in PxHitCallback::block member.
- eTOUCH: Whenever a raycast, sweep or overlap query was called with non-zero PxHitCallback::nbTouches and PxHitCallback::touches
parameters, eTOUCH type hits that are closer or same distance (touchDistance <= blockDistance condition)
as the globally nearest eBLOCK type hit, will be reported.
- For example, to record all hits from a raycast query, always return eTOUCH.
All hits in overlap() queries are treated as if the intersection distance were zero.
This means the hits are unsorted and all eTOUCH hits are recorded by the callback even if an eBLOCK overlap hit was encountered.
Even though all overlap() blocking hits have zero length, only one (arbitrary) eBLOCK overlap hit is recorded in PxHitCallback::block.
All overlap() eTOUCH type hits are reported (zero touchDistance <= zero blockDistance condition).
For raycast/sweep/overlap calls with zero touch buffer or PxHitCallback::nbTouches member,
only the closest hit of type eBLOCK is returned. All eTOUCH hits are discarded.
@see PxQueryFilterCallback.preFilter PxQueryFilterCallback.postFilter PxScene.raycast PxScene.sweep PxScene.overlap
*/
struct PxQueryHitType
{
enum Enum
{
eNONE = 0, //!< the query should ignore this shape
eTOUCH = 1, //!< a hit on the shape touches the intersection geometry of the query but does not block it
eBLOCK = 2 //!< a hit on the shape blocks the query (does not block overlap queries)
};
};
/**
\brief Scene query filtering data.
Whenever the scene query intersects a shape, filtering is performed in the following order:
\li For non-batched queries only:<br>If the data field is non-zero, and the bitwise-AND value of data AND the shape's
queryFilterData is zero, the shape is skipped
\li If filter callbacks are enabled in flags field (see #PxQueryFlags) they will get invoked accordingly.
\li If neither #PxQueryFlag::ePREFILTER or #PxQueryFlag::ePOSTFILTER is set, the hit defaults
to type #PxQueryHitType::eBLOCK when the value of PxHitCallback::nbTouches provided with the query is zero and to type
#PxQueryHitType::eTOUCH when PxHitCallback::nbTouches is positive.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlag::eANY_HIT
*/
struct PxQueryFilterData
{
/** \brief default constructor */
explicit PX_INLINE PxQueryFilterData() : flags(PxQueryFlag::eDYNAMIC | PxQueryFlag::eSTATIC) {}
/** \brief constructor to set both filter data and filter flags */
explicit PX_INLINE PxQueryFilterData(const PxFilterData& fd, PxQueryFlags f) : data(fd), flags(f) {}
/** \brief constructor to set filter flags only */
explicit PX_INLINE PxQueryFilterData(PxQueryFlags f) : flags(f) {}
PxFilterData data; //!< Filter data associated with the scene query
PxQueryFlags flags; //!< Filter flags (see #PxQueryFlags)
};
/**
\brief Scene query filtering callbacks.
Custom filtering logic for scene query intersection candidates. If an intersection candidate object passes the data based filter
(see #PxQueryFilterData), filtering callbacks are executed if requested (see #PxQueryFilterData.flags)
\li If #PxQueryFlag::ePREFILTER is set, the preFilter function runs before exact intersection tests.
If this function returns #PxQueryHitType::eTOUCH or #PxQueryHitType::eBLOCK, exact testing is performed to
determine the intersection location.
The preFilter function may overwrite the copy of queryFlags it receives as an argument to specify any of #PxHitFlag::eMODIFIABLE_FLAGS
on a per-shape basis. Changes apply only to the shape being filtered, and changes to other flags are ignored.
\li If #PxQueryFlag::ePREFILTER is not set, precise intersection testing is performed using the original query's filterData.flags.
\li If #PxQueryFlag::ePOSTFILTER is set, the postFilter function is called for each intersection to determine the touch/block status.
This overrides any touch/block status previously returned from the preFilter function for this shape.
Filtering calls are not guaranteed to be sorted along the ray or sweep direction.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlags PxHitFlags
*/
class PxQueryFilterCallback
{
public:
/**
\brief This filter callback is executed before the exact intersection test if PxQueryFlag::ePREFILTER flag was set.
\param[in] filterData custom filter data specified as the query's filterData.data parameter.
\param[in] shape A shape that has not yet passed the exact intersection test.
\param[in] actor The shape's actor.
\param[in,out] queryFlags scene query flags from the query's function call (only flags from PxHitFlag::eMODIFIABLE_FLAGS bitmask can be modified)
\return the updated type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum preFilter(const PxFilterData& filterData, const PxShape* shape, const PxRigidActor* actor, PxHitFlags& queryFlags) = 0;
/**
\brief This filter callback is executed if the exact intersection test returned true and PxQueryFlag::ePOSTFILTER flag was set.
\param[in] filterData custom filter data of the query
\param[in] hit Scene query hit information. faceIndex member is not valid for overlap queries. For sweep and raycast queries the hit information can be cast to #PxSweepHit and #PxRaycastHit respectively.
\param[in] shape Hit shape
\param[in] actor Hit actor
\return the updated hit type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxQueryHit& hit, const PxShape* shape, const PxRigidActor* actor) = 0;
/**
\brief virtual destructor
*/
virtual ~PxQueryFilterCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,786 | C | 44.948357 | 206 | 0.759963 |
NVIDIA-Omniverse/PhysX/physx/include/PxSmoothing.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 PX_SMOOTHING_H
#define PX_SMOOTHING_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxgKernelLauncher;
class PxParticleNeighborhoodProvider;
/**
\brief Ccomputes smoothed positions for a particle system to improve rendering quality
*/
class PxSmoothedPositionGenerator
{
public:
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] gpuParticleSystem A gpu pointer to access particle system data
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0;
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] particlePositionsGpu A gpu pointer containing the particle positions
\param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries
\param[in] numParticles The number of particles
\param[in] particleContactOffset The particle contact offset
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0;
/**
\brief Set a host buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A host buffer with memory for all particles already allocated
*/
virtual void setResultBufferHost(PxVec4* smoothedPositions) = 0;
/**
\brief Set a device buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A device buffer with memory for all particles already allocated
*/
virtual void setResultBufferDevice(PxVec4* smoothedPositions) = 0;
/**
\brief Sets the intensity of the position smoothing effect
\param[in] smoothingStrenght The strength of the smoothing effect
*/
virtual void setSmoothing(float smoothingStrenght) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the device pointer for the smoothed positions. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the smoothed positions
*/
virtual PxVec4* getSmoothedPositionsDevicePointer() const = 0;
/**
\brief Enables or disables the smoothed position generator
\param[in] enabled The boolean to set the generator to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the smoothed position generator is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxSmoothedPositionGenerator() {}
};
/**
\brief Default implementation of a particle system callback to trigger smoothed position calculations. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxSmoothedPositionCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the smoothing callback
\param[in] smoothedPositionGenerator The smoothed position generator
*/
void initialize(PxSmoothedPositionGenerator* smoothedPositionGenerator)
{
mSmoothedPositionGenerator = smoothedPositionGenerator;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
if (mSmoothedPositionGenerator)
{
mSmoothedPositionGenerator->generateSmoothedPositions(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream);
}
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxSmoothedPositionGenerator* mSmoothedPositionGenerator;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,555 | C | 33.324607 | 196 | 0.769031 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleNeighborhoodProvider.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 PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
#define PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Computes neighborhood information for a point cloud
*/
class PxParticleNeighborhoodProvider
{
public:
/**
\brief Schedules the compuation of neighborhood information on the specified cuda stream
\param[in] deviceParticlePos A gpu pointer containing the particle positions
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
\param[in] devicePhases An optional gpu pointer with particle phases
\param[in] validPhaseMask An optional phase mask to define which particles should be included into the neighborhood computation
\param[in] deviceActiveIndices An optional device pointer containing all indices of particles that are currently active
*/
virtual void buildNeighborhood(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* devicePhases = NULL,
PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid, const PxU32* deviceActiveIndices = NULL) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the maximal number of grid cells
\return The maximal number of grid cells
*/
virtual PxU32 getMaxGridCells() const = 0;
/**
\brief Gets the cell size
\return The cell size
*/
virtual PxReal getCellSize() const = 0;
/**
\brief Gets the number of grid cells in use
\return The number of grid cells in use
*/
virtual PxU32 getNumGridCellsInUse() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxGridCells The maximal number of grid cells
\param[in] cellSize The cell size. Should be equal to 2*contactOffset for PBD particle systems.
*/
virtual void setCellProperties(PxU32 maxGridCells, PxReal cellSize) = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxParticleNeighborhoodProvider() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,383 | C | 31.474074 | 130 | 0.751312 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleSolverType.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 PX_PARTICLE_SOLVER_TYPE_H
#define PX_PARTICLE_SOLVER_TYPE_H
/** \addtogroup physics
@{ */
#include "foundation/PxPreprocessor.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief Identifies the solver to use for a particle system.
*/
struct PxParticleSolverType
{
enum Enum
{
ePBD = 1 << 0, //!< The position based dynamics solver that can handle fluid, granular material, cloth, inflatables etc. See #PxPBDParticleSystem.
eFLIP = 1 << 1, //!< The FLIP fluid solver. See #PxFLIPParticleSystem.
eMPM = 1 << 2 //!< The MPM (material point method) solver that can handle a variety of materials. See #PxMPMParticleSystem.
};
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,528 | C | 34.619718 | 150 | 0.743275 |
NVIDIA-Omniverse/PhysX/physx/include/PxAggregate.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 PX_AGGREGATE_H
#define PX_AGGREGATE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxActor;
class PxBVH;
class PxScene;
struct PxAggregateType
{
enum Enum
{
eGENERIC = 0, //!< Aggregate will contain various actors of unspecified types
eSTATIC = 1, //!< Aggregate will only contain static actors
eKINEMATIC = 2 //!< Aggregate will only contain kinematic actors
};
};
// PxAggregateFilterHint is used for more efficient filtering of aggregates outside of the broadphase.
// It is a combination of a PxAggregateType and a self-collision bit.
typedef PxU32 PxAggregateFilterHint;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateFilterHint PxGetAggregateFilterHint(PxAggregateType::Enum type, bool enableSelfCollision)
{
const PxU32 selfCollisionBit = enableSelfCollision ? 1 : 0;
return PxAggregateFilterHint((PxU32(type)<<1)|selfCollisionBit);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxGetAggregateSelfCollisionBit(PxAggregateFilterHint hint)
{
return hint & 1;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateType::Enum PxGetAggregateType(PxAggregateFilterHint hint)
{
return PxAggregateType::Enum(hint>>1);
}
/**
\brief Class to aggregate actors into a single broad-phase entry.
A PxAggregate object is a collection of PxActors, which will exist as a single entry in the
broad-phase structures. This has 3 main benefits:
1) it reduces "broad phase pollution" by allowing a collection of spatially coherent broad-phase
entries to be replaced by a single aggregated entry (e.g. a ragdoll or a single actor with a
large number of attached shapes).
2) it reduces broad-phase memory usage
3) filtering can be optimized a lot if self-collisions within an aggregate are not needed. For
example if you don't need collisions between ragdoll bones, it's faster to simply disable
filtering once and for all, for the aggregate containing the ragdoll, rather than filtering
out each bone-bone collision in the filter shader.
@see PxActor, PxPhysics.createAggregate
*/
class PxAggregate : public PxBase
{
public:
/**
\brief Deletes the aggregate object.
Deleting the PxAggregate object does not delete the aggregated actors. If the PxAggregate object
belongs to a scene, the aggregated actors are automatically re-inserted in that scene. If you intend
to delete both the PxAggregate and its actors, it is best to release the actors first, then release
the PxAggregate when it is empty.
*/
virtual void release() = 0;
/**
\brief Adds an actor to the aggregate object.
A warning is output if the total number of actors is reached, or if the incoming actor already belongs
to an aggregate.
If the aggregate belongs to a scene, adding an actor to the aggregate also adds the actor to that scene.
If the actor already belongs to a scene, a warning is output and the call is ignored. You need to remove
the actor from the scene first, before adding it to the aggregate.
\note When a BVH is provided the actor shapes are grouped together.
The scene query pruning structure inside PhysX SDK will store/update one
bound per actor. The scene queries against such an actor will query actor
bounds and then make a local space query against the provided BVH, which is in actor's local space.
\param [in] actor The actor that should be added to the aggregate
\param [in] bvh BVH for actor shapes.
return true if success
*/
virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0;
/**
\brief Removes an actor from the aggregate object.
A warning is output if the incoming actor does not belong to the aggregate. Otherwise the actor is
removed from the aggregate. If the aggregate belongs to a scene, the actor is reinserted in that
scene. If you intend to delete the actor, it is best to call #PxActor::release() directly. That way
the actor will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] actor The actor that should be removed from the aggregate
return true if success
*/
virtual bool removeActor(PxActor& actor) = 0;
/**
\brief Adds an articulation to the aggregate object.
A warning is output if the total number of actors is reached (every articulation link counts as an actor),
or if the incoming articulation already belongs to an aggregate.
If the aggregate belongs to a scene, adding an articulation to the aggregate also adds the articulation to that scene.
If the articulation already belongs to a scene, a warning is output and the call is ignored. You need to remove
the articulation from the scene first, before adding it to the aggregate.
\param [in] articulation The articulation that should be added to the aggregate
return true if success
*/
virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Removes an articulation from the aggregate object.
A warning is output if the incoming articulation does not belong to the aggregate. Otherwise the articulation is
removed from the aggregate. If the aggregate belongs to a scene, the articulation is reinserted in that
scene. If you intend to delete the articulation, it is best to call #PxArticulationReducedCoordinate::release() directly. That way
the articulation will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] articulation The articulation that should be removed from the aggregate
return true if success
*/
virtual bool removeArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Returns the number of actors contained in the aggregate.
You can use #getActors() to retrieve the actor pointers.
\return Number of actors contained in the aggregate.
@see PxActor getActors()
*/
virtual PxU32 getNbActors() const = 0;
/**
\brief Retrieves max amount of actors that can be contained in the aggregate.
\return Max actor size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbActors() const = 0;
/**
\brief Retrieves max amount of shapes that can be contained in the aggregate.
\return Max shape size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbShapes() const = 0;
/**
\brief Retrieve all actors contained in the aggregate.
You can retrieve the number of actor pointers by calling #getNbActors()
\param[out] userBuffer The buffer to store the actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actor pointers written to the buffer.
@see PxShape getNbShapes()
*/
virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Retrieves the scene which this aggregate belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() = 0;
/**
\brief Retrieves aggregate's self-collision flag.
\return self-collision flag
*/
virtual bool getSelfCollision() const = 0;
virtual const char* getConcreteTypeName() const { return "PxAggregate"; }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxAggregate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxAggregate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxAggregate() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxAggregate", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,371 | C | 36.338645 | 134 | 0.762672 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneQuerySystem.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 PX_SCENE_QUERY_SYSTEM_H
#define PX_SCENE_QUERY_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxTransform.h"
#include "PxSceneQueryDesc.h"
#include "PxQueryReport.h"
#include "PxQueryFiltering.h"
#include "geometry/PxGeometryQueryFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxRenderOutput;
class PxGeometry;
class PxRigidActor;
class PxShape;
class PxBVH;
class PxPruningStructure;
/**
\brief Built-in enum for default PxScene pruners
This is passed as a pruner index to various functions in the following APIs.
@see PxSceneQuerySystemBase::forceRebuildDynamicTree PxSceneQuerySystem::preallocate
@see PxSceneQuerySystem::visualize PxSceneQuerySystem::sync PxSceneQuerySystem::prepareSceneQueryBuildStep
*/
enum PxScenePrunerIndex
{
PX_SCENE_PRUNER_STATIC = 0,
PX_SCENE_PRUNER_DYNAMIC = 1,
PX_SCENE_COMPOUND_PRUNER = 0xffffffff
};
/**
\brief Base class for the scene-query system.
Methods defined here are common to both the traditional PxScene API and the PxSceneQuerySystem API.
@see PxScene PxSceneQuerySystem
*/
class PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystemBase() {}
virtual ~PxSceneQuerySystemBase() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets the rebuild rate of the dynamic tree pruning structures.
\param[in] dynamicTreeRebuildRateHint Rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint getDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint) = 0;
/**
\brief Retrieves the rebuild rate of the dynamic tree pruning structures.
\return The rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual PxU32 getDynamicTreeRebuildRateHint() const = 0;
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] prunerIndex Index of pruner containing the dynamic tree to rebuild
\note PxScene will call this function with the PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC value.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
virtual void forceRebuildDynamicTree(PxU32 prunerIndex) = 0;
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) = 0;
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const = 0;
/**
\brief Retrieves the system's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
virtual PxU32 getStaticTimestamp() const = 0;
/**
\brief Flushes any changes to the scene query representation.
This method updates the state of the scene query representation to match changes in the scene state.
By default, these changes are buffered until the next query is submitted. Calling this function will not change
the results from scene queries, but can be used to ensure that a query will not perform update work in the course of
its execution.
A thread performing updates will hold a write lock on the query structure, and thus stall other querying threads. In multithread
scenarios it can be useful to explicitly schedule the period where this lock may be held for a significant period, so that
subsequent queries issued from multiple threads will not block.
*/
virtual void flushUpdates() = 0;
/**
\brief Performs a raycast against objects in the scene, returns results in a PxRaycastBuffer object
or via a custom user callback implementation inheriting from PxRaycastCallback.
\note Touching hits are not ordered.
\note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in user guide article SceneQuery. User can ignore such objects by employing one of the provided filter mechanisms.
\param[in] origin Origin of the ray.
\param[in] unitDir Normalized direction of the ray.
\param[in] distance Length of the ray. Has to be in the [0, inf) range.
\param[out] hitCall Raycast hit buffer or callback object used to report raycast hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data passed to the filter shader.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Ray is tested against cached shape first. If no hit is found the ray gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxRaycastCallback PxRaycastBuffer PxQueryFilterData PxQueryFilterCallback PxQueryCache PxRaycastHit PxQueryFlag PxQueryFlag::eANY_HIT PxGeometryQueryFlag
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance,
PxRaycastCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs a sweep test against objects in the scene, returns results in a PxSweepBuffer object
or via a custom user callback implementation inheriting from PxSweepCallback.
\note Touching hits are not ordered.
\note If a shape from the scene is already overlapping with the query shape in its starting position,
the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified.
\param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the sweep object.
\param[in] unitDir Normalized direction of the sweep.
\param[in] distance Sweep distance. Needs to be in [0, inf) range and >0 if eASSUME_NO_INITIAL_OVERLAP was specified. Will be clamped to PX_MAX_SWEEP_DISTANCE.
\param[out] hitCall Sweep hit buffer or callback object used to report sweep hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data and simple logic.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first. If no hit is found the sweep gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal.
Note: ePRECISE_SWEEP doesn't support inflation. Therefore the sweep will be performed with zero inflation.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxSweepCallback PxSweepBuffer PxQueryFilterData PxQueryFilterCallback PxSweepHit PxQueryCache PxGeometryQueryFlag
*/
virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance,
PxSweepCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs an overlap test of a given geometry against objects in the scene, returns results in a PxOverlapBuffer object
or via a custom user callback implementation inheriting from PxOverlapCallback.
\note Filtering: returning eBLOCK from user filter for overlap queries will cause a warning (see #PxQueryHitType).
\param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the object.
\param[out] hitCall Overlap hit buffer or callback object used to report overlap hits.
\param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to overlap.
\param[in] cache Cached hit shape (optional). Overlap is performed against cached shape first. If no hit is found the overlap gets queried against the scene.
\param[in] queryFlags Optional flags controlling the query.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
\note eBLOCK should not be returned from user filters for overlap(). Doing so will result in undefined behavior, and a warning will be issued.
\note If the PxQueryFlag::eNO_BLOCK flag is set, the eBLOCK will instead be automatically converted to an eTOUCH and the warning suppressed.
@see PxOverlapCallback PxOverlapBuffer PxHitFlags PxQueryFilterData PxQueryFilterCallback PxGeometryQueryFlag
*/
virtual bool overlap(const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hitCall,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
//@}
};
/**
\brief Traditional SQ system for PxScene.
Methods defined here are only available through the traditional PxScene API.
Thus PxSceneSQSystem effectively captures the scene-query related part of the PxScene API.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneSQSystem : public PxSceneQuerySystemBase
{
protected:
PxSceneSQSystem() {}
virtual ~PxSceneSQSystem() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE void setSceneQueryUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) { setUpdateMode(updateMode); }
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE PxSceneQueryUpdateMode::Enum getSceneQueryUpdateMode() const { return getUpdateMode(); }
/**
\brief Retrieves the scene's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
PX_FORCE_INLINE PxU32 getSceneQueryStaticTimestamp() const { return getStaticTimestamp(); }
/**
\brief Flushes any changes to the scene query representation.
@see flushUpdates
*/
PX_FORCE_INLINE void flushQueryUpdates() { flushUpdates(); }
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] rebuildStaticStructure True to rebuild the dynamic tree containing static objects
\param[in] rebuildDynamicStructure True to rebuild the dynamic tree containing dynamic objects
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
PX_FORCE_INLINE void forceDynamicTreeRebuild(bool rebuildStaticStructure, bool rebuildDynamicStructure)
{
if(rebuildStaticStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC);
if(rebuildDynamicStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_DYNAMIC);
}
/**
\brief Return the value of PxSceneQueryDesc::staticStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::staticStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getStaticStructure() const = 0;
/**
\brief Return the value of PxSceneQueryDesc::dynamicStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::dynamicStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getDynamicStructure() const = 0;
/**
\brief Executes scene queries update tasks.
This function will refit dirty shapes within the pruner and will execute a task to build a new AABB tree, which is
build on a different thread. The new AABB tree is built based on the dynamic tree rebuild hint rate. Once
the new tree is ready it will be commited in next fetchQueries call, which must be called after.
This function is equivalent to the following PxSceneQuerySystem calls:
Synchronous calls:
- PxSceneQuerySystemBase::flushUpdates()
- handle0 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_STATIC)
- handle1 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_DYNAMIC)
Asynchronous calls:
- PxSceneQuerySystem::sceneQueryBuildStep(handle0);
- PxSceneQuerySystem::sceneQueryBuildStep(handle1);
This function is part of the PxSceneSQSystem interface because it uses the PxScene task system under the hood. But
it calls PxSceneQuerySystem functions, which are independent from this system and could be called in a similar
fashion by a separate, possibly user-defined task manager.
\note If PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED is used, it is required to update the scene queries
using this function.
\param[in] completionTask if non-NULL, this task will have its refcount incremented in sceneQueryUpdate(), then
decremented when the scene is ready to have fetchQueries called. So the task will not run until the
application also calls removeReference().
\param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave
true unless the application is calling the PxTaskManager start/stopSimulation() methods itself.
@see PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED
*/
virtual void sceneQueriesUpdate(PxBaseTask* completionTask = NULL, bool controlSimulation = true) = 0;
/**
\brief This checks to see if the scene queries update has completed.
This does not cause the data available for reading to be updated with the results of the scene queries update, it is simply a status check.
The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true
\param[in] block When set to true will block until the condition is met.
\return True if the results are available.
@see sceneQueriesUpdate() fetchResults()
*/
virtual bool checkQueries(bool block = false) = 0;
/**
This method must be called after sceneQueriesUpdate. It will wait for the scene queries update to finish. If the user makes an illegal scene queries update call,
the SDK will issue an error message.
If a new AABB tree build finished, then during fetchQueries the current tree within the pruning structure is swapped with the new tree.
\param[in] block When set to true will block until the condition is met, which is tree built task must finish running.
*/
virtual bool fetchQueries(bool block = false) = 0;
//@}
};
typedef PxU32 PxSQCompoundHandle;
typedef PxU32 PxSQPrunerHandle;
typedef void* PxSQBuildStepHandle;
/**
\brief Scene-queries external sub-system for PxScene-based objects.
The default PxScene has hardcoded support for 2 regular pruners + 1 compound pruner, but these interfaces
should work with multiple pruners.
Regular shapes are traditional PhysX shapes that belong to an actor. That actor can be a compound, i.e. it has
more than one shape. *All of these go to the regular pruners*. This is important because it might be misleading:
by default all shapes go to one of the two regular pruners, even shapes that belong to compound actors.
For compound actors, adding all the actor's shapes individually to the SQ system can be costly, since all the
corresponding bounds will always move together and remain close together - that can put a lot of stress on the
code that updates the SQ spatial structures. In these cases it can be more efficient to add the compound's bounds
(i.e. the actor's bounds) to the system, as the first level of a bounds hierarchy. The scene queries would then
be performed against the actor's bounds first, and only visit the shapes' bounds second. This is only useful
for actors that have more than one shape, i.e. compound actors. Such actors added to the SQ system are thus
called "SQ compounds". These objects are managed by the "compound pruner", which is only used when an explicit
SQ compound is added to the SQ system via the addSQCompound call. So in the end one has to distinguish between:
- a "compound shape", which is added to regular pruners as its own individual entity.
- an "SQ compound shape", which is added to the compound pruner as a subpart of an SQ compound actor.
A compound shape has an invalid compound ID, since it does not belong to an SQ compound.
An SQ compound shape has a valid compound ID, that identifies its SQ compound owner.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneQuerySystem : public PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystem() {}
virtual ~PxSceneQuerySystem() {}
public:
/**
\brief Decrements the reference count of the object and releases it if the new reference count is zero.
*/
virtual void release() = 0;
/**
\brief Acquires a counted reference to this object.
This method increases the reference count of the object by 1. Decrement the reference count by calling release()
*/
virtual void acquireReference() = 0;
/**
\brief Preallocates internal arrays to minimize the amount of reallocations.
The system does not prevent more allocations than given numbers. It is legal to not call this function at all,
or to add more shapes to the system than the preallocated amounts.
\param[in] prunerIndex Index of pruner to preallocate (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[in] nbShapes Expected number of (regular) shapes
*/
virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) = 0;
/**
\brief Frees internal memory that may not be in-use anymore.
This is an entry point for reclaiming transient memory allocated at some point by the SQ system,
but which wasn't been immediately freed for performance reason. Calling this function might free
some memory, but it might also produce a new set of allocations in the next frame.
*/
virtual void flushMemory() = 0;
/**
\brief Adds a shape to the SQ system.
The same function is used to add either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] bounds Shape bounds, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] transform Shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] compoundHandle Handle of SQ compound owner, or NULL for regular shapes.
\param[in] hasPruningStructure True if the shape is part of a pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner.
@see merge() PxPruningStructure
*/
virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds,
const PxTransform& transform, const PxSQCompoundHandle* compoundHandle=NULL, bool hasPruningStructure=false) = 0;
/**
\brief Removes a shape from the SQ system.
The same function is used to remove either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
*/
virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape) = 0;
/**
\brief Updates a shape in the SQ system.
The same function is used to update either a regular shape, or a SQ compound shape.
The transforms are eager-evaluated, but the bounds are lazy-evaluated. This means that
the updated transform has to be passed to the update function, while the bounds are automatically
recomputed by the system whenever needed.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] transform New shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
*/
virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) = 0;
/**
\brief Adds a compound to the SQ system.
\param[in] actor The compound actor
\param[in] shapes The compound actor's shapes
\param[in] bvh BVH structure containing the compound's shapes in local space
\param[in] transforms Shape transforms, in local-space
\return SQ compound handle
@see PxBVH PxCooking::createBVH
*/
virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) = 0;
/**
\brief Removes a compound from the SQ system.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
*/
virtual void removeSQCompound(PxSQCompoundHandle compoundHandle) = 0;
/**
\brief Updates a compound in the SQ system.
The compound structures are immediately updated when the call occurs.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
\param[in] compoundTransform New actor/compound transform, in world-space
*/
virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) = 0;
/**
\brief Shift the data structures' origin by the specified vector.
Please refer to the notes of the similar function in PxScene.
\param[in] shift Translation vector to shift the origin by.
*/
virtual void shiftOrigin(const PxVec3& shift) = 0;
/**
\brief Visualizes the system's internal data-structures, for debugging purposes.
\param[in] prunerIndex Index of pruner to visualize (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[out] out Filled with render output data
@see PxRenderOutput
*/
virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const = 0;
/**
\brief Merges a pruning structure with the SQ system's internal pruners.
\param[in] pruningStructure The pruning structure to merge
@see PxPruningStructure
*/
virtual void merge(const PxPruningStructure& pruningStructure) = 0;
/**
\brief Shape to SQ-pruner-handle mapping function.
This function finds and returns the SQ pruner handle associated with a given (actor/shape) couple
that was previously added to the system. This is needed for the sync function.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[out] prunerIndex Index of pruner the shape belongs to
\return Associated SQ pruner handle.
*/
virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const = 0;
/**
\brief Synchronizes the scene-query system with another system that references the same objects.
This function is used when the scene-query objects also exist in another system that can also update them. For example the scene-query objects
(used for raycast, overlap or sweep queries) might be driven by equivalent objects in an external rigid-body simulation engine. In this case
the rigid-body simulation engine computes the new poses and transforms, and passes them to the scene-query system using this function. It is
more efficient than calling updateSQShape on each object individually, since updateSQShape would end up recomputing the bounds already available
in the rigid-body engine.
\param[in] prunerIndex Index of pruner being synched (PX_SCENE_PRUNER_DYNAMIC for regular PhysX usage)
\param[in] handles Handles of updated objects
\param[in] indices Bounds & transforms indices of updated objects, i.e. object handles[i] has bounds[indices[i]] and transforms[indices[i]]
\param[in] bounds Array of bounds for all objects (not only updated bounds)
\param[in] transforms Array of transforms for all objects (not only updated transforms)
\param[in] count Number of updated objects
\param[in] ignoredIndices Optional bitmap of ignored indices, i.e. update is skipped if ignoredIndices[indices[i]] is set.
@see PxBounds3 PxTransform32 PxBitMap
*/
virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0;
/**
\brief Finalizes updates made to the SQ system.
This function should be called after updates have been made to the SQ system, to fully reflect the changes
inside the internal pruners. In particular it should be called:
- after calls to updateSQShape
- after calls to sync
This function:
- recomputes bounds of manually updated shapes (i.e. either regular or SQ compound shapes modified by updateSQShape)
- updates dynamic pruners (refit operations)
- incrementally rebuilds AABB-trees
The amount of work performed in this function depends on PxSceneQueryUpdateMode.
@see PxSceneQueryUpdateMode updateSQShape() sync()
*/
virtual void finalizeUpdates() = 0;
/**
\brief Prepares asynchronous build step.
This is directly called (synchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function is called to let the system execute any necessary synchronous operation before the
asynchronous sceneQueryBuildStep() function is called.
If there is any work to do for the specific pruner, the function returns a pruner-specific handle that
will be passed to the corresponding, asynchronous sceneQueryBuildStep function.
\return A pruner-specific handle that will be sent to sceneQueryBuildStep if there is any work to do, i.e. to execute the corresponding sceneQueryBuildStep() call.
\param[in] prunerIndex Index of pruner being built. (PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC when called by PxScene).
\return Null if there is no work to do, otherwise a pruner-specific handle.
@see PxSceneSQSystem::sceneQueriesUpdate sceneQueryBuildStep
*/
virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex) = 0;
/**
\brief Executes asynchronous build step.
This is directly called (asynchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function incrementally builds the internal trees/pruners. It is called asynchronously, i.e. this can be
called from different threads for building multiple trees at the same time.
\param[in] handle Pruner-specific handle previously returned by the prepareSceneQueryBuildStep function.
@see PxSceneSQSystem::sceneQueriesUpdate prepareSceneQueryBuildStep
*/
virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle) = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,407 | C | 45.283105 | 242 | 0.769625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.